<?php
// public/logout.php

session_start();
require_once '../config/db.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Store user info before destroying session
$userId = $_SESSION['user_id'] ?? null;
$username = $_SESSION['username'] ?? 'Unknown User';

// Debug log
error_log("Logout attempt - UserID: $userId, Username: $username");

// Log the logout action
if ($userId) {
    try {
        // Simplified query without transaction
        $stmt = $pdo->prepare("INSERT INTO log_history (user_id, action) VALUES (?, ?)");
        $result = $stmt->execute([$userId, "Logged out"]);

        if ($result) {
            error_log("Successfully logged logout action for user: $username");
        } else {
            error_log("Failed to log logout action. PDO Error Info: " . json_encode($stmt->errorInfo()));
        }

    } catch (PDOException $e) {
        error_log("Database Error: " . $e->getMessage());
    }
}

// Clear session and redirect
session_unset();
session_destroy();

// Debug - Check if session was destroyed
error_log("Session destroyed. Session ID: " . session_id());

header("Location: login.php");
exit();
