<?php
$config = json_decode(file_get_contents(__DIR__ . '/valores.json'), true);

$modoPix = $config['modo_pix']; // 1 = manual, 0 = Mercado Pago
$tokenMP = $config['token_mp'] ?? '';
$nome = $config['nome'];
$cidade = $config['cidade'];
$chave = $config['chave'];
$planos = $config['planos'];
$ipCliente = $_SERVER['REMOTE_ADDR']; 

define('CACHE_FILE', __DIR__.'/pix_cache.json');

// ======================= FUNÇÕES =======================
function gerarPixCode($nome, $cidade, $chave, $valor = null) {
    $nome = strtoupper($nome);
    $cidade = strtoupper($cidade);
    $payloadFormat = '000201';
    $merchantAccount = montarMerchantAccount($chave);
    $merchantCategoryCode = '52040000';
    $transactionCurrency = '5303986';
    $transactionAmount = $valor ? '54'.str_pad(strlen(number_format($valor,2,'.','')),2,'0',STR_PAD_LEFT).number_format($valor,2,'.','') : '';
    $countryCode = '5802BR';
    $merchantName = '59'.str_pad(strlen($nome),2,'0',STR_PAD_LEFT).$nome;
    $merchantCity = '60'.str_pad(strlen($cidade),2,'0',STR_PAD_LEFT).$cidade;
    $txid = '62070503***';
    $fullPix = $payloadFormat.$merchantAccount.$merchantCategoryCode.$transactionCurrency.$transactionAmount.$countryCode.$merchantName.$merchantCity.$txid;
    $fullPix .= '6304';
    return $fullPix.strtoupper(crc16($fullPix));
}

function montarMerchantAccount($chave) {
    $gui = 'BR.GOV.BCB.PIX';
    $chaveLength = str_pad(strlen($chave),2,'0',STR_PAD_LEFT);
    $value = '0014'.$gui.'01'.$chaveLength.$chave;
    return '26'.str_pad(strlen($value),2,'0',STR_PAD_LEFT).$value;
}

function crc16($payload) {
    $polynom = 0x1021;
    $result = 0xFFFF;
    for ($offset = 0; $offset < strlen($payload); $offset++) {
        $result ^= (ord($payload[$offset]) << 8);
        for ($bitwise = 0; $bitwise < 8; $bitwise++) {
            if (($result <<= 1) & 0x10000) $result ^= $polynom;
            $result &= 0xFFFF;
        }
    }
    return strtoupper(str_pad(dechex($result), 4, '0', STR_PAD_LEFT));
}

function lerCache() {
    if (!file_exists(CACHE_FILE)) return [];
    $data = json_decode(file_get_contents(CACHE_FILE), true);
    $now = time();
    foreach ($data as $key => $entry) {
        if ($now - $entry['timestamp'] > 1800) unset($data[$key]);
    }
    return $data;
}

