<?php
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../lib/mikrotik_client.php';

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

$settings = mt_get_settings($conn);
$wan = trim($settings['wan_interface'] ?? '');
$sub = trim($settings['subscriber_interface'] ?? '');

$api = mt_connect($conn);
if (!$api) {
    echo json_encode([
        'ok' => false,
        'note' => 'Demo',
        'wan' => ['rx_bps' => 0, 'tx_bps' => 0, 'interface' => $wan],
        'subscribers' => ['rx_bps' => 0, 'tx_bps' => 0, 'interface' => $sub],
        'ts' => date('c'),
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$wanData = $wan !== '' ? mt_monitor_traffic($api, $wan) : ['rx_bps' => 0, 'tx_bps' => 0];
$subData = $sub !== '' ? mt_monitor_traffic($api, $sub) : ['rx_bps' => 0, 'tx_bps' => 0];

mt_disconnect($api);

echo json_encode([
    'ok' => true,
    'wan' => $wanData + ['interface' => $wan],
    'subscribers' => $subData + ['interface' => $sub],
    'ts' => date('c'),
], JSON_UNESCAPED_UNICODE);
