<?php
declare(strict_types = 1);

/**
 * Gestion des pages.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class Pages
{
	const CUSTOM_FILE_REGEXP = '`^[-a-z0-9_]{1,64}\.(html?|php)$`i';



	/**
	 * Modifie les paramètres des pages.
	 *
	 * Exemple :
	 *
	 * Pages::params([
	 *	'add'     => ['new_page' => ['status' => 1]],
	 *	'delete'  => ['worldmap'],
	 *	'rename'  => ['members' => 'users'],
	 *	'replace' => ['comments' => ['status' => 0]],
	 *	'modify'  => ['users' => ['status' => 0, 'new_param' => 1]]
	 * ]);
	 *
	 * @param array $alter
	 *
	 * @return bool
	 */
	public static function params(array $alter): bool
	{
		$pages_order = Config::$params['pages_order'];
		$pages_params = Config::$params['pages_params'];

		// Ajout de pages.
		if (isset($alter['add']))
		{
			foreach ($alter['add'] as $p => &$value)
			{
				$pages_order[] = $p;
				$pages_params[$p] = $value;
			}
		}

		$pages_order = array_flip($pages_order);

		// Suppression de pages.
		if (isset($alter['delete']))
		{
			foreach ($alter['delete'] as &$p)
			{
				unset($pages_order[$p]);
				unset($pages_params[$p]);
			}
		}

		// Renommage de pages.
		if (isset($alter['rename']))
		{
			foreach ($alter['rename'] as $old => &$new)
			{
				Utility::arrayKeyRename($old, $new, $pages_params);
				Utility::arrayKeyRename($old, $new, $pages_order);
			}
		}

		// Modifications des paramètres de pages.
		if (isset($alter['modify']))
		{
			foreach ($alter['modify'] as $p => &$value)
			{
				if (isset($pages_params[$p]))
				{
					$pages_params[$p] = array_replace($pages_params[$p], $value);
				}
			}
		}

		// Remplacement des paramètres de pages.
		if (isset($alter['replace']))
		{
			foreach ($alter['replace'] as $p => &$value)
			{
				if (isset($pages_params[$p]))
				{
					$pages_params[$p] = $value;
				}
			}
		}

		$pages_order = array_keys($pages_order);
		ksort($pages_params);

		$params = ['pages_order' => $pages_order, 'pages_params' => $pages_params];
		return Config::changeDBParams($params) != -1;
	}
}
?>