<?php
require_once __DIR__ . '/../../includes/header.php';
require_once __DIR__ . '/../../mikrotik/includes/bandwidth.php';

$pdo = db();

// Interfaces monitoradas (alert_on_down = true) do usuário
$stmt = $pdo->prepare("
    SELECT ni.id, ni.if_name, ni.if_alias, ni.last_status,
           ni.last_in_bps, ni.last_out_bps,
           ni.alert_email, ni.last_alert_sent_at, ni.last_alert_status,
           nd.name AS device_name, nd.id AS device_id, nd.hostname AS device_host
    FROM nms_interfaces ni
    JOIN nms_devices nd ON nd.id = ni.device_id
    WHERE nd.user_id = ? AND ni.alert_on_down = TRUE
    ORDER BY ni.last_status ASC, nd.name ASC, ni.if_name ASC
");
$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 último 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;">✅ 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;">🔴 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;">⚠️ Última queda: ' . $dtLabel . ' · durou ' . $durStr . '</span>';
}
?>

<div style="display:flex;flex-direction:column;gap:24px;">

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#1e293b,#0f172a);border-radius:20px;padding:32px;color:#f1f5f9;position:relative;overflow:hidden;">
        <div style="position:absolute;top:-40px;right:-40px;width:220px;height:220px;background:radial-gradient(circle,rgba(99,102,241,0.18),transparent 70%);pointer-events:none;"></div>
        <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:16px;position:relative;">
            <div>
                <p style="color:#64748b;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:6px;">🔔 Monitoramento de Interfaces</p>
                <h1 style="font-size:2rem;font-weight:900;margin:0;color:#f8fafc;">Interfaces Monitoradas</h1>
                <p style="color:#94a3b8;margin-top:6px;font-size:0.95rem;">Interfaces com alerta de queda ativo — atualização automática a cada 60s</p>
            </div>
            <a href="<?= NMS_URL ?>?page=nms_devices" style="text-decoration:none;">
                <button style="background:linear-gradient(135deg,#4f46e5,#4338ca);color:#fff;border:none;padding:13px 22px;border-radius:12px;font-weight:700;cursor:pointer;font-size:0.9rem;box-shadow:0 4px 14px rgba(79,70,229,0.4);">
                    🖥️ Gerenciar Dispositivos
                </button>
            </a>
        </div>
    </div>

    <!-- Cards de resumo -->
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;">
        <div style="background:#f8fafc;border:2px solid #e2e8f0;border-radius:16px;padding:24px;text-align:center;">
            <div style="font-size:2.8rem;font-weight:900;color:#0f172a;"><?= $total ?></div>
            <div style="font-size:0.82rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:1px;margin-top:4px;">Total Monitoradas</div>
        </div>
        <div style="background:#f0fdf4;border:2px solid #86efac;border-radius:16px;padding:24px;text-align:center;">
            <div style="font-size:2.8rem;font-weight:900;color:#16a34a;"><?= $online ?></div>
            <div style="font-size:0.82rem;font-weight:700;color:#16a34a;text-transform:uppercase;letter-spacing:1px;margin-top:4px;">Online</div>
        </div>
        <div style="background:#fef2f2;border:2px solid #fca5a5;border-radius:16px;padding:24px;text-align:center;">
            <div style="font-size:2.8rem;font-weight:900;color:#dc2626;"><?= $offline ?></div>
            <div style="font-size:0.82rem;font-weight:700;color:#dc2626;text-transform:uppercase;letter-spacing:1px;margin-top:4px;">Offline</div>
        </div>
    </div>

    <?php if (empty($monitored)): ?>
    <!-- Estado vazio -->
    <div style="background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:64px;text-align:center;">
        <div style="font-size:3.5rem;margin-bottom:16px;">🔕</div>
        <div style="font-size:1.2rem;font-weight:700;color:#1e293b;margin-bottom:8px;">Nenhuma interface monitorada</div>
        <p style="color:#64748b;font-size:0.95rem;max-width:420px;margin:0 auto 24px;">
            Acesse um dispositivo, clique em <strong>🔕 Monitorar</strong> em uma interface e configure o e-mail de alerta.
        </p>
        <a href="<?= NMS_URL ?>?page=nms_devices" style="display:inline-block;padding:12px 24px;background:#4f46e5;color:#fff;border-radius:10px;font-weight:700;text-decoration:none;">
            Ir para Dispositivos →
        </a>
    </div>
    <?php else: ?>

    <!-- Grid de cards das interfaces -->
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(380px,1fr));gap:20px;">
        <?php foreach ($monitored as $iface):
            $isUp      = ($iface['last_status'] ?? '') === 'up';
            $stBg      = $isUp ? '#f0fdf4' : '#fef2f2';
            $stBorder  = $isUp ? '#86efac' : '#fca5a5';
            $stColor   = $isUp ? '#15803d' : '#dc2626';
            $stTopBar  = $isUp ? '#22c55e' : '#ef4444';
            $stHdrBg   = $isUp ? '#f0fdf4' : '#fff1f2';
            $stIcon    = $isUp ? '🟢' : '🔴';
            $stLabel   = $isUp ? 'Online' : 'Offline';
            $label     = h($iface['if_alias'] ?: $iface['if_name']);
            $ifRaw     = h($iface['if_name']);
            $dashUrl   = h(NMS_URL . '?page=nms_interface_dashboard&id=' . (int)$iface['id']);
            $devUrl    = h(NMS_URL . '?page=nms_device_detail&id='       . (int)$iface['device_id']);
            $inBps     = (int)($iface['last_in_bps']  ?? 0);
            $outBps    = (int)($iface['last_out_bps'] ?? 0);
            $chartId   = 'mc-' . (int)$iface['id'];
        ?>
        <div style="background:#fff;border:2px solid <?= $stBorder ?>;border-radius:18px;overflow:hidden;box-shadow:0 2px 10px rgba(0,0,0,.07);transition:box-shadow .2s,transform .15s;"
             onmouseover="this.style.boxShadow='0 6px 24px rgba(0,0,0,.13)';this.style.transform='translateY(-2px)'"
             onmouseout="this.style.boxShadow='0 2px 10px rgba(0,0,0,.07)';this.style.transform='translateY(0)'">

            <!-- Faixa colorida de status no topo -->
            <div style="height:5px;background:<?= $stTopBar ?>;"></div>

            <!-- Card header com fundo tintado -->
            <div style="padding:20px 22px 16px;background:<?= $stHdrBg ?>;border-bottom:1px solid <?= $stBorder ?>;">
                <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px;">
                    <div style="min-width:0;flex:1;">
                        <!-- Nome da interface em destaque -->
                        <div style="font-size:1.45rem;font-weight:900;color:#0f172a;line-height:1.2;word-break:break-word;margin-bottom:6px;" title="<?= $label ?>"><?= $label ?></div>
                        <?php if ($iface['if_alias'] && $iface['if_alias'] !== $iface['if_name']): ?>
                            <div style="font-size:0.95rem;font-weight:800;color:#fff;font-family:monospace;background:linear-gradient(135deg,#ea580c,#f97316);display:inline-block;padding:3px 12px;border-radius:7px;margin-bottom:5px;box-shadow:0 2px 6px rgba(234,88,12,.3);"><?= $ifRaw ?></div>
                        <?php endif; ?>
                        <a href="<?= $devUrl ?>" style="font-size:0.82rem;color:#4f46e5;text-decoration:none;font-weight:700;display:inline-flex;align-items:center;gap:4px;">
                            🖥️ <?= h($iface['device_name']) ?>
                        </a>
                    </div>
                    <!-- Badge de status maior -->
                    <span style="background:<?= $stColor ?>;color:#fff;font-size:0.82rem;font-weight:800;padding:7px 15px;border-radius:20px;white-space:nowrap;flex-shrink:0;letter-spacing:.02em;box-shadow:0 2px 6px rgba(0,0,0,.15);">
                        <?= $stIcon ?> <?= $stLabel ?>
                    </span>
                </div>
            </div>

            <!-- Banda atual -->
            <div style="padding:14px 22px;display:flex;gap:20px;border-bottom:1px solid #f1f5f9;background:#fff;">
                <div>
                    <div style="font-size:0.7rem;color:#94a3b8;font-weight:700;text-transform:uppercase;letter-spacing:.05em;">↓ Entrada</div>
                    <div style="font-size:1.15rem;font-weight:900;color:#16a34a;"><?= format_bps($inBps) ?></div>
                </div>
                <div>
                    <div style="font-size:0.7rem;color:#94a3b8;font-weight:700;text-transform:uppercase;letter-spacing:.05em;">↑ Saída</div>
                    <div style="font-size:1.15rem;font-weight:900;color:#dc2626;"><?= format_bps($outBps) ?></div>
                </div>
                <div style="margin-left:auto;text-align:right;">
                    <div style="font-size:0.7rem;color:#94a3b8;font-weight:700;text-transform:uppercase;letter-spacing:.05em;">Alerta</div>
                    <div style="font-size:0.78rem;color:#92400e;font-weight:600;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= h($iface['alert_email']) ?>">
                        📧 <?= h($iface['alert_email']) ?>
                    </div>
                </div>
            </div>

            <!-- Gráfico de tráfego -->
            <div style="padding:12px 22px 8px;background:#fff;">
                <div style="font-size:0.7rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px;">📈 Tráfego — última 1h</div>
                <div style="position:relative;height:140px;">
                    <div id="loading-<?= $chartId ?>" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#94a3b8;font-size:0.8rem;">Carregando...</div>
                    <canvas id="<?= $chartId ?>" style="display:none;"></canvas>
                </div>
            </div>

            <!-- Último evento -->
            <div style="padding:8px 22px 10px;border-top:1px solid #f1f5f9;font-size:0.8rem;background:#fafafa;">
                <?= fmt_event_footer($iface, $eventsByIface, $userTz) ?>
            </div>

            <!-- Botão -->
            <div style="padding:12px 22px 16px;background:#fafafa;">
                <a href="<?= $dashUrl ?>"
                   style="display:flex;align-items:center;justify-content:center;gap:8px;padding:11px;background:#4f46e5;color:#fff;border-radius:10px;font-size:0.9rem;font-weight:700;text-decoration:none;transition:background .15s;box-shadow:0 2px 8px rgba(79,70,229,.3);"
                   onmouseover="this.style.background='#4338ca'" onmouseout="this.style.background='#4f46e5'">
                    📊 Ver dashboard completo
                </a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
