<?php
// admin/api/live_dashboard_stats.php
// Live dashboard JSON endpoint.
// Stage 11: no longer includes api/speed_gauges.php as a nested endpoint.
// Speed readings come from speed_gauges_lib.php and subscriber counters come from ua_unified_stats_lib.php.

require_once __DIR__ . '/api_common.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../mikrotik_lib.php';
require_once __DIR__ . '/../speed_gauges_lib.php';
require_once __DIR__ . '/../ua_unified_stats_lib.php';
require_once __DIR__ . '/../stats_snapshot_lib.php';

api_require_login();

$conn = null;
try {
  $conn = api_ensure_db(false);
} catch (Throwable $e) {
  $conn = $GLOBALS['conn'] ?? null;
}

// Speed gauges are the single source for WAN/consumed speed values.
try {
  $g = ua_speed_gauges_payload();
} catch (Throwable $e) {
  $g = function_exists('ua_speed_default_payload') ? ua_speed_default_payload() : ['status'=>'offline','rx_bps'=>0,'tx_bps'=>0,'consumed_bps'=>0,'message'=>''];
}

$rx_mbps = round(((float)($g['rx_bps'] ?? 0)) / 1000000, 2);
$tx_mbps = round(((float)($g['tx_bps'] ?? 0)) / 1000000, 2);
$total_mbps = round($rx_mbps + $tx_mbps, 2);
$rx_gb = (float)($g['rx_gb'] ?? 0);
$tx_gb = (float)($g['tx_gb'] ?? 0);
$router_online = in_array((string)($g['status'] ?? 'offline'), ['online','ok'], true);

// Unified subscriber counters. Do not count random fallback tables here.
$users = 0;
$alerts = 0;
if ($conn instanceof mysqli && (function_exists('ua_app_stats_snapshot') || function_exists('ua_unified_stats'))) {
  try {
    $counts = function_exists('ua_app_stats_snapshot') ? ua_app_stats_snapshot($conn, 10, false) : ua_unified_stats($conn, 10, false);
    $users = (int)($counts['total'] ?? 0);
    if ((int)($counts['unsafe_speed'] ?? 0) > 0) $alerts++;
  } catch (Throwable $e) {}
}

$cpu_pct = 0;
$ram_pct = 0;
$uptime = '0d 00:00';
$router_name = '';
$router_model = '';
$router_label = '';

if ($conn instanceof mysqli && function_exists('mt_api_connect')) {
  $api = null;
  try {
    $api = mt_api_connect($conn);
    if ($api) {
      try {
        $idRows = $api->command(['/system/identity/print']);
        foreach ($idRows as $r) {
          if (($r['.type'] ?? '') !== '!re') continue;
          $router_name = (string)($r['name'] ?? $router_name);
          break;
        }
      } catch (Throwable $e) {}

      $rows = $api->command(['/system/resource/print']);
      foreach ($rows as $r) {
        if (($r['.type'] ?? '') !== '!re') continue;
        $cpu_pct = (int)($r['cpu-load'] ?? 0);
        $uptime = (string)($r['uptime'] ?? $uptime);
        $router_model = (string)($r['board-name'] ?? $router_model);
        $total = (float)($r['total-memory'] ?? 0);
        $free  = (float)($r['free-memory'] ?? 0);
        if ($total > 0) {
          $used = max(0, $total - $free);
          $ram_pct = (int)round(($used / $total) * 100);
        }
        break;
      }

      // If RouterOS resource/identity was reachable, mark router online even if traffic is 0.
      $router_online = true;
    }
  } catch (Throwable $e) {
    // Keep speed_gauges status as source of truth for online/offline.
  } finally {
    if (is_object($api) && method_exists($api, 'disconnect')) {
      try { $api->disconnect(); } catch (Throwable $e) {}
    }
  }
}

$router_label = trim($router_name);
if ($router_model !== '') {
  $router_label = $router_label !== '' ? ($router_label . ' / ' . $router_model) : $router_model;
}

out([
  'ok' => true,
  'router' => ['online' => $router_online],
  'router_label' => $router_label,
  'router_name' => $router_name,
  'router_model' => $router_model,
  'users' => $users,
  'alerts' => $alerts,
  'max_mbps' => 300,
  'rx_mbps' => $rx_mbps,
  'tx_mbps' => $tx_mbps,
  'total_mbps' => $total_mbps,
  'rx_gb' => $rx_gb,
  'tx_gb' => $tx_gb,
  'cpu_pct' => $cpu_pct,
  'ram_pct' => $ram_pct,
  'uptime' => $uptime,
  'download_mbps' => $rx_mbps,
  'up_mbps' => $tx_mbps,
  'down_mbps' => $rx_mbps,
  'raw' => [
    'status' => $g['status'] ?? 'offline',
    'message' => $g['message'] ?? ''
  ]
]);