// ======================= PROCESSA PLANOS =======================
$cache = lerCache();
foreach ($planos as $index => $plano) {
    $key = md5($plano['nome'].$plano['valor']);
    if ($modoPix === 1) {
        $planos[$index]['pix_manual'] = gerarPixCode($nome, $cidade, $chave, $plano['valor']);
    } else {
        $planos[$index]['pix_mp'] = $cache[$key]['pix'] ?? null;
        $planos[$index]['qr_mp'] = $cache[$key]['qr'] ?? null;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Pagamento via Pix</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<style>
body { background-color:#121212; color:#fff; font-family:'Segoe UI',sans-serif; margin:0; padding:20px; }
.container { display:flex; flex-wrap:wrap; justify-content:center; gap:10px; }
.pix-box { background:#1e1e1e; border-radius:12px; padding:12px; width:220px; text-align:center; box-shadow:0 5px 15px rgba(0,0,0,0.3); transition:transform 0.2s ease; margin-bottom:15px; }
.pix-box:hover { transform:scale(1.03); }
.pix-title { font-size:0.9rem; color:#00ffcc; margin-bottom:8px; font-weight:600; }
.qrcode-card { background:#fff; padding:8px; border-radius:8px; display:inline-block; margin-bottom:8px; }
textarea { width:100%; height:50px; background:#2c2c2c; color:#ccc; border:none; border-radius:6px; padding:6px; resize:none; font-size:0.75rem; margin-bottom:6px; }
.copy-btn { width:100%; padding:8px; background:linear-gradient(135deg,#6a11cb,#2575fc); border:none; border-radius:6px; color:#fff; font-weight:bold; cursor:pointer; transition:background 0.3s ease; }
.copy-btn:hover { background:linear-gradient(135deg,#00cc7a,#00a86b); }
.container .pix-box:nth-child(3) { border:2px solid #ff0000; background:#2c2c2c; box-shadow:0 8px 18px rgba(255,69,0,0.5); }
@media(max-width:768px){ .pix-box{ width:45%; } }
@media(max-width:480px){ .pix-box{ width:100%; } }

/* Modal */
#modalPagamento {display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); justify-content:center; align-items:center; z-index:9999;}
#modalPagamento .content {background:#1e1e1e; padding:25px; border-radius:14px; max-width:420px; width:90%; text-align:center; color:#fff; box-shadow:0 8px 20px rgba(0,0,0,0.6);}
#modalPagamento h2 {color:#00ffcc; margin-bottom:10px;}
#modalPagamento p {font-size:1rem; margin:6px 0;}
#modalPagamento .valor {font-size:1.2rem; font-weight:bold; color:#ffcc00;}
#modalPagamento button {padding:10px 20px; margin-top:15px; border:none; border-radius:6px; background:linear-gradient(135deg,#6a11cb,#2575fc); color:#fff; cursor:pointer; font-weight:bold;}
#modalPagamento button:hover {background:linear-gradient(135deg,#00cc7a,#00a86b);}
</style>
</head>
<body>

<div class="container">
<?php foreach ($planos as $index => $plano): ?>
<div class="pix-box">
    <div class="pix-title" style="color:#ffcc00;font-size:1.1rem;margin-bottom:5px;">🏷️ <?= $plano['nome'] ?></div>
    <div class="pix-title">💰 R$ <?= number_format($plano['valor'],2,',','.') ?></div>
    <div class="qrcode-card" id="qrcode<?= $index ?>"></div>
    <textarea id="pixCode<?= $index ?>" readonly></textarea>
    <button class="copy-btn" onclick="copiarPix(<?= $index ?>)">📋 Copiar Pix</button>
</div>
<?php endforeach; ?>
</div>

<!-- Modal de pagamento aprovado -->
<div id="modalPagamento">
    <div class="content">
        <h2>✅ Pagamento Aprovado!</h2>
        <p>Sua conta foi renovada com sucesso 🎉</p>
        <p id="modalInfo" class="valor"></p>
        <button onclick="fecharModal()">Fechar</button>
    </div>
</div>

<script>
const CLIENT_IP = '<?= $ipCliente ?>';
const planos = <?= json_encode($planos); ?>;
const modoPix = <?= $modoPix; ?>;
const TOKEN_MP = '<?= $tokenMP ?>';

async function gerarPixMP(valor, descricao, plano) {
    const resp = await fetch('https://tv3.thefullnet.com.br/app/gerar-pix', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ token:TOKEN_MP, valor, descricao, ip: CLIENT_IP, plano })
    });
    return await resp.json();
}


window.addEventListener('DOMContentLoaded', async () => {
    for(let i=0; i<planos.length; i++){
        const plano = planos[i];
        let codigo = '', qrImg = '';
        if(modoPix === 1){
            codigo = plano.pix_manual;
        } else {
            if(plano.pix_mp && plano.qr_mp){
                codigo = plano.pix_mp; qrImg = plano.qr_mp;
            } else {
                const data = await gerarPixMP(plano.valor, plano.nome, 'plano'+(i+1));

                codigo = data.qrCodeText; qrImg = data.qrCodeBase64;
                fetch('salvar_cache.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({ chave: plano.nome+plano.valor, pix: codigo, qr: qrImg })
                });
            }
        }
        document.getElementById('pixCode'+i).value = codigo;
        const qrContainer = document.getElementById('qrcode'+i);
        qrContainer.innerHTML = '';
        if(qrImg){
            const img = document.createElement('img');
            img.src = 'data:image/png;base64,'+qrImg;
            img.style.width='140px'; img.style.height='140px';
            qrContainer.appendChild(img);
        } else {
            new QRCode(qrContainer, { text: codigo, width:140, height:140, colorDark:"#000", colorLight:"#fff", correctLevel:QRCode.CorrectLevel.H });
        }
    }
});

// ========== Modal ==========
function abrirModal(paymentId, valor) {
    document.getElementById('modalInfo').textContent = "Valor pago: R$ " + valor.toFixed(2).replace('.',',');
    document.getElementById('modalPagamento').style.display = 'flex';
}
function fecharModal() {
    document.getElementById('modalPagamento').style.display = 'none';
}

// ========== Atualizar Pagamentos ==========
async function atualizarPagamentos() {
    try {
        const resp = await fetch('https://tv3.thefullnet.com.br/app/checar-pagamentos?ip=' + CLIENT_IP);
        const aprovados = await resp.json();

        if (aprovados.length > 0) {
            for(const p of aprovados){
                if(!document.getElementById('pag-' + p.paymentId)){
                    abrirModal(p.paymentId, parseFloat(p.valor));

                    const div = document.createElement('div');
                    div.id = 'pag-' + p.paymentId;
                    document.body.appendChild(div);

                    // agora envia também qual plano foi aprovado
                    fetch('atualizar_expire.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            paymentId: p.paymentId, 
                            plano: p.plano 
                        })
                    });
                }
            }
        }
    } catch(err) {
        console.error('Erro ao buscar pagamentos:', err);
    }
}

setInterval(atualizarPagamentos, 5000);

function copiarPix(index){
    const t = document.getElementById('pixCode'+index);
    t.select(); t.setSelectionRange(0,99999);
    document.execCommand('copy'); alert('✅ Código Pix copiado!');
}
</script>
</body>
</html>