const HISTORY_URL = <?= json_encode(NMS_URL . '?page=nms_api_history') ?>;
const IFACES = <?= json_encode(array_map(fn($i) => ['id' => (int)$i['id'], 'chartId' => 'mc-' . (int)$i['id']], $monitored)) ?>;

function formatBps(v) {
    if (!v || v <= 0) return '0';
    if (v >= 1e9)  return (v/1e9).toFixed(1)  + ' G';
    if (v >= 1e6)  return (v/1e6).toFixed(1)  + ' M';
    if (v >= 1e3)  return (v/1e3).toFixed(0)  + ' K';
    return v + ' b';
}

function loadMiniChart(ifaceId, chartId) {
    fetch(HISTORY_URL + '&interface_id=' + ifaceId + '&period=1h')
        .then(r => r.json())
        .then(data => {
            const loading = document.getElementById('loading-' + chartId);
            const canvas  = document.getElementById(chartId);
            if (!canvas || !data.labels) return;
            if (loading) loading.style.display = 'none';
            canvas.style.display = 'block';
            new Chart(canvas.getContext('2d'), {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [
                        { label: '↓ Entrada', data: data.in_bps,  borderColor: '#22c55e', borderWidth: 2, pointRadius: 0, fill: true, backgroundColor: 'rgba(34,197,94,0.08)', tension: 0.3 },
                        { label: '↑ Saída',   data: data.out_bps, borderColor: '#ef4444', borderWidth: 2, pointRadius: 0, fill: true, backgroundColor: 'rgba(239,68,68,0.06)',  tension: 0.3 }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    animation: false,
                    interaction: { mode: 'index', intersect: false },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: { font: { size: 10, weight: '700' }, padding: 8, boxWidth: 10, boxHeight: 2 }
                        },
                        tooltip: {
                            callbacks: { label: ctx => ' ' + ctx.dataset.label + ': ' + formatBps(ctx.parsed.y) }
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            ticks: { maxTicksLimit: 5, font: { size: 9 }, color: '#94a3b8', maxRotation: 0 },
                            grid: { display: false }
                        },
                        y: {
                            display: true,
                            beginAtZero: true,
                            ticks: { maxTicksLimit: 4, font: { size: 9 }, color: '#94a3b8', callback: v => formatBps(v) },
                            grid: { color: 'rgba(0,0,0,.04)' }
                        }
                    }
                }
            });
        })
        .catch(() => {
            const loading = document.getElementById('loading-' + chartId);
            if (loading) loading.textContent = '—';
        });
}

// Carrega todos os mini-gráficos
IFACES.forEach(i => loadMiniChart(i.id, i.chartId));

// Auto-refresh a cada 60s
setTimeout(() => location.reload(), 60000);
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
