<?php
/**
 * Student-access link actions (create, toggle, set_password, archive).
 */
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
require_once __DIR__ . '/../../../src/ShareLink.php';
require_once __DIR__ . '/../../../src/AdminLogger.php';

App::adminGuard();

if ($_SERVER['REQUEST_METHOD'] !== 'POST'
    || !isset($_POST['csrf_token'], $_SESSION['csrf_token'])
    || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    http_response_code(403);
    exit('CSRF token invalide.');
}

$action    = $_POST['action'] ?? '';
$id        = isset($_POST['id']) ? intval($_POST['id']) : 0;
$shareLink = ShareLink::make();
$logger    = AdminLogger::make();

switch ($action) {
    case 'create':
        $name       = !empty($_POST['name']) ? trim($_POST['name']) : null;
        $password   = !empty($_POST['password']) ? trim($_POST['password']) : null;
        $expiresRaw = !empty($_POST['expires_at']) ? trim($_POST['expires_at']) : null;
        $expiresAt  = null;
        if ($expiresRaw) {
            $expiresAt = date('Y-m-d H:i:s', strtotime($expiresRaw));
            if ($expiresAt <= date('Y-m-d H:i:s')) {
                App::redirect('/admin/acces.php', error: "La date d'expiration doit être dans le futur.");
            }
        }
        $objetRaw = $_POST['objet_restriction'] ?? ['tfe'];
        $validObjet = ['tfe', 'thèse', 'frart'];
        $selected = is_array($objetRaw) ? array_intersect($objetRaw, $validObjet) : [];
        $objetRestriction = !empty($selected) ? implode(',', $selected) : 'tfe';
        $link = $shareLink->create(1, $password, $expiresAt, $objetRestriction, $name);
        $logger->logLinkCreate(
            $link['slug'] ?? '',
            $password !== null,
            $expiresAt,
            $objetRestriction
        );
        App::redirect('/admin/acces.php', success: 'Lien d\'accès créé.');
        break;

    case 'toggle':
        if ($id > 0) {
            $nowActive = $shareLink->toggleActive($id);
            $logger->logLinkToggle($id, $nowActive);
            App::redirect('/admin/acces.php', success: 'Statut du lien modifié.');
        } else {
            App::redirect('/admin/acces.php', error: 'Lien introuvable.');
        }
        break;

    case 'set_password':
        if ($id > 0) {
            $password = isset($_POST['password']) && $_POST['password'] !== '' ? trim($_POST['password']) : null;
            $shareLink->setPassword($id, $password);
            $logger->logLinkPasswordChange($id, $password === null);
            App::redirect('/admin/acces.php', success: 'Mot de passe mis à jour.');
        } else {
            App::redirect('/admin/acces.php', error: 'Lien introuvable.');
        }
        break;

    case 'archive':
        if ($id > 0) {
            $shareLink->archive($id);
            $logger->logLinkArchive($id);
            App::redirect('/admin/acces.php', success: 'Lien archivé.');
        } else {
            App::redirect('/admin/acces.php', error: 'Lien introuvable.');
        }
        break;

    case 'update':
        if ($id > 0) {
            $name       = isset($_POST['name']) ? trim($_POST['name']) : null;
            $password   = isset($_POST['password']) ? trim($_POST['password']) : null;
            $expiresRaw = isset($_POST['expires_at']) ? trim($_POST['expires_at']) : null;
            $shareLink->update($id, $name, $password, $expiresRaw);
            App::redirect('/admin/acces.php', success: 'Lien mis à jour.');
        } else {
            App::redirect('/admin/acces.php', error: 'Lien introuvable.');
        }
        break;

    default:
        App::redirect('/admin/acces.php', error: 'Action inconnue.');
        break;
}
