<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('login.php');
if (session_status() === PHP_SESSION_ACTIVE) { @session_write_close(); }
require_once __DIR__ . '/../db_bootstrap.php';
if (function_exists('ensure_db')) { ensure_db(true); }
require_once __DIR__ . '/../mikrotik_lib.php';
require_once __DIR__ . '/../routeros_api.php';
require_once __DIR__ . '/../mikrotik_connection_lib.php';

header('Content-Type: application/json; charset=utf-8');
@ini_set('display_errors', '0');
while (ob_get_level() > 0) { @ob_end_clean(); }
ob_start();
if (function_exists('mysqli_report')) { @mysqli_report(MYSQLI_REPORT_OFF); }

function noc_traffic_out($out, $code) {
    http_response_code((int)$code);
    while (ob_get_level() > 0) { @ob_end_clean(); }
    echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
function noc_traffic_setting($conn, $key, $default = null) {
    $keyEsc = $conn->real_escape_string($key);
    $r = @$conn->query("SELECT setting_value v FROM app_settings WHERE setting_key='$keyEsc' LIMIT 1");
    if ($r && ($row = $r->fetch_assoc())) return $row['v'];
    $r = @$conn->query("SELECT value v FROM app_settings WHERE `key`='$keyEsc' LIMIT 1");
    if ($r && ($row = $r->fetch_assoc())) return $row['v'];
    return $default;
}
function noc_traffic_setting_any($conn, $keys, $default = null) {
    foreach ($keys as $k) {
        $v = noc_traffic_setting($conn, $k, null);
        if ($v !== null && $v !== '') return $v;
    }
    return $default;
}
function noc_traffic_get_routers($conn) {
    $rows = array();
    $r = @$conn->query("SHOW TABLES LIKE 'routers'");
    if (!$r || !$r->num_rows) return $rows;
    $sql = "SELECT * FROM routers";
    $c = @$conn->query("SHOW COLUMNS FROM routers LIKE 'is_enabled'");
    if ($c && $c->num_rows) $sql .= " WHERE is_enabled=1";
    $sql .= " ORDER BY id ASC";
    $r = @$conn->query($sql);
    if ($r) while ($row = $r->fetch_assoc()) $rows[] = $row;
    return $rows;
}
function noc_traffic_router_api($router) {
    if (!is_array($router)) return false;
    $err = '';
    return ua_mt_connect_config($router, $err, 0.8);
}

$conn = isset($GLOBALS['conn']) ? $GLOBALS['conn'] : null;
if (!($conn instanceof mysqli)) noc_traffic_out(array('ok' => false, 'reason' => 'db_not_ready'), 500);

$defaultMax = (float)noc_traffic_setting_any($conn, array('noc_hud_max_mbps', 'hud_max_mbps'), 300);
$out = array(
    'ok' => true,
    'server_time' => date('Y-m-d H:i:s'),
    'iface' => array('selected' => '', 'max_mbps' => $defaultMax),
    'sum' => array('rx_mbps' => 0.0, 'tx_mbps' => 0.0, 'total_mbps' => 0.0),
    'kpi' => array('wan_rx_mbps' => 0.0, 'wan_tx_mbps' => 0.0, 'wan_total_mbps' => 0.0),
    'sources' => array(),
    'peak' => array('iface' => '', 'wan_peak_mbps' => 0.0),
    'meta' => array('errors' => array())
);

try {
    $routers = noc_traffic_get_routers($conn);
    $byId = array(); foreach ($routers as $r) $byId[(int)$r['id']] = $r;

    $sources = json_decode((string)noc_traffic_setting_any($conn, array('noc_traffic_sources','hud_traffic_sources'), '[]'), true);
    if (!is_array($sources)) $sources = array();
    if (!$sources) {
        $legacyIface = trim((string)noc_traffic_setting_any($conn, array('noc_hud_iface_name','hud_iface_name'), ''));
        $primaryRouterId = (int)noc_traffic_setting_any($conn, array('noc_primary_router_id','hud_primary_router_id'), '0');
        if ($legacyIface !== '' && !empty($routers)) {
            $fallbackRouter = isset($byId[$primaryRouterId]) ? $byId[$primaryRouterId] : $routers[0];
            $sources[] = array('router_id' => (int)$fallbackRouter['id'], 'iface' => $legacyIface, 'label' => 'القراءة الأساسية', 'max_mbps' => $defaultMax, 'enabled' => 1);
        }
    }

    $sumRx = 0.0; $sumTx = 0.0; $selected = array(); $maxSeen = $defaultMax;
    foreach ($sources as $src) {
        if (isset($src['enabled']) && (int)$src['enabled'] !== 1) continue;
        $rid = (int)($src['router_id'] ?? 0);
        $iface = trim((string)($src['iface'] ?? ''));
        if ($rid <= 0 || $iface === '' || !isset($byId[$rid])) continue;
        $router = $byId[$rid];
        $api = noc_traffic_router_api($router);
        $rx = 0.0; $tx = 0.0; $ok = false;
        if ($api) {
            try {
                $m = mt_monitor_traffic($api, $iface);
                $rx = round(((float)($m['rx_bps'] ?? 0)) / 1000000, 1);
                $tx = round(((float)($m['tx_bps'] ?? 0)) / 1000000, 1);
                $ok = true;
            } catch (Throwable $e) {
                $out['meta']['errors'][] = 'monitor_traffic: ' . $e->getMessage();
            }
            if (method_exists($api,'disconnect')) { try { $api->disconnect(); } catch (Throwable $e) {} }
        }
        $total = round($rx + $tx, 1);
        $sumRx += $rx; $sumTx += $tx;
        $maxSeen = max($maxSeen, (float)($src['max_mbps'] ?? $defaultMax));
        $selected[] = trim((string)($src['label'] ?? '')) !== '' ? trim((string)$src['label']) : $iface;
        $out['sources'][] = array(
            'router_id' => $rid,
            'router_name' => (string)($router['name'] ?? ''),
            'router_host' => (string)($router['host'] ?? ''),
            'iface' => $iface,
            'label' => trim((string)($src['label'] ?? '')) !== '' ? trim((string)$src['label']) : $iface,
            'rx_mbps' => $rx,
            'tx_mbps' => $tx,
            'total_mbps' => $total,
            'max_mbps' => (float)($src['max_mbps'] ?? $defaultMax),
            'ok' => $ok
        );
    }

    $total = round($sumRx + $sumTx, 1);
    $out['sum']['rx_mbps'] = round($sumRx, 1);
    $out['sum']['tx_mbps'] = round($sumTx, 1);
    $out['sum']['total_mbps'] = $total;
    $out['kpi']['wan_rx_mbps'] = $out['sum']['rx_mbps'];
    $out['kpi']['wan_tx_mbps'] = $out['sum']['tx_mbps'];
    $out['kpi']['wan_total_mbps'] = $total;
    $out['iface']['selected'] = implode(' + ', $selected);
    $out['iface']['max_mbps'] = $maxSeen;
    noc_traffic_out($out, 200);
} catch (Throwable $e) {
    $out['ok'] = false;
    $out['reason'] = 'exception';
    $out['error'] = $e->getMessage();
    noc_traffic_out($out, 200);
}
