<?php
require 'db.php';

$page  = isset($_GET['page']) ? (int)$_GET['page'] : 0;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 15;
$offset = $page * $limit;

$stmt = $pdo->prepare("
    SELECT 
        ls.id,
        ls.user_id,
        u.firstname,
        ls.ip_address,
        ls.user_agent,
        ls.login_time,
        ls.logout_time,
        CASE 
            WHEN ls.is_active = 1 
                 AND ls.last_activity > NOW() - INTERVAL 15 MINUTE 
            THEN 1
            ELSE 0
        END AS is_online
    FROM login_sessions ls
    JOIN users u ON u.id = ls.user_id
    ORDER BY ls.login_time DESC
    LIMIT :limit OFFSET :offset
");

$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

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

    echo "<tr>";
   echo "<tr data-session-id='{$row['id']}'>";
echo "<td>{$row['firstname']}</td>";
echo "<td>{$row['ip_address']}</td>";
echo "<td>{$device}</td>";

echo "<td class='status-cell'>";
if ($row['is_online']) {
    echo "<span class='text-success fw-bold'>ðŸŸ¢ Online</span>";
} else {
    echo "<span class='text-danger'>ðŸ”´ Offline</span>";
}
echo "</td>";

echo "<td class='text-end action-cell'>";
if ($row['is_online']) {
    echo "<button class='btn btn-sm btn-danger'
            onclick='forceLogoutUser({$row['user_id']})'>
            Logout
          </button>";
} else {
    echo "-";
}
echo "</td>";
echo "</tr>";
}
