<?php
session_start();
include('includes/config.php'); // make sure DB connection is included
date_default_timezone_set('Asia/Kolkata');

// If a log entry exists for this session, update logout time
if (isset($_SESSION['primaryID'])) {
    try {
        $logoutTime = date('Y-m-d H:i:s');
        $sqlLogout = "UPDATE tblstudentlogs SET logoutTime = :logouttime WHERE StudentId = :primaryID AND logoutTime IS NULL";
        $queryLogout = $dbh->prepare($sqlLogout);
        $queryLogout->bindParam(':primaryID', $_SESSION['primaryID'], PDO::PARAM_INT);
        $queryLogout->bindParam(':logouttime', $logoutTime);

        $queryLogout->execute();
    } catch (Exception $e) {
        // Optional: log error somewhere
        error_log("Logout log update failed: " . $e->getMessage());
    }
}

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

// If cookies are used, clear them too
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        '',
        time() - 60 * 60,
        $params["path"],
        $params["domain"],
        $params["secure"],
        $params["httponly"]
    );
}

// Destroy session completely
session_destroy();

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