<?php
// /api/ping.php
// Tracks "visitors online" based on last-seen timestamps.
// Returns JSON: {ok:true, online:int}
header('Content-Type: application/json; charset=utf-8');

$storeFile = __DIR__ . '/../data/visitors_online.json';
$windowSeconds = 120; // online window
$maxKeepSeconds = 1800; // keep entries up to 30 mins

function read_json($file, $default=[]) {
  if (!file_exists($file)) return $default;
  $raw = @file_get_contents($file);
  $j = json_decode($raw, true);
  return is_array($j) ? $j : $default;
}

function write_json($file, $data) {
  $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)); // privacy-friendly
$now = time();

$data = read_json($storeFile, []);
$data[$key] = $now;

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

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

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