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

error_log('[edit.php] ENTRY | method=' . $_SERVER['REQUEST_METHOD'] . ' | content_type=' . ($_SERVER['CONTENT_TYPE'] ?? 'none') . ' | content_length=' . ($_SERVER['CONTENT_LENGTH'] ?? '0') . ' | post_keys=' . implode(',', array_keys($_POST)) . ' | files_count=' . count($_FILES) . ' | files_keys=' . implode(',', array_keys($_FILES)) . ' | queue_tfe=' . (isset($_FILES['queue_file']['name']['tfe']) ? count(array_filter($_FILES['queue_file']['name']['tfe'])) : 0));

// PHP-level auth guard (defence-in-depth behind nginx Basic Auth)
AdminAuth::requireLogin();

// Only handle POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../index.php');
    exit();
}

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

$thesisId = isset($_POST['thesis_id']) ? intval($_POST['thesis_id']) : 0;
if ($thesisId <= 0) {
    die("ID de TFE invalide.");
}

require_once APP_ROOT . '/src/Controllers/ThesisEditController.php';
require_once APP_ROOT . '/src/AdminLogger.php';
require_once APP_ROOT . '/src/ErrorHandler.php';

try {
    $ctrl = ThesisEditController::create();
    $ctrl->save($thesisId, $_POST, $_FILES);

    // Regenerate CSRF token after successful save
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

    AdminLogger::make()->logEdit($thesisId, $_POST['titre'] ?? $_POST['title'] ?? '');

    App::flash('success', "TFE mis à jour avec succès!");
    header('Location: ../edit.php?id=' . $thesisId);
    exit();

} catch (Exception $e) {
    ErrorHandler::log('thesis_edit', $e, ['thesis_id' => $thesisId]);
    App::flash('error', ErrorHandler::userMessage($e));

    // WCAG 3.3.1 — map error message to field name for autofocus on re-render.
    $autofocusField = ThesisEditController::autofocusFieldForError($e->getMessage());
    if ($autofocusField !== null) {
        App::flashAutofocus($autofocusField);
    }

    header('Location: ../edit.php?id=' . $thesisId);
    exit();
}
