<?php
declare(strict_types = 1);

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

/**
 * Gestion des appareils photos.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AdminCameras extends Admin
{
	/**
	 * Actions sur la sélection.
	 *
	 * @return void
	 */
	public static function actions(): void
	{
		if (isset($_POST['cancel']) || !isset($_POST['selection']))
		{
			return;
		}
		switch (self::_getSelectedIds($selected_ids))
		{
			case 'delete' :
				$type = substr($_GET['section'], 8, -1);
				$r = Cameras::delete($type, $selected_ids);
				if ($r < 0)
				{
					Report::error();
				}
				else if ($r < 1)
				{
					Report::info($type == 'brand'
						? __('Aucune marque n\'a été supprimée.')
						: __('Aucun modèle n\'a été supprimé.'));
				}
				else
				{
					if ($type == 'brand')
					{
						Report::success($r > 1
							? sprintf(__('%s marques ont été supprimées.'), $r)
							: __('1 marque a été supprimée.'));
					}
					else
					{
						Report::success($r > 1
							? sprintf(__('%s modèles ont été supprimés.'), $r)
							: __('1 modèle a été supprimé.'));
					}
				}
				break;
		}
	}

	/**
	 * Récupération des marques ou modèles d'appareils photos.
	 *
	 * @return void
	 */
	public static function getCameras(): void
	{
		$type = substr($_GET['section'], 8, -1);

		Template::set('breadcrumb',
		[
			[
				'current' => TRUE,
				'name' => $type == 'brand'
					? __('Marques d\'appareils photos')
					: __('Modèles d\'appareils photos'),
				'url' => App::getURL($_GET['q_pageless'])
			]
		]);
		Template::set('cameras', []);
		Template::set('objects_count', 0);

		// Nombre d'objets par page.
		$nb_per_page = Auth::$infos['user_prefs']["cameras_{$type}s"]['nb_per_page'];

		// Clause WHERE.
		self::_sqlWhere($sql_where, $params);

		// Nombre d'objets.
		if (!DB::execute("SELECT COUNT(*) FROM {cameras_{$type}s} WHERE $sql_where", $params))
		{
			return;
		}
		Template::set('objects_count', $objects_count = DB::fetchVal());

		// Nombre de pages.
		Template::set('nb_pages', ceil($objects_count / $nb_per_page));
		$sql_limit_start = $nb_per_page * ($_GET['page'] - 1);

		// Critère de tri.
		$sql_order_by = "camera_{$type}_"
			. Auth::$infos['user_prefs']["cameras_{$type}s"]['order_by_column'];
		$sql_order_by = substr($sql_order_by, -4) == 'name'
			? "LOWER($sql_order_by)"
			: $sql_order_by;
		$sql_order_by_order = Auth::$infos['user_prefs']["cameras_{$type}s"]['order_by_order'];

		// Récupération des objets.
		if ($type == 'brand')
		{
			$sql = "SELECT camera_brand_name AS brand_name,
						   cam_b.camera_brand_id AS id,
						   COUNT(item_id) AS camera_brand_count
					  FROM {cameras_brands} AS cam_b
				 LEFT JOIN {cameras_models} AS cam_m
						ON cam_m.camera_brand_id = cam_b.camera_brand_id
				 LEFT JOIN {cameras_items} AS cam_i
						ON cam_i.camera_model_id = cam_m.camera_model_id
					 WHERE $sql_where
				  GROUP BY cam_b.camera_brand_id
				  ORDER BY $sql_order_by $sql_order_by_order, LOWER(camera_brand_name) ASC
					 LIMIT $sql_limit_start,$nb_per_page";
		}
		else
		{
			$sql = "SELECT camera_brand_name AS brand_name,
						   camera_model_name AS model_name,
						   cam_m.camera_model_id AS id,
						   COUNT(item_id) AS camera_model_count
					  FROM {cameras_models} AS cam_m
				 LEFT JOIN {cameras_brands} AS cam_b
						ON cam_b.camera_brand_id = cam_m.camera_brand_id
				 LEFT JOIN {cameras_items} AS cam_i
						ON cam_i.camera_model_id = cam_m.camera_model_id
					 WHERE $sql_where
				  GROUP BY cam_m.camera_model_id,
						   cam_b.camera_brand_name 
				  ORDER BY $sql_order_by $sql_order_by_order, LOWER(camera_model_name) ASC
					 LIMIT $sql_limit_start,$nb_per_page";
		}
		if (!DB::execute($sql, $params)
		|| !self::_objectsNoResult(count($cameras = DB::fetchAll())))
		{
			return;
		}

		// Formatage des données.
		$cameras_formated = [];
		foreach ($cameras as &$i)
		{
			$count = $i["camera_{$type}_count"];
			$data =
			[
				'brand_name' => Metadata::getExifCameraMake($i['brand_name']),
				'count' => $count,
				'link' => $count > 0 ? App::getURL("category/1/camera-$type/{$i['id']}") : NULL,
				'id' => $i['id'],
			];
			if ($type == 'model')
			{
				$model = $i['model_name'];
				if (isset(Metadata::MODELS[$model]))
				{
					$model .= ' (' . Metadata::MODELS[$model] . ')';
				}
				$data['model_name'] = $model;
			}
			$cameras_formated[] = $data;
		}
		Template::set('cameras', $cameras_formated);
	}

	/**
	 * Informations de template pour le moteur de recherche.
	 *
	 * @param array $functions
	 *
	 * @return void
	 */
	public static function tplSearch(array &$functions): void
	{
		Template::set('search', ['columns' => $functions['columns'](
		[
			'camera_brand_name' => TRUE,
			'camera_model_name' => TRUE,
		])]);
	}



	/**
	 * Clause WHERE d'une requête SQL.
	 *
	 * @param mixed $sql
	 * @param mixed $params
	 *
	 * @return void
	 */
	private static function _sqlWhere(&$sql, &$params): void
	{
		$sql = '1=1';
		$params = [];
		switch ($_GET['filter'] ?? '')
		{
			case 'search' :
				if (!$search = self::$search->sql())
				{
					App::redirect($_GET['q_filterless']);
				}
				$sql = $search['sql'];
				$params = $search['params'];
				break;
		}
	}
}
?>