<?php
// Bootstrap application
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error.log');

AdminAuth::requireLogin();

// Verify CSRF token
if (!isset($_POST['csrf_token'], $_SESSION['csrf_token'])
    || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    error_log('CSRF token validation failed in formulaire.php');
    die('Erreur de sécurité : token invalide. Veuillez recharger le formulaire.');
}

error_log('FILES array: ' . print_r($_FILES, true));

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

try {
    $ctrl     = ThesisCreateController::make();
    $thesisId = $ctrl->submit($_POST, $_FILES);

    unset($_SESSION['csrf_token']);

    header('Location: ' . $redirect);
    exit();

} catch (Exception $e) {
    error_log('ThesisCreateController error: ' . $e->getMessage());

    App::flash('error', $e->getMessage());
    $_SESSION['form_data'] = $_POST;

    $redirect = '../add.php';

    $autofocusField = ThesisCreateController::autofocusFieldForError($e->getMessage());
    if ($autofocusField !== null) {
        App::flashAutofocus($autofocusField);
    }

    header('Location: ' . $redirect);
    exit();
}
