<?php
declare(strict_types = 1);

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

/**
 * Gestion des votes.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AdminVotes 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' :
				$r = Rating::delete($selected_ids);
				if ($r < 0)
				{
					Report::error();
				}
				else if ($r < 1)
				{
					Report::info(__('Aucun vote n\'a été supprimé.'));
				}
				else
				{
					Report::success($r > 1
						? sprintf(__('%s votes ont été supprimés.'), $r)
						: __('1 vote a été supprimé.'));
				}
				break;
		}
	}

	/**
	 * Construit une liste des catégories contenant des votes.
	 *
	 * @return void
	 */
	public static function getCategoriesLists(): void
	{
		$get_url = function($page)
		{
			$filter = '';
			if (isset($_GET['filter']))
			{
				switch ($_GET['filter'])
				{
					case 'date' :
					case 'ip' :
					case 'item' :
					case 'note' :
					case 'search' :
					case 'user' :
						$filter = '/' . $_GET['filter'] . '/' . $_GET['filter_value'];
						break;
				}
			}
			return App::getURL('votes/' . $page . $filter);
		};
		$cat_id = isset($_GET['filter_cat_id']) && $_GET['filter_cat_id'] > 0
			? $_GET['filter_cat_id']
			: ($_GET['category_id'] ?? 1);
		$categories = Category::getList($makelist, $get_url, (int) $cat_id);
		if (!$makelist)
		{
			return;
		}

		// Réduction de la liste "parcourir".
		self::_sqlWhere($sql_where, $params);
		$sql = "SELECT cat.cat_id,
					   COUNT(vote_id) AS count
				  FROM {votes} AS v
			 LEFT JOIN {items} AS i USING (item_id)
			 LEFT JOIN {categories} AS cat USING (cat_id)
				 WHERE cat.cat_id = i.cat_id
				   AND $sql_where
			  GROUP BY cat.cat_id";
		if (!DB::execute($sql, $params))
		{
			return;
		}
		$infos = DB::fetchAll('cat_id', 'count');
		Category::reduceList($categories, $infos);
		self::_categoriesBrowse($makelist($categories));
	}

	/**
	 * Formate les informations d'un commentaire.
	 *
	 * @param array $i
	 *   Informations brutes du commentaire.
	 *
	 * @return array
	 */
	public static function getFormatedInfos(array &$i): array
	{
		return
		[
			'id' => $i['vote_id'],

			// Album.
			'album_id' => (int) $i['cat_id'],
			'album_link' => App::getURL('album/' . $i['cat_id']),
			'album_name' => $i['cat_name'],

			// Dates.
			'datetime_created' => L10N::dt(__('%A %d %B %Y à %H:%M:%S'), $i['vote_date']),
			'date_created' => L10N::dt(__('%A %d %B %Y'), $i['vote_date']),
			'time_created' => L10N::dt(__('%H:%M:%S'), $i['vote_date']),

			// Filtres.
			'filter_album_link' => App::getURL('votes/album/' . $i['cat_id']),
			'filter_date_link' => App::getURL('votes/date/' . substr($i['vote_date'], 0, 10)),
			'filter_ip_link' => App::getURL('votes/ip/' . $i['vote_ip']),
			'filter_item_link' => App::getURL('votes/item/' . $i['item_id']),
			'filter_note_link' => App::getURL('votes/note/' . $i['vote_rating']),
			'filter_user_link' => App::getURL('votes/user/' . $i['user_id']),

			// Fichier.
			'item_duration_text' => $i['item_duration']
				? App::formatDuration($i['item_duration'])
				: '00:00',
			'item_id' => $i['item_id'],
			'item_link' => App::getURL('item-edit/' . $i['item_id']),
			'item_name' => $i['item_name'],
			'item_thumb_src' => function($size = '', $quality = '') use ($i)
			{
				return htmlspecialchars(App::getThumbSource('item',
					$i, self::$thumbSize, self::$thumbQuality));
			},
			'item_type' => Item::isVideo($i['item_type']) ? 'video' : 'image',

			// Note.
			'rating' => $i['vote_rating'],
			'rating_array' => Rating::formatArray($i['vote_rating']),

			// Utilisateur.
			'user_avatar_src' => Avatar::getURL((int) $i['user_id'], (bool) $i['user_avatar']),
			'user_id' => $i['user_id'],
			'user_ip' => $i['vote_ip'],
			'user_link' => $i['user_id'] == 2 ? NULL : App::getURL('user/' . $i['user_id']),
			'user_name' => $i['user_id'] == 2
				? __('Invité')
				: User::getNickname($i['user_login'], $i['user_nickname'])
		];
	}

	/**
	 * Récupération des votes.
	 *
	 * @return void
	 */
	public static function getVotes(): void
	{
		Template::set('objects_count', 0);

		// Nombre de votes par page.
		$nb_per_page = Auth::$infos['user_prefs']['votes']['nb_per_page'];

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

		// Limitation à la catégorie courante.
		if (isset($_GET['category_id']) && $_GET['category_id'] > 1)
		{
			$sql = 'SELECT cat_id,
						   cat_path,
						   cat_name,
						   cat_parents,
						   CASE WHEN cat_filemtime IS NULL
								THEN "category" ELSE "album"
								 END AS cat_type
					  FROM {categories}
					 WHERE cat_id = ?';
			if (DB::execute($sql, $_GET['category_id']))
			{
				$cat_infos = DB::fetchRow();
				$sql_where .= ' AND item_path LIKE :path';
				$params['path'] = DB::likeEscape($cat_infos['cat_path']) . '/%';
			}
		}
		if (!isset($cat_infos))
		{
			$cat_infos = 
			[
				'cat_id' => 1,
				'cat_name' => __('galerie'),
				'cat_parents' => '1',
				'cat_type' => NULL
			];
		}

		// Fil d'Ariane.
		Template::breadcrumb($cat_infos, FALSE, 'votes/category');

		// Nombre de votes.
		$sql = "SELECT COUNT(*)
				  FROM {votes} AS v
			 LEFT JOIN {items} USING (item_id)
				 WHERE $sql_where";
		if (!DB::execute($sql, $params))
		{
			return;
		}
		Template::set('objects_count', $nb_votes = DB::fetchVal());

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

		// Critère de tri.
		$sql_order_by = Auth::$infos['user_prefs']['votes']['order_by_column'];
		$sql_order_by_order = Auth::$infos['user_prefs']['votes']['order_by_order'];

		// Récupération des votes.
		$sql = "SELECT v.*,
					   user_avatar,
					   user_login,
					   user_nickname,
					   item_adddt,
					   item_name,
					   item_path,
					   item_type,
					   item_duration,
					   item_orientation,
					   cat.cat_id,
					   cat_name
				  FROM {votes} AS v
			 LEFT JOIN {users} AS u USING (user_id)
			 LEFT JOIN {items} AS i USING (item_id)
			 LEFT JOIN {categories} AS cat USING (cat_id)
				 WHERE $sql_where
			  ORDER BY vote_$sql_order_by $sql_order_by_order
			     LIMIT $sql_limit_start,$nb_per_page";
		if (!DB::execute($sql, $params))
		{
			return;
		}
		$votes = DB::fetchAll();
		if (!self::_objectsNoResult(count($votes)))
		{
			return;
		}

		// Formatage des données.
		$votes_formated = [];
		foreach ($votes as &$i)
		{
			$votes_formated[] = self::getFormatedInfos($i);
		}
		Template::set('votes', $votes_formated);
	}

	/**
	 * Informations de template pour le moteur de recherche.
	 *
	 * @param array $functions
	 *
	 * @return void
	 */
	public static function tplSearch(array &$functions): void
	{
		// Colonnes.
		$columns = $functions['columns'](
		[
			'vote_ip' => TRUE
		]);

		Template::set('search', $functions['date']());
		Template::set('search', [
			'date' => self::$search->options['date'] ?? FALSE,
			'date_column' => self::$search->options['date_column'] ?? 'vote_date',
			'columns' => $columns
		]);
	}



	/**
	 * 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 'date' :
				$sql = 'vote_date >= :date_start AND vote_date <= :date_end';
				$params =
				[
					'date_start' => $_GET['filter_value'] . ' 00:00:00',
					'date_end' => $_GET['filter_value'] . ' 23:59:59'
				];
				break;

			case 'ip' :
				$sql = 'vote_ip = :filter';
				$params['filter'] = $_GET['filter_value'];
				break;

			case 'item' :
				$sql = 'v.item_id = :filter';
				$params['filter'] = $_GET['filter_value'];
				break;

			case 'note' :
				$sql = 'v.vote_rating = :filter';
				$params['filter'] = $_GET['filter_value'];
				break;

			case 'search' :
				if (!$search = self::$search->sql())
				{
					App::redirect($_GET['q_filterless']);
				}
				$sql = $search['sql'];
				$params = $search['params'];
				break;

			case 'user' :
				$sql = 'v.user_id != 2 AND v.user_id = :filter';
				$params['filter'] = $_GET['filter_value'];
				break;
		}
	}
}
?>