<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache');

$dbPath = __DIR__ . '/data/database.sqlite';

try {
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec('PRAGMA journal_mode = WAL');
    $db->exec('PRAGMA busy_timeout = 3000');
    
    $now = time();
    $cutoff = $now - 12;
    
    // عدد كل الزوار الأونلاين
    $stmt = $db->prepare('SELECT COUNT(*) as cnt FROM heartbeats WHERE time >= :cutoff');
    $stmt->execute([':cutoff' => $cutoff]);
    $onlineCount = (int) $stmt->fetch(PDO::FETCH_ASSOC)['cnt'];
    
    // المستخدمين المسجلين الأونلاين
    $stmt = $db->prepare('SELECT DISTINCT user_id FROM heartbeats WHERE time >= :cutoff AND user_id > 0');
    $stmt->execute([':cutoff' => $cutoff]);
    $onlineUsers = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $onlineUsers[] = (int) $row['user_id'];
    }
    
    echo json_encode([
        'online_count' => $onlineCount,
        'online_users' => $onlineUsers
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'online_count' => 0,
        'online_users' => []
    ]);
}
