<?php
/*****************************************************************************
 * EditAlbum.php
 * Contains the album edit controller.
 *
 * Kabuki CMS (C) 2013-2017, Aaron van Geffen
 *****************************************************************************/

class EditAlbum extends HTMLController
{
	public function __construct()
	{
		// Ensure it's just admins at this point.
		if (!Registry::get('user')->isAdmin())
			throw new NotAllowedException();

		$id_tag = isset($_GET['id']) ? (int) $_GET['id'] : 0;
		if (empty($id_tag) && !isset($_GET['add']) && $_GET['action'] !== 'addalbum')
			throw new UnexpectedValueException('Requested album not found or not requesting a new album.');

		if (!empty($id_tag))
			$album = Tag::fromId($id_tag);

		// Adding an album?
		if (isset($_GET['add']) || $_GET['action'] === 'addalbum')
		{
			parent::__construct('Add a new album');
			$form_title = 'Add a new album';
			$this->page->addClass('editalbum');
		}
		// Deleting one?
		elseif (isset($_GET['delete']))
		{
			// So far so good?
			if (Session::validateSession('get') && $album->kind === 'Album' && $album->delete())
			{
				header('Location: ' . BASEURL . '/managealbums/');
				exit;
			}
			else
				trigger_error('Cannot delete album: an error occured while processing the request.', E_USER_ERROR);
		}
		// Editing one, then, surely.
		else
		{
			if ($album->kind !== 'Album')
				trigger_error('Cannot edit album: not an album.', E_USER_ERROR);

			parent::__construct('Edit album \'' . $album->tag . '\'');
			$form_title = 'Edit album \'' . $album->tag . '\'';
			$this->page->addClass('editalbum');
		}

		// Session checking!
		if (empty($_POST))
			Session::resetSessionToken();
		else
			Session::validateSession();

		if ($id_tag)
			$after_form = '<a href="' . BASEURL . '/editalbum/?id=' . $id_tag . '&delete&' . Session::getSessionTokenKey() . '=' . Session::getSessionToken() . '" class="btn btn-danger" onclick="return confirm(\'Are you sure you want to delete this album? You cannot undo this!\');">Delete album</a>';
		elseif (!$id_tag)
			$after_form = '<button name="submit_and_new" class="btn">Save and add another</button>';

		// Gather possible parents for this album to be filed into
		$parentChoices = [0 => '-root-'];
		foreach (PhotoAlbum::getHierarchy('tag', 'up') as $parent)
		{
			if (!empty($id_tag) && $parent['id_tag'] == $id_tag)
				continue;

			$parentChoices[$parent['id_tag']] = $parent['tag'];
		}

		$fields = [
			'id_parent' => [
				'type' => 'select',
				'label' => 'Parent album',
				'options' => $parentChoices,
			],
			'id_asset_thumb' => [
				'type' => 'numeric',
				'label' => 'Thumbnail asset ID',
				'is_optional' => true,
			],
			'tag' => [
				'type' => 'text',
				'label' => 'Album title',
				'size' => 50,
				'maxlength' => 255,
			],
			'slug' => [
				'type' => 'text',
				'label' => 'URL slug',
				'size' => 50,
				'maxlength' => 255,
			],
			'description' => [
				'type' => 'textbox',
				'label' => 'Description',
				'size' => 50,
				'maxlength' => 255,
				'is_optional' => true,
			],
		];

		// Fetch image assets for this album
		if (!empty($id_tag))
		{
			list($assets, $num_assets) = AssetIterator::getByOptions([
				'direction' => 'desc',
				'limit' => 500,
				'id_tag' => $id_tag,
			], true);

			if ($num_assets > 0)
				unset($fields['id_asset_thumb']);
		}

		$form = new Form([
			'request_url' => BASEURL . '/editalbum/?' . ($id_tag ? 'id=' . $id_tag : 'add'),
			'content_below' => $after_form,
			'fields' => $fields,
		]);

		// Add defaults for album if none present
		if (empty($_POST) && isset($_GET['tag']))
		{
			$parentTag = Tag::fromId($_GET['tag']);
			if ($parentTag->kind === 'Album')
			{
				$formDefaults = [
					'id_parent' => $parentTag->id_tag,
					'tag' => 'New Album Title Here',
					'slug' => ($parentTag->slug ? $parentTag->slug . '/' : '') . 'NEW_ALBUM_SLUG_HERE',
				];
			}
		}

		if (!isset($formDefaults))
			$formDefaults = isset($album) ? get_object_vars($album) : $_POST;

		// Create the form, add in default values.
		$form->setData($formDefaults);
		$formview = new FormView($form, $form_title ?? '');
		$this->page->adopt($formview);

		// If we have asset images, show the thumbnail manager
		if (!empty($id_tag) && $num_assets > 0)
			$this->page->adopt(new FeaturedThumbnailManager($assets, $id_tag ? $album->id_asset_thumb : 0));

		if (isset($_POST['changeThumbnail']))
			$this->processThumbnail($album);
		elseif (!empty($_POST))
			$this->processTagDetails($form, $id_tag, $album ?? null);
	}

	private function processThumbnail($tag)
	{
		if (empty($_POST))
			return;

		$tag->id_asset_thumb = $_POST['featuredThumbnail'];
		$tag->save();

		header('Location: ' . BASEURL . '/editalbum/?id=' . $tag->id_tag);
		exit;
	}

	private function processTagDetails($form, $id_tag, $album)
	{
		if (!empty($_POST))
		{
			$form->verify($_POST);

			// Anything missing?
			if (!empty($form->getMissing()))
				return $formview->adopt(new Alert('Some data missing', 'Please fill out the following fields: ' . implode(', ', $form->getMissing()), 'danger'));

			$data = $form->getData();

			// Sanity check: don't let an album be its own parent
			if ($data['id_parent'] == $id_tag)
			{
				return $formview->adopt(new Alert('Invalid parent', 'An album cannot be its own parent.', 'danger'));
			}

			// Quick stripping.
			$data['tag'] = htmlspecialchars($data['tag']);
			$data['description'] = htmlspecialchars($data['description']);
			$data['slug'] = strtr($data['slug'], [' ' => '-', '--' => '-', '&' => 'and', '=>' => '', "'" => "", ":"=> "", '\\' => '-']);

			// TODO: when updating slug, update slug for all photos in this album.

			// Creating a new album?
			if (!$id_tag)
			{
				$data['kind'] = 'Album';
				$newTag = Tag::createNew($data);
				if ($newTag === false)
					return $formview->adopt(new Alert('Cannot create this album', 'Something went wrong while creating the album...', 'danger'));

				if (isset($_POST['submit_and_new']))
				{
					header('Location: ' . BASEURL . '/editalbum/?add&tag=' . $data['id_parent']);
					exit;
				}
			}
			// Just updating?
			else
			{
				foreach ($data as $key => $value)
					$album->$key = $value;

				$album->save();
			}

			// Redirect to the album management page.
			header('Location: ' . BASEURL . '/managealbums/');
			exit;
		}
	}
}