<?php
/**
 * Save handler for static page content (Markdown).
 */
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
error_log('[page.php] ENTRY | method=' . $_SERVER['REQUEST_METHOD'] . ' | slug=' . ($_POST['slug'] ?? 'none') . ' | post_keys=' . implode(',', array_keys($_POST)));
AdminAuth::requireLogin();

if (!isset($_POST['csrf_token'], $_SESSION['csrf_token'])
    || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    App::flash('error', 'Erreur de sécurité : token invalide.');
    header('Location: /admin/contenus.php');
    exit;
}

$allowedSlugs = ['about', 'licenses'];
$slug         = $_POST['slug'] ?? '';
$content      = $_POST['content'] ?? '';

if (!in_array($slug, $allowedSlugs, true)) {
    App::flash('error', 'Slug de page invalide.');
    header('Location: /admin/contenus.php');
    exit;
}

require_once APP_ROOT . '/src/Database.php';
require_once APP_ROOT . '/src/AdminLogger.php';
require_once APP_ROOT . '/src/ErrorHandler.php';
$db = new Database();

try {
    $db->savePage($slug, $content);
    AdminLogger::make()->logPageEdit($slug);
    App::flash('success', 'Page « ' . htmlspecialchars($slug) . ' » mise à jour.');
} catch (Exception $e) {
    ErrorHandler::log('page', $e);
    App::flash('error', 'Erreur lors de la sauvegarde : ' . ErrorHandler::userMessage($e));
}

$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
header('Location: /admin/contenus.php');
exit;
