<?php 
session_start();
include('includes/config.php'); // Make sure this path is correct

if (isset($_SESSION['user_id'], $_SESSION['login_time'])) {
    $user_id = $_SESSION['user_id'];
    $login_time = $_SESSION['login_time'];
    $logout_time = date('Y-m-d H:i:s');
    $duration = strtotime($logout_time) - strtotime($login_time);

    // Insert into session_durations table
    $stmt = $conn->prepare("INSERT INTO session_durations (user_id, login_time, logout_time, duration_seconds) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("issi", $user_id, $login_time, $logout_time, $duration);
    $stmt->execute();
    $stmt->close();

    // Update last_logged_out in users table
    $update = $conn->prepare("UPDATE users SET last_logged_out = ? WHERE id = ?");
    $update->bind_param("si", $logout_time, $user_id);
    $update->execute();
    $update->close();
}

// Unset all session variables
$_SESSION = [];

// Destroy the session
session_destroy();

// Redirect to login page
header("Location: index.php");
exit();
