<?php
session_start();
include('includes/config.php'); // make sure DB connection is included
date_default_timezone_set('Asia/Kolkata');
$updatetime = date('Y-m-d H:i:s');
// If a log entry exists for this session, update logout time
if (isset($_SESSION['staffprimaryID'])) {
    try {
        $sqlLogout = "UPDATE tblstafflogs SET logoutTime = :updatetime' WHERE StaffId = :primaryID AND logoutTime IS NULL";
        $queryLogout = $dbh->prepare($sqlLogout);
        $queryLogout->bindParam(':primaryID', $_SESSION['staffprimaryID'], PDO::PARAM_INT);
        $queryLogout->bindParam(':updatetime', $updatetime);

        $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;
?>