<?php
// Admin-specific logout endpoint
// Ensures only admins can invoke, logs event, and clears session securely

// JSON and security headers
header('Content-Type: application/json');
// Dynamic origin for credentials
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Hardened cache and security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

// Guard and session
define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/db.php';
// Note: do not enforce requireAdmin here; we want logout to succeed even if session is broken.

// Log event if user session exists
$userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
$isAdmin = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
if ($userId) {
    try {
        $stmt = $pdo->prepare('INSERT INTO security_logs (event_type, user_id, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, NOW())');
        $stmt->execute([
            $isAdmin ? 'admin_logout' : 'user_logout',
            $userId,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        ]);
    } catch (Throwable $e) {
        error_log('Failed to log admin logout event: ' . $e->getMessage());
    }
}

// Clear all session variables
$_SESSION = [];

// Delete the session cookie (must match attributes from session_init.php)
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http');
    $isHttps = ($scheme === 'https') || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $opts = [
        'expires' => time() - 42000,
        'path' => '/',
        'secure' => $isHttps ? true : false,
        'httponly' => true,
        'samesite' => $isHttps ? 'None' : 'Lax'
    ];
    if (!empty($params['domain'])) {
        $opts['domain'] = $params['domain'];
    }
    setcookie(session_name(), '', $opts);
}

// Destroy the session
if (session_status() === PHP_SESSION_ACTIVE) {
    session_destroy();
}

// Clear any existing output buffers
while (ob_get_level()) {
    ob_end_clean();
}

// No-cache response headers (again, to be safe)
header_remove('Pragma');
header_remove('Expires');
header_remove('Last-Modified');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0');
header('Pragma: no-cache');

// Return success response
echo json_encode([
    'success' => true,
    'message' => 'Admin logout successful',
    'redirect' => '/admin'
]);
