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

$pdo = db();
$ifaceId = (int)($_GET['id'] ?? 0);
if (!$ifaceId) {
    echo '<script>location.href=' . json_encode(NMS_URL . '?page=nms_devices') . ';</script>';
    exit;
}

// Busca interface + device (com verificação de ownership)
$stmt = $pdo->prepare("
    SELECT ni.*, nd.name AS device_name, nd.hostname AS device_host, nd.id AS device_id, nd.type AS device_type
    FROM nms_interfaces ni
    JOIN nms_devices nd ON nd.id = ni.device_id
    WHERE ni.id = ? AND nd.user_id = ?
");
$stmt->execute([$ifaceId, $user['id']]);
$iface = $stmt->fetch();

if (!$iface) {
    echo "<div style='padding:40px;text-align:center;color:#ef4444;font-size:1.1rem;'>Interface não encontrada.</div>";
    require __DIR__ . '/../../includes/footer.php';
    exit;
}

// Último registro de banda
$latestStmt = $pdo->prepare("
    SELECT in_bps, out_bps, recorded_at
    FROM nms_bandwidth_history
    WHERE interface_id = ?
    ORDER BY recorded_at DESC
    LIMIT 1
");
$latestStmt->execute([$ifaceId]);
$latest = $latestStmt->fetch();

// Máximos nas últimas 24h
$peakStmt = $pdo->prepare("
    SELECT MAX(in_bps) AS peak_in, MAX(out_bps) AS peak_out,
           AVG(in_bps) AS avg_in, AVG(out_bps) AS avg_out
    FROM nms_bandwidth_history
    WHERE interface_id = ? AND recorded_at >= NOW() - INTERVAL '24 hours'
");
$peakStmt->execute([$ifaceId]);
$peaks = $peakStmt->fetch();

// Histórico 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 últimos 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;

$isUp        = ($iface['last_status'] ?? 'unknown') === 'up';
$statusColor = $isUp ? '#22c55e' : '#ef4444';
$statusLabel = $isUp ? 'Online' : 'Offline';
$statusBg    = $isUp ? '#dcfce7' : '#fee2e2';
$statusBorder= $isUp ? '#86efac' : '#fca5a5';

$tz = new DateTimeZone(in_array($user['timezone'] ?? '', timezone_identifiers_list(), true) ? $user['timezone'] : 'America/Sao_Paulo');
$deviceDetailUrl = h(NMS_URL . '?page=nms_dashboard');
$ifName  = h($iface['if_name']);
$ifAlias = h($iface['if_alias'] ?? '');
$devName = h($iface['device_name']);

function fmt_bps_val(?int $bps): string {
    if ($bps === null || $bps <= 0) return '—';
    if ($bps >= 1_000_000_000) return round($bps / 1_000_000_000, 2) . ' Gbps';
    if ($bps >= 1_000_000)     return round($bps / 1_000_000, 2)     . ' Mbps';
    if ($bps >= 1_000)         return round($bps / 1_000, 1)         . ' Kbps';
    return $bps . ' bps';
}
?>

<div style="max-width:1200px;margin:0 auto;padding:24px 20px;">

    <!-- Breadcrumb / voltar -->
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:24px;flex-wrap:wrap;">
        <a href="<?= $deviceDetailUrl ?>"
           style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:8px;font-size:0.9rem;font-weight:600;color:#475569;text-decoration:none;">
            ← Voltar
        </a>
        <span style="color:#94a3b8;font-size:0.9rem;"><?= $devName ?> / <?= $ifName ?></span>
    </div>

    <!-- Header card -->
    <div style="background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:28px 32px;margin-bottom:24px;display:flex;align-items:center;gap:24px;flex-wrap:wrap;box-shadow:0 1px 4px rgba(0,0,0,.06);">
        <div style="flex:1;min-width:220px;">
            <div style="font-size:1.5rem;font-weight:800;color:#1e293b;margin-bottom:4px;">
                <?= $ifName ?>
                <?php if ($ifAlias): ?>
                    <span style="font-size:1rem;font-weight:500;color:#64748b;margin-left:10px;"><?= $ifAlias ?></span>
                <?php endif; ?>
            </div>
            <div style="font-size:0.9rem;color:#64748b;">Dispositivo: <strong><?= $devName ?></strong></div>
        </div>
        <!-- Status badge -->
        <div style="background:<?= $statusBg ?>;border:1px solid <?= $statusBorder ?>;border-radius:12px;padding:12px 24px;text-align:center;">
            <div style="font-size:1.6rem;margin-bottom:2px;"><?= $isUp ? '🟢' : '🔴' ?></div>
            <div style="font-size:1rem;font-weight:800;color:<?= $statusColor ?>;"><?= $statusLabel ?></div>
        </div>
        <!-- Alerta badge -->
        <?php if (!empty($iface['alert_on_down']) && !empty($iface['alert_email'])): ?>
        <div style="background:#fefce8;border:1px solid #fde68a;border-radius:12px;padding:12px 24px;text-align:center;">
            <div style="font-size:1.4rem;margin-bottom:2px;">🔔</div>
            <div style="font-size:0.8rem;font-weight:700;color:#92400e;">Alertas ativos</div>
            <div style="font-size:0.75rem;color:#78350f;margin-top:2px;"><?= h($iface['alert_email']) ?></div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Cards de métricas -->
    <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;">↓ Entrada atual</div>
            <div style="font-size:1.4rem;font-weight:800;color:#22c55e;"><?= fmt_bps_val($latest ? (int)$latest['in_bps'] : null) ?></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;">↑ Saída atual</div>
            <div style="font-size:1.4rem;font-weight:800;color:#ef4444;"><?= fmt_bps_val($latest ? (int)$latest['out_bps'] : null) ?></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;">↓ Pico 24h</div>
            <div style="font-size:1.4rem;font-weight:800;color:#0ea5e9;"><?= fmt_bps_val($peaks ? (int)$peaks['peak_in'] : null) ?></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;">↑ Pico 24h</div>
            <div style="font-size:1.4rem;font-weight:800;color:#f97316;"><?= fmt_bps_val($peaks ? (int)$peaks['peak_out'] : null) ?></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;">↓ Média 24h</div>
            <div style="font-size:1.4rem;font-weight:800;color:#8b5cf6;"><?= fmt_bps_val($peaks ? (int)$peaks['avg_in'] : null) ?></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;">↑ Média 24h</div>
            <div style="font-size:1.4rem;font-weight:800;color:#ec4899;"><?= fmt_bps_val($peaks ? (int)$peaks['avg_out'] : null) ?></div>
        </div>

    </div>

    <!-- 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;">📅 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;">⚠️ 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;">🕐 Tempo offline 30d</div>
            <div style="font-size:1.4rem;font-weight:800;color:#ef4444;"><?= $dstr ?></div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Gráfico principal -->
    <div style="background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:28px 32px;box-shadow:0 1px 4px rgba(0,0,0,.06);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;flex-wrap:wrap;gap:12px;">
            <div style="font-size:1.1rem;font-weight:700;color:#1e293b;">📈 Tráfego de Banda</div>
            <!-- Seletor de período -->
            <div style="display:flex;gap:6px;flex-wrap:wrap;" id="period-selector">
                <?php foreach (['5min' => '5 min', '1h' => '1 hora', '6h' => '6 horas', '24h' => '24 horas', '7d' => '7 dias'] as $val => $lbl): ?>
                <button onclick="loadChart('<?= $val ?>')"
                    id="btn-<?= $val ?>"
                    style="padding:7px 14px;border-radius:8px;font-size:0.82rem;font-weight:600;cursor:pointer;border:1px solid #e2e8f0;background:#f8fafc;color:#64748b;transition:all .15s;">
                    <?= $lbl ?>
                </button>
                <?php endforeach; ?>
            </div>
        </div>
        <div id="chart-loading" style="text-align:center;padding:60px;color:#94a3b8;display:none;">Carregando dados...</div>
        <div id="chart-empty"   style="text-align:center;padding:60px;color:#94a3b8;display:none;">Sem dados para o período selecionado.</div>
        <div style="position:relative;height:380px;">
            <canvas id="ifaceChart"></canvas>
        </div>
    </div>

    <!-- Histórico 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;">📋 Histórico de Quedas</div>
        <?php if (empty($events)): ?>
            <div style="text-align:center;padding:40px;color:#94a3b8;">✅ 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;">Início 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;">Recuperação</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;">Duração</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 ? '—' : (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;">🔴 Em queda</span>
                    <?php else: ?>
                        <span style="background:#dcfce7;color:#16a34a;padding:3px 10px;border-radius:20px;font-size:0.75rem;font-weight:700;">✅ 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"></script>
<script>
const IFACE_ID  = <?= (int)$ifaceId ?>;
const HISTORY_URL = <?= json_encode(NMS_URL . '?page=nms_api_history') ?>;
let _chart = null;
let _activePeriod = '1h';

function setActivePeriodBtn(period) {
    document.querySelectorAll('#period-selector button').forEach(b => {
        const active = b.id === 'btn-' + period;
        b.style.background = active ? '#4f46e5' : '#f8fafc';
        b.style.color       = active ? '#fff'    : '#64748b';
        b.style.borderColor = active ? '#4f46e5' : '#e2e8f0';
    });
}

function formatBps(bps) {
    if (!bps || bps <= 0) return '0 bps';
    if (bps >= 1e9)  return (bps / 1e9).toFixed(2)  + ' Gbps';
    if (bps >= 1e6)  return (bps / 1e6).toFixed(2)  + ' Mbps';
    if (bps >= 1e3)  return (bps / 1e3).toFixed(1)  + ' Kbps';
    return bps + ' bps';
}

function loadChart(period) {
    _activePeriod = period;
    setActivePeriodBtn(period);
    document.getElementById('chart-loading').style.display = 'block';
    document.getElementById('chart-empty').style.display   = 'none';

    fetch(HISTORY_URL + '&interface_id=' + IFACE_ID + '&period=' + period)
        .then(r => r.json())
        .then(data => {
            document.getElementById('chart-loading').style.display = 'none';
            if (!data.labels || data.labels.length === 0) {
                document.getElementById('chart-empty').style.display = 'block';
                return;
            }
            const ctx = document.getElementById('ifaceChart').getContext('2d');
            if (_chart) { _chart.destroy(); }
            _chart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [
                        {
                            label: '↓ Entrada',
                            data: data.in_bps,
                            borderColor: '#22c55e',
                            backgroundColor: 'rgba(34,197,94,0.08)',
                            borderWidth: 2,
                            pointRadius: data.labels.length > 100 ? 0 : 3,
                            fill: true,
                            tension: 0.3,
                        },
                        {
                            label: '↑ Saída',
                            data: data.out_bps,
                            borderColor: '#ef4444',
                            backgroundColor: 'rgba(239,68,68,0.06)',
                            borderWidth: 2,
                            pointRadius: data.labels.length > 100 ? 0 : 3,
                            fill: true,
                            tension: 0.3,
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: { font: { size: 13, weight: '600' }, padding: 16 }
                        },
                        tooltip: {
                            callbacks: {
                                label: ctx => ' ' + ctx.dataset.label + ': ' + formatBps(ctx.parsed.y)
                            }
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                maxTicksLimit: 12,
                                font: { size: 11 },
                                color: '#94a3b8',
                                maxRotation: 0,
                            },
                            grid: { color: 'rgba(0,0,0,.04)' }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                font: { size: 11 },
                                color: '#94a3b8',
                                callback: v => formatBps(v)
                            },
                            grid: { color: 'rgba(0,0,0,.04)' }
                        }
                    }
                }
            });
        })
        .catch(() => {
            document.getElementById('chart-loading').style.display = 'none';
            document.getElementById('chart-empty').style.display   = 'block';
        });
}

// Auto-reload a cada 60s
loadChart('1h');
setInterval(() => loadChart(_activePeriod), 60000);
</script>

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