<?php
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
error_log('[maintenance.php] ENTRY | method=' . $_SERVER['REQUEST_METHOD'] . ' | action=' . ($_POST['action'] ?? 'none') . ' | post_keys=' . implode(',', array_keys($_POST)));
AdminAuth::requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST'
    || !isset($_POST['csrf_token'], $_SESSION['csrf_token'])
    || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    http_response_code(403);
    die("Accès refusé.");
}

require_once APP_ROOT . '/src/AdminLogger.php';

$action = $_POST['action'] ?? '';

if ($action === 'enable_maintenance') {
    file_put_contents(MAINTENANCE_FLAG, date('c'));
    AdminLogger::make()->logMaintenance(true);
    App::flash('success', "Mode maintenance activé.");
} elseif ($action === 'disable_maintenance') {
    if (file_exists(MAINTENANCE_FLAG)) {
        unlink(MAINTENANCE_FLAG);
    }
    AdminLogger::make()->logMaintenance(false);
    App::flash('success', "Mode maintenance désactivé.");
} else {
    App::flash('error', "Action inconnue.");
}

$redirect = isset($_POST['redirect']) ? $_POST['redirect'] : '/admin/';
// Allow only internal admin redirects for safety
if (!preg_match('#^/admin/#', $redirect)) {
    $redirect = '/admin/';
}
header('Location: ' . $redirect);
exit();
