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

$filterPanel = isset($_GET['panel_id']) ? (int)$_GET['panel_id'] : 0;
$filterType  = $_GET['type'] ?? '';
$page_num    = max(1, (int)($_GET['p'] ?? 1));
$perPage     = 50;
$offset      = ($page_num - 1) * $perPage;

// Painéis do usuário (para filtro)
$panelList = $pdo->prepare("SELECT id, name FROM ubiquiti_panels WHERE user_id=? ORDER BY name ASC");
$panelList->execute([$user['id']]);
$panelOptions = $panelList->fetchAll(PDO::FETCH_ASSOC);

// Query com filtros
$where = ["a.user_id = ?"];
$params = [$user['id']];
if ($filterPanel) { $where[] = "a.panel_id = ?"; $params[] = $filterPanel; }
if ($filterType)  { $where[] = "a.type = ?";     $params[] = $filterType; }
$whereStr = implode(' AND ', $where);

$totalStmt = $pdo->prepare("SELECT COUNT(*) FROM ubiquiti_alerts a WHERE $whereStr");
$totalStmt->execute($params);
$total = (int)$totalStmt->fetchColumn();
$pages = max(1, (int)ceil($total / $perPage));

$alertStmt = $pdo->prepare("
    SELECT a.*, p.name AS panel_name, p.hostname
    FROM ubiquiti_alerts a
    JOIN ubiquiti_panels p ON p.id = a.panel_id
    WHERE $whereStr
    ORDER BY a.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$alertStmt->execute($params);
$alerts = $alertStmt->fetchAll(PDO::FETCH_ASSOC);

// Contadores por tipo
$countStmt = $pdo->prepare("
    SELECT type, severity, COUNT(*) AS cnt
    FROM ubiquiti_alerts a WHERE a.user_id = ?
    AND created_at >= NOW() - INTERVAL '24 hours'
    GROUP BY type, severity
");
$countStmt->execute([$user['id']]);
$counts = $countStmt->fetchAll(PDO::FETCH_ASSOC);
$totalAlerts24h = array_sum(array_column($counts, 'cnt'));

$typeLabels = [
    'iface_speed'    => 'Queda de Velocidade',
    'iface_down'     => 'Painel Offline',
    'iface_up'       => 'Painel Online',
    'client_drop'    => 'Queda de Clientes',
    'client_recover' => 'Recuperação de Clientes',
];
?>

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

    <!-- Breadcrumb -->
    <div style="display:flex;align-items:center;gap:8px;font-size:0.85rem;color:#64748b;">
        <a href="<?= UBNT_URL ?>?page=ubnt_panels" style="color:#1d4ed8;text-decoration:none;font-weight:600;">Painéis</a>
        <span>›</span>
        <span style="font-weight:700;color:#0f172a;">Alertas</span>
    </div>

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#7f1d1d,#991b1b);border-radius:20px;padding:28px 32px;color:#fef2f2;">
        <h1 style="margin:0 0 6px;font-size:1.7rem;font-weight:800;">Alertas Ubiquiti</h1>
        <p style="margin:0;opacity:0.8;">Últimas 24h: <strong><?= $totalAlerts24h ?></strong> alertas gerados</p>
    </div>

    <!-- Filtros -->
    <div style="background:#fff;border-radius:16px;border:1px solid #e2e8f0;padding:20px 24px;">
        <form method="GET" action="<?= UBNT_URL ?>" style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
            <input type="hidden" name="page" value="ubnt_alerts">
            <div>
                <label style="display:block;font-size:0.78rem;font-weight:600;color:#64748b;margin-bottom:4px;">Painel</label>
                <select name="panel_id" style="padding:9px 14px;border:1px solid #d1d5db;border-radius:8px;font-size:0.88rem;">
                    <option value="">Todos</option>
                    <?php foreach ($panelOptions as $opt): ?>
                        <option value="<?= $opt['id'] ?>" <?= $filterPanel == $opt['id'] ? 'selected' : '' ?>><?= h($opt['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;font-size:0.78rem;font-weight:600;color:#64748b;margin-bottom:4px;">Tipo</label>
                <select name="type" style="padding:9px 14px;border:1px solid #d1d5db;border-radius:8px;font-size:0.88rem;">
                    <option value="">Todos</option>
                    <?php foreach ($typeLabels as $k => $l): ?>
                        <option value="<?= $k ?>" <?= $filterType === $k ? 'selected' : '' ?>><?= $l ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" style="padding:9px 20px;background:#1d4ed8;color:#fff;border:none;border-radius:8px;font-weight:600;font-size:0.88rem;cursor:pointer;">Filtrar</button>
            <?php if ($filterPanel || $filterType): ?>
                <a href="<?= UBNT_URL ?>?page=ubnt_alerts" style="padding:9px 16px;border:1px solid #e2e8f0;border-radius:8px;color:#475569;text-decoration:none;font-size:0.88rem;">Limpar</a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Tabela -->
    <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;overflow:hidden;">
        <?php if (empty($alerts)): ?>
            <div style="padding:48px;text-align:center;color:#94a3b8;font-size:0.9rem;">Nenhum alerta encontrado para os filtros selecionados.</div>
        <?php else: ?>
            <div style="overflow-x:auto;">
                <table style="width:100%;border-collapse:collapse;">
                    <thead><tr style="background:#f8fafc;border-bottom:2px solid #e2e8f0;">
                        <th style="padding:14px 20px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Horário</th>
                        <th style="padding:14px 16px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Painel</th>
                        <th style="padding:14px 16px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Tipo</th>
                        <th style="padding:14px 16px;text-align:center;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Severidade</th>
                        <th style="padding:14px 16px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Detalhe</th>
                    </tr></thead>
                    <tbody>
                        <?php foreach ($alerts as $a):
                            $details   = json_decode($a['details'] ?? '{}', true) ?? [];
                            $typeLabel = $typeLabels[$a['type']] ?? $a['type'];
                            $sevColor  = $a['severity'] === 'critical' ? '#dc2626' : '#d97706';
                            $sevBg     = $a['severity'] === 'critical' ? '#fef2f2' : '#fffbeb';
                        ?>
                        <tr style="border-bottom:1px solid #f1f5f9;">
                            <td style="padding:13px 20px;font-size:0.83rem;color:#475569;white-space:nowrap;"><?= date('d/m/Y H:i', strtotime($a['created_at'])) ?></td>
                            <td style="padding:13px 16px;">
                                <a href="<?= UBNT_URL ?>?page=ubnt_panel_detail&id=<?= $a['panel_id'] ?>" style="font-weight:700;color:#0f172a;text-decoration:none;font-size:0.88rem;"><?= h($a['panel_name']) ?></a>
                                <div style="font-size:0.78rem;color:#94a3b8;"><?= h($a['hostname']) ?></div>
                            </td>
                            <td style="padding:13px 16px;font-size:0.88rem;color:#374151;"><?= h($typeLabel) ?></td>
                            <td style="padding:13px 16px;text-align:center;">
                                <span style="background:<?= $sevBg ?>;color:<?= $sevColor ?>;border:1px solid <?= $sevColor ?>30;border-radius:6px;padding:2px 10px;font-size:0.78rem;font-weight:700;text-transform:uppercase;"><?= $a['severity'] ?></span>
                            </td>
                            <td style="padding:13px 16px;font-size:0.82rem;color:#64748b;">
                                <?php
                                if (isset($details['msg'])) {
                                    echo h($details['msg']);
                                } elseif ($a['type'] === 'iface_speed') {
                                    echo h("Interface degradou de {$details['prev_speed']}M para {$details['curr_speed']}M");
                                } elseif ($a['type'] === 'client_drop') {
                                    echo h("Clientes: {$details['prev_count']} → {$details['curr_count']} (queda: {$details['drop']})");
                                } else {
                                    echo h(json_encode($details));
                                }
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Paginação -->
            <?php if ($pages > 1): ?>
                <div style="padding:16px 24px;border-top:1px solid #e2e8f0;display:flex;gap:8px;justify-content:center;flex-wrap:wrap;">
                    <?php for ($i = 1; $i <= $pages; $i++): ?>
                        <a href="?page=ubnt_alerts&panel_id=<?= $filterPanel ?>&type=<?= urlencode($filterType) ?>&p=<?= $i ?>"
                            style="display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;border-radius:8px;text-decoration:none;font-size:0.88rem;font-weight:600;
                            <?= $i === $page_num ? 'background:#1d4ed8;color:#fff;' : 'background:#f1f5f9;color:#475569;' ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>

            <div style="padding:12px 24px;background:#f8fafc;border-top:1px solid #e2e8f0;font-size:0.8rem;color:#94a3b8;">
                <?= $total ?> alerta<?= $total !== 1 ? 's' : '' ?> encontrado<?= $total !== 1 ? 's' : '' ?>
            </div>
        <?php endif; ?>
    </div>
</div>

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