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

AdminAuth::requireLogin();

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

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;
}

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

if (!in_array($action, ['publish', 'unpublish'], true)) {
    App::flash('error', 'Action invalide.');
    header('Location: ../index.php');
    exit;
}

$published = ($action === 'publish');

try {
    $db = new Database();

    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->bulkSetPublished($ids, $published);
        $count = count($ids);
        App::flash('success', $published
            ? "$count TFE(s) publié(s) avec succès."
            : "$count TFE(s) retiré(s) de la publication.");

    } 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->setPublished($thesisId, $published);
        App::flash('success', $published ? 'TFE publié avec succès.' : 'TFE retiré de la publication.');
    }

} catch (Exception $e) {
    error_log('publish.php error: ' . $e->getMessage());
    App::flash('error', 'Erreur lors de la modification : ' . $e->getMessage());
}

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