<?php
// monitor_ping.php - VERSÃO FUTURISTA MODERNA
date_default_timezone_set('America/Sao_Paulo');

// Caminho do banco de PING
$ping_db = __DIR__ . '/a/ping/ping.db';
$now = time();

if (!file_exists($ping_db)) {
    die("❌ Banco não encontrado!");
}

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 | Live Monitor</title>
    <meta http-equiv="refresh" content="5">
    
    <!-- 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;
            --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: 1400px;
            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);
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { box-shadow: 0 0 20px rgba(0, 255, 157, 0.3); }
            50% { box-shadow: 0 0 30px rgba(0, 255, 157, 0.5); }
        }
        
        .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;
        }
        
        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }
        
        .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);
        }
        
        .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-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;
        }
        
        /* Device Card */
        .device-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }
        
        .device-card {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 25px;
            border: 1px solid var(--border);
            transition: all 0.3s ease;
            position: relative;
            backdrop-filter: blur(10px);
        }
        
        .device-card.online {
            border-color: var(--primary);
            box-shadow: 0 0 15px rgba(0, 255, 157, 0.2);
        }
        
        .device-card.offline {
            border-color: var(--danger);
            box-shadow: 0 0 15px rgba(255, 0, 85, 0.2);
        }
        
        .device-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }
        
        .device-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .mac-address {
            font-family: 'Orbitron', sans-serif;
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--primary);
            letter-spacing: 1px;
        }
        
        .status-badge {
            padding: 6px 15px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .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);
        }
        
        .device-info {
            margin-bottom: 15px;
        }
        
        .info-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            font-size: 0.9rem;
        }
        
        .info-icon {
            width: 30px;
            color: var(--primary);
            font-size: 1.1rem;
        }
        
        .info-label {
            color: var(--text-muted);
            min-width: 100px;
        }
        
        .info-value {
            color: var(--text);
            font-weight: 500;
        }
        
        /* Progress Bar */
        .progress-container {
            margin: 20px 0;
        }
        
        .progress-label {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 0.85rem;
        }
        
        .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;
            position: relative;
        }
        
        .progress-fill.online {
            background: linear-gradient(90deg, var(--primary), #00ff9d);
            box-shadow: 0 0 10px var(--primary);
        }
        
        .progress-fill.offline {
            background: linear-gradient(90deg, var(--danger), #ff0055);
            box-shadow: 0 0 10px var(--danger);
        }
        
        /* 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: 768px) {
            .title {
                font-size: 2.2rem;
            }
            
            .device-grid {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .container {
                padding: 10px;
            }
        }
        
        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .device-card {
            animation: slideIn 0.5s ease forwards;
        }
        
        /* Data glow effect */
        .data-glow {
            position: absolute;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: radial-gradient(circle, var(--primary-glow) 0%, transparent 70%);
            filter: blur(20px);
            z-index: 0;
            pointer-events: none;
        }
    </style>
    
    <script>
        // Função para atualizar progress bars
        function updateProgressBars() {
            document.querySelectorAll('.progress-fill').forEach(bar => {
                const percent = bar.getAttribute('data-percent');
                bar.style.width = percent + '%';
            });
        }
        
        // Função para atualizar tempo dinâmico
        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 atrás`;
                } else if (secondsAgo < 3600) {
                    element.textContent = `${Math.floor(secondsAgo/60)}m atrás`;
                } else if (secondsAgo < 86400) {
                    element.textContent = `${Math.floor(secondsAgo/3600)}h atrás`;
                } else {
                    element.textContent = `${Math.floor(secondsAgo/86400)}d atrás`;
                }
                
                // Atualizar barra de progresso
                const progressBar = element.closest('.device-card').querySelector('.progress-fill');
                if (progressBar) {
                    const timeout = progressBar.getAttribute('data-timeout');
                    const percent = Math.max(0, Math.min(100, 100 - (secondsAgo / timeout * 100)));
                    progressBar.style.width = percent + '%';
                    progressBar.setAttribute('data-percent', percent.toFixed(1));
                }
            });
        }
        
        // Inicializar
        document.addEventListener('DOMContentLoaded', function() {
            updateProgressBars();
            updateTimes();
            
            // Atualizar tempo a cada segundo
            setInterval(updateTimes, 1000);
            
            // Efeito de partículas (simples)
            const container = document.querySelector('.container');
            for (let i = 0; i < 5; i++) {
                const glow = document.createElement('div');
                glow.className = 'data-glow';
                glow.style.left = Math.random() * 100 + '%';
                glow.style.top = Math.random() * 100 + '%';
                glow.style.opacity = Math.random() * 0.3 + 0.1;
                container.appendChild(glow);
            }
        });
    </script>
</head>
<body>
    <div class="grid-lines"></div>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1 class="title">
                <i class="fas fa-satellite"></i> EON MONITOR SYSTEM
            </h1>
            <p class="subtitle">Live Device Tracking • Real-time Analytics • Network Intelligence</p>
        </div>
        
        <?php
        try {
            $db = new SQLite3($ping_db);
            $now_timestamp = time();
            
            // ============ ESTATÍSTICAS ============
            $total = $db->querySingle("SELECT COUNT(*) FROM pings");
            
            $online_count = 0;
            $total_pings = 0;
            $all_devices = $db->query("SELECT * FROM pings");
            
            while ($device = $all_devices->fetchArray(SQLITE3_ASSOC)) {
                $last_ping_time = strtotime($device['last_ping']);
                $device_type = $device['device_type'] ?? '📱 Device';
                
                // Timeout diferenciado
                $timeout_seconds = 120;
                
                if (strpos($device_type, 'Celular') !== false || 
                    strpos($device_type, '4G') !== false ||
                    strpos($device_type, '5G') !== false) {
                    $timeout_seconds = 180;
                }
                elseif (strpos($device_type, '💻') !== false || 
                        strpos($device_type, 'Emulador') !== false) {
                    $timeout_seconds = 120;
                }
                elseif (strpos($device_type, '📺') !== false) {
                    $timeout_seconds = 150;
                }
                
                if ($last_ping_time > $now_timestamp) {
                    $online_count++;
                } else {
                    $seconds_ago = $now_timestamp - $last_ping_time;
                    if ($seconds_ago <= $timeout_seconds) {
                        $online_count++;
                    }
                }
                
                $total_pings += $device['total_pings'];
            }
            
            $offline_count = $total - $online_count;
            $online_percent = $total > 0 ? round(($online_count / $total) * 100, 1) : 0;
            
            echo '<div class="stats-grid">';
            
            // Card 1: Total Devices
            echo '<div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-microchip"></i>
                    </div>
                    <div class="stat-number">' . $total . '</div>
                    <div class="stat-label">Active Devices</div>
                    <div class="stat-desc">Unique MAC addresses tracked in system</div>
                  </div>';
            
            // Card 2: Online Now
            echo '<div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-signal"></i>
                    </div>
                    <div class="stat-number" style="color: var(--primary)">' . $online_count . '</div>
                    <div class="stat-label">Live Connections</div>
                    <div class="stat-desc">Currently active and responding</div>
                  </div>';
            
            // Card 3: Offline
            echo '<div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-plug-circle-xmark"></i>
                    </div>
                    <div class="stat-number" style="color: var(--danger)">' . $offline_count . '</div>
                    <div class="stat-label">Disconnected</div>
                    <div class="stat-desc">No recent activity detected</div>
                  </div>';
            
            // Card 4: Total Pings
            echo '<div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-bullseye"></i>
                    </div>
                    <div class="stat-number" style="color: var(--warning)">' . number_format($total_pings) . '</div>
                    <div class="stat-label">Total Pings</div>
                    <div class="stat-desc">All network requests processed</div>
                  </div>';
            
            echo '</div>'; // Fecha stats-grid
            
            // ============ LISTA DE DISPOSITIVOS ============
            echo '<div class="device-grid">';
            
            $query = $db->query("SELECT * FROM pings ORDER BY last_ping DESC");
            $device_index = 0;
            
            while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
                $device_index++;
                $mac = $row['mac'];
                $last_ping_time = strtotime($row['last_ping']);
                $device_type = $row['device_type'] ?? '📱 Device';
                
                // Timeout diferenciado
                $timeout_seconds = 120;
                
                if (strpos($device_type, 'Celular') !== false || 
                    strpos($device_type, '4G') !== false ||
                    strpos($device_type, '5G') !== false) {
                    $timeout_seconds = 180;
                }
                elseif (strpos($device_type, '💻') !== false || 
                        strpos($device_type, 'Emulador') !== false) {
                    $timeout_seconds = 120;
                }
                elseif (strpos($device_type, '📺') !== false) {
                    $timeout_seconds = 150;
                }
                
                // Status calculation
                if ($last_ping_time > $now_timestamp) {
                    $is_online = true;
                    $seconds_ago = 0;
                    $status = "FUTURE";
                    $status_class = "online";
                } else {
                    $seconds_ago = $now_timestamp - $last_ping_time;
                    $is_online = ($seconds_ago <= $timeout_seconds);
                    $status = $is_online ? "LIVE" : "OFFLINE";
                    $status_class = $is_online ? "online" : "offline";
                }
                
                // Format MAC
                if (strlen($mac) == 12 && ctype_xdigit($mac)) {
                    $mac_display = implode(':', str_split($mac, 2));
                } else {
                    $mac_display = $mac;
                }
                
                // Calculate progress percentage
                $progress_percent = $is_online ? 
                    max(0, 100 - ($seconds_ago / $timeout_seconds * 100)) : 
                    0;
                
                // Time display
                if ($seconds_ago < 60) {
                    $time_display = $seconds_ago . "s ago";
                } elseif ($seconds_ago < 3600) {
                    $time_display = floor($seconds_ago / 60) . "m ago";
                } else {
                    $time_display = floor($seconds_ago / 3600) . "h ago";
                }
                
                echo '<div class="device-card ' . $status_class . '" style="animation-delay: ' . ($device_index * 0.1) . 's">';
                echo '<div class="device-header">';
                echo '<div class="mac-address">' . strtoupper($mac_display) . '</div>';
                echo '<div class="status-badge ' . $status_class . '">' . $status . '</div>';
                echo '</div>';
                
                echo '<div class="device-info">';
                
                // Device Type
                echo '<div class="info-row">';
                echo '<div class="info-icon"><i class="fas fa-laptop"></i></div>';
                echo '<div class="info-label">Device Type</div>';
                echo '<div class="info-value">' . $device_type . '</div>';
                echo '</div>';
                
                // IP Address
                echo '<div class="info-row">';
                echo '<div class="info-icon"><i class="fas fa-network-wired"></i></div>';
                echo '<div class="info-label">IP Address</div>';
                echo '<div class="info-value" style="font-family: \'Courier New\', monospace;">' . $row['ip'] . '</div>';
                echo '</div>';
                
                // Last Ping
                echo '<div class="info-row">';
                echo '<div class="info-icon"><i class="fas fa-clock"></i></div>';
                echo '<div class="info-label">Last Ping</div>';
                echo '<div class="info-value time-ago" data-timestamp="' . $last_ping_time . '">' . $time_display . '</div>';
                echo '</div>';
                
                // Total Pings
                echo '<div class="info-row">';
                echo '<div class="info-icon"><i class="fas fa-bullseye"></i></div>';
                echo '<div class="info-label">Total Pings</div>';
                echo '<div class="info-value">' . number_format($row['total_pings']) . '</div>';
                echo '</div>';
                
                // First Seen
                echo '<div class="info-row">';
                echo '<div class="info-icon"><i class="fas fa-calendar-alt"></i></div>';
                echo '<div class="info-label">First Seen</div>';
                echo '<div class="info-value">' . substr($row['first_seen'], 0, 10) . '</div>';
                echo '</div>';
                
                echo '</div>'; // Fecha device-info
                
                // Progress Bar
                echo '<div class="progress-container">';
                echo '<div class="progress-label">';
                echo '<span>Connection Health</span>';
                echo '<span>' . round($progress_percent, 1) . '%</span>';
                echo '</div>';
                echo '<div class="progress-bar">';
                echo '<div class="progress-fill ' . $status_class . '" 
                          data-percent="' . $progress_percent . '" 
                          data-timeout="' . $timeout_seconds . '"
                          style="width: ' . $progress_percent . '%"></div>';
                echo '</div>';
                echo '</div>';
                
                echo '</div>'; // Fecha device-card
            }
            
            if ($device_index == 0) {
                echo '<div class="device-card" style="text-align: center; padding: 50px;">
                        <i class="fas fa-wifi-slash" style="font-size: 3rem; color: var(--text-muted); margin-bottom: 20px;"></i>
                        <h3 style="color: var(--text-muted);">No Devices Found</h3>
                        <p style="color: var(--text-muted);">Waiting for device connections...</p>
                      </div>';
            }
            
            echo '</div>'; // Fecha device-grid
            
            $db->close();
            
        } catch (Exception $e) {
            echo '<div class="device-card" style="border-color: var(--danger);">
                    <div class="device-header">
                        <div class="mac-address" style="color: var(--danger);">
                            <i class="fas fa-exclamation-triangle"></i> SYSTEM ERROR
                        </div>
                    </div>
                    <div class="device-info">
                        <div class="info-row">
                            <div class="info-label">Error Message:</div>
                            <div class="info-value" style="color: var(--danger);">' . htmlspecialchars($e->getMessage()) . '</div>
                        </div>
                    </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 5 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 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 Connections Monitored
                </p>
            </div>
        </div>
</body>
</html>