<?php
declare(strict_types=1);
require_once __DIR__ . '/../db/config.php';

$db = db();
// Active in the last 15 minutes, has username and phone
// Use GROUP BY to avoid duplicates if same session/user has multiple entries (though session_id should be unique-ish)
$stmt = $db->prepare("
    SELECT 
        v.username, 
        v.phone_number, 
        v.country_code, 
        v.last_activity,
        f.points,
        f.loyalty_points,
        f.is_fan_of_month,
        f.chat_color,
        f.dj_day_until
    FROM visitor_logs v
    LEFT JOIN fans f ON v.username = f.name
    WHERE v.last_activity > DATE_SUB(NOW(), INTERVAL 15 MINUTE) 
    AND v.username IS NOT NULL 
    AND v.phone_number IS NOT NULL 
    AND v.username != ''
    AND v.phone_number != ''
    GROUP BY v.username, v.phone_number
    ORDER BY v.last_activity DESC
    LIMIT 20
");
$stmt->execute();
$users = $stmt->fetchAll();

// Get total active sessions (last 5 minutes) for a live counter
$stmtTotal = $db->prepare("SELECT COUNT(DISTINCT session_id) as total FROM visitor_logs WHERE last_activity > DATE_SUB(NOW(), INTERVAL 5 MINUTE)");
$stmtTotal->execute();
$totalActive = $stmtTotal->fetch()['total'] ?? 0;

echo json_encode([
    'success' => true, 
    'users' => $users,
    'total_active' => $totalActive
]);
