<?php
session_start();

require_once __DIR__ . '/library/config.php';
require_once __DIR__ . '/library/audit_log.php';

// Get user data BEFORE destroying session
$user_id = $_SESSION['user_id'] ?? null;
$school_id = $_SESSION['school_id'] ?? null;
$username = $_SESSION['username'] ?? 'Unknown';
$name = $_SESSION['name'] ?? 'Unknown';
$role = $_SESSION['role'] ?? 'Unknown';

// Audit Log - Logout (BEFORE destroying session)
if ($user_id) {
    logActivity($pdo, [
        'school_id' => $school_id,
        'user_id'   => $user_id,
        'module'    => 'Authentication',
        'action'    => 'LOGOUT',
        'record_id' => $user_id,
        'message'   => "User logged out: {$username} ({$role})",
        'old_data'  => null,
        'new_data'  => [
            'username'     => $username,
            'name'         => $name,
            'role'         => $role,
            'logout_time'  => date('Y-m-d H:i:s'),
            'ip_address'   => $_SERVER['REMOTE_ADDR'] ?? null,
            'user_agent'   => $_SERVER['HTTP_USER_AGENT'] ?? null,
            'session_duration' => isset($_SESSION['login_time']) 
                ? date('Y-m-d H:i:s') 
                : null
        ]
    ]);
}

// Session variables ko clear karo
$_SESSION = array();

// Session cookie ko delete karo
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 ko destroy karo
session_destroy();

// Redirect to login
header("Location: /schools/login.php?msg=✅ Logged out successfully!");
exit;
?>