<?php
// Patch 1: bandwidth.php — descarta bps impossível no calculate_bps
$f1 = "/var/www/html/mikrotik/includes/bandwidth.php";
$c1 = file_get_contents($f1);

$old1 = '    $bytesPerSec = $delta / $deltaSeconds;
    return (int)($bytesPerSec * 8); // bytes ' . "\xe2\x86\x92" . ' bits
}';

$new1 = '    $bytesPerSec = $delta / $deltaSeconds;
    $bps = (int)($bytesPerSec * 8); // bytes ' . "\xe2\x86\x92" . ' bits

    // Descarta leituras impossíveis (> 400 Gbps) — ocorre no primeiro poll
    if ($bps > 400000000000) {
        return null;
    }

    return $bps;
}';

if (strpos($c1, '400000000000') !== false) {
    echo "SKIP bandwidth.php\n";
} elseif (strpos($c1, $old1) !== false) {
    file_put_contents($f1, str_replace($old1, $new1, $c1));
    echo "OK bandwidth.php\n";
} else {
    // tenta sem utf8
    $old1b = '    $bytesPerSec = $delta / $deltaSeconds;
    return (int)($bytesPerSec * 8); // bytes -> bits
}';
    if (strpos($c1, $old1b) !== false) {
        file_put_contents($f1, str_replace($old1b, str_replace("\xe2\x86\x92", '->', $new1), $c1));
        echo "OK bandwidth.php (variant)\n";
    } else {
        echo "FAIL bandwidth.php\n";
    }
}

// Patch 2: history.php — filtra valores impossíveis no retorno da API
$f2 = "/var/www/html/mikrotik/views/api/history.php";
$c2 = file_get_contents($f2);

if (strpos($c2, '400_000_000_000') !== false || strpos($c2, '400000000000') !== false) {
    echo "SKIP history.php\n";
    exit;
}

$old2 = '$labels  = array_map(fn($r) => (new DateTimeImmutable($r[\'recorded_at\']))->format($fmt), $rows);
$in_bps  = array_map(fn($r) => (int)$r[\'in_bps\'],  $rows);
$out_bps = array_map(fn($r) => (int)$r[\'out_bps\'], $rows);

echo json_encode(compact(\'labels\', \'in_bps\', \'out_bps\'));';

$new2 = '// Filtra leituras impossiveis (primeiros polls com delta enorme do contador acumulado)
$MAX_BPS = 400000000000; // 400 Gbps
$labels  = [];
$in_bps  = [];
$out_bps = [];
foreach ($rows as $r) {
    $in  = (int)$r[\'in_bps\'];
    $out = (int)$r[\'out_bps\'];
    if ($in > $MAX_BPS || $out > $MAX_BPS) continue;
    $labels[]  = (new DateTimeImmutable($r[\'recorded_at\']))->format($fmt);
    $in_bps[]  = $in;
    $out_bps[] = $out;
}

echo json_encode(compact(\'labels\', \'in_bps\', \'out_bps\'));';

if (strpos($c2, $old2) !== false) {
    file_put_contents($f2, str_replace($old2, $new2, $c2));
    echo "OK history.php\n";
} else {
    echo "FAIL history.php\n";
}

echo "DONE\n";
