<?php
require_once 'config.php';

echo "<h2>Active Sessions Debug</h2>";

// Check if active_sessions table exists
$result = mysqli_query($link, "SHOW TABLES LIKE 'active_sessions'");
if (mysqli_num_rows($result) > 0) {
    echo "<p>✅ Active sessions table exists</p>";
    
    // Get all active sessions
    $result = mysqli_query($link, "SELECT * FROM active_sessions ORDER BY last_activity DESC");
    if ($result && mysqli_num_rows($result) > 0) {
        echo "<h3>Current Active Sessions:</h3>";
        echo "<table border='1' style='border-collapse: collapse; margin: 10px 0;'>";
        echo "<tr><th>ID</th><th>Username</th><th>Session ID</th><th>Login Time</th><th>Last Activity</th><th>IP</th></tr>";
        
        while ($row = mysqli_fetch_assoc($result)) {
            $last_activity = new DateTime($row['last_activity']);
            $now = new DateTime();
            $diff = $now->diff($last_activity);
            $minutes_ago = $diff->i + ($diff->h * 60);
            
            $status = $minutes_ago <= 30 ? "🟢 Active" : "🔴 Expired";
            
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['id']) . "</td>";
            echo "<td>" . htmlspecialchars($row['username']) . "</td>";
            echo "<td>" . htmlspecialchars(substr($row['session_id'], 0, 10)) . "...</td>";
            echo "<td>" . htmlspecialchars($row['login_time']) . "</td>";
            echo "<td>" . htmlspecialchars($row['last_activity']) . " ({$minutes_ago}m ago) {$status}</td>";
            echo "<td>" . htmlspecialchars($row['ip_address']) . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p>✅ No active sessions (this is correct if everyone is logged out)</p>";
    }
    
    // Show count that admin dashboard would use
    $count_result = mysqli_query($link, "
        SELECT COUNT(DISTINCT s.username) as active_count
        FROM active_sessions s 
        INNER JOIN users u ON s.username = u.username 
        WHERE s.last_activity > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
    ");
    
    if ($count_result && $row = mysqli_fetch_assoc($count_result)) {
        echo "<h3>Admin Dashboard Count: " . $row['active_count'] . "</h3>";
    }
    
} else {
    echo "<p>❌ Active sessions table does not exist</p>";
}

mysqli_close($link);
?>