<?php
declare(strict_types = 1);

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

/**
 * Page des incidents.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AdminErrors extends Admin
{
	/**
	 * Actions sur la sélection.
	 *
	 * @return void
	 */
	public static function actions(): void
	{
		if (isset($_POST['cancel']) || !isset($_POST['selection']))
		{
			return;
		}

		$files = array_keys((array) ($_POST['selected'] ?? []));

		// Action à effectuer.
		switch ($_POST['action'])
		{
			// Suppression.
			case 'delete' :
				$r = ErrorHandler::delete($files);
				if ($r < 1)
				{
					Report::info(__('Aucun incident n\'a été supprimé.'));
				}
				else
				{
					Report::success($r > 1
						? sprintf(__('%s incidents ont été supprimés.'), $r)
						: __('1 incident a été supprimé.'));
				}
				break;

			// Exportation.
			case 'export' :
				if ($files)
				{
					ErrorHandler::export($files);
				}
				break;
		}
	}

	/**
	 * Récupération des erreurs.
	 *
	 * @return void
	 */
	public static function getXMLFiles(): void
	{
		// Fil d'Ariane.
		$breadcrumb =
		[
			[
				'current' => TRUE,
				'name' => __('Tous'),
				'url' => App::getURL('errors')
			]
		];
		Template::set('breadcrumb', $breadcrumb);

		// Récupération du contenu des fichiers XML.
		$nb_errors = 0;
		$errors = glob(GALLERY_ROOT . '/errors/*.xml');
		$errors_infos = [];
		if (function_exists('simplexml_load_file') && !empty($errors))
		{
			foreach ($errors as &$file)
			{
				if (($xml = simplexml_load_file($file)) === FALSE)
				{
					continue;
				}

				$e =
				[
					'date' => (string) $xml->date,
					'error_file' => basename($file),
					'file' => urldecode((string) $xml->file),
					'line' => (string) $xml->line,
					'md5' => (string) $xml['md5'],
					'message' => str_replace(GALLERY_ROOT, '',
						html_entity_decode(urldecode((string) $xml->message))),
					'q' => urldecode((string) $xml->q),
					'type' => (string) $xml->type,
					'app_version' => urldecode((string) ($xml->app_version
						? $xml->app_version : $xml->version)),
					'php_version' => urldecode((string) ($xml->php_version
						? $xml->php_version : '?'))
				];
				$trace = json_decode(urldecode((string) $xml->trace), TRUE);
				if ($trace)
				{
					$e['trace'] = $trace;
				}
				$errors_infos[(string) $xml->date . (string) $xml['md5']] = $e;
			}
			krsort($errors_infos);
			$errors_infos = array_values($errors_infos);
			$nb_errors = count($errors_infos);
		}
		else
		{
			$nb_errors = count($errors);
		}

		Template::set('objects_count', $nb_errors);
		Template::set('errors', $errors_infos);
	}
}
?>