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

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

// Devices offline
$offlineStmt = $pdo->prepare("
    SELECT * FROM nms_devices
    WHERE user_id=? AND last_status='offline' AND active = TRUE
    ORDER BY last_check_at ASC
");
$offlineStmt->execute([$user['id']]);
$offlineDevices = $offlineStmt->fetchAll();

// Devices com CPU alta (>80%)
$cpuStmt = $pdo->prepare("
    SELECT * FROM nms_devices
    WHERE user_id=? AND last_status='online' AND last_cpu > 80 AND active = TRUE
    ORDER BY last_cpu DESC
");
$cpuStmt->execute([$user['id']]);
$highCpuDevices = $cpuStmt->fetchAll();

// Devices com RAM alta (>85%)
$ramStmt = $pdo->prepare("
    SELECT * FROM nms_devices
    WHERE user_id=? AND last_status='online' AND last_memory_pct > 85 AND active = TRUE
    ORDER BY last_memory_pct DESC
");
$ramStmt->execute([$user['id']]);
$highRamDevices = $ramStmt->fetchAll();

// Histórico de eventos offline (últimas 72h)
$histStmt = $pdo->prepare("
    SELECT dm.recorded_at, nd.name, nd.hostname, dm.cpu_pct, dm.memory_pct
    FROM nms_device_metrics dm
    JOIN nms_devices nd ON nd.id = dm.device_id
    WHERE nd.user_id=? AND dm.recorded_at >= NOW() - INTERVAL '72 hours'
    ORDER BY dm.recorded_at DESC
    LIMIT 100
");
$histStmt->execute([$user['id']]);
$recentMetrics = $histStmt->fetchAll();

$totalAlerts = count($offlineDevices) + count($highCpuDevices) + count($highRamDevices);
?>

<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="<?= NMS_URL ?>?page=nms_dashboard" style="color:#3b82f6; text-decoration:none; font-weight:600;">NMS</a>
        <span>›</span>
        <span style="color:#0f172a; font-weight:700;">Alertas</span>
    </div>

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#7f1d1d,#991b1b); border-radius:20px; padding:28px 32px; color:#fef2f2; position:relative; overflow:hidden;">
        <div style="position:absolute; top:-40px; right:-40px; width:200px; height:200px; background:radial-gradient(circle, rgba(239,68,68,0.2), transparent 70%); pointer-events:none;"></div>
        <div style="position:relative;">
            <p style="color:#fca5a5; font-size:0.8rem; text-transform:uppercase; letter-spacing:2px; margin-bottom:6px; font-weight:700;">🔔 Central de Alertas NMS</p>
            <h1 style="font-size:1.7rem; font-weight:900; margin:0; color:#fff;">Alertas Ativos</h1>
            <p style="margin:6px 0 0; color:#fca5a5; font-size:0.9rem;">
                <?= $totalAlerts ?> alerta<?= $totalAlerts !== 1 ? 's' : '' ?> ativo<?= $totalAlerts !== 1 ? 's' : '' ?> no momento
            </p>
        </div>
    </div>

    <!-- Counters -->
    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:14px;">
        <div style="background:#fef2f2; border:1px solid #fecaca; border-radius:14px; padding:18px 20px; text-align:center;">
            <div style="font-size:2rem; font-weight:900; color:#dc2626;"><?= count($offlineDevices) ?></div>
            <div style="font-size:0.8rem; font-weight:700; color:#991b1b; text-transform:uppercase; margin-top:4px;">Offline</div>
        </div>
        <div style="background:#fffbeb; border:1px solid #fde68a; border-radius:14px; padding:18px 20px; text-align:center;">
            <div style="font-size:2rem; font-weight:900; color:#d97706;"><?= count($highCpuDevices) ?></div>
            <div style="font-size:0.8rem; font-weight:700; color:#92400e; text-transform:uppercase; margin-top:4px;">CPU Alta</div>
        </div>
        <div style="background:#fff7ed; border:1px solid #fed7aa; border-radius:14px; padding:18px 20px; text-align:center;">
            <div style="font-size:2rem; font-weight:900; color:#ea580c;"><?= count($highRamDevices) ?></div>
            <div style="font-size:0.8rem; font-weight:700; color:#9a3412; text-transform:uppercase; margin-top:4px;">RAM Alta</div>
        </div>
        <?php if ($totalAlerts === 0): ?>
        <div style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:14px; padding:18px 20px; text-align:center;">
            <div style="font-size:2rem;">✅</div>
            <div style="font-size:0.85rem; font-weight:700; color:#166534; margin-top:4px;">Tudo Normal</div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Devices Offline -->
    <div style="background:#fff; border-radius:16px; border:1px solid <?= empty($offlineDevices) ? '#e2e8f0' : '#fecaca' ?>; overflow:hidden;">
        <div style="padding:18px 24px; border-bottom:1px solid <?= empty($offlineDevices) ? '#e2e8f0' : '#fecaca' ?>; background:<?= empty($offlineDevices) ? '#f8fafc' : '#fef2f2' ?>; display:flex; align-items:center; gap:10px;">
            <span style="font-size:1.2rem;"><?= empty($offlineDevices) ? '✅' : '🔴' ?></span>
            <h3 style="margin:0; font-size:1rem; font-weight:700; color:<?= empty($offlineDevices) ? '#0f172a' : '#991b1b' ?>;">
                Equipamentos Offline
                <?php if (!empty($offlineDevices)): ?>
                    <span style="background:#ef4444; color:#fff; font-size:0.75rem; padding:2px 8px; border-radius:20px; margin-left:8px;"><?= count($offlineDevices) ?></span>
                <?php endif; ?>
            </h3>
        </div>
        <?php if (empty($offlineDevices)): ?>
            <div style="padding:28px; text-align:center; color:#94a3b8;">
                <p style="font-weight:600;">Nenhum equipamento offline. ✅</p>
            </div>
        <?php else: ?>
            <div style="overflow-x:auto;">
                <table style="width:100%; border-collapse:collapse; font-size:0.9rem;">
                    <thead>
                        <tr style="background:#fef2f2;">
                            <th style="padding:12px 20px; text-align:left; font-weight:700; color:#991b1b; font-size:0.75rem; text-transform:uppercase; border-bottom:1px solid #fecaca;">Equipamento</th>
                            <th style="padding:12px 20px; text-align:left; font-weight:700; color:#991b1b; font-size:0.75rem; text-transform:uppercase; border-bottom:1px solid #fecaca;">Host</th>
                            <th style="padding:12px 20px; text-align:left; font-weight:700; color:#991b1b; font-size:0.75rem; text-transform:uppercase; border-bottom:1px solid #fecaca;">Tipo</th>
                            <th style="padding:12px 20px; text-align:center; font-weight:700; color:#991b1b; font-size:0.75rem; text-transform:uppercase; border-bottom:1px solid #fecaca;">Último Check</th>
                            <th style="padding:12px 20px; text-align:center; font-weight:700; color:#991b1b; font-size:0.75rem; text-transform:uppercase; border-bottom:1px solid #fecaca;">Ação</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($offlineDevices as $dev):
                            $typeLabels = ['mikrotik'=>'MikroTik','olt'=>'OLT','switch'=>'Switch','server'=>'Servidor','other'=>'Outro'];
                            $lastCheck = $dev['last_check_at'] ? (new DateTimeImmutable($dev['last_check_at'])) : null;
                            $diffSec = $lastCheck ? (time() - $lastCheck->getTimestamp()) : null;
                            $diffStr = $diffSec !== null ? ($diffSec < 3600 ? round($diffSec/60).'min atrás' : round($diffSec/3600).'h atrás') : '—';
                        ?>
                        <tr style="border-bottom:1px solid #fef2f2; transition:background 0.15s;" onmouseover="this.style.background='#fef9f9'" onmouseout="this.style.background='transparent'">
                            <td style="padding:14px 20px;">
                                <div style="display:flex; align-items:center; gap:8px;">
                                    <span style="width:10px; height:10px; border-radius:50%; background:#ef4444; display:inline-block; animation:pulse-alert 1.5s infinite;"></span>
                                    <strong style="color:#0f172a;"><?= h($dev['name']) ?></strong>
                                </div>
                                <?php if ($dev['location']): ?><div style="font-size:0.75rem; color:#94a3b8; padding-left:18px;">📍 <?= h($dev['location']) ?></div><?php endif; ?>
                            </td>
                            <td style="padding:14px 20px;">
                                <code style="background:#fff7ed; color:#ea580c; padding:4px 10px; border-radius:6px; font-size:0.85rem; border:1px solid #fed7aa; font-weight:700;"><?= h($dev['hostname']) ?></code>
                            </td>
                            <td style="padding:14px 20px;">
                                <span style="background:#eff6ff; color:#1d4ed8; padding:4px 12px; border-radius:20px; font-size:0.75rem; font-weight:700;"><?= $typeLabels[$dev['type']] ?? $dev['type'] ?></span>
                            </td>
                            <td style="padding:14px 20px; text-align:center;">
                                <div style="font-size:0.9rem; font-weight:700; color:#dc2626;"><?= $diffStr ?></div>
                                <div style="font-size:0.75rem; color:#94a3b8;"><?= $lastCheck ? $lastCheck->setTimezone($userTz)->format('d/m H:i:s') : '—' ?></div>
                            </td>
                            <td style="padding:14px 20px; text-align:center;">
                                <a href="<?= NMS_URL ?>?page=nms_device_detail&id=<?= $dev['id'] ?>" style="display:inline-flex; align-items:center; gap:6px; padding:8px 14px; background:#eff6ff; color:#3b82f6; border-radius:8px; font-size:0.82rem; font-weight:700; text-decoration:none;">
                                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
                                    Detalhes
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <!-- CPU Alta -->
    <div style="background:#fff; border-radius:16px; border:1px solid <?= empty($highCpuDevices) ? '#e2e8f0' : '#fde68a' ?>; overflow:hidden;">
        <div style="padding:18px 24px; border-bottom:1px solid <?= empty($highCpuDevices) ? '#e2e8f0' : '#fde68a' ?>; background:<?= empty($highCpuDevices) ? '#f8fafc' : '#fffbeb' ?>; display:flex; align-items:center; gap:10px;">
            <span style="font-size:1.2rem;"><?= empty($highCpuDevices) ? '✅' : '⚠️' ?></span>
            <h3 style="margin:0; font-size:1rem; font-weight:700; color:<?= empty($highCpuDevices) ? '#0f172a' : '#92400e' ?>;">
                CPU Elevada (&gt;80%)
                <?php if (!empty($highCpuDevices)): ?>
                    <span style="background:#f59e0b; color:#fff; font-size:0.75rem; padding:2px 8px; border-radius:20px; margin-left:8px;"><?= count($highCpuDevices) ?></span>
                <?php endif; ?>
            </h3>
        </div>
        <?php if (empty($highCpuDevices)): ?>
            <div style="padding:28px; text-align:center; color:#94a3b8;"><p style="font-weight:600;">Nenhum equipamento com CPU elevada. ✅</p></div>
        <?php else: ?>
            <?php foreach ($highCpuDevices as $dev):
                $cpuPct = (int)$dev['last_cpu'];
                $barColor = $cpuPct >= 95 ? '#ef4444' : ($cpuPct >= 90 ? '#f97316' : '#f59e0b');
            ?>
            <div style="padding:16px 24px; border-bottom:1px solid #fffbeb; display:flex; justify-content:space-between; align-items:center; gap:16px; transition:background 0.15s;" onmouseover="this.style.background='#fefce8'" onmouseout="this.style.background='transparent'">
                <div style="flex:1;">
                    <div style="display:flex; align-items:center; gap:8px; margin-bottom:6px;">
                        <strong style="color:#0f172a;"><?= h($dev['name']) ?></strong>
                        <code style="background:#fff7ed; color:#ea580c; padding:2px 8px; border-radius:6px; font-size:0.8rem; border:1px solid #fed7aa; font-weight:700;"><?= h($dev['hostname']) ?></code>
                    </div>
                    <div style="display:flex; align-items:center; gap:8px;">
                        <div style="flex:1; background:#e2e8f0; border-radius:4px; height:8px; max-width:200px;">
                            <div style="width:<?= $cpuPct ?>%; background:<?= $barColor ?>; height:100%; border-radius:4px; transition:width 0.5s;"></div>
                        </div>
                        <span style="font-size:0.8rem; color:#64748b;">RAM: <?= $dev['last_memory_pct'] !== null ? $dev['last_memory_pct'].'%' : '—' ?></span>
                    </div>
                </div>
                <div style="text-align:right; flex-shrink:0;">
                    <div style="font-size:2rem; font-weight:900; color:<?= $barColor ?>; line-height:1;"><?= $cpuPct ?>%</div>
                    <div style="font-size:0.7rem; color:#94a3b8; text-transform:uppercase; letter-spacing:0.5px;">CPU</div>
                </div>
                <a href="<?= NMS_URL ?>?page=nms_device_detail&id=<?= $dev['id'] ?>" style="display:inline-flex; align-items:center; justify-content:center; width:36px; height:36px; background:#eff6ff; color:#3b82f6; border-radius:8px; text-decoration:none; flex-shrink:0;">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                </a>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- RAM Alta -->
    <div style="background:#fff; border-radius:16px; border:1px solid <?= empty($highRamDevices) ? '#e2e8f0' : '#fed7aa' ?>; overflow:hidden;">
        <div style="padding:18px 24px; border-bottom:1px solid <?= empty($highRamDevices) ? '#e2e8f0' : '#fed7aa' ?>; background:<?= empty($highRamDevices) ? '#f8fafc' : '#fff7ed' ?>; display:flex; align-items:center; gap:10px;">
            <span style="font-size:1.2rem;"><?= empty($highRamDevices) ? '✅' : '🟠' ?></span>
            <h3 style="margin:0; font-size:1rem; font-weight:700; color:<?= empty($highRamDevices) ? '#0f172a' : '#9a3412' ?>;">
                RAM Elevada (&gt;85%)
                <?php if (!empty($highRamDevices)): ?>
                    <span style="background:#ea580c; color:#fff; font-size:0.75rem; padding:2px 8px; border-radius:20px; margin-left:8px;"><?= count($highRamDevices) ?></span>
                <?php endif; ?>
            </h3>
        </div>
        <?php if (empty($highRamDevices)): ?>
            <div style="padding:28px; text-align:center; color:#94a3b8;"><p style="font-weight:600;">Nenhum equipamento com RAM elevada. ✅</p></div>
        <?php else: ?>
            <?php foreach ($highRamDevices as $dev):
                $ramPct = (int)$dev['last_memory_pct'];
                $barColor = $ramPct >= 95 ? '#ef4444' : ($ramPct >= 90 ? '#f97316' : '#ea580c');
            ?>
            <div style="padding:16px 24px; border-bottom:1px solid #fff7ed; display:flex; justify-content:space-between; align-items:center; gap:16px; transition:background 0.15s;" onmouseover="this.style.background='#fff7ed'" onmouseout="this.style.background='transparent'">
                <div style="flex:1;">
                    <div style="display:flex; align-items:center; gap:8px; margin-bottom:6px;">
                        <strong style="color:#0f172a;"><?= h($dev['name']) ?></strong>
                        <code style="background:#fff7ed; color:#ea580c; padding:2px 8px; border-radius:6px; font-size:0.8rem; border:1px solid #fed7aa; font-weight:700;"><?= h($dev['hostname']) ?></code>
                    </div>
                    <div style="display:flex; align-items:center; gap:8px;">
                        <div style="flex:1; background:#e2e8f0; border-radius:4px; height:8px; max-width:200px;">
                            <div style="width:<?= $ramPct ?>%; background:<?= $barColor ?>; height:100%; border-radius:4px;"></div>
                        </div>
                        <span style="font-size:0.8rem; color:#64748b;">CPU: <?= $dev['last_cpu'] !== null ? $dev['last_cpu'].'%' : '—' ?></span>
                    </div>
                </div>
                <div style="text-align:right; flex-shrink:0;">
                    <div style="font-size:2rem; font-weight:900; color:<?= $barColor ?>; line-height:1;"><?= $ramPct ?>%</div>
                    <div style="font-size:0.7rem; color:#94a3b8; text-transform:uppercase; letter-spacing:0.5px;">RAM</div>
                </div>
                <a href="<?= NMS_URL ?>?page=nms_device_detail&id=<?= $dev['id'] ?>" style="display:inline-flex; align-items:center; justify-content:center; width:36px; height:36px; background:#eff6ff; color:#3b82f6; border-radius:8px; text-decoration:none; flex-shrink:0;">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                </a>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Gráfico histórico de métricas (últimas 24h) -->
    <?php if (!empty($recentMetrics)): ?>
    <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; padding:24px;">
        <h3 style="margin:0 0 16px; font-size:1rem; font-weight:700; color:#0f172a;">📈 Histórico de Recursos — Últimas 72h</h3>
        <?php
        // Agrupar por device para o gráfico
        $byDevice = [];
        foreach ($recentMetrics as $m) {
            $key = $m['name'];
            if (!isset($byDevice[$key])) $byDevice[$key] = ['labels'=>[], 'cpu'=>[], 'ram'=>[]];
            $byDevice[$key]['labels'][] = (new DateTimeImmutable($m['recorded_at']))->setTimezone($userTz)->format('d/m H:i');
            $byDevice[$key]['cpu'][]    = $m['cpu_pct'];
            $byDevice[$key]['ram'][]    = $m['memory_pct'];
        }
        $colors = ['#3b82f6','#8b5cf6','#22c55e','#f59e0b','#ef4444','#06b6d4','#ec4899'];
        $colorIdx = 0;
        ?>
        <canvas id="alertMetricsChart" style="max-height:240px;"></canvas>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const datasets = [];
            <?php foreach ($byDevice as $devName => $data): $c = $colors[$colorIdx++ % count($colors)]; ?>
            datasets.push(
                { label: '<?= addslashes($devName) ?> CPU%', data: <?= json_encode($data['cpu']) ?>,
                  borderColor: '<?= $c ?>', backgroundColor: 'transparent', tension: 0.4, pointRadius: 0,
                  borderDash: [] },
                { label: '<?= addslashes($devName) ?> RAM%', data: <?= json_encode($data['ram']) ?>,
                  borderColor: '<?= $c ?>', backgroundColor: 'transparent', tension: 0.4, pointRadius: 0,
                  borderDash: [5,3], borderWidth: 1.5 }
            );
            <?php endforeach; ?>
            new Chart(document.getElementById('alertMetricsChart').getContext('2d'), {
                type: 'line',
                data: { labels: <?= json_encode(array_map(fn($m) => (new DateTimeImmutable($m['recorded_at']))->setTimezone($userTz)->format('d/m H:i'), $recentMetrics)) ?>, datasets },
                options: { responsive: true, interaction: { mode: 'index' }, plugins: { legend: { position: 'top', labels: { boxWidth: 14 } } },
                    scales: { y: { min: 0, max: 100, ticks: { callback: v => v+'%' } } } }
            });
        });
        </script>
        <div style="margin-top:10px; font-size:0.75rem; color:#94a3b8;">— linha contínua = CPU · - - linha tracejada = RAM</div>
    </div>
    <?php endif; ?>

</div>

<style>
@keyframes pulse-alert {
    0%, 100% { opacity: 1; transform: scale(1); }
    50% { opacity: 0.5; transform: scale(1.2); }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
