<?php
// Patch dashboard.php — adiciona dados de eventos nas interfaces monitoradas
$f = "/var/www/html/mikrotik/views/dashboard.php";
$c = file_get_contents($f);

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

// Parte 1: adiciona query de eventos e funcao helper apos fetchAll dos monitored
$old1 = '$stmt->execute([$user[\'id\']]);
$monitored = $stmt->fetchAll();

$total   = count($monitored);
$online  = count(array_filter($monitored, fn($i) => ($i[\'last_status\'] ?? \'\') === \'up\'));
$offline = count(array_filter($monitored, fn($i) => ($i[\'last_status\'] ?? \'\') === \'down\'));';

$new1 = '$stmt->execute([$user[\'id\']]);
$monitored = $stmt->fetchAll();

$total   = count($monitored);
$online  = count(array_filter($monitored, fn($i) => ($i[\'last_status\'] ?? \'\') === \'up\'));
$offline = count(array_filter($monitored, fn($i) => ($i[\'last_status\'] ?? \'\') === \'down\'));

// Busca ultimo evento de cada interface monitorada
$eventsByIface = [];
if (!empty($monitored)) {
    $ids = implode(\',\', array_map(fn($i) => (int)$i[\'id\'], $monitored));
    $evtRows = $pdo->query("
        SELECT DISTINCT ON (interface_id)
            interface_id, started_at, recovered_at, duration_seconds
        FROM nms_interface_events
        WHERE interface_id IN ($ids)
        ORDER BY interface_id, started_at DESC
    ")->fetchAll();
    foreach ($evtRows as $ev) {
        $eventsByIface[(int)$ev[\'interface_id\']] = $ev;
    }
}

$userTz = new DateTimeZone(in_array($user[\'timezone\'] ?? \'\', timezone_identifiers_list(), true) ? $user[\'timezone\'] : \'America/Sao_Paulo\');

function fmt_event_footer(array $iface, array $eventsByIface, DateTimeZone $tz): string {
    $isUp  = ($iface[\'last_status\'] ?? \'\') === \'up\';
    $ev    = $eventsByIface[(int)$iface[\'id\']] ?? null;
    if (!$ev) {
        return \'<span style="color:#22c55e;font-weight:700;">&#x2705; Sem quedas registradas</span>\';
    }
    $started  = (new DateTimeImmutable($ev[\'started_at\']))->setTimezone($tz);
    $isOpen   = $ev[\'recovered_at\'] === null;
    if ($isOpen && !$isUp) {
        $since = $started->format(\'d/m H:i\');
        $diff  = $started->diff(new DateTimeImmutable(\'now\', $tz));
        $mins  = $diff->days * 1440 + $diff->h * 60 + $diff->i;
        $dur   = $mins < 60 ? $mins . \'min\' : (int)floor($mins/60) . \'h\' . ($mins%60 > 0 ? ($mins%60) . \'min\' : \'\');
        return \'<span style="color:#dc2626;font-weight:700;">&#x1F534; Em queda desde \' . $since . \' (\' . $dur . \')</span>\';
    }
    $dtLabel = $started->format(\'d/m H:i\');
    $durSec  = (int)($ev[\'duration_seconds\'] ?? 0);
    if ($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 = \'< 1min\';
    }
    return \'<span style="color:#ca8a04;font-weight:700;">&#x26A0;&#xFE0F; Ultima queda: \' . $dtLabel . \' &middot; durou \' . $durStr . \'</span>\';
}';

if (strpos($c, $old1) === false) { echo "FAIL1\n"; exit; }
$c = str_replace($old1, $new1, $c);
echo "PART1 OK\n";

// Parte 2: insere footer de evento antes do botao de dashboard
$old2 = '            <!-- Botao -->
            <div style="padding:12px 20px 16px;">
                <a href="<?= $dashUrl ?>"';

$new2 = '            <!-- Ultimo evento -->
            <div style="padding:8px 20px 10px;border-top:1px solid #f1f5f9;font-size:0.78rem;">
                <?= fmt_event_footer($iface, $eventsByIface, $userTz) ?>
            </div>

            <!-- Botao -->
            <div style="padding:12px 20px 16px;">
                <a href="<?= $dashUrl ?>"';

if (strpos($c, $old2) === false) {
    // tenta sem acento
    $old2b = '            <!-- Bot' . "\xc3\xa3" . 'o -->
            <div style="padding:12px 20px 16px;">
                <a href="<?= $dashUrl ?>"';
    if (strpos($c, $old2b) !== false) {
        $c = str_replace($old2b, $new2, $c);
        file_put_contents($f, $c);
        echo "PART2 OK (variant)\n";
        exit;
    }
    echo "FAIL2\n"; exit;
}
$c = str_replace($old2, $new2, $c);
file_put_contents($f, $c);
echo "PART2 OK\n";
echo "DONE\n";
