<?php
require 'db.php';

$stmt = $pdo->query("
SELECT * FROM (
    SELECT 
        ls.id,
        u.id AS user_id,
        u.email,
        u.firstname,
        ls.ip_address,
        ls.user_agent,
        ls.login_time,
        ls.logout_time,
        ls.last_activity,
        CASE 
            WHEN ls.is_active = 1 
                 AND ls.last_activity > NOW() - INTERVAL 15 MINUTE 
            THEN 1
            ELSE 0
        END AS is_online,

        ROW_NUMBER() OVER (
            PARTITION BY u.id 
            ORDER BY ls.last_activity DESC
        ) as rn

    FROM login_sessions ls
    JOIN users u ON u.id = ls.user_id
) ranked_sessions
WHERE rn = 1
ORDER BY is_online DESC, last_activity DESC;


");

while ($row = $stmt->fetch()) {

    // Detect device type from user agent
    $device = (strpos($row['user_agent'], 'Mobile') !== false) ? "ðŸ“± Mobile" : "ðŸ’» Desktop";

    echo "<tr>";
    echo "<td>{$row['firstname']}</td>";
    echo "<td>{$row['ip_address']}</td>";
    echo "<td>{$device}</td>";
    echo "<td>{$row['login_time']}</td>";
    echo "<td>" . ($row['logout_time'] ?? '-') . "</td>";

 if ($row['is_online']) {
    echo "<td style='color:green;font-weight:bold;'>🟢 Online</td>";
    echo "<td class='text-end'>
            <button class='btn btn-sm btn-danger' onclick='forceLogoutUser({$row['user_id']})'>
            Logout
            </button>
          </td>";
} else {
    echo "<td style='color:red;'>🔴 Offline</td>";
    echo "<td class='text-end'>-</td>";
}


    echo "</tr>";
}
