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

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

$total   = count($devices);
$online  = count(array_filter($devices, fn($d) => $d['last_status'] === 'online'));
$offline = count(array_filter($devices, fn($d) => $d['last_status'] === 'offline'));
?>

<div style="background:#fff; border-radius:20px; border:1px solid #e2e8f0; box-shadow:0 4px 16px rgba(0,0,0,0.04); overflow:hidden;">
    <div style="padding:24px 32px; border-bottom:1px solid #e2e8f0; background:#f8fafc; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;">
        <div>
            <h2 style="margin:0; font-size:1.6rem; font-weight:800; color:#0f172a;">🖥️ Equipamentos NMS</h2>
            <p style="margin:4px 0 0; color:#64748b; font-size:0.9rem;"><?= $total ?> equipamento<?= $total !== 1 ? 's' : '' ?> cadastrado<?= $total !== 1 ? 's' : '' ?></p>
        </div>
        <a href="<?= NMS_URL ?>?page=nms_device_form" style="text-decoration:none;">
            <button style="display:inline-flex; align-items:center; gap:8px; padding:12px 24px; border-radius:12px; font-weight:700; cursor:pointer; font-size:1rem;">
                <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>
                Novo Equipamento
            </button>
        </a>
    </div>

    <div style="padding:24px 32px;">
        <!-- Counters -->
        <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:12px; margin-bottom:24px;">
            <div style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:12px; padding:14px 18px; text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#16a34a;"><?= $online ?></div>
                <div style="font-size:0.8rem; font-weight:600; color:#166534; text-transform:uppercase;">Online</div>
            </div>
            <div style="background:#fef2f2; border:1px solid #fecaca; border-radius:12px; padding:14px 18px; text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#dc2626;"><?= $offline ?></div>
                <div style="font-size:0.8rem; font-weight:600; color:#991b1b; text-transform:uppercase;">Offline</div>
            </div>
            <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:12px; padding:14px 18px; text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#64748b;"><?= $total ?></div>
                <div style="font-size:0.8rem; font-weight:600; color:#475569; text-transform:uppercase;">Total</div>
            </div>
        </div>

        <!-- Search -->
        <div style="position:relative; margin-bottom:20px;">
            <svg width="20" height="20" fill="none" stroke="#94a3b8" viewBox="0 0 24 24" style="position:absolute; left:14px; top:50%; transform:translateY(-50%); pointer-events:none;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
            <input type="text" id="devSearchBox" placeholder="Buscar por nome, IP ou tipo..."
                style="width:100%; padding:14px 16px 14px 44px; border:1px solid #cbd5e1; border-radius:12px; font-size:1rem; font-family:inherit; outline:none; transition:border-color 0.2s;"
                onfocus="this.style.borderColor='#3b82f6'"
                onblur="this.style.borderColor='#cbd5e1'">
            <span id="devSearchCount" style="position:absolute; right:14px; top:50%; transform:translateY(-50%); font-size:0.8rem; color:#94a3b8; font-weight:600;"></span>
        </div>

        <!-- No results -->
        <div id="devNoResults" style="display:none; text-align:center; padding:40px 0; color:#94a3b8;">
            <div style="font-size:2rem;">🔍</div>
            <p style="font-weight:600; margin-top:8px;">Nenhum equipamento encontrado.</p>
        </div>

        <!-- Table -->
        <div id="devTableWrapper" style="overflow-x:auto; border-radius:12px; border:1px solid #e2e8f0;">
            <table style="width:100%; border-collapse:collapse; font-size:0.92rem;">
                <thead>
                    <tr style="background:#f8fafc;">
                        <th style="padding:14px 16px; text-align:left; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #e2e8f0;">Nome</th>
                        <th style="padding:14px 16px; text-align:left; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #e2e8f0;">Host</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Tipo</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Status</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">CPU</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">RAM</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Uptime</th>
                        <th style="padding:14px 16px; text-align:right; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Ações</th>
                    </tr>
                </thead>
                <tbody id="devTableBody">
                    <?php foreach ($devices as $dev):
                        $search = strtolower($dev['name'] . ' ' . $dev['hostname'] . ' ' . $dev['type'] . ' ' . $dev['last_status']);
                        $cpuColor = ($dev['last_cpu'] ?? 0) > 80 ? '#ef4444' : (($dev['last_cpu'] ?? 0) > 60 ? '#f59e0b' : '#22c55e');
                        $typeLabels = ['mikrotik'=>'MikroTik','olt'=>'OLT','switch'=>'Switch','server'=>'Servidor','other'=>'Outro'];
                    ?>
                    <?php $detailUrl = NMS_URL . '?page=nms_device_detail&id=' . $dev['id']; ?>
                    <tr class="dev-row" data-search="<?= h($search) ?>" style="border-bottom:1px solid #f1f5f9; transition:background 0.15s; cursor:pointer;" onclick="location.href='<?= $detailUrl ?>'" onmouseover="this.style.background='#fff7ed'" onmouseout="this.style.background='transparent'">
                        <td style="padding:14px 16px; font-weight:700; color:#0f172a;">
                            <?= h($dev['name']) ?>
                            <?php if ($dev['location']): ?><div style="font-size:0.75rem; color:#94a3b8; font-weight:400;"><?= h($dev['location']) ?></div><?php endif; ?>
                        </td>
                        <td style="padding:14px 16px;" onclick="location.href='<?= $detailUrl ?>'; event.stopPropagation();">
                            <a href="<?= $detailUrl ?>" style="text-decoration:none;" onclick="event.stopPropagation();">
                                <code style="background:#ea580c; padding:6px 14px; border-radius:8px; font-size:0.95rem; color:#fff; font-weight:800; border:2px solid #c2410c; letter-spacing:0.5px; display:inline-block;"><?= h($dev['hostname']) ?></code>
                            </a>
                        </td>
                        <td style="padding:14px 16px; text-align:center;">
                            <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 16px; text-align:center;">
                            <?php if ($dev['last_status'] === 'online'): ?>
                                <span style="background:#dcfce7; color:#166534; padding:5px 14px; border-radius:20px; font-weight:700; font-size:0.8rem; border:1px solid #bbf7d0; display:inline-flex; align-items:center; gap:6px;">
                                    <span style="width:8px;height:8px;border-radius:50%;background:#22c55e;display:inline-block;"></span> Online
                                </span>
                            <?php elseif ($dev['last_status'] === 'offline'): ?>
                                <span style="background:#fee2e2; color:#991b1b; padding:5px 14px; border-radius:20px; font-weight:700; font-size:0.8rem; border:1px solid #fecaca; display:inline-flex; align-items:center; gap:6px;">
                                    <span style="width:8px;height:8px;border-radius:50%;background:#ef4444;display:inline-block;"></span> Offline
                                </span>
                            <?php else: ?>
                                <span style="background:#f1f5f9; color:#64748b; padding:5px 14px; border-radius:20px; font-weight:700; font-size:0.8rem; border:1px solid #e2e8f0;">Desconhecido</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:14px 16px; text-align:center; font-weight:700; color:<?= $cpuColor ?>;"><?= $dev['last_cpu'] !== null ? $dev['last_cpu'].'%' : '—' ?></td>
                        <td style="padding:14px 16px; text-align:center; font-weight:700; color:#64748b;"><?= $dev['last_memory_pct'] !== null ? $dev['last_memory_pct'].'%' : '—' ?></td>
                        <td style="padding:14px 16px; text-align:center; color:#64748b; font-size:0.85rem;"><?= $dev['uptime_seconds'] !== null ? format_uptime((int)$dev['uptime_seconds']) : '—' ?></td>
                        <td style="padding:14px 16px; text-align:right; white-space:nowrap;" onclick="event.stopPropagation();">
                            <a href="<?= NMS_URL ?>?page=nms_device_form&id=<?= $dev['id'] ?>" onclick="event.stopPropagation();" style="display:inline-flex; align-items:center; gap:6px; padding:8px 14px; border-radius:10px; color:#8b5cf6; background:#f5f3ff; text-decoration:none; border:1px solid transparent; transition:0.2s; font-size:0.82rem; font-weight:700;" onmouseover="this.style.borderColor='#c4b5fd'" onmouseout="this.style.borderColor='transparent'">
                                <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                Editar
                            </a>
                            <form method="post" action="<?= NMS_URL ?>?page=nms_devices" style="display:inline;" onsubmit="return confirm('Remover este equipamento e todos os dados?');" onclick="event.stopPropagation();">
                                <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
                                <input type="hidden" name="action" value="delete_device">
                                <input type="hidden" name="id" value="<?= (int)$dev['id'] ?>">
                                <button type="submit" style="display:inline-flex; align-items:center; gap:6px; padding:8px 14px; border-radius:10px; color:#ef4444; background:#fef2f2; border:1px solid transparent; cursor:pointer; margin-left:6px; transition:0.2s; font-size:0.82rem; font-weight:700; font-family:inherit;" onmouseover="this.style.borderColor='#fca5a5'" onmouseout="this.style.borderColor='transparent'">
                                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                    Remover
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($devices)): ?>
            <div style="text-align:center; padding:48px 0; color:#94a3b8;">
                <div style="font-size:3rem;">📡</div>
                <p style="font-size:1.1rem; font-weight:600; color:#64748b; margin-top:12px;">Nenhum equipamento cadastrado.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
(function() {
    const box = document.getElementById('devSearchBox');
    const rows = document.querySelectorAll('.dev-row');
    const noRes = document.getElementById('devNoResults');
    const wrap = document.getElementById('devTableWrapper');
    const cnt = document.getElementById('devSearchCount');
    if (!box) return;
    box.addEventListener('input', function() {
        const q = this.value.trim().toLowerCase();
        let vis = 0;
        rows.forEach(r => {
            const match = !q || (r.dataset.search||'').includes(q);
            r.style.display = match ? '' : 'none';
            if (match) vis++;
        });
        cnt.textContent = q ? vis+' de '+rows.length : '';
        noRes.style.display = (q && vis===0) ? 'block' : 'none';
        wrap.style.display  = (q && vis===0) ? 'none'  : '';
    });
})();
</script>

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