<?php
session_start();

// Initialize response array for AJAX requests
$response = [
    'success' => false,
    'message' => '',
    'redirect' => ''
];

try {
    // Clear all session variables
    $_SESSION = array();

    // Destroy the session cookie
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 3600, '/');
    }

    // Destroy the session
    session_destroy();

    // Clear any other cookies you might have set
    setcookie('remember_me', '', time() - 3600, '/');
    setcookie('user_theme', '', time() - 3600, '/');
    // Add any other cookies you need to clear

    // Set success response
    $response['success'] = true;
    $response['message'] = 'Logout successful';
    $response['redirect'] = '../login.php';

    // Log the logout action
    if (isset($_SESSION['user_id'])) {
        // You can add logging here
        $user_id = $_SESSION['user_id'];
        $ip = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        // Log to database or file
    }

} catch (Exception $e) {
    $response['message'] = 'Error during logout';
}

// Check if it's an AJAX request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// If not AJAX, redirect to login page
header('Location: login.php');
exit;
