<?php
/*****************************************************************************
 * ManageAssets.php
 * Contains the asset management controller.
 *
 * Kabuki CMS (C) 2013-2017, Aaron van Geffen
 *****************************************************************************/

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

		if (isset($_POST['deleteChecked'], $_POST['delete']) && Session::validateSession())
			$this->handleAssetDeletion();

		Session::resetSessionToken();

		$options = [
			'form' => [
				'action' => BASEURL . '/manageassets/?' . Session::getSessionTokenKey() . '=' . Session::getSessionToken(),
				'method' => 'post',
				'class' => 'col-md-6 text-end',
				'is_embed' => true,
				'buttons' => [
					'deleteChecked' => [
						'type' => 'submit',
						'caption' => 'Delete checked',
						'class' => 'btn-danger',
						'onclick' => 'return confirm(\'Are you sure you want to delete these items?\')',
					],
				],
			],
			'columns' => [
				'checkbox' => [
					'header' => '<input type="checkbox" id="selectall">',
					'is_sortable' => false,
					'format' => fn($row) =>
						'<input type="checkbox" class="asset_select" name="delete[]" value="' . $row['id_asset'] . '">',
				],
				'thumbnail' => [
					'header' => '&nbsp;',
					'is_sortable' => false,
					'cell_class' => 'text-center',
					'format' => function($row) {
						$asset = Image::byRow($row);
						$width = $height = 65;
						if ($asset->isImage())
						{
							if ($asset->isPortrait())
								$width = null;
							else
								$height = null;

							$thumb = $asset->getThumbnailUrl($width, $height);
						}
						else
							$thumb = BASEURL . '/images/nothumb.svg';

						$width = isset($width) ? $width . 'px' : 'auto';
						$height = isset($height) ? $height . 'px' : 'auto';

						return sprintf('<img src="%s" style="width: %s; height: %s;">', $thumb, $width, $height);
					},
				],
				'id_asset' => [
					'value' => 'id_asset',
					'header' => 'ID',
					'is_sortable' => true,
				],
				'subdir' => [
					'value' => 'subdir',
					'header' => 'Subdirectory',
					'is_sortable' => true,
				],
				'filename' => [
					'value' => 'filename',
					'header' => 'Filename',
					'is_sortable' => true,
					'link' => BASEURL . '/editasset/?id={ID_ASSET}',
					'value' => 'filename',
				],
				'id_user_uploaded' => [
					'header' => 'User uploaded',
					'is_sortable' => true,
					'format' => function($row) {
						if (!empty($row['id_user']))
							return sprintf('<a href="%s/edituser/?id=%d">%s</a>', BASEURL, $row['id_user'],
								$row['first_name'] . ' ' . $row['surname']);
						else
							return 'n/a';
					},
				],
				'dimensions' => [
					'header' => 'Dimensions',
					'is_sortable' => false,
					'format' => function($row) {
						if (!empty($row['image_width']))
							return $row['image_width'] . ' x ' . $row['image_height'];
						else
							return 'n/a';
					},
				],
			],
			'default_sort_order' => 'id_asset',
			'default_sort_direction' => 'down',
			'start' => $_GET['start'] ?? 0,
			'sort_order' => $_GET['order'] ?? '',
			'sort_direction' => $_GET['dir'] ?? '',
			'title' => 'Manage assets',
			'no_items_label' => 'No assets meet the requirements of the current filter.',
			'items_per_page' => 30,
			'index_class' => 'col-md-6',
			'base_url' => BASEURL . '/manageassets/',
			'get_data' => 'Asset::getOffset',
			'get_count' => 'Asset::getCount',
		];

		$table = new GenericTable($options);
		parent::__construct('Asset management - Page ' . $table->getCurrentPage());

		$wrapper = new AssetManagementWrapper();
		$this->page->adopt($wrapper);
		$wrapper->adopt(new TabularData($table));
	}

	private function handleAssetDeletion()
	{
		if (!isset($_POST['delete']) || !is_array($_POST['delete']))
			throw new UnexpectedValueException();

		foreach ($_POST['delete'] as $id_asset)
		{
			$asset = Asset::fromId($id_asset);
			$asset->delete();
		}

		header('Location: ' . BASEURL . '/manageassets/');
		exit;
	}
}