<?php
$admin_user = 'admin';
$admin_pass = 'Cyber@Panel@2026';

if (!isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['HTTP_AUTHORIZATION'])) {
    if (preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
        $credentials = explode(':', base64_decode($matches[1]), 2);
        if (count($credentials) === 2) {
            list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $credentials;
        }
    }
}

if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== $admin_user || $_SERVER['PHP_AUTH_PW'] !== $admin_pass) {
    header('WWW-Authenticate: Basic realm="Traffic Monitor"');
    header('HTTP/1.0 401 Unauthorized');
    exit('Unauthorized access.');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shield Traffic Monitor | Live</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .bg-payload { background-color: #22c55e; }
        .bg-safe { background-color: #64748b; }
        .status-pill { padding: 2px 8px; border-radius: 9999px; font-size: 0.75rem; text-transform: uppercase; font-weight: 700; color: white; }
        @keyframes pulse-green { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }
        .live-indicator { width: 8px; height: 8px; background: #22c55e; border-radius: 50%; display: inline-block; margin-right: 8px; animation: pulse-green 2s infinite; }
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: #0f172a; }
        ::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
        .modal-enter-active { opacity: 1; transform: scale(1); transition: opacity 0.3s ease-out, transform 0.3s ease-out; }
    </style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen p-4 md:p-8 font-sans pb-20 relative">

    <div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
        <div>
            <h1 class="text-2xl font-bold tracking-tight">Traffic Control Center</h1>
            <p class="text-slate-400 text-sm flex items-center mt-1">
                <span class="live-indicator"></span>
                <span id="status-text">Synchronizing with server...</span>
            </p>
        </div>
        <div class="flex items-center gap-4">
            <select id="time-filter" onchange="updateTraffic()" class="bg-slate-800 border border-slate-700 text-slate-200 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block px-4 py-2 outline-none font-semibold cursor-pointer">
                <option value="today">Today</option>
                <option value="yesterday">Yesterday</option>
                <option value="7days" selected>Last 7 Days</option>
                <option value="all">All Time</option>
            </select>
            <button onclick="updateTraffic()" class="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg text-sm transition-all font-semibold shadow-lg shadow-blue-500/20">
                Force Refresh
            </button>
        </div>
    </div>

    <div class="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 flex flex-col items-center justify-center">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-2">Distribution</h3>
            <div style="height: 120px; width: 120px;"><canvas id="trafficChart"></canvas></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 flex flex-col justify-center">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider">Payload Conversions</h3>
            <div class="flex items-baseline gap-2 mt-2"><span id="payload-count" class="text-4xl font-bold text-green-500">0</span><span class="text-slate-500 text-sm">hits</span></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 flex flex-col justify-center">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider">Filtered Bots</h3>
            <div class="flex items-baseline gap-2 mt-2"><span id="safe-count" class="text-4xl font-bold text-slate-300">0</span><span class="text-slate-500 text-sm">hits</span></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 flex flex-col justify-center">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider">Pass Rate</h3>
            <div class="flex items-baseline gap-2 mt-2"><span id="pass-rate" class="text-4xl font-bold text-blue-400">0%</span></div>
            <div class="w-full bg-slate-700 rounded-full h-1.5 mt-4"><div id="rate-bar" class="bg-blue-400 h-1.5 rounded-full" style="width: 0%"></div></div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 lg:col-span-2">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-4">Traffic Timeline</h3>
            <div style="height: 250px; width: 100%;"><canvas id="timelineChart"></canvas></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 flex flex-col">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-4">Top Countries</h3>
            <div id="countries-list" class="space-y-4 flex-grow"><p class="text-slate-500 text-sm italic">Loading data...</p></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 flex flex-col">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-4">Threat Breakdown</h3>
            <div id="threats-list" class="space-y-3 flex-grow"><p class="text-slate-500 text-sm italic">Loading data...</p></div>
            <div class="mt-4 pt-4 border-t border-slate-700">
                <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-1">Total VPN/Proxies Caught</h3>
                <span id="proxy-count" class="text-2xl font-bold text-red-400">0</span>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-4">Device Types</h3>
            <div id="intel-devices" class="space-y-3"><p class="text-slate-500 text-sm italic">Loading...</p></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-4">Operating Systems</h3>
            <div id="intel-os" class="space-y-3"><p class="text-slate-500 text-sm italic">Loading...</p></div>
        </div>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700">
            <h3 class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-4">Browsers</h3>
            <div id="intel-browsers" class="space-y-3"><p class="text-slate-500 text-sm italic">Loading...</p></div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto bg-slate-800 rounded-2xl border border-slate-700 overflow-hidden">
        <div class="px-6 py-4 border-b border-slate-700 flex flex-col sm:flex-row justify-between items-center gap-4">
            <h2 class="font-semibold text-slate-200">Recent Activity <span class="text-xs text-slate-500 ml-2 font-normal italic">(Click IP to inspect)</span></h2>
            <input type="text" id="search-logs" placeholder="Search IP, Geo, OS..." class="w-full sm:w-64 bg-slate-900 border border-slate-700 text-slate-200 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block px-3 py-2 outline-none">
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-slate-900/50 text-slate-400 text-xs uppercase tracking-widest">
                    <tr>
                        <th class="px-6 py-4">Timestamp</th>
                        <th class="px-6 py-4">IP / Geo</th>
                        <th class="px-6 py-4">Status / Reason</th>
                        <th class="px-6 py-4">Device Intel</th>
                    </tr>
                </thead>
                <tbody id="traffic-body" class="divide-y divide-slate-700/50"></tbody>
            </table>
        </div>
    </div>

    <div class="max-w-7xl mx-auto bg-slate-800 rounded-2xl border border-red-900/50 overflow-hidden mt-8 shadow-[0_0_15px_rgba(220,38,38,0.1)]">
        <div class="px-6 py-4 border-b border-red-900/50 flex justify-between items-center bg-red-950/20">
            <h2 class="font-semibold text-red-400 flex items-center gap-2">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                Honeypot Burn List (Permanent Bans)
            </h2>
            <span class="bg-red-500/10 text-red-400 border border-red-500/20 px-2 py-1 rounded text-xs font-bold" id="honeypot-total">0 Banned</span>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-red-950/10 text-red-300/70 text-xs uppercase tracking-widest">
                    <tr>
                        <th class="px-6 py-4">Time Caught</th>
                        <th class="px-6 py-4">IP Address</th>
                        <th class="px-6 py-4">Scraper User-Agent</th>
                        <th class="px-6 py-4 text-right">Action</th>
                    </tr>
                </thead>
                <tbody id="honeypot-body" class="divide-y divide-red-900/30"></tbody>
            </table>
        </div>
    </div>

    <div id="forensic-modal" class="hidden fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
        <div class="bg-slate-800 border border-slate-600 rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden modal-enter-active">
            <div class="px-6 py-4 border-b border-slate-700 flex justify-between items-center bg-slate-800/50">
                <h3 class="text-lg font-bold text-slate-200 flex items-center gap-2">
                    <svg class="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><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"></path></svg>
                    IP Dossier: <span id="modal-ip" class="text-blue-400 font-mono tracking-wider"></span>
                </h3>
                <button onclick="closeModal()" class="text-slate-400 hover:text-white transition-colors">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
            
            <div class="p-6 space-y-6">
                <div>
                    <h4 class="text-xs font-semibold text-slate-400 uppercase tracking-widest mb-3 border-b border-slate-700 pb-1">Geolocation Data</h4>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div><p class="text-slate-500 mb-0.5">City</p><p id="modal-city" class="font-medium text-slate-200">-</p></div>
                        <div><p class="text-slate-500 mb-0.5">Region/State</p><p id="modal-region" class="font-medium text-slate-200">-</p></div>
                        <div><p class="text-slate-500 mb-0.5">Country</p><p id="modal-country" class="font-medium text-slate-200">-</p></div>
                        <div>
                            <p class="text-slate-500 mb-0.5">Coordinates</p>
                            <a id="modal-map" href="#" target="_blank" class="font-medium text-blue-400 hover:underline flex items-center gap-1">
                                <span id="modal-coords">-</span>
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path></svg>
                            </a>
                        </div>
                    </div>
                </div>
                <div>
                    <h4 class="text-xs font-semibold text-slate-400 uppercase tracking-widest mb-3 border-b border-slate-700 pb-1">Network & ISP</h4>
                    <div class="grid grid-cols-1 gap-4 text-sm">
                        <div><p class="text-slate-500 mb-0.5">Internet Service Provider (ISP)</p><p id="modal-isp" class="font-medium text-slate-200">-</p></div>
                        <div><p class="text-slate-500 mb-0.5">Organization / ASN</p><p id="modal-org" class="font-medium text-slate-200 font-mono text-xs">-</p></div>
                    </div>
                </div>
                <div id="modal-flags" class="flex gap-2 pt-2"></div>
            </div>
            
            <div id="modal-loading" class="absolute inset-0 bg-slate-800/90 backdrop-blur-sm flex flex-col items-center justify-center hidden">
                <div class="w-8 h-8 border-2 border-slate-600 border-t-blue-500 rounded-full animate-spin mb-4"></div>
                <p class="text-slate-300 font-medium animate-pulse">Running Deep Scan...</p>
            </div>
        </div>
    </div>

    <script>
        let trafficChart, timelineChart, allLogs = [];

        function initCharts() {
            trafficChart = new Chart(document.getElementById('trafficChart').getContext('2d'), {
                type: 'doughnut', data: { labels: ['Payload', 'Safe'], datasets: [{ data: [0, 0], backgroundColor: ['#22c55e', '#64748b'], borderWidth: 0 }] },
                options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, cutout: '75%' }
            });
            timelineChart = new Chart(document.getElementById('timelineChart').getContext('2d'), {
                type: 'line', data: { labels: [], datasets: [
                    { label: 'Payload', data: [], borderColor: '#22c55e', backgroundColor: 'rgba(34, 197, 94, 0.1)', borderWidth: 2, tension: 0.4, fill: true },
                    { label: 'Safe', data: [], borderColor: '#64748b', backgroundColor: 'transparent', borderWidth: 2, tension: 0.4 }
                ]},
                options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { display: false } }, scales: { x: { grid: { display: false } }, y: { grid: { color: '#334155' } } } }
            });
        }

        document.getElementById('search-logs').addEventListener('input', function(e) {
            const term = e.target.value.toLowerCase();
            renderTable(term ? allLogs.filter(log => log.ip_address.toLowerCase().includes(term) || log.country_code.toLowerCase().includes(term) || (log.os && log.os.toLowerCase().includes(term))) : allLogs);
        });

        function renderTable(logs) {
            const tbody = document.getElementById('traffic-body');
            if (logs.length === 0) return tbody.innerHTML = `<tr><td colspan="4" class="px-6 py-10 text-center text-slate-500 italic">No traffic found for this period.</td></tr>`;
            tbody.innerHTML = logs.map(log => {
                const safeUA = log.user_agent ? log.user_agent.replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>') : 'Unknown';
                
                return `
                <tr class="hover:bg-slate-700/30 transition-colors">
                    <td class="px-6 py-4 text-sm text-slate-400 font-mono whitespace-nowrap">${log.created_at.split(' ')[1] || log.created_at}</td>
                    <td class="px-6 py-4 flex flex-col gap-1">
                        <div class="flex items-center">
                            <span onclick="investigateIP('${log.ip_address}')" class="font-mono text-sm text-blue-400 cursor-pointer hover:text-blue-300 hover:underline flex items-center gap-1 group">
                                ${log.ip_address}
                                <svg class="w-3 h-3 opacity-0 group-hover:opacity-100 transition-opacity" fill="none" stroke="currentColor" viewBox="0 0 24 24"><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"></path></svg>
                            </span>
                            ${log.is_proxy == 1 ? '<span class="ml-2 bg-red-500/10 text-red-500 border border-red-500/30 text-[10px] font-bold px-1.5 py-0.5 rounded uppercase">VPN</span>' : ''}
                        </div>
                        <span class="text-xs text-slate-500 font-bold">${log.country_code}</span>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex flex-col items-start gap-1">
                            <span class="status-pill ${log.destination === 'payload' ? 'bg-payload shadow-[0_0_10px_rgba(34,197,94,0.3)]' : 'bg-safe'}">${log.destination}</span>
                            ${log.destination === 'safe' ? `<span class="text-[10px] text-slate-500 uppercase tracking-wide font-semibold">${log.block_reason || 'Unknown'}</span>` : ''}
                        </div>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex items-center gap-2">
                            <span class="bg-slate-700 px-2 py-1 rounded text-xs text-slate-300 font-semibold">${log.os || 'Unknown'}</span>
                            <span class="bg-slate-700 px-2 py-1 rounded text-xs text-slate-300 font-semibold">${log.browser || 'Unknown'}</span>
                            <span class="text-xs text-slate-500 ml-1" title="${safeUA}">${log.device_type || 'Desktop'}</span>
                        </div>
                    </td>
                </tr>
            `}).join('');
        }

        function closeModal() { document.getElementById('forensic-modal').classList.add('hidden'); }

        async function investigateIP(ip) {
            const modal = document.getElementById('forensic-modal');
            const loader = document.getElementById('modal-loading');
            
            document.getElementById('modal-ip').innerText = ip;
            modal.classList.remove('hidden');
            loader.classList.remove('hidden');

            try {
                const response = await fetch(`traffic_api.php?action=investigate&ip=${ip}`, { credentials: 'same-origin' });
                const data = await response.json();
                
                if (data.status === 'success') {
                    document.getElementById('modal-city').innerText = data.city || 'Unknown';
                    document.getElementById('modal-region').innerText = data.regionName || 'Unknown';
                    document.getElementById('modal-country').innerText = data.country || 'Unknown';
                    
                    if (data.lat && data.lon) {
                        document.getElementById('modal-coords').innerText = `${data.lat}, ${data.lon}`;
                        document.getElementById('modal-map').href = `https://maps.google.com/?q=${data.lat},${data.lon}`;
                    } else {
                        document.getElementById('modal-coords').innerText = 'Unavailable';
                        document.getElementById('modal-map').removeAttribute('href');
                    }

                    document.getElementById('modal-isp').innerText = data.isp || 'Unknown';
                    document.getElementById('modal-org').innerText = `${data.org || 'Unknown'} (${data.as || '-'})`;

                    let flagsHTML = '';
                    if (data.proxy || data.hosting) flagsHTML += `<span class="bg-red-500/10 text-red-400 border border-red-500/20 px-3 py-1 rounded-full text-xs font-bold flex items-center gap-1">Datacenter / Proxy</span>`;
                    if (data.mobile) flagsHTML += `<span class="bg-blue-500/10 text-blue-400 border border-blue-500/20 px-3 py-1 rounded-full text-xs font-bold">Cellular Network</span>`;
                    if (!flagsHTML) flagsHTML = `<span class="bg-green-500/10 text-green-400 border border-green-500/20 px-3 py-1 rounded-full text-xs font-bold">Residential IP</span>`;
                    
                    document.getElementById('modal-flags').innerHTML = flagsHTML;
                } else {
                    alert('Lookup failed. IP might be a local or reserved address.');
                }
            } catch (error) {
                alert('Connection to forensic endpoint failed.');
            } finally {
                loader.classList.add('hidden');
            }
        }

        // NEW: Unban Functionality
        async function unbanIP(ip) {
            if (!confirm(`Are you sure you want to release ${ip} from the Honeypot Burn List?`)) return;
            
            try {
                const response = await fetch(`traffic_api.php?action=unban&ip=${ip}`, { credentials: 'same-origin' });
                const data = await response.json();
                
                if (data.status === 'success') {
                    updateTraffic(); // Refresh tables instantly
                } else {
                    alert(`Failed to unban: ${data.message}`);
                }
            } catch (error) {
                alert('Connection to API failed.');
            }
        }

        function renderIntelBars(containerId, dataArray, totalHits) {
            const container = document.getElementById(containerId);
            if (!dataArray || dataArray.length === 0) return container.innerHTML = '<p class="text-slate-500 text-sm italic">No data yet.</p>';
            container.innerHTML = dataArray.map(item => {
                const name = item.device_type || item.os || item.browser || item.block_reason || 'Unknown';
                const percentage = totalHits > 0 ? Math.round((item.count / totalHits) * 100) : 0;
                return `
                <div class="mb-3">
                    <div class="flex justify-between text-xs mb-1"><span class="text-slate-300 font-semibold">${name}</span><span class="text-slate-500">${percentage}% (${item.count})</span></div>
                    <div class="w-full bg-slate-700 rounded-full h-1.5"><div class="bg-blue-500 h-1.5 rounded-full" style="width: ${percentage}%"></div></div>
                </div>`;
            }).join('');
        }

        async function updateTraffic() {
            try {
                const period = document.getElementById('time-filter').value;
                const response = await fetch(`traffic_api.php?period=${period}`, { credentials: 'same-origin' });
                const data = await response.json();
                
                const pCount = data.stats.payload || 0, sCount = data.stats.safe || 0, total = pCount + sCount;
                document.getElementById('payload-count').innerText = pCount;
                document.getElementById('safe-count').innerText = sCount;
                document.getElementById('pass-rate').innerText = (total > 0 ? Math.round((pCount / total) * 100) : 0) + '%';
                document.getElementById('rate-bar').style.width = (total > 0 ? Math.round((pCount / total) * 100) : 0) + '%';
                document.getElementById('proxy-count').innerText = data.stats.proxies || 0;
                
                trafficChart.data.datasets[0].data = [pCount, sCount]; trafficChart.update();
                
                if (data.timeline && data.timeline.length > 0) {
                    timelineChart.data.labels = data.timeline.map(t => t.label);
                    timelineChart.data.datasets[0].data = data.timeline.map(t => t.payload_count);
                    timelineChart.data.datasets[1].data = data.timeline.map(t => t.safe_count);
                    timelineChart.update();
                }

                if (data.top_countries && data.top_countries.length > 0) {
                    document.getElementById('countries-list').innerHTML = data.top_countries.map((c, i) => `
                        <div class="flex items-center justify-between p-2 rounded hover:bg-slate-700/50 transition">
                            <div class="flex items-center gap-3"><span class="text-slate-500 text-xs font-bold w-4">${i + 1}.</span><span class="bg-slate-700 text-slate-200 px-2 py-0.5 rounded text-xs font-bold">${c.country_code}</span></div>
                            <span class="text-slate-400 text-sm font-mono">${c.count} hits</span>
                        </div>
                    `).join('');
                } else {
                    document.getElementById('countries-list').innerHTML = `<p class="text-slate-500 text-sm italic">No data.</p>`;
                }

                if (data.threats) renderIntelBars('threats-list', data.threats, sCount);
                if (data.intelligence) {
                    renderIntelBars('intel-devices', data.intelligence.devices, total);
                    renderIntelBars('intel-os', data.intelligence.oses, total);
                    renderIntelBars('intel-browsers', data.intelligence.browsers, total);
                }

                allLogs = data.logs; 
                const term = document.getElementById('search-logs').value.toLowerCase();
                renderTable(term ? allLogs.filter(log => log.ip_address.toLowerCase().includes(term) || log.country_code.toLowerCase().includes(term) || (log.os && log.os.toLowerCase().includes(term))) : allLogs);
                
                // Render Honeypot Data
                if (data.honeypot) {
                    document.getElementById('honeypot-total').innerText = `${data.honeypot.length} Banned`;
                    const hpBody = document.getElementById('honeypot-body');
                    
                    if (data.honeypot.length === 0) {
                        hpBody.innerHTML = `<tr><td colspan="4" class="px-6 py-8 text-center text-red-400/50 italic">No bots have triggered the honeypot yet.</td></tr>`;
                    } else {
                        hpBody.innerHTML = data.honeypot.map(bot => `
                            <tr class="hover:bg-red-950/20 transition-colors">
                                <td class="px-6 py-3 text-sm text-slate-400 font-mono whitespace-nowrap">${bot.caught_time}</td>
                                <td class="px-6 py-3">
                                    <span onclick="investigateIP('${bot.ip_address}')" class="font-mono text-sm text-red-400 cursor-pointer hover:text-red-300 hover:underline">
                                        ${bot.ip_address}
                                    </span>
                                </td>
                                <td class="px-6 py-3 text-xs text-slate-500 font-mono truncate max-w-md" title="${bot.user_agent ? bot.user_agent.replace(/"/g, '&quot;') : 'Unknown'}">
                                    ${bot.user_agent || 'Unknown'}
                                </td>
                                <td class="px-6 py-3 text-right">
                                    <button onclick="unbanIP('${bot.ip_address}')" class="bg-red-900/40 hover:bg-red-700/60 text-red-300 border border-red-700/50 px-3 py-1 rounded text-xs transition-colors font-semibold">
                                        Unban
                                    </button>
                                </td>
                            </tr>
                        `).join('');
                    }
                }

                document.getElementById('status-text').innerText = 'System Live - Last Sync: ' + new Date().toLocaleTimeString();
                document.getElementById('status-text').classList.remove('text-red-400');
            } catch (e) {
                document.getElementById('status-text').innerText = 'Connection Error - Retrying...';
                document.getElementById('status-text').classList.add('text-red-400');
            }
        }

        window.onload = () => { initCharts(); updateTraffic(); setInterval(updateTraffic, 5000); };
    </script>
</body>
</html>