<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$storeFile = __DIR__ . '/../data/visitors_online.json';
$windowSeconds = 120;
$maxKeepSeconds = 1800;

function ugfx_ping_read_json(string $file, array $default = []): array {
    if (!is_file($file)) return $default;
    $raw = @file_get_contents($file);
    $data = json_decode((string)$raw, true);
    return is_array($data) ? $data : $default;
}

function ugfx_ping_write_json(string $file, array $data): void {
    $dir = dirname($file);
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    @file_put_contents($file, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), LOCK_EX);
}

$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$key = hash('sha256', $ip . '|' . substr($ua, 0, 120));
$now = time();
$data = ugfx_ping_read_json($storeFile, []);
$data[$key] = $now;

foreach ($data as $k => $ts) {
    if (!is_int($ts) || ($now - $ts) > $maxKeepSeconds) {
        unset($data[$k]);
    }
}
ugfx_ping_write_json($storeFile, $data);

$online = 0;
foreach ($data as $ts) {
    if (($now - (int)$ts) <= $windowSeconds) {
        $online++;
    }
}

echo json_encode(['ok' => true, 'online' => $online], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
