<?php
session_start();
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/Logger.php';

try {
    $database = new Database();
    $conn = $database->getConnection();
    $logger = new Logger($conn, $_SESSION['user_id'] ?? null, $_SESSION['username'] ?? null, $_SESSION['role'] ?? null);
    if (!empty($_SESSION['user_id'])) {
        $logger->logAuth('LOGOUT', true, 'User logged out from IP: ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
    }
} catch (Throwable $e) {
    error_log('Logout logging failed: ' . $e->getMessage());
}

$_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();
session_write_close();

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Location: /IMS/login.php?logged_out=1');
exit();
?>