<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once 'main_db_connect.php';

// Set cache control headers to prevent back button issues
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// Function to log actions to audit_logs table
function logAction($conn, $userId, $username, $action, $documentId = null, $documentName = null) {
    $stmt = $conn->prepare("INSERT INTO audit_logs (user_id, username, action, document_id, file_name) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("issis", $userId, $username, $action, $documentId, $documentName);
    $stmt->execute();
    $stmt->close();
}

// Log logout action if user was logged in
if (isset($_SESSION['user_id']) && isset($_SESSION['username'])) {
    $userId = $_SESSION['user_id'];
    $username = $_SESSION['username'];
    
    // Log the logout action
    logAction($conn, $userId, $username, "Logged out from Gender and Development");
}

// Destroy all session data
session_destroy();

// Clear any session cookies
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-3600, '/');
}

// Redirect to login page with meta refresh as backup
header("Location: index.php");
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="refresh" content="0;url=index.php">
    <title>Logging out...</title>
</head>
<body>
    <p>Logging out... If you are not redirected automatically, <a href="index.php">click here</a>.</p>
    <script>
        // Clear any stored data
        sessionStorage.clear();
        localStorage.clear();
        
        // Force redirect
        window.location.replace('index.php');
        
        // Prevent back button
        window.history.forward();
    </script>
</body>
</html>
<?php
exit();
?>