<?php
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    exit;
}

// Lee JSON si viene con sendBeacon/fetch
$raw = file_get_contents('php://input') ?: '';
$ct  = $_SERVER['CONTENT_TYPE'] ?? '';
$body = (stripos($ct, 'application/json') !== false) ? (json_decode($raw, true) ?: []) : [];

// --- Logout por POST { cerrar_sesion: true } ---
if (!empty($body['cerrar_sesion'])) {
    // CSRF (ajusta a tu token)
    $token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    if (empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $token)) {
        http_response_code(403);
        exit;
    }

    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', [
            'expires'  => time() - 42000,
            'path'     => $p['path'],
            'domain'   => $p['domain'],
            'secure'   => $p['secure'],
            'httponly' => $p['httponly'],
            'samesite' => $p['samesite'] ?? 'Lax',
        ]);
    }
    session_destroy();
    http_response_code(204);
    exit;
}

// --- Keep‑alive por POST ---
if (empty($_SESSION['id_usuario'])) {
    http_response_code(401);
    exit;
}

$_SESSION['last_activity'] = time();
session_write_close();
http_response_code(204);
exit;
