<?php
// admin/api/server_speed.php
// Instant "server speed" without external tools.
//
// IMPORTANT:
// - We do NOT run a real speedtest every second (heavy/unreliable).
// - We expose *instantaneous WAN throughput* by reading the existing endpoint speed_gauges.php.
// - This satisfies "لحظي" safely.
//
// Output JSON:
// { status: "ok|offline", down_bps: int, up_bps: int, ping_ms: null, server: {...}, message: string }

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
header('Content-Type: application/json; charset=utf-8');

// Use a unique function name to avoid collisions with other included endpoints
if (!function_exists('ua_out_json')) {
    function ua_out_json($arr, $code = 200) {
        http_response_code($code);
        echo json_encode($arr, JSON_UNESCAPED_UNICODE);
        exit;
    }
}

$ua_logged = !empty($_SESSION['admin_id']) || !empty($_SESSION['admin_user_id']) || !empty($_SESSION['admin_user']);
if (!$ua_logged) {
    ua_out_json(['status' => 'offline', 'ok' => false, 'message' => 'Unauthorized'], 401);
}

$path = __DIR__ . '/speed_gauges.php';

if (!is_file($path)) {
    ua_out_json([
        'status'   => 'offline',
        'down_bps' => 0,
        'up_bps'   => 0,
        'ping_ms'  => null,
        'server'   => null,
        'message'  => 'speed_gauges.php غير موجود'
    ], 200);
}

// Capture JSON output from speed_gauges.php safely
ob_start();
include $path;
$raw = trim((string)ob_get_clean());

$j = json_decode($raw, true);
if (!is_array($j)) {
    ua_out_json([
        'status'   => 'offline',
        'down_bps' => 0,
        'up_bps'   => 0,
        'ping_ms'  => null,
        'server'   => null,
        'message'  => 'Non-JSON from speed_gauges'
    ], 200);
}

// speed_gauges.php expected keys: rx_bps, tx_bps, status
$rx = (int)($j['rx_bps'] ?? 0);
$tx = (int)($j['tx_bps'] ?? 0);

$st = (($j['status'] ?? 'offline') === 'ok') ? 'ok' : 'offline';

ua_out_json([
    'status'   => $st,
    'down_bps' => max(0, $rx),
    'up_bps'   => max(0, $tx),
    'ping_ms'  => null,
    'server'   => [
        'name'     => 'mikrotik (instant throughput)',
        'location' => null,
        'country'  => null,
        'host'     => null,
        'id'       => null
    ],
    'message'  => 'لحظي من حركة WAN (بدون برامج خارجية)'
], 200);
