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

// If a log entry exists for this session, update logout time
if (isset($_SESSION['adminID']) && $_SESSION['alogin'] != "adminbluebase") {
    try {
        $logoutTime = date('Y-m-d H:i:s'); // Current time in Asia/Kolkata
        $sqlLogout = "UPDATE tbladminlogs 
                      SET logoutTime = :logoutime 
                      WHERE AdminId = :adminID AND logoutTime IS NULL 
                      ORDER BY id DESC LIMIT 1";
        $queryLogout = $dbh->prepare($sqlLogout);
        $queryLogout->bindParam(':logoutime', $logoutTime, PDO::PARAM_STR);
        $queryLogout->bindParam(':adminID', $_SESSION['adminID'], PDO::PARAM_INT);
        $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;
?>
