<?php
declare(strict_types = 1);

/**
 * Gestion des votes.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AjaxVote extends Ajax
{
	/**
	 * Ajoute un vote sur un fichier.
	 *
	 * @return void
	 */
	public static function add(): void
	{
		if (!Utility::checkPost('item_id', '`^\d{1,12}$`')
		 || !Utility::checkPost('rating', '`^[1-5]$`')
		 || !self::_permission())
		{
			self::_forbidden();
		}

		self::_response(Rating::add(
			(int) $_POST['item_id'],
			Config::$params['users'] ? Auth::$id : 2,
			(int) $_POST['rating']
		));
	}

	/**
	 * Supprime un vote sur un fichier.
	 *
	 * @return void
	 */
	public static function remove(): void
	{
		if (!Utility::checkPost('item_id', '`^\d{1,12}$`') || !self::_permission())
		{
			self::_forbidden();
		}

		$post = ['item_id' => $_POST['item_id']];

		// Vérification par liste noire des adresses IP.
		if (App::blacklists('vote_delete', '', '', '', $post) !== TRUE)
		{
			self::_forbidden();
		}

		if (Auth::$id == 2)
		{
			$sql = 'SELECT vote_id FROM {votes} WHERE vote_cookie = ? AND item_id = ?';
			$params = [Auth::$prefs->read('rating'), $_POST['item_id']];
		}
		else
		{
			$sql = 'SELECT vote_id FROM {votes} WHERE user_id = ? AND item_id = ?';
			$params = [Auth::$id, $_POST['item_id']];
		}
		if (!DB::execute($sql, $params))
		{
			self::_error();
		}
		if (!$vote_id = DB::fetchVal())
		{
			self::_forbidden();
		}

		// Log d'activité.
		App::logActivity('vote_delete', '', $post);

		self::_response(Rating::delete($vote_id));
	}



	/**
	 * Vérifie que l'utilisateur a la permission de voter.
	 *
	 * @return bool
	 */
	private static function _permission(): bool
	{
		// Fonctionnalité activée ?
		if (!Config::$params['votes'])
		{
			return FALSE;
		}

		// Permission de groupe ?
		if (Config::$params['users'] && !Auth::$groupPerms['votes'])
		{
			return FALSE;
		}

		// Fichier activé et permission d'accès ?
		$sql = 'SELECT item_votable,
					   cat.cat_id,
					   cat_parents
				  FROM {items}
			 LEFT JOIN {categories} AS cat USING (cat_id)
				 WHERE item_id = :item_id
				   AND item_status = "1"
				   AND ' . SQL::catPerms() . '
				   AND ' . SQL::catPassword();
		DB::params(['item_id' => (int) $_POST['item_id']]);
		if (!DB::execute($sql) || !$infos = DB::fetchRow())
		{
			return FALSE;
		}

		// Fichier votable ?
		$infos['cat_parents'] .= $infos['cat_id'] . Parents::SEPARATOR;
		$infos = [$infos];
		Parents::settings($infos);
		if (!$infos[0]['parent_votable'] || !$infos[0]['item_votable'])
		{
			return FALSE;
		}

		return TRUE;
	}

	/**
	 * Réponse JSON.
	 *
	 * @param int $r
	 *
	 * @return void
	 */
	private static function _response(int $r): void
	{
		if ($r == 0)
		{
			self::_forbidden();
		}
		if ($r == -1)
		{
			self::_error();
		}

		$sql = 'SELECT item_rating, item_votes FROM {items} WHERE item_id = ?';
		if (!DB::execute($sql, $_POST['item_id']))
		{
			self::_error();
		}
		$i = DB::fetchRow();

		self::_printResponse(
		[
			'delete' => $_POST['section'] == 'vote-remove',
			'rating' => L10N::formatRating($i['item_rating']),
			'rating_array' => Rating::formatArray($i['item_rating']),
			'user_rating' => $_POST['rating'] ?? NULL,
			'user_rating_array' => Rating::formatArray($_POST['rating'] ?? 0),
			'votes' => $i['item_votes'],
			'votes_short' => L10N::formatShortNumber((int) $i['item_votes']),
			'status' => 'success'
		]);
	}
}
?>