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

$pdo = db();

$stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(last_status='online') as online, SUM(last_status='offline') as offline FROM nms_devices WHERE user_id=?");
$stmt->execute([$user['id']]);
$counts = $stmt->fetch();

$topIfaces = $pdo->prepare("
    SELECT ni.if_name, ni.if_alias, ni.last_in_bps, ni.last_out_bps,
           nd.name as device_name, nd.id as device_id
    FROM nms_interfaces ni
    JOIN nms_devices nd ON nd.id = ni.device_id
    WHERE nd.user_id = ? AND ni.monitored = 1
      AND (ni.last_in_bps IS NOT NULL OR ni.last_out_bps IS NOT NULL)
    ORDER BY (COALESCE(ni.last_in_bps,0) + COALESCE(ni.last_out_bps,0)) DESC
    LIMIT 5
");
$topIfaces->execute([$user['id']]);
$topBandwidth = $topIfaces->fetchAll();

$alertStmt = $pdo->prepare("SELECT * FROM nms_devices WHERE user_id=? AND last_status='offline' ORDER BY last_check_at DESC LIMIT 10");
$alertStmt->execute([$user['id']]);
$alerts = $alertStmt->fetchAll();

$allDevices = $pdo->prepare("SELECT * FROM nms_devices WHERE user_id=? ORDER BY last_status ASC, name ASC LIMIT 20");
$allDevices->execute([$user['id']]);
$devices = $allDevices->fetchAll();
?>

<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(59,130,246,0.18), transparent 70%); pointer-events:none;"></div>
        <div style="position:absolute; bottom:-30px; left:30px; width:160px; height:160px; background:radial-gradient(circle, rgba(234,88,12,0.1), 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;">📡 MikroTik NMS</p>
                <h1 style="font-size:2.2rem; font-weight:900; margin:0; color:#f8fafc;">Network Dashboard</h1>
                <p style="color:#94a3b8; margin-top:6px; font-size:0.95rem;">Monitoramento em tempo real de equipamentos, interfaces e clientes</p>
                <div style="margin-top:10px; display:inline-flex; align-items:center; gap:6px; background:rgba(255,255,255,0.07); padding:5px 12px; border-radius:20px; font-size:0.78rem; color:#94a3b8;">
                    <span style="width:7px;height:7px;border-radius:50%;background:#22c55e;display:inline-block;animation:pulse 1.5s infinite;"></span>
                    Atualizando em <strong id="refresh-counter" style="color:#f1f5f9; margin:0 2px;">30s</strong>
                </div>
                <style>@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.4}}</style>
            </div>
            <a href="<?= NMS_URL ?>?page=nms_device_form" style="text-decoration:none;">
                <button style="background:linear-gradient(135deg,#ea580c,#c2410c); color:#fff; border:none; padding:13px 26px; border-radius:12px; font-weight:700; cursor:pointer; display:inline-flex; align-items:center; gap:8px; font-size:0.95rem; box-shadow:0 4px 14px rgba(234,88,12,0.4);">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"/></svg>
                    Adicionar Equipamento
                </button>
            </a>
        </div>
    </div>

    <!-- Stats Cards -->
    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,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;"><?= (int)($counts['total'] ?? 0) ?></div>
            <div style="font-size:0.82rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:1px; margin-top:4px;">Total</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;"><?= (int)($counts['online'] ?? 0) ?></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;"><?= (int)($counts['offline'] ?? 0) ?></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>

    <div style="display:grid; grid-template-columns:2fr 1fr; gap:20px;">

        <!-- Devices -->
        <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;">
            <div style="padding:20px 24px; border-bottom:1px solid #e2e8f0; background:#f8fafc; display:flex; justify-content:space-between; align-items:center;">
                <h3 style="margin:0; font-size:1.05rem; font-weight:800; color:#0f172a;">🖥️ Equipamentos</h3>
                <a href="<?= NMS_URL ?>?page=nms_devices" style="font-size:0.85rem; color:#ea580c; text-decoration:none; font-weight:700;">Ver todos →</a>
            </div>
            <?php if (empty($devices)): ?>
                <div style="padding:40px; text-align:center; color:#94a3b8;">
                    <div style="font-size:2.5rem;">📡</div>
                    <p style="margin-top:8px; font-weight:600;">Nenhum equipamento cadastrado.</p>
                </div>
            <?php else: ?>
                <?php foreach ($devices as $dev):
                    $cpuColor = ($dev['last_cpu'] ?? 0) > 80 ? '#ef4444' : (($dev['last_cpu'] ?? 0) > 60 ? '#f59e0b' : '#22c55e');
                    $statusColor = $dev['last_status'] === 'online' ? '#22c55e' : ($dev['last_status'] === 'offline' ? '#ef4444' : '#94a3b8');
                    $detailUrl = NMS_URL . '?page=nms_device_detail&id=' . $dev['id'];
                ?>
                    <div style="padding:16px 24px; border-bottom:1px solid #f1f5f9; display:flex; justify-content:space-between; align-items:center; cursor:pointer; transition:background 0.15s;"
                        onclick="location.href='<?= $detailUrl ?>'"
                        onmouseover="this.style.background='#fff7ed'"
                        onmouseout="this.style.background='transparent'">
                        <div style="display:flex; align-items:center; gap:14px;">
                            <span style="width:12px; height:12px; border-radius:50%; background:<?= $statusColor ?>; display:inline-block; flex-shrink:0; box-shadow:0 0 6px <?= $statusColor ?>55;"></span>
                            <div>
                                <div style="font-weight:800; color:#0f172a; font-size:1rem;"><?= h($dev['name']) ?></div>
                                <code style="background:#ea580c; color:#fff; font-size:0.78rem; font-weight:700; padding:2px 8px; border-radius:5px; display:inline-block; margin-top:3px;"><?= h($dev['hostname']) ?></code>
                            </div>
                        </div>
                        <div style="display:flex; align-items:center; gap:20px;">
                            <?php if ($dev['last_cpu'] !== null): ?>
                                <div style="text-align:center;">
                                    <div style="font-size:0.68rem; color:#94a3b8; text-transform:uppercase; font-weight:600;">CPU</div>
                                    <div style="font-weight:800; color:<?= $cpuColor ?>; font-size:1.05rem;"><?= $dev['last_cpu'] ?>%</div>
                                </div>
                            <?php endif; ?>
                            <?php if ($dev['last_memory_pct'] !== null): ?>
                                <div style="text-align:center;">
                                    <div style="font-size:0.68rem; color:#94a3b8; text-transform:uppercase; font-weight:600;">RAM</div>
                                    <div style="font-weight:800; color:#64748b; font-size:1.05rem;"><?= $dev['last_memory_pct'] ?>%</div>
                                </div>
                            <?php endif; ?>
                            <div style="display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:8px; color:#ea580c; background:#fff7ed; border:1px solid #fed7aa;">
                                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7"/></svg>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Top Bandwidth -->
        <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;">
            <div style="padding:20px 24px; border-bottom:1px solid #e2e8f0; background:linear-gradient(135deg,#fff7ed,#fff);">
                <h3 style="margin:0; font-size:1.05rem; font-weight:800; color:#0f172a;">📊 Top Consumo de Banda</h3>
            </div>
            <?php if (empty($topBandwidth)): ?>
                <div style="padding:40px; text-align:center; color:#94a3b8;">
                    <div style="font-size:2rem;">📉</div>
                    <p style="margin-top:8px; font-size:0.9rem; font-weight:600;">Aguardando dados de polling...</p>
                </div>
            <?php else: ?>
                <?php foreach ($topBandwidth as $i => $iface):
                    $totalBps = ($iface['last_in_bps'] ?? 0) + ($iface['last_out_bps'] ?? 0);
                    $rankColors = ['#ea580c','#f97316','#fb923c','#fdba74','#fed7aa'];
                    $rankColor  = $rankColors[$i] ?? '#94a3b8';
                ?>
                    <div style="padding:16px 20px; border-bottom:1px solid #f1f5f9; display:flex; align-items:center; gap:14px;">
                        <div style="width:28px; height:28px; border-radius:50%; background:<?= $rankColor ?>; color:#fff; font-size:0.78rem; font-weight:900; display:flex; align-items:center; justify-content:center; flex-shrink:0;"><?= $i+1 ?></div>
                        <div style="flex:1; min-width:0;">
                            <div style="font-weight:800; font-size:0.92rem; color:#0f172a; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?= h($iface['if_alias'] ?: $iface['if_name']) ?></div>
                            <div style="font-size:0.75rem; color:#94a3b8; margin-top:2px;"><?= h($iface['device_name']) ?> · <?= h($iface['if_name']) ?></div>
                            <div style="display:flex; gap:10px; margin-top:5px;">
                                <span style="font-size:0.82rem; font-weight:700; color:#22c55e;">↓ <?= format_bps((int)($iface['last_in_bps'] ?? 0)) ?></span>
                                <span style="font-size:0.82rem; font-weight:700; color:#ef4444;">↑ <?= format_bps((int)($iface['last_out_bps'] ?? 0)) ?></span>
                            </div>
                        </div>
                        <div style="font-size:1rem; font-weight:900; color:<?= $rankColor ?>; white-space:nowrap;"><?= format_bps((int)$totalBps) ?></div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Alertas -->
    <?php if (!empty($alerts)): ?>
        <div style="background:#fff; border-radius:16px; border:2px solid #fecaca; overflow:hidden;">
            <div style="padding:16px 24px; border-bottom:1px solid #fecaca; background:#fef2f2; display:flex; align-items:center; gap:10px;">
                <span style="width:10px; height:10px; border-radius:50%; background:#ef4444; display:inline-block; box-shadow:0 0 8px #ef4444;"></span>
                <h3 style="margin:0; font-size:1rem; font-weight:800; color:#991b1b;">Equipamentos com Falha (<?= count($alerts) ?>)</h3>
            </div>
            <?php foreach ($alerts as $dev): ?>
                <div style="padding:14px 24px; border-bottom:1px solid #fef2f2; display:flex; justify-content:space-between; align-items:center; cursor:pointer; transition:background 0.15s;"
                    onclick="location.href='<?= NMS_URL ?>?page=nms_device_detail&id=<?= $dev['id'] ?>'"
                    onmouseover="this.style.background='#fef2f2'"
                    onmouseout="this.style.background='transparent'">
                    <div style="display:flex; align-items:center; gap:12px;">
                        <svg width="16" height="16" fill="none" stroke="#ef4444" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                        <div>
                            <strong style="color:#0f172a; font-size:0.95rem;"><?= h($dev['name']) ?></strong>
                            <code style="margin-left:8px; background:#ea580c; color:#fff; font-size:0.75rem; font-weight:700; padding:2px 8px; border-radius:5px;"><?= h($dev['hostname']) ?></code>
                        </div>
                    </div>
                    <div style="font-size:0.82rem; color:#94a3b8; font-weight:600;">
                        Último check: <?= $dev['last_check_at'] ? (new DateTimeImmutable($dev['last_check_at']))->format('d/m H:i:s') : '—' ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

</div>

<script>
(function() {
    var seconds = 30;
    var el = document.getElementById('refresh-counter');
    var interval = setInterval(function() {
        seconds--;
        if (el) el.textContent = seconds + 's';
        if (seconds <= 0) { clearInterval(interval); location.reload(); }
    }, 1000);
})();
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
