<?php
// Include your database connection code here
require_once '../config.php';

// Function to log the logout entry to the database
function logLogoutEntry($username, $ipAddress, $userAgent) {
    global $db_host, $db_name, $db_user, $db_password;

    $connection = mysqli_connect($db_host, $db_user, $db_password, $db_name);

    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $timezone = new DateTimeZone('Europe/Paris'); // Set the desired timezone, such as Europe/Paris for GMT+1 (Central European Time)
    $timestamp = (new DateTime('now', $timezone))->format('Y-m-d H:i:s');

    $query = "INSERT INTO userlogs (username, logout_time, ip_address, user_agent) VALUES ('$username', '$timestamp', '$ipAddress', '$userAgent')";

    if (!mysqli_query($connection, $query)) {
        echo "Error: " . $query . "<br>" . mysqli_error($connection);
    }

    mysqli_close($connection);
}

// Check if the user is logged in
session_start();
if (isset($_SESSION['username'])) {
    // Store the username before destroying the session
    $username = $_SESSION['username'];

    // Log the logout entry
    logLogoutEntry($username, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);

    // Destroy the session
    session_destroy();
}

// Redirect to the login page
header('Location: login.php');
exit();
?>
