<?php
require_once __DIR__ . "/../../bootstrap.php";
require_once __DIR__ . '/../../src/AdminAuth.php';
AdminAuth::requireLogin();

if (empty($_SESSION["csrf_token"])) {
    $_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}

$pageTitle = "Ajouter un TFE";

require_once __DIR__ . '/../../src/Controllers/ThesisCreateController.php';

try {
    $ctrl = ThesisCreateController::make();
    extract($ctrl->loadFormData());
} catch (Exception $e) {
    error_log('Failed to load form data: ' . $e->getMessage());
    die('Erreur lors du chargement du formulaire.');
}

$formData      = $_SESSION['form_data'] ?? [];
unset($_SESSION['form_data']);
$autofocusField = App::consumeAutofocus();

// Site settings for licence / access type toggles
$siteSettings = Database::getInstance()->getAllSettings();
// Form help blocks
$helpBlocks = Database::getInstance()->getAllFormHelpBlocks();
$helpFn = fn(string $key) => empty($helpBlocks[$key]['enabled']) ? '' : ($helpBlocks[$key]['content'] ?? '');

function withAutofocus(string $fieldName, array $attrs = []): array {
    global $autofocusField;
    if ($autofocusField === $fieldName) {
        $attrs['autofocus'] = true;
    }
    return $attrs;
}

function old($key, $default = "") {
    global $formData;
    if (!isset($formData[$key])) return $default;
    if (is_array($formData[$key])) return $formData[$key]; // Return raw array for callers that handle it
    if ($formData[$key] === null) return $default;
    return htmlspecialchars((string)$formData[$key]);
}

function wasSelected($key, $value) {
    global $formData;
    if (!isset($formData[$key])) return false;
    if (is_array($formData[$key])) return in_array($value, $formData[$key]);
    return $formData[$key] == $value;
}

$isAdmin = true;
$bodyClass = 'admin-body';
$extraCss  = ['/assets/css/form.css', '/assets/css/filepond.min.css', '/assets/css/filepond-plugin-image-preview.min.css'];
$extraJs   = ['/assets/js/filepond.min.js', '/assets/js/filepond-plugin-file-validate-type.min.js', '/assets/js/filepond-plugin-file-validate-size.min.js', '/assets/js/filepond-plugin-image-preview.min.js', '/assets/js/filepond-plugin-image-exif-orientation.min.js', '/assets/js/file-upload-filepond.js', '/assets/js/beforeunload-guard.js'];
require_once APP_ROOT . '/templates/head.php';
include APP_ROOT . '/templates/header.php';
include APP_ROOT . '/templates/admin/add.php';
require_once APP_ROOT . '/templates/admin/footer.php';
