<?php
// Strict session handling
declare(strict_types=1);

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");

// Start secure session
if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'domain' => $_SERVER['HTTP_HOST'],
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Strict'
    ]);
    session_start();
}


// Generate new CSRF token for login page
$newToken = bin2hex(random_bytes(32));
if (isset($_SESSION['csrf_tokens'])) {
    $_SESSION['csrf_tokens']['login'] = $newToken;
}

// Complete session destruction
$_SESSION = [];
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        '',
        time() - 42000,
        $params['path'],
        $params['domain'],
        $params['secure'],
        $params['httponly']
    );
}
session_destroy();

// Determine redirect URL
$redirectUrl = '/login.php';
$queryParams = [];

if (isset($_GET['timeout'])) {
    $queryParams['reason'] = 'timeout';
    http_response_code(401); // Unauthorized
} elseif (isset($_GET['expired'])) {
    $queryParams['reason'] = 'session_expired';
    http_response_code(401); // Unauthorized
} else {
    $queryParams['reason'] = 'logout';
    http_response_code(303); // See Other
}

// Add new CSRF token to redirect
$queryParams['token'] = $newToken;

// Secure redirect
$redirectUrl .= '?' . http_build_query($queryParams);
header("Location: $redirectUrl", true, 303);
exit;