<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('login.php');
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../mikrotik_lib.php';
require_once __DIR__ . '/../ppp_active_cache_lib.php';
if (session_status() === PHP_SESSION_ACTIVE) { @session_write_close(); }
header('Content-Type: application/json; charset=utf-8');
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { echo json_encode(['ok'=>false,'message'=>'db'], JSON_UNESCAPED_UNICODE); exit; }
$force = ((string)($_GET['force'] ?? '') === '1');
$data = $force ? ua_ppp_cache_rebuild($conn, 10, true) : ua_ppp_cache_snapshot(86400);
echo json_encode([
  'ok' => !empty($data['ok']),
  'online' => (int)($data['online'] ?? 0),
  'age' => (int)($data['age'] ?? 0),
  'source' => (string)($data['source'] ?? 'ppp_active_cache'),
  'ts' => (int)($data['ts'] ?? 0),
  'message' => (string)($data['message'] ?? ''),
], JSON_UNESCAPED_UNICODE);
