<?php
session_start();
require_once 'config.php';

// Remove from active sessions before destroying session
if (isset($_SESSION['username'])) {
    $session_id = session_id();
    $username = $_SESSION['username'];
    
    $cleanup_sql = "DELETE FROM active_sessions WHERE session_id = ? OR username = ?";
    if ($cleanup_stmt = mysqli_prepare($link, $cleanup_sql)) {
        mysqli_stmt_bind_param($cleanup_stmt, 'ss', $session_id, $username);
        mysqli_stmt_execute($cleanup_stmt);
        mysqli_stmt_close($cleanup_stmt);
    }
}

$_SESSION = array();
session_destroy();
header('location: login.php');
exit;
?>
