<?php
error_reporting(0);
include('includes/dbconnection.php');

// Validate tab_id
if (!isset($_GET['tab_id'])) {
    die("Invalid Logout Attempt.");
}

$tabSessionID = $_GET['tab_id'];

// Close any active session to avoid locking
session_write_close();
session_id($tabSessionID);
session_name("student_portal_" . $tabSessionID);
session_start();

// Get student ID from session (if available)
$studentId = $_SESSION['student_id'] ?? null;

// Clear remember_token from database
if ($studentId) {
    $stmt = $con->prepare("UPDATE students SET remember_token = NULL WHERE id = ?");
    $stmt->bind_param("i", $studentId);
    $stmt->execute();
    $stmt->close();
} elseif (isset($_COOKIE['remember_token'])) {
    // If session expired but cookie still exists
    $token = $_COOKIE['remember_token'];
    $stmt = $con->prepare("UPDATE students SET remember_token = NULL WHERE remember_token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $stmt->close();
}

// Destroy session
session_unset();
session_destroy();

// Clear remember_token cookie
setcookie("remember_token", "", time() - 3600, "/", "", false, true);

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