<?php
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
error_log('[delete.php] ENTRY | method=' . $_SERVER['REQUEST_METHOD'] . ' | is_bulk=' . (!empty($_POST['bulk']) ? '1' : '0') . ' | post_keys=' . implode(',', array_keys($_POST)));

AdminAuth::requireLogin();

require_once __DIR__ . '/../../../src/Database.php';
require_once __DIR__ . '/../../../src/AdminLogger.php';
require_once __DIR__ . '/../../../src/ErrorHandler.php';

// CSRF validation
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: ../index.php');
    exit;
}

$isBulk = !empty($_POST['bulk']);

try {
    $db = new Database();

    $logger = AdminLogger::make();

    if ($isBulk) {
        $ids = array_filter(array_map('intval', $_POST['selected_theses'] ?? []), fn($id) => $id > 0);

        if (empty($ids)) {
            App::flash('error', 'Aucun TFE sélectionné.');
            header('Location: ../index.php');
            exit;
        }

        $db->bulkDeleteTheses($ids);
        $logger->logDelete(array_values($ids));
        $count = count($ids);
        App::flash('success', "$count TFE(s) supprimé(s) avec succès.");

    } else {
        $thesisId = filter_var($_POST['thesis_id'] ?? '', FILTER_VALIDATE_INT);

        if (!$thesisId || $thesisId <= 0) {
            App::flash('error', 'ID invalide.');
            header('Location: ../index.php');
            exit;
        }

        $db->deleteThesis($thesisId);
        $logger->logDelete([$thesisId]);
        App::flash('success', 'TFE supprimé avec succès.');
    }

} catch (Exception $e) {
    ErrorHandler::log('thesis_delete', $e);
    App::flash('error', 'Erreur lors de la suppression : ' . ErrorHandler::userMessage($e));
}

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