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

$pdo = db();

// Busca dispositivos com tráfego agregado das interfaces
$stmt = $pdo->prepare("
    SELECT d.*,
           COALESCE(SUM(ni.last_in_bps), 0)  AS total_in_bps,
           COALESCE(SUM(ni.last_out_bps), 0) AS total_out_bps
    FROM nms_devices d
    LEFT JOIN nms_interfaces ni ON ni.device_id = d.id
    WHERE d.user_id = ?
    GROUP BY d.id
    ORDER BY d.last_status ASC, d.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>

<?php
// Filtra apenas dispositivos com coordenadas
$devicesOnMap = array_filter($devices, fn($d) => $d['map_lat'] !== null && $d['map_lng'] !== null);
?>

<!-- Mapa de Dispositivos -->
<div style="background:#fff; border-radius:20px; border:1px solid #e2e8f0; box-shadow:0 4px 16px rgba(0,0,0,0.04); overflow:hidden; margin-top:24px;">
    <div style="padding:20px 32px; border-bottom:1px solid #e2e8f0; background:#f8fafc; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
        <div>
            <h2 style="margin:0; font-size:1.3rem; font-weight:800; color:#0f172a;">🗺️ Mapa de Equipamentos</h2>
            <p style="margin:4px 0 0; color:#64748b; font-size:0.85rem;">
                <?= count($devicesOnMap) ?> de <?= $total ?> equipamento<?= $total !== 1 ? 's' : '' ?> posicionado<?= count($devicesOnMap) !== 1 ? 's' : '' ?> no mapa
                <?php if (count($devicesOnMap) < $total): ?>
                    — <a href="<?= NMS_URL ?>?page=nms_device_form" style="color:#3b82f6; text-decoration:none; font-weight:600;">defina coordenadas</a> nos que faltam
                <?php endif; ?>
            </p>
        </div>
        <div style="display:flex; align-items:center; gap:16px; font-size:0.82rem; font-weight:600; color:#64748b;">
            <span style="display:inline-flex; align-items:center; gap:6px;"><span style="width:12px;height:12px;background:#22c55e;border-radius:50%;display:inline-block;border:2px solid #fff;box-shadow:0 0 0 2px #22c55e;"></span> Online</span>
            <span style="display:inline-flex; align-items:center; gap:6px;"><span style="width:12px;height:12px;background:#ef4444;border-radius:50%;display:inline-block;border:2px solid #fff;box-shadow:0 0 0 2px #ef4444;"></span> Offline</span>
            <span style="display:inline-flex; align-items:center; gap:6px;"><span style="width:12px;height:12px;background:#94a3b8;border-radius:50%;display:inline-block;border:2px solid #fff;box-shadow:0 0 0 2px #94a3b8;"></span> Desconhecido</span>
        </div>
    </div>
    <div style="padding:0;">
        <div id="devicesMap" style="height:480px; background:#e2e8f0;"></div>
    </div>
    <?php if (empty($devicesOnMap)): ?>
    <div style="padding:32px; text-align:center; color:#94a3b8;">
        <div style="font-size:2.5rem; margin-bottom:12px;">📍</div>
        <p style="font-weight:600; color:#64748b; margin:0 0 8px;">Nenhum equipamento posicionado no mapa ainda.</p>
        <p style="font-size:0.85rem; margin:0 0 16px; color:#94a3b8;">Edite um equipamento e defina sua latitude e longitude para vê-lo aqui.</p>
        <a href="<?= NMS_URL ?>?page=nms_device_form" style="display:inline-block; padding:10px 22px; background:#4f46e5; color:#fff; border-radius:10px; font-weight:700; text-decoration:none; font-size:0.9rem;">
            ➕ Cadastrar Equipamento com Localização
        </a>
    </div>
    <?php endif; ?>
</div>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
(function() {
    const mapEl = document.getElementById('devicesMap');
    if (!mapEl) return;

    const devices = <?= json_encode(array_values(array_map(function($d) {
        return [
            'id'       => (int)$d['id'],
            'name'     => $d['name'],
            'hostname' => $d['hostname'],
            'type'     => $d['type'],
            'location' => $d['location'] ?? '',
            'status'   => $d['last_status'],
            'cpu'      => $d['last_cpu'],
            'ram'      => $d['last_memory_pct'],
            'in_bps'   => (int)($d['total_in_bps'] ?? 0),
            'out_bps'  => (int)($d['total_out_bps'] ?? 0),
            'lat'      => (float)$d['map_lat'],
            'lng'      => (float)$d['map_lng'],
            'url'      => NMS_URL . '?page=nms_device_detail&id=' . (int)$d['id'],
        ];
    }, $devicesOnMap))) ?>;

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

    const colorMap = { online: '#22c55e', offline: '#ef4444', unknown: '#94a3b8' };
    const labelMap = { online: 'Online', offline: 'Offline', unknown: 'Desconhecido' };

    function makeIcon(d) {
        const color = colorMap[d.status] || '#94a3b8';
        const label = d.name.length > 14 ? d.name.slice(0, 13) + '…' : d.name;
        const inStr = fmtBps(d.in_bps);
        const outStr= fmtBps(d.out_bps);
        const html = `
        <div style="
            position:relative;display:inline-block;background:#fff;
            border:2px solid ${color};border-radius:10px;
            box-shadow:0 4px 16px rgba(0,0,0,0.18);padding:0;
            min-width:148px;font-family:system-ui,sans-serif;cursor:pointer;white-space:nowrap;">
            <div style="height:4px;background:${color};border-radius:8px 8px 0 0;"></div>
            <div style="padding:6px 10px 5px;">
                <div style="font-size:0.78rem;font-weight:800;color:#0f172a;margin-bottom:4px;">${label}</div>
                <div style="display:flex;gap:8px;align-items:center;">
                    <span style="display:inline-flex;align-items:center;gap:3px;font-size:0.7rem;font-weight:700;color:#16a34a;">
                        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="3"><path d="M12 19V5M5 12l7 7 7-7"/></svg>${inStr}
                    </span>
                    <span style="display:inline-flex;align-items:center;gap:3px;font-size:0.7rem;font-weight:700;color:#dc2626;">
                        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="3"><path d="M12 5v14M5 12l7-7 7 7"/></svg>${outStr}
                    </span>
                </div>
            </div>
            <div style="position:absolute;bottom:-10px;left:50%;transform:translateX(-50%);width:0;height:0;border-left:9px solid transparent;border-right:9px solid transparent;border-top:10px solid ${color};"></div>
            <div style="position:absolute;bottom:-7px;left:50%;transform:translateX(-50%);width:0;height:0;border-left:7px solid transparent;border-right:7px solid transparent;border-top:8px solid #fff;"></div>
        </div>`;
        return L.divIcon({ html, className:'', iconSize:[148,62], iconAnchor:[74,62], popupAnchor:[0,-66] });
    }

    // Centro inicial
    let initLat = -15.7801, initLng = -47.9292, initZoom = 5;
    if (devices.length === 1) {
        initLat = devices[0].lat; initLng = devices[0].lng; initZoom = 13;
    } else if (devices.length > 1) {
        initLat = devices.reduce((s, d) => s + d.lat, 0) / devices.length;
        initLng = devices.reduce((s, d) => s + d.lng, 0) / devices.length;
        initZoom = 6;
    }

    const map = L.map('devicesMap').setView([initLat, initLng], initZoom);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
        maxZoom: 19
    }).addTo(map);

    if (devices.length > 1) {
        const bounds = L.latLngBounds(devices.map(d => [d.lat, d.lng]));
        map.fitBounds(bounds, { padding: [48, 48] });
    }

    const typeLabels = {mikrotik:'MikroTik',cisco:'Cisco',olt:'OLT',switch:'Switch',server:'Servidor',other:'Outro'};

    devices.forEach(function(d) {
        const marker = L.marker([d.lat, d.lng], { icon: makeIcon(d) }).addTo(map);
        const statusColor = colorMap[d.status] || '#94a3b8';
        const popup = `
            <div style="min-width:220px; font-family:system-ui,sans-serif;">
                <div style="font-size:1rem; font-weight:800; color:#0f172a; margin-bottom:4px;">${d.name}</div>
                <div style="font-size:0.78rem; color:#64748b; margin-bottom:8px;">${typeLabels[d.type]||d.type}${d.location ? ' · ' + d.location : ''}</div>
                <code style="background:#ea580c; color:#fff; font-size:0.78rem; padding:3px 8px; border-radius:5px; font-weight:700;">${d.hostname}</code>
                <div style="margin-top:10px; padding:6px 10px; background:${statusColor}20; border-left:3px solid ${statusColor}; border-radius:4px;">
                    <span style="font-weight:700; color:${statusColor}; font-size:0.82rem;">● ${labelMap[d.status]||d.status}</span>
                </div>
                <div style="margin-top:10px; display:grid; grid-template-columns:1fr 1fr; gap:6px;">
                    <div style="background:#f0fdf4; border-radius:6px; padding:6px 10px; text-align:center;">
                        <div style="font-size:0.65rem; color:#64748b; font-weight:700; text-transform:uppercase;">↓ Down</div>
                        <div style="font-size:0.88rem; font-weight:800; color:#16a34a;">${fmtBps(d.in_bps)}</div>
                    </div>
                    <div style="background:#fef2f2; border-radius:6px; padding:6px 10px; text-align:center;">
                        <div style="font-size:0.65rem; color:#64748b; font-weight:700; text-transform:uppercase;">↑ Up</div>
                        <div style="font-size:0.88rem; font-weight:800; color:#dc2626;">${fmtBps(d.out_bps)}</div>
                    </div>
                    ${d.cpu !== null ? `<div style="background:#eff6ff; border-radius:6px; padding:6px 10px; text-align:center;">
                        <div style="font-size:0.65rem; color:#64748b; font-weight:700; text-transform:uppercase;">CPU</div>
                        <div style="font-size:0.88rem; font-weight:800; color:#1d4ed8;">${d.cpu}%</div>
                    </div>` : ''}
                    ${d.ram !== null ? `<div style="background:#faf5ff; border-radius:6px; padding:6px 10px; text-align:center;">
                        <div style="font-size:0.65rem; color:#64748b; font-weight:700; text-transform:uppercase;">RAM</div>
                        <div style="font-size:0.88rem; font-weight:800; color:#7c3aed;">${d.ram}%</div>
                    </div>` : ''}
                </div>
                <a href="${d.url}" style="display:block; margin-top:12px; padding:8px 12px; background:#4f46e5; color:#fff; text-align:center; border-radius:8px; font-size:0.82rem; font-weight:700; text-decoration:none;">
                    📊 Ver Detalhes
                </a>
            </div>`;
        marker.bindPopup(popup, { maxWidth: 280 });
    });
})();
</script>

<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'; ?>
