<?php
// Patch interface_dashboard.php — adiciona historico de eventos de queda
$f = "/var/www/html/mikrotik/views/interface_dashboard.php";
$c = file_get_contents($f);

if (strpos($c, 'nms_interface_events') !== false) { echo "SKIP\n"; exit; }

// Parte 1: adiciona queries de eventos apos o bloco de alertHistory
$old1 = '// Tempo online/offline (ultima transicao)
$alertHistory = [];
if (!empty($iface[\'last_alert_sent_at\'])) {
    $alertHistory[] = $iface[\'last_alert_sent_at\'];
}';

// tenta com acento
if (strpos($c, $old1) === false) {
    $old1 = '// Tempo online/offline (' . "\xc3\xba" . 'ltima transi' . "\xc3\xa7" . "\xc3\xa3" . 'o)
$alertHistory = [];
if (!empty($iface[\'last_alert_sent_at\'])) {
    $alertHistory[] = $iface[\'last_alert_sent_at\'];
}';
}

$new1 = '// Historico de eventos de queda
$evtStmt = $pdo->prepare("
    SELECT id, started_at, recovered_at, duration_seconds, alert_sent
    FROM nms_interface_events
    WHERE interface_id = ?
    ORDER BY started_at DESC
    LIMIT 50
");
$evtStmt->execute([$ifaceId]);
$events = $evtStmt->fetchAll();

// Disponibilidade nos ultimos 30 dias
$availStmt = $pdo->prepare("
    SELECT COALESCE(SUM(duration_seconds), 0) AS total_down_sec, COUNT(*) AS total_events
    FROM nms_interface_events
    WHERE interface_id = ? AND started_at >= NOW() - INTERVAL \'30 days\'
");
$availStmt->execute([$ifaceId]);
$availStats = $availStmt->fetch();
$totalDownSec  = (int)($availStats[\'total_down_sec\'] ?? 0);
$totalEvents30 = (int)($availStats[\'total_events\'] ?? 0);
$availPct = $totalDownSec > 0 ? round((1 - $totalDownSec / (30 * 86400)) * 100, 3) : 100.0;';

if (strpos($c, $old1) !== false) {
    $c = str_replace($old1, $new1, $c);
    echo "PART1 OK\n";
} else {
    echo "FAIL1 — anchor not found\n"; exit;
}

// Parte 2: adiciona $tz antes de $deviceDetailUrl
$old2 = '$deviceDetailUrl = h(NMS_URL . \'?page=nms_dashboard\');';
$new2 = '$tz = new DateTimeZone(in_array($user[\'timezone\'] ?? \'\', timezone_identifiers_list(), true) ? $user[\'timezone\'] : \'America/Sao_Paulo\');
$deviceDetailUrl = h(NMS_URL . \'?page=nms_dashboard\');';

if (strpos($c, $old2) !== false) {
    $c = str_replace($old2, $new2, $c);
    echo "PART2 OK\n";
} else {
    echo "FAIL2\n"; exit;
}

// Parte 3: insere cards de disponibilidade antes do grafico principal
$old3 = '    <!-- Gr' . "\xc3\xa1" . 'fico principal -->';
if (strpos($c, $old3) === false) {
    $old3 = '    <!-- Grafico principal -->';
}

$new3 = '    <!-- Disponibilidade 30d -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:24px;">
        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);">
            <div style="font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px;">&#x1F4C5; Disponibilidade 30d</div>
            <div style="font-size:1.4rem;font-weight:800;color:<?= $availPct >= 99 ? \'#22c55e\' : ($availPct >= 95 ? \'#ca8a04\' : \'#ef4444\') ?>;"><?= $availPct ?>%</div>
        </div>
        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);">
            <div style="font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px;">&#x26A0;&#xFE0F; Quedas 30d</div>
            <div style="font-size:1.4rem;font-weight:800;color:#f97316;"><?= $totalEvents30 ?></div>
        </div>
        <?php if ($totalDownSec > 0):
            $dmin = (int)round($totalDownSec / 60);
            $dstr = $dmin < 60 ? $dmin . \' min\' : (int)floor($dmin/60) . \'h\' . ($dmin%60 > 0 ? \' \' . ($dmin%60) . \'min\' : \'\');
        ?>
        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);">
            <div style="font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px;">&#x1F550; Tempo offline 30d</div>
            <div style="font-size:1.4rem;font-weight:800;color:#ef4444;"><?= $dstr ?></div>
        </div>
        <?php endif; ?>
    </div>

    ' . $old3;

if (strpos($c, $old3) !== false) {
    $c = str_replace($old3, $new3, $c);
    echo "PART3 OK\n";
} else {
    echo "FAIL3\n"; exit;
}

// Parte 4: insere tabela de historico antes do fechamento </div> + script
$old4 = '</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js">';
$new4 = '    <!-- Historico de Quedas -->
    <div style="background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:28px 32px;margin-top:24px;box-shadow:0 1px 4px rgba(0,0,0,.06);">
        <div style="font-size:1.1rem;font-weight:700;color:#1e293b;margin-bottom:20px;">&#x1F4CB; Historico de Quedas</div>
        <?php if (empty($events)): ?>
            <div style="text-align:center;padding:40px;color:#94a3b8;">&#x2705; Nenhuma queda registrada.</div>
        <?php else: ?>
        <div style="overflow-x:auto;">
        <table style="width:100%;border-collapse:collapse;font-size:0.875rem;">
            <thead>
                <tr style="background:#f8fafc;">
                    <th style="padding:10px 14px;text-align:left;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">#</th>
                    <th style="padding:10px 14px;text-align:left;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Inicio da queda</th>
                    <th style="padding:10px 14px;text-align:left;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Recuperacao</th>
                    <th style="padding:10px 14px;text-align:right;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Duracao</th>
                    <th style="padding:10px 14px;text-align:center;font-size:0.75rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid #e2e8f0;">Status</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($events as $idx => $ev):
                $startDt = (new DateTimeImmutable($ev[\'started_at\']))->setTimezone($tz)->format(\'d/m/Y H:i:s\');
                $isOpen  = $ev[\'recovered_at\'] === null;
                $recDt   = $isOpen ? \'&mdash;\' : (new DateTimeImmutable($ev[\'recovered_at\']))->setTimezone($tz)->format(\'d/m/Y H:i:s\');
                $durSec  = (int)($ev[\'duration_seconds\'] ?? 0);
                if ($isOpen) {
                    $durStr = \'<span style="color:#dc2626;font-weight:700;">Em andamento</span>\';
                } elseif ($durSec > 0) {
                    $m = (int)round($durSec / 60);
                    $durStr = $m < 60 ? $m . \' min\' : (int)floor($m/60) . \'h \' . ($m%60 > 0 ? ($m%60).\'min\' : \'\');
                } else {
                    $durStr = \'< 1 min\';
                }
                $rowBg = ($idx % 2 === 0) ? \'#fff\' : \'#f8fafc\';
            ?>
            <tr style="background:<?= $rowBg ?>;border-left:<?= $isOpen ? \'3px solid #ef4444\' : \'3px solid transparent\' ?>;">
                <td style="padding:10px 14px;color:#94a3b8;font-size:0.8rem;"><?= count($events) - $idx ?></td>
                <td style="padding:10px 14px;font-family:monospace;color:#1e293b;"><?= $startDt ?></td>
                <td style="padding:10px 14px;font-family:monospace;color:<?= $isOpen ? \'#94a3b8\' : \'#16a34a\' ?>;"><?= $recDt ?></td>
                <td style="padding:10px 14px;text-align:right;font-weight:700;color:#374151;"><?= $durStr ?></td>
                <td style="padding:10px 14px;text-align:center;">
                    <?php if ($isOpen): ?>
                        <span style="background:#fee2e2;color:#dc2626;padding:3px 10px;border-radius:20px;font-size:0.75rem;font-weight:700;">&#x1F534; Em queda</span>
                    <?php else: ?>
                        <span style="background:#dcfce7;color:#16a34a;padding:3px 10px;border-radius:20px;font-size:0.75rem;font-weight:700;">&#x2705; Recuperada</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js">';

if (strpos($c, $old4) !== false) {
    $c = str_replace($old4, $new4, $c);
    file_put_contents($f, $c);
    echo "PART4 OK\n";
    echo "DONE\n";
} else {
    echo "FAIL4 — script anchor not found\n"; exit;
}
