<?php
// monito.php - VERSÃO LISTA HORIZONTAL
date_default_timezone_set('America/Sao_Paulo');

// Caminho dos bancos
$ping_db = __DIR__ . '/a/ping/ping.db';
$eggzie_db = __DIR__ . '/a/.eggziedb.db';

// ============================================
// FUNÇÃO PARA BUSCAR NOME DO CLIENTE
// ============================================
function getClientName($mac, $eggzie_db) {
    if (!file_exists($eggzie_db)) return null;
    try {
        $db = new SQLite3($eggzie_db);
        $mac_clean = strtolower(str_replace(':', '', $mac));
        $stmt = $db->prepare("SELECT title, username, extra FROM ibo WHERE 
                  LOWER(REPLACE(mac_address, ':', '')) = :mac 
                  OR LOWER(mac_address) LIKE :mac_like LIMIT 1");
        $stmt->bindValue(':mac', $mac_clean, SQLITE3_TEXT);
        $stmt->bindValue(':mac_like', "%$mac_clean%", SQLITE3_TEXT);
        $result = $stmt->execute();
        if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $db->close();
            return !empty($row['title']) ? $row['title'] : (!empty($row['username']) ? "Usuário " . $row['username'] : "Cliente " . $mac);
        }
        $db->close();
        return null;
    } catch (Exception $e) { return null; }
}

// Continuar com o código normal...
$now = time();
if (!file_exists($ping_db)) {
    die("❌ Banco de pings não encontrado!");
}

// Processar filtro por status
$filter = $_GET['filter'] ?? 'all';

include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>👑 EON SYSTEM | Client Monitor</title>
    <meta http-equiv="refresh" content="10">
    
    <!-- Fonts & Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;700;900&family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #00ff9d;
            --primary-glow: rgba(0, 255, 157, 0.5);
            --secondary: #7700ff;
            --danger: #ff0055;
            --warning: #ffaa00;
            --info: #00d4ff;
            --bg-dark: #0a0a0f;
            --bg-card: rgba(10, 15, 25, 0.9);
            --bg-gradient: linear-gradient(135deg, #0a0a0f 0%, #151522 100%);
            --text: #ffffff;
            --text-muted: #8899aa;
            --border: rgba(0, 255, 157, 0.2);
            --glow: 0 0 20px var(--primary-glow);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Montserrat', sans-serif;
            background: var(--bg-gradient);
            color: var(--text);
            min-height: 100vh;
            overflow-x: hidden;
            position: relative;
        }
        
        /* Background effects */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 20% 30%, rgba(119, 0, 255, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 70%, rgba(0, 255, 157, 0.1) 0%, transparent 50%);
            z-index: -1;
        }
        
        .grid-lines {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: 
                linear-gradient(rgba(0, 255, 157, 0.05) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 255, 157, 0.05) 1px, transparent 1px);
            background-size: 50px 50px;
            z-index: -1;
        }
        
        .container {
            max-width: 1800px;
            margin: 0 auto;
            padding: 20px;
            position: relative;
            z-index: 1;
        }
        
        /* Header */
        .header {
            text-align: center;
            margin-bottom: 40px;
            padding: 30px;
            background: var(--bg-card);
            border-radius: 20px;
            border: 1px solid var(--border);
            box-shadow: var(--glow);
            backdrop-filter: blur(10px);
            box-shadow: 0 0 20px rgba(0, 255, 157, 0.3);
        }
        
        .title {
            font-family: 'Orbitron', sans-serif;
            font-size: 3rem;
            font-weight: 900;
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 2px;
        }
        
        .subtitle {
            color: var(--text-muted);
            font-size: 1.2rem;
            font-weight: 300;
        }
        
        /* Warning Box */
        .warning-box {
            background: rgba(255, 0, 85, 0.1);
            border: 1px solid var(--danger);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 30px;
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            gap: 15px;
            box-shadow: 0 0 15px rgba(255, 0, 85, 0.2);
        }
        
        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 25px;
            border: 1px solid var(--border);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(10px);
            cursor: pointer;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(0, 255, 157, 0.1), transparent);
            transition: 0.5s;
        }
        
        .stat-card:hover::before {
            left: 100%;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--glow);
        }
        
        .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 15px;
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .stat-number {
            font-family: 'Orbitron', sans-serif;
            font-size: 2.8rem;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .stat-total { color: var(--info); }
        .stat-online { color: var(--primary); }
        .stat-offline { color: var(--danger); }
        .stat-pings { color: var(--warning); }
        
        .stat-label {
            color: var(--text-muted);
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            margin-bottom: 10px;
        }
        
        .stat-desc {
            font-size: 0.85rem;
            opacity: 0.8;
            line-height: 1.4;
        }
        
        /* Filtros */
        .filters-container {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 20px;
            border: 1px solid var(--border);
            margin-bottom: 30px;
            backdrop-filter: blur(10px);
        }
        
        .filters-title {
            font-family: 'Orbitron', sans-serif;
            color: var(--primary);
            font-size: 1.2rem;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .filters {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .filter-btn {
            padding: 12px 25px;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid var(--border);
            color: var(--text);
            cursor: pointer;
            transition: all 0.3s ease;
            font-family: 'Montserrat', sans-serif;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .filter-btn:hover {
            background: rgba(0, 255, 157, 0.1);
            border-color: var(--primary);
            transform: translateY(-2px);
        }
        
        .filter-btn.active {
            background: var(--primary);
            color: var(--bg-dark);
            border-color: var(--primary);
            font-weight: 600;
        }
        
        /* DEVICE LIST TABLE */
        .devices-table-container {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 25px;
            border: 1px solid var(--border);
            margin-bottom: 40px;
            backdrop-filter: blur(10px);
            overflow-x: auto;
        }
        
        .table-header {
            font-family: 'Orbitron', sans-serif;
            color: var(--primary);
            font-size: 1.5rem;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .devices-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1200px;
        }
        
        .devices-table thead {
            background: rgba(0, 255, 157, 0.1);
            border-bottom: 2px solid var(--primary);
        }
        
        .devices-table th {
            padding: 15px 12px;
            text-align: left;
            font-family: 'Orbitron', sans-serif;
            font-weight: 600;
            color: var(--primary);
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .devices-table th:last-child {
            border-right: none;
        }
        
        .devices-table tbody tr {
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            transition: all 0.3s ease;
            animation: slideIn 0.3s ease forwards;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        .devices-table tbody tr:hover {
            background: rgba(0, 255, 157, 0.05);
        }
        
        .devices-table tr.online {
            border-left: 4px solid var(--primary);
        }
        
        .devices-table tr.offline {
            border-left: 4px solid var(--danger);
        }
        
        .devices-table td {
            padding: 12px;
            color: var(--text);
            font-size: 0.9rem;
            border-right: 1px solid rgba(255, 255, 255, 0.05);
            vertical-align: middle;
        }
        
        .devices-table td:last-child {
            border-right: none;
        }
        
        /* Status Badge */
        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-family: 'Orbitron', sans-serif;
        }
        
        .status-badge.online {
            background: rgba(0, 255, 157, 0.15);
            color: var(--primary);
            border: 1px solid var(--primary);
        }
        
        .status-badge.offline {
            background: rgba(255, 0, 85, 0.15);
            color: var(--danger);
            border: 1px solid var(--danger);
        }
        
        /* MAC Address */
        .mac-cell {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            color: var(--primary);
        }
        
        .client-name {
            color: var(--warning);
            font-size: 0.8rem;
            margin-top: 3px;
            font-weight: 500;
        }
        
        /* Device Type */
        .device-type {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        /* IP Address */
        .ip-address {
            font-family: 'Courier New', monospace;
            color: var(--info);
        }
        
        /* Time */
        .time-cell {
            min-width: 120px;
        }
        
        .time-ago {
            font-family: 'Courier New', monospace;
        }
        
        /* Actions */
        .actions-cell {
            min-width: 150px;
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        
        .action-btn {
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            display: flex;
            align-items: center;
            gap: 5px;
            font-family: 'Montserrat', sans-serif;
        }
        
        .action-delete {
            background: rgba(255, 0, 85, 0.2);
            color: var(--danger);
            border: 1px solid var(--danger);
        }
        
        .action-delete:hover {
            background: var(--danger);
            color: white;
            transform: translateY(-2px);
        }
        
        .action-details {
            background: rgba(0, 212, 255, 0.2);
            color: var(--info);
            border: 1px solid var(--info);
        }
        
        .action-details:hover {
            background: var(--info);
            color: white;
            transform: translateY(-2px);
        }
        
        /* Progress Bar */
        .progress-container {
            width: 100px;
        }
        
        .progress-bar {
            height: 6px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            overflow: hidden;
            position: relative;
        }
        
        .progress-fill {
            height: 100%;
            border-radius: 3px;
            transition: width 1s ease;
        }
        
        .progress-fill.online {
            background: linear-gradient(90deg, var(--primary), #00ff9d);
            box-shadow: 0 0 8px var(--primary);
        }
        
        .progress-fill.offline {
            background: linear-gradient(90deg, var(--danger), #ff0055);
            box-shadow: 0 0 8px var(--danger);
        }
        
        .progress-percent {
            font-size: 0.75rem;
            color: var(--text-muted);
            text-align: center;
            margin-top: 4px;
        }
        
        /* Summary */
        .summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 30px;
            padding: 20px;
            background: rgba(0, 255, 157, 0.05);
            border-radius: 12px;
            border: 1px solid var(--border);
            backdrop-filter: blur(10px);
        }
        
        .summary-item {
            text-align: center;
        }
        
        .summary-value {
            font-family: 'Orbitron', sans-serif;
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .summary-label {
            color: var(--text-muted);
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--text-muted);
            grid-column: 1 / -1;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        /* Footer */
        .footer {
            text-align: center;
            padding: 30px;
            background: var(--bg-card);
            border-radius: 20px;
            border: 1px solid var(--border);
            backdrop-filter: blur(10px);
            margin-top: 40px;
        }
        
        .update-indicator {
            display: inline-flex;
            align-items: center;
            gap: 15px;
            background: rgba(0, 255, 157, 0.1);
            padding: 15px 30px;
            border-radius: 25px;
            border: 1px solid var(--primary);
            margin-bottom: 20px;
        }
        
        .pulse-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--primary);
            animation: pulse-dot 1.5s infinite;
        }
        
        @keyframes pulse-dot {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.5; transform: scale(1.3); }
        }
        
        .footer-info {
            color: var(--text-muted);
            font-size: 0.9rem;
            line-height: 1.6;
        }
        
        /* Responsive */
        @media (max-width: 1200px) {
            .container {
                overflow-x: auto;
            }
            
            .devices-table-container {
                min-width: 1200px;
            }
        }
        
        @media (max-width: 768px) {
            .title {
                font-size: 2.2rem;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .container {
                padding: 10px;
            }
            
            .filters {
                justify-content: center;
            }
            
            .filter-btn {
                flex: 1;
                min-width: 120px;
                justify-content: center;
            }
        }
        
        @media (max-width: 480px) {
            .title {
                font-size: 1.8rem;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .stat-number {
                font-size: 2.2rem;
            }
            
            .filters {
                flex-direction: column;
            }
        }
    </style>
    
    <script>
        function filterDevices(filter) {
            const url = new URL(window.location);
            url.searchParams.set('filter', filter);
            window.location.href = url;
        }
        
        function confirmDelete(mac) {
            if (confirm('⚠️ Tem certeza que deseja deletar este dispositivo?\n\nMAC: ' + mac + '\n\nEsta ação não pode ser desfeita!')) {
                window.location.href = 'delete_device.php?mac=' + encodeURIComponent(mac);
            }
        }
        
        function updateTimes() {
            const now = Math.floor(Date.now() / 1000);
            document.querySelectorAll('.time-ago').forEach(element => {
                const timestamp = parseInt(element.getAttribute('data-timestamp'));
                const secondsAgo = now - timestamp;
                
                if (secondsAgo < 60) {
                    element.textContent = `${secondsAgo}s`;
                } else if (secondsAgo < 3600) {
                    element.textContent = `${Math.floor(secondsAgo/60)}m`;
                } else if (secondsAgo < 86400) {
                    element.textContent = `${Math.floor(secondsAgo/3600)}h`;
                } else {
                    element.textContent = `${Math.floor(secondsAgo/86400)}d`;
                }
            });
        }
        
        // Inicializar
        document.addEventListener('DOMContentLoaded', function() {
            updateTimes();
            setInterval(updateTimes, 1000);
            
            // Destacar filtro ativo
            const currentFilter = '<?php echo $filter; ?>';
            document.querySelectorAll('.filter-btn').forEach(btn => {
                if (btn.getAttribute('onclick').includes(currentFilter)) {
                    btn.classList.add('active');
                }
            });
            
            // Destacar cards de estatística
            document.querySelectorAll('.stat-card').forEach(card => {
                card.addEventListener('click', function() {
                    const filter = this.getAttribute('data-filter');
                    filterDevices(filter);
                });
            });
        });
    </script>
</head>
<body>
    <div class="grid-lines"></div>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1 class="title">
                <i class="fas fa-crown"></i> EON CLIENT MONITOR
            </h1>
            <p class="subtitle">Client Identification • Real-time Status • Advanced Management</p>
        </div>
        
        <?php
        try {
            $db = new SQLite3($ping_db);
            $now_timestamp = time();
            
            // ============ AVISO DE DATA FUTURA ============
            $check_future = $db->query("SELECT mac, last_ping FROM pings");
            $has_future_dates = false;
            $future_devices = [];
            
            while ($row = $check_future->fetchArray(SQLITE3_ASSOC)) {
                $last_ping_time = strtotime($row['last_ping']);
                if ($last_ping_time > $now) {
                    $has_future_dates = true;
                    $future_devices[] = $row['mac'];
                }
            }
            
            if ($has_future_dates) {
                echo '<div class="warning-box">
                        <i class="fas fa-exclamation-triangle" style="color: var(--danger); font-size: 1.5rem;"></i>
                        <div>
                            <strong style="color: var(--danger);">ATENÇÃO: Datas futuras detectadas!</strong><br>
                            <span style="color: var(--text-muted);">Alguns dispositivos têm last_ping no futuro: ' . implode(', ', array_slice($future_devices, 0, 3)) . 
                            (count($future_devices) > 3 ? ' e mais ' . (count($future_devices) - 3) . ' outros' : '') . '</span><br>
                            <small style="color: var(--text-muted);">Isso afeta o cálculo de status online/offline.</small>
                        </div>
                      </div>';
            }
            
            // ============ ESTATÍSTICAS ============
            $total_devices = $db->querySingle("SELECT COUNT(*) FROM pings");
            
            $online_count = 0;
            $total_pings_sum = 0;
            $all_devices = $db->query("SELECT * FROM pings");
            
            while ($device = $all_devices->fetchArray(SQLITE3_ASSOC)) {
                $last_ping_time = strtotime($device['last_ping']);
                $seconds_ago = $now - $last_ping_time;
                $device_type = $device['device_type'] ?? '📱 Dispositivo';
                
                // ✅ MESMA LÓGICA DE TEMPO DIFERENCIADO
                $timeout_seconds = 20;
                
                if (strpos($device_type, 'Celular') !== false || 
                    strpos($device_type, 'Algar') !== false ||
                    strpos($device_type, '4G') !== false ||
                    strpos($device_type, '5G') !== false) {
                    $timeout_seconds = 35;
                }
                elseif (strpos($device_type, '💻') !== false || 
                        strpos($device_type, 'Emulador') !== false) {
                    $timeout_seconds = 20;
                }
                elseif (strpos($device_type, '📺') !== false || 
                        strpos($device_type, '📦') !== false ||
                        strpos($device_type, '🔥') !== false) {
                    $timeout_seconds = 30;
                }
                
                if ($last_ping_time > $now) {
                    $online_count++;
                } elseif ($seconds_ago <= $timeout_seconds) {
                    $online_count++;
                }
                
                $total_pings_sum += $device['total_pings'];
            }
            
            $offline_count = $total_devices - $online_count;
            $online_percent = $total_devices > 0 ? round(($online_count / $total_devices) * 100, 1) : 0;
            
            echo '<div class="stats-grid">';
            
            // Card 1: Total Devices
            echo '<div class="stat-card" data-filter="all">
                    <div class="stat-icon"><i class="fas fa-microchip"></i></div>
                    <div class="stat-number stat-total">' . $total_devices . '</div>
                    <div class="stat-label">Dispositivos Totais</div>
                    <div class="stat-desc">Cadastrados no sistema</div>
                  </div>';
            
            // Card 2: Online Now
            echo '<div class="stat-card" data-filter="online">
                    <div class="stat-icon"><i class="fas fa-signal"></i></div>
                    <div class="stat-number stat-online">' . $online_count . '</div>
                    <div class="stat-label">Online Agora</div>
                    <div class="stat-desc">Ativos nos últimos minutos</div>
                  </div>';
            
            // Card 3: Offline
            echo '<div class="stat-card" data-filter="offline">
                    <div class="stat-icon"><i class="fas fa-plug-circle-xmark"></i></div>
                    <div class="stat-number stat-offline">' . $offline_count . '</div>
                    <div class="stat-label">Offline</div>
                    <div class="stat-desc">Sem ping recente</div>
                  </div>';
            
           
            
            echo '</div>';
            
            // ============ FILTROS ============
            echo '<div class="filters-container">
                    <div class="filters-title">
                        <i class="fas fa-filter"></i> FILTRAR DISPOSITIVOS
                    </div>
                    <div class="filters">
                        <button class="filter-btn ' . ($filter == 'all' ? 'active' : '') . '" onclick="filterDevices(\'all\')">
                            <i class="fas fa-layer-group"></i> Todos (' . $total_devices . ')
                        </button>
                        <button class="filter-btn ' . ($filter == 'online' ? 'active' : '') . '" onclick="filterDevices(\'online\')">
                            <i class="fas fa-wifi"></i> Online (' . $online_count . ')
                        </button>
                        <button class="filter-btn ' . ($filter == 'offline' ? 'active' : '') . '" onclick="filterDevices(\'offline\')">
                            <i class="fas fa-ban"></i> Offline (' . $offline_count . ')
                        </button>
                    </div>
                  </div>';
            
            // ============ LISTA DE DISPOSITIVOS EM TABELA ============
            echo '<div class="devices-table-container">';
            echo '<div class="table-header">
                    <i class="fas fa-list"></i> LISTA DE DISPOSITIVOS
                  </div>';
            
            echo '<table class="devices-table">';
            echo '<thead>
                    <tr>
                        <th>Status</th>
                        <th>MAC Address</th>
                        <th>Cliente</th>
                        <th>Tipo</th>
                        <th>IP Address</th>
                        <th>Último Ping</th>
                        <th>Total Pings</th>
                        <th>Primeiro Visto</th>
                        <th>Conexão</th>
                        <th>Ações</th>
                    </tr>
                  </thead>';
            echo '<tbody>';
            
            $query = $db->query("SELECT * FROM pings ORDER BY last_ping DESC");
            $device_count = 0;
            $filtered_pings_sum = 0;
            $filtered_online_count = 0;
            $filtered_offline_count = 0;
            
            while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
                $device_count++;
                $mac = $row['mac'];
                $last_ping_time = strtotime($row['last_ping']);
                $seconds_ago = $now - $last_ping_time;
                $device_type = $row['device_type'] ?? '📱 Dispositivo';
                
                // ✅✅✅ TEMPO DIFERENCIADO POR DISPOSITIVO
                $timeout_seconds = 20; // Padrão
                
                // CELULAR REAL (mais tempo)
                if (strpos($device_type, 'Celular') !== false || 
                    strpos($device_type, 'Algar') !== false ||
                    strpos($device_type, 'Vivo') !== false ||
                    strpos($device_type, 'Claro') !== false ||
                    strpos($device_type, 'Tim') !== false ||
                    strpos($device_type, 'Oi') !== false ||
                    strpos($device_type, '4G') !== false ||
                    strpos($device_type, '5G') !== false ||
                    strpos($device_type, 'Móvel') !== false) {
                    $timeout_seconds = 35;
                }
                // EMULADOR/PC (tempo normal)
                elseif (strpos($device_type, '💻') !== false || 
                        strpos($device_type, 'Emulador') !== false ||
                        strpos($device_type, 'PC') !== false ||
                        strpos($device_type, 'Notebook') !== false) {
                    $timeout_seconds = 20;
                }
                // TV/BOX (tempo médio)
                elseif (strpos($device_type, '📺') !== false || 
                        strpos($device_type, '📦') !== false ||
                        strpos($device_type, '🔥') !== false ||
                        strpos($device_type, 'TV') !== false ||
                        strpos($device_type, 'Box') !== false) {
                    $timeout_seconds = 30;
                }
                
                // VERIFICAÇÃO COM TEMPO DIFERENCIADO
                if ($last_ping_time > $now) {
                    $is_online = true;
                    $seconds_ago = 0;
                } else {
                    $is_online = ($seconds_ago <= $timeout_seconds);
                }
                
                // Aplicar filtro
                if ($filter == 'online' && !$is_online) continue;
                if ($filter == 'offline' && $is_online) continue;
                
                $filtered_pings_sum += $row['total_pings'];
                
                if ($is_online) {
                    $filtered_online_count++;
                } else {
                    $filtered_offline_count++;
                }
                
                // Calcular progresso
                $progress_percent = $is_online ? 
                    max(0, 100 - ($seconds_ago / $timeout_seconds * 100)) : 
                    0;
                
                // Status
                if ($last_ping_time > $now) {
                    $status = "FUTURO";
                    $status_class = "online";
                } else {
                    $status = $is_online ? "ONLINE" : "OFFLINE";
                    $status_class = $is_online ? "online" : "offline";
                }
                
                // Formatar MAC
                if (strlen($mac) == 12 && ctype_xdigit($mac)) {
                    $mac_display = implode(':', str_split(strtoupper($mac), 2));
                } else {
                    $mac_display = strtoupper($mac);
                }
                
                // Buscar nome do cliente
                $client_name = getClientName($mac, $eggzie_db);
                
                echo '<tr class="' . $status_class . '" style="animation-delay: ' . ($device_count * 0.1) . 's">';
                
                // Coluna 1: Status
                echo '<td><span class="status-badge ' . $status_class . '">' . $status . '</span></td>';
                
                // Coluna 2: MAC Address
                echo '<td class="mac-cell">' . $mac_display . '</td>';
                
                // Coluna 3: Nome do Cliente
                echo '<td>';
                if ($client_name) {
                    echo '<div class="client-name">👤 ' . htmlspecialchars($client_name) . '</div>';
                } else {
                    echo '<span style="color: var(--text-muted); font-size: 0.8rem;">Não identificado</span>';
                }
                echo '</td>';
                
                // Coluna 4: Tipo de Dispositivo
                echo '<td><span class="device-type">' . $device_type . '</span></td>';
                
                // Coluna 5: IP Address
                echo '<td><span class="ip-address">' . $row['ip'] . '</span></td>';
                
                // Coluna 6: Último Ping
                echo '<td class="time-cell"><span class="time-ago" data-timestamp="' . $last_ping_time . '">' . 
                     ($seconds_ago < 60 ? $seconds_ago . 's' : 
                     ($seconds_ago < 3600 ? floor($seconds_ago/60) . 'm' : 
                     floor($seconds_ago/3600) . 'h')) . '</span></td>';
                
                // Coluna 7: Total Pings
                echo '<td><strong>' . number_format($row['total_pings']) . '</strong></td>';
                
                // Coluna 8: Primeiro Visto
                echo '<td>' . substr($row['first_seen'], 0, 10) . '</td>';
                
                // Coluna 9: Saúde da Conexão
                echo '<td>
                        <div class="progress-container">
                            <div class="progress-bar">
                                <div class="progress-fill ' . $status_class . '" 
                                      style="width: ' . $progress_percent . '%"></div>
                            </div>
                            <div class="progress-percent">' . round($progress_percent, 1) . '%</div>
                        </div>
                      </td>';
                
                // Coluna 10: Ações
                echo '<td class="actions-cell">
                        <div class="action-buttons">
                            <button class="action-btn action-delete" onclick="confirmDelete(\'' . $mac . '\')">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                            <button class="action-btn action-details" onclick="alert(\'Detalhes:\\n\\nMAC: ' . $mac_display . '\\nIP: ' . $row['ip'] . '\\nTipo: ' . $device_type . '\\nTotal Pings: ' . $row['total_pings'] . '\\nÚltimo: ' . $row['last_ping'] . '\')">
                                <i class="fas fa-info-circle"></i>
                            </button>
                        </div>
                      </td>';
                
                echo '</tr>';
            }
            
            echo '</tbody></table>';
            
            if ($device_count == 0) {
                echo '<div class="empty-state">
                        <i class="fas fa-wifi-slash"></i>
                        <h3>Nenhum dispositivo encontrado</h3>
                        <p>Nenhum dispositivo corresponde ao filtro selecionado</p>
                      </div>';
            } else {
                // Resumo dos dispositivos filtrados
                echo '<div class="summary">';
                echo '<div class="summary-item">
                        <div class="summary-value stat-total">' . $device_count . '</div>
                        <div class="summary-label">Dispositivos</div>
                      </div>';
                echo '<div class="summary-item">
                        <div class="summary-value stat-online">' . $filtered_online_count . '</div>
                        <div class="summary-label">Online</div>
                      </div>';
                echo '<div class="summary-item">
                        <div class="summary-value stat-offline">' . $filtered_offline_count . '</div>
                        <div class="summary-label">Offline</div>
                      </div>';
                echo '<div class="summary-item">
                        <div class="summary-value stat-pings">' . number_format($filtered_pings_sum) . '</div>
                        <div class="summary-label">Total Pings</div>
                      </div>';
                echo '</div>';
                
                echo '<div style="text-align: center; color: var(--text-muted); font-size: 0.9rem; margin-top: 15px;">
                        <i class="fas fa-info-circle"></i> Mostrando ' . $device_count . ' dispositivo(s) 
                        ' . ($filter != 'all' ? '(filtro: ' . ($filter == 'online' ? 'apenas online' : 'apenas offline') . ')' : '') . '
                      </div>';
            }
            
            echo '</div>'; // Fecha devices-table-container
            
            $db->close();
            
        } catch (Exception $e) {
            echo '<div class="warning-box">
                    <i class="fas fa-exclamation-triangle" style="color: var(--danger); font-size: 1.5rem;"></i>
                    <div>
                        <strong style="color: var(--danger);">ERRO NO SISTEMA</strong><br>
                        <span style="color: var(--text-muted);">' . htmlspecialchars($e->getMessage()) . '</span>
                    </div>
                  </div>';
        }
        ?>
        
        <!-- Footer -->
        <div class="footer">
            <div class="update-indicator">
                <div class="pulse-dot"></div>
                <div>
                    <strong>Live Update:</strong> <?php echo date('H:i:s'); ?><br>
                    <small>Next refresh in 10 seconds</small>
                </div>
            </div>
            
            <div class="footer-info">
                <p><i class="fas fa-database"></i> Database: <?php echo basename($ping_db); ?> | <?php echo round(filesize($ping_db)/1024, 2); ?> KB</p>
                <p><i class="fas fa-server"></i> Server Time: <?php echo date('d/m/Y H:i:s'); ?> | São Paulo Timezone</p>
                <p><i class="fas fa-code"></i> System: EON Client Monitor v2.0 | Power by PHP + SQLite3</p>
                <p style="margin-top: 15px; color: var(--primary);">
                    <i class="fas fa-copyright"></i> <?php echo date('Y'); ?> • EONBRY SYSTEMS • All Clients Monitored
                </p>
            </div>
        </div>
    </div>
</body>
</html>