<?php
declare(strict_types = 1);

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

/**
 * Gestion des albums.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AdminPages extends Admin
{
	/**
	 * Création d'une nouvelle page.
	 *
	 * @return void
	 */
	public static function createPage(): void
	{
		if (!$_POST)
		{
			return;
		}

		// Nom de la page.
		for ($i = 1; $i < 99; $i++)
		{
			if (!isset(Config::$params['pages_params']['custom_' . $i]))
			{
				$page = 'custom_' . $i;
				break;
			}
		}
		if (!isset($page))
		{
			return;
		}

		if (!$fields = self::_custom())
		{
			return;
		}

		// Modification des paramètres des pages.
		$order = Config::$params['pages_order'];
		$order[] = $page;
		$params = Config::$params['pages_params'];
		$params[$page] =
		[
			'status' => 1,
			'new' => 1,
			'title' => $fields['title'],
			'url' => $fields['url'],
			'content' => $fields['content'],
			'filename' => $fields['filename']
		];

		// Mise à jour.
		$params =
		[
			'pages_order' => $order,
			'pages_params' => $params
		];
		switch (Config::changeDBParams($params))
		{
			case -1 :
				Report::error();
				break;

			case 0 :
				Report::noChange();
				break;

			default :
				App::redirect('page/' . str_replace('_', '/', $page));
				break;
		}
	}

	/**
	 * Récupération des paramètres de la page $page.
	 *
	 * @param string $page
	 *
	 * @return void
	 */
	public static function getPageParams(string $page): void
	{
		$params = Config::$params['pages_params'][$page] ?? NULL;

		switch ($page)
		{
			case 'comments' :
				$params =
				[
					'title' => L10N::getTextPage($page),
					'nb_per_page' => (int) $params['nb_per_page']
				];
				break;

			case 'contact' :
				$params =
				[
					'title' => L10N::getTextPage($page),
					'email' => $params['email'],
					'message' => $params['message']
				];
				break;

			case 'members' :
				$order_by = explode(' ', (string) $params['order_by']);
				$params =
				[
					'title' => L10N::getTextPage($page),
					'order_by_column' =>
					[
						'selected' => $order_by[0],
						'values' =>
						[
							'user_login' => __('Nom d\'utilisateur'),
							'user_crtdt' => __('Date d\'inscription'),
							'user_lastvstdt' => __('Date de dernière visite')
						]
					],
					'order_by_order' =>
					[
						'selected' => $order_by[1],
						'values' =>
						[
							'ASC' => __('croissant'),
							'DESC' => __('décroissant')
						]
					],
					'nb_per_page' => (int) $params['nb_per_page'],
					'show_crtdt' => (bool) $params['show_crtdt'],
					'show_lastvstdt' => (bool) $params['show_lastvstdt'],
					'show_title' => (bool) $params['show_title']
				];
				break;

			case 'worldmap' :
				$params =
				[
					'title' => L10N::getTextPage($page),
					'layer' => Config::$params['geolocation_default_layer'],
					'latitude' => $params['center_lat'],
					'longitude' => $params['center_long'],
					'zoom' => $params['zoom']
				];
				break;

			// Page personnalisée.
			default :
				if ($page != 'new_page' && !$params)
				{
					App::redirect('pages');
					return;
				}
				$files = [];
				foreach (scandir(GALLERY_ROOT . '/files/pages') as $f)
				{
					if (preg_match(Pages::CUSTOM_FILE_REGEXP, $f))
					{
						$files[] =
						[
							'filename' => $f,
							'selected' => (isset($_POST['page_file'])
								&& isset($_POST['page_filename'])
								&& $_POST['page_filename'] == $f)
								|| (isset($params['file'])
								&& isset($params['filename'])
								&& $params['filename'] == $f)
						];
					}
				}
				if (isset($params['new']))
				{
					$pages_params = Config::$params['pages_params'];
					unset($pages_params[$page]['new']);
					Config::changeDBParams(['pages_params' => $pages_params]);
					Report::success('Page créée avec succès.');
				}
				$params =
				[
					'title' => isset($_POST['page_title'])
						&& !Utility::isEmpty($_POST['page_title'])
						? $_POST['page_title'] : ($params['title'] ?? __('Nouvelle page')),
					'content' => $_POST['page_content'] ??
						$params['content'] ?? '',
					'file' => isset($_POST['page_file'])
						? TRUE
						: ($params['filename'] ?? FALSE),
					'files' => $files
				];
				$page = 'custom';
		}
		Template::set('gallery_page', [$page => $params]);
	}

	/**
	 * Récupération des pages.
	 *
	 * @return void
	 */
	public static function getPages(): void
	{
		$pages_order = Config::$params['pages_order'];
		$pages_params = Config::$params['pages_params'];

		$pages = [];
		$pages_link = ['comments', 'contact', 'members', 'worldmap'];
		foreach ($pages_order as $id => &$page)
		{
			$custom = substr($page, 0, 7) == 'custom_';
			$status = (!empty($_POST) && isset($_POST['items'][$page]['activated']))
				|| $pages_params[$page]['status'];
			$link = (in_array($page, $pages_link) || $custom)
				? App::getURL('page/' . ($custom
					? str_replace('_', '/', $page)
					: str_replace('_', '-', $page))
				  )
				: NULL;
			$pages[] =
			[
				'disabled' => !in_array($custom ? 'custom' : $page, THEME_PAGES),
				'id' => $id,
				'link' => $link,
				'name' => $page,
				'custom' => $custom,
				'status' =>  $status,
				'title' => $custom ? $pages_params[$page]['title'] : L10N::getTextPage($page)
			];
		}

		Template::set('pages', $pages);
	}

	/**
	 * Définit les paramètres de template pour la section.
	 *
	 * @param string $tpl_filename
	 *
	 * @return void
	 */
	public static function tplSection(string $tpl_filename): void
	{
		Template::set('page',
		[
			'link' => App::getURL('pages'),
			'title' => __('Pages')
		]);
		Template::set('section', 'pages');
		Template::set('template',
		[
			'file' => $tpl_filename . '.tpl.php'
		]);
	}

	/**
	 * Mise à jour des paramètres de la page $page.
	 *
	 * @param string $page
	 *
	 * @return void
	 */
	public static function updatePageParams(string $page): void
	{
		if (!$_POST)
		{
			return;
		}

		$params = Config::$params['pages_params'];
		if (!isset($params[$page]))
		{
			return;
		}

		// Pages.
		switch ($page)
		{
			case 'comments' :
				if ((int) $_POST['nb_per_page'] > 0)
				{
					$params[$page]['nb_per_page'] = (int) $_POST['nb_per_page'];
				}
				break;

			case 'contact' :
				$params[$page]['email'] = substr($_POST['email'],
					0, User::COLUMNS_LENGTH_MAX['email']);
				$params[$page]['message'] = substr($_POST['message'], 0, 9999);
				break;

			case 'members' :
				if ((int) $_POST['nb_per_page'] > 0)
				{
					$params[$page]['nb_per_page'] = (int) $_POST['nb_per_page'];
				}
				foreach (['show_crtdt', 'show_lastvstdt', 'show_title'] as $col)
				{
					$params[$page][$col] = isset($_POST[$col]);
				}
				if (preg_match('`^[a-z_]{1,30}$`i', $_POST['order_by_column'])
				&& in_array($_POST['order_by_order'], ['ASC', 'DESC']))
				{
					$params[$page]['order_by'] = $_POST['order_by_column']
						. ' ' . $_POST['order_by_order'];
				}
				break;

			case 'worldmap' :
				if (Utility::checkPost('latitude', '`^\d+(\.\d+)?$`')
				 && Utility::checkPost('longitude', '`^\d+(\.\d+)?$`')
				 && Utility::checkPost('zoom', '`^\d{1,2}$`'))
				{
					$params[$page]['center_lat'] = $_POST['latitude'];
					$params[$page]['center_long'] = $_POST['longitude'];
					$params[$page]['zoom'] = $_POST['zoom'];
				}
				break;

			default :
				if (!$fields = self::_custom())
				{
					return;
				}
				$params[$page]['title'] = $fields['title'];
				$params[$page]['url'] = $fields['url'];
				$params[$page]['content'] = $fields['content'];
				$params[$page]['filename'] = $fields['filename'];
				break;
		}

		// Mise à jour.
		switch (Config::changeDBParams(['pages_params' => $params]))
		{
			case -1 :
				Report::error();
				break;

			case 0 :
				Report::noChange();
				break;

			default :
				Report::success();
				break;
		}
	}



	/**
	 * Modification d'une page personnalisée.
	 *
	 * @return array
	 */
	private static function _custom(): array
	{
		// Titre.
		$title = mb_substr(Utility::trimAll($_POST['page_title'] ?? ''), 0, 32);
		if (mb_strlen($title) < 1)
		{
			Report::warning(__('Le titre ne peut pas être vide.'));
			return [];
		}

		// URL.
		$url = App::getURLName($title);

		// Contenu.
		$content = mb_substr(Utility::trimAll($_POST['page_content'] ?? ''), 0, 2000);

		// Fichier.
		if (isset($_POST['page_file']) && isset($_POST['page_filename'])
		&& preg_match(Pages::CUSTOM_FILE_REGEXP, $_POST['page_filename']))
		{
			$filename = $_POST['page_filename'];
		}

		return
		[
			'title' => $title,
			'url' => $url,
			'content' => $content,
			'filename' => $filename ?? NULL
		];
	}
}
?>