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

$now = time();

// حساب المتصلين من heartbeats
$pdo = $jsonDB->getPDO();
$cutoff = $now - 15;
$stmt = $pdo->prepare('SELECT COUNT(*) as cnt FROM heartbeats WHERE time > :cutoff');
$stmt->execute([':cutoff' => $cutoff]);
$row = $stmt->fetch();
$onlineCount = (int) $row['cnt'];

// حساب المستخدمين المتصلين (للنقطة الخضراء)
$users = $jsonDB->readAll('users');
$totalVisits = count($users);
$onlineUsers = [];
foreach ($users as $user) {
    if (isset($user['last_activity']) && is_numeric($user['last_activity']) && ($now - intval($user['last_activity'])) < 8) {
        $onlineUsers[] = $user['id'];
    }
}

echo json_encode([
    'online_count' => $onlineCount,
    'total_visits' => $totalVisits,
    'online_users' => $onlineUsers
]);
