<?php
declare(strict_types = 1);

require_once(__DIR__ . '/AdminAlbums.class.php');

/**
 * Fichiers en attente de validation.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AdminItemsPending extends AdminAlbums
{
	/**
	 * Actions sur la sélection de fichiers.
	 *
	 * @return void
	 */
	public static function actions(): void
	{
		if (isset($_POST['cancel']) || !isset($_POST['selection']))
		{
			return;
		}
		switch (self::_getSelectedIds($selected_ids))
		{
			case 'activate' :
			case 'deactivate' :
				$r = Pending::add($selected_ids, $_POST['action'] == 'activate' ? 1 : 0);
				if ($r < 0)
				{
					Report::error();
				}
				else if ($r < 1)
				{
					Report::info(__('Aucun fichier n\'a été ajouté à la galerie.'));
				}
				else
				{
					Report::success($r > 1
						? sprintf(__('%s fichiers ont été ajoutés à la galerie.'), $r)
						: __('1 fichier a été ajouté à la galerie.'));
				}
				break;

			case 'delete' :
				$r = Pending::delete($selected_ids);
				if ($r < 0)
				{
					Report::error();
				}
				else if ($r < 1)
				{
					Report::info(__('Aucun fichier n\'a été supprimé.'));
				}
				else
				{
					Report::success($r > 1
						? sprintf(__('%s fichiers ont été supprimés.'), $r)
						: __('1 fichier a été supprimé.'));
				}
				break;
		}
	}

	/**
	 * Construit la liste des albums ayant des fichiers en attente.
	 *
	 * @param bool $move_only_cat
	 *
	 * @return void
	 */
	public static function getCategoriesLists(bool $move_only_cat = FALSE): void
	{
		$get_url = function($page)
		{
			return App::getURL(str_replace(['album', 'category'], 'items-pending', $page));
		};
		$categories = Category::getList($makelist, $get_url, (int) $_GET['value_1']);
		if (!$makelist)
		{
			return;
		}
		$sql = 'SELECT cat_id,
					   COUNT(pending_id) AS count
				  FROM {items_pending}
			  GROUP BY cat_id';
		if (!DB::execute($sql))
		{
			return;
		}
		$infos = DB::fetchAll('cat_id', 'count');
		Category::reduceList($categories, $infos);
		self::_categoriesBrowse($makelist($categories));
	}

	/**
	 * Retourne les informations formatées d'un fichier.
	 *
	 * @param array $i
	 *   Informations du fichier.
	 *
	 * @return array
	 */
	public static function getFormatedInfos(array &$i): array
	{
		$type = Item::isImage($i['pending_type']) ? 'image' : 'video';

		// Orientation.
		$orientation = 1;
		if ($type == 'image')
		{
			$metadata = new Metadata(GALLERY_ROOT . '/pending/' . $i['pending_file']);
			$orientation = (int) $metadata->getExifValue('orientation');
		}
		if (in_array($orientation, [5, 6, 7, 8]))
		{
			$width = $i['pending_width'];
			$i['pending_width'] = $i['pending_height'];
			$i['pending_height'] = $width;
		}

		return
		[
			'adddt_formated' => L10N::dt(__('%A %d %B %Y à %H:%M:%S'), $i['pending_adddt']),
			'album_name' => $i['cat_name'],
			'album_link' => App::getURL('album/' . $i['cat_id']),
			'duration' => $type == 'video' ? App::formatDuration($i['pending_duration']) : '/',
			'duration_text' => $i['pending_duration']
				? App::formatDuration($i['pending_duration'])
				: '00:00',
			'filesize_formated' => $i['pending_filesize']
				? L10N::formatFilesize($i['pending_filesize'])
				: 0,
			'height' => $i['pending_height'],
			'id' => $i['pending_id'],
			'ip' => $i['pending_ip'],
			'link' => App::getFileSource('/pending/' . $i['pending_file']),
			'status_text' => L10N::getTextStatus(-1),
			'type' => $type,
			'type_mime' => Item::getTypeMime($i['pending_type']),
			'type_text' => Item::getTypeText($i['pending_type']),
			'thumb_src' => function() use ($i, $orientation)
			{
				$thumb_src = App::getThumbSource('pending',
				[
					'item_adddt' => $i['pending_adddt'],
					'item_id' => $i['pending_id'],
					'item_path' => $i['pending_file'],
					'item_type' => $i['pending_type'],
					'item_orientation' => $orientation
				], self::$thumbSize, self::$thumbQuality);
				return htmlspecialchars($thumb_src);
			},
			'title' => $_POST[$i['pending_id']]['pending_name']
				?? $i['pending_name'],
			'user_link' => App::getURL('user/' . $i['user_id']),
			'user_nickname' => User::getNickname($i['user_login'], $i['user_nickname']),
			'width' => $i['pending_width']
		];
	}

	/**
	 * Récupération des fichiers de la page courante.
	 *
	 * @return void
	 */
	public static function getItems(): void
	{
		$user_prefs = Auth::$infos['user_prefs']['pending'];

		// Limitation à la catégorie courante.
		$sql_where = '1=1';
		$params = [];
		$sql = 'SELECT cat_id,
					   CASE WHEN cat_filemtime IS NULL
							THEN "category" ELSE "album"
							 END AS cat_type,
					   cat_name,
					   cat_parents,
					   cat_path
				 FROM {categories}
				WHERE cat_id = ?';
		if (DB::execute($sql, $_GET['value_1']))
		{
			if (!$cat_infos = DB::fetchRow())
			{
				App::redirect('items-pending/1');
				return;
			}
			if ($_GET['value_1'] > 1)
			{
				$sql_where = "(cat.cat_id = ? OR cat_path LIKE ?)";
				$params = [$_GET['value_1'], DB::likeEscape($cat_infos['cat_path']) . '/%'];
			}
		}

		// Fil d'Ariane.
		Template::breadcrumb($cat_infos, FALSE, 'items-pending');

		// Nombre de fichiers par page.
		$nb_per_page = $user_prefs['nb_per_page'];

		// Clause LIMIT.
		$sql_limit = 'LIMIT ' . ($nb_per_page * ($_GET['page'] - 1)) . ',' . $nb_per_page;

		// Clause ORDER BY.
		$sql_order_by = sprintf(
			'pending_%s %s',
			$user_prefs['order_by_column'],
			$user_prefs['order_by_order']
		);

		// Nombre de fichiers en attente.
		$sql = "SELECT COUNT(*)
				  FROM {items_pending} AS ip,
					   {categories} AS cat
				 WHERE $sql_where
				   AND ip.cat_id = cat.cat_id";
		if (!DB::execute($sql, $params))
		{
			return;
		}
		Template::$data['objects_count'] = DB::fetchVal();

		if ($user_prefs['display'] == 'grid')
		{
			if ($_GET['q_pageless'] != $_GET['q'])
			{
				App::redirect($_GET['q_pageless']);
			}
			return;
		}

		// Nombre de pages.
		Template::set('nb_pages', ceil(Template::$data['objects_count'] / $nb_per_page));

		// Récupération des fichiers en attente.
		$sql = "SELECT ip.*,
					   cat.cat_name,
					   user_login,
					   user_nickname
				  FROM {items_pending} AS ip,
					   {categories} AS cat,
					   {users} AS u
				 WHERE $sql_where
				   AND ip.cat_id = cat.cat_id
				   AND ip.user_id = u.user_id
			  ORDER BY $sql_order_by
			           $sql_limit";
		if (!DB::execute($sql, $params))
		{
			return;
		}
		$items = DB::fetchAll('pending_id');
		if ((!isset($cat_infos) || $_GET['page'] > 1)
		&& !self::_objectsNoResult(count($items)))
		{
			return;
		}

		// Formatage des informations pour le template.
		$formated_infos = [];
		foreach ($items as &$i)
		{
			$formated_infos[] = self::getFormatedInfos($i);
		}
		Template::set('items', $formated_infos);
	}
}
?>