<?php
session_start();
include "config.php"; // Ensure this includes the $con variable for DB connection

// Get user data before destroying session
if (isset($_SESSION['user'])) {
    $user = $_SESSION['user'];
    $uid = $user['id'];
    $pid = $user['pid'];
    $ipAddress = $_SERVER['REMOTE_ADDR'];

    // Add logout log
    addLogs($uid, $pid, $ipAddress);
}

// Clear session
$_SESSION = array();
session_destroy();

// Redirect to login page
echo '<script>window.location.href = "index.php";</script>';
exit();

// Function to log logout event
function addLogs($uid, $pid, $ipAddress) {
    global $con;

    $timestamp = date('Y-m-d H:i:s');
    $sql = "INSERT INTO logs (uid, pid, ip_address, in_out, time_stamp) 
            VALUES ('$uid', '$pid', '$ipAddress', 'out', '$timestamp')";

    mysqli_query($con, $sql) or die("Log insert failed: " . mysqli_error($con));
}
?>