<?php
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../lang.php';
require_once __DIR__ . '/../mikrotik_lib.php';

require_login();
if(function_exists('require_perm')) require_perm('can_settings');

header('Content-Type: application/json; charset=utf-8');

$conn = null;
if (function_exists('ensure_db')) {
  try { $conn = ensure_db(true); } catch (Throwable $e) { $conn = null; }
}
if (!($conn instanceof mysqli)) {
  $conn = $GLOBALS['conn'] ?? null;
}

$subsInterface = get_app_setting($conn, 'mikrotik_subs_interface', '');

try {
  $traffic = $subsInterface ? mt_monitor_traffic($conn, $subsInterface) : ['rx_bps'=>0,'tx_bps'=>0];
  $ppp = mt_ppp_active($conn);
  $queues = mt_simple_queues($conn, 100);
  echo json_encode([
    'ok'=>true,
    'subs_interface'=>$subsInterface,
    'traffic'=>$traffic,
    'pppoe_active'=>$ppp,
    'queues'=>$queues,
  ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
