<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php';

// Função para gerar um CPF matematicamente válido e aleatório para o Asaas aceitar
function gerarCpfAleatorio() {
    $n1 = rand(0, 9); $n2 = rand(0, 9); $n3 = rand(0, 9);
    $n4 = rand(0, 9); $n5 = rand(0, 9); $n6 = rand(0, 9);
    $n7 = rand(0, 9); $n8 = rand(0, 9); $n9 = rand(0, 9);
    
    $d1 = $n9*2 + $n8*3 + $n7*4 + $n6*5 + $n5*6 + $n4*7 + $n3*8 + $n2*9 + $n1*10;
    $d1 = 11 - ($d1 % 11);
    if ($d1 >= 10) $d1 = 0;
    
    $d2 = $d1*2 + $n9*3 + $n8*4 + $n7*5 + $n6*6 + $n5*7 + $n4*8 + $n3*9 + $n2*10 + $n1*11;
    $d2 = 11 - ($d2 % 11);
    if ($d2 >= 10) $d2 = 0;
    
    return "{$n1}{$n2}{$n3}{$n4}{$n5}{$n6}{$n7}{$n8}{$n9}{$d1}{$d2}";
}

// Conexão com o banco local para buscar planos e configs
$pdo_int = getConexaoInterna();
$pdo_int->exec("SET NAMES utf8mb4");

// 1. RECEBE E DESCRIPTOGRAFA O LINK
$hash_r = $_GET['r'] ?? '';
$hash_c = $_GET['c'] ?? '';

$revendedor_id = 0;
$cliente_user = '';

if (!empty($hash_r) && !empty($hash_c)) {
    $dec_r = base64_decode($hash_r);
    $dec_c = base64_decode($hash_c);
    
    if (strpos($dec_r, 'RS-') !== false) {
        $revendedor_id = (int) str_replace('RS-', '', $dec_r);
    }
    if (strpos($dec_c, 'CL-') !== false) {
        $cliente_user = str_replace('CL-', '', $dec_c);
    }
}

// Bloqueia se o link for inválido ou forjado
if (empty($cliente_user)) {
    die("
    <div style='background:#0f1114; height:100vh; display:flex; justify-content:center; align-items:center; color:#fff; font-family:sans-serif;'>
        <div style='text-align:center; background:#1e2227; padding:40px; border-radius:10px; border:1px solid #dc3545;'>
            <h2 style='color:#dc3545; margin-top:0;'>Link Inválido</h2>
            <p style='color:#8a94a1;'>Este link de pagamento expirou ou está corrompido.<br>Solicite um novo link ao seu vendedor.</p>
        </div>
    </div>");
}

// BUSCA AS CREDENCIAIS DO WHATSAPP DO REVENDEDOR OU DO ADMIN ADIANTADO
$wa_url = ''; $wa_key = ''; $wa_inst = ''; $wa_status = 0;
try {
    $tabela_rev_det = 'reg_users';
    $pdo_test = getConexaoAtiva();
    $check_xui_rev = $pdo_test->query("SHOW TABLES LIKE 'lines'");
    if ($check_xui_rev && $check_xui_rev->fetch()) { $tabela_rev_det = '`users`'; }

    $api_user = $pdo_test->prepare("SELECT wa_api_url, wa_api_key, wa_instancia, wa_status FROM $tabela_rev_det WHERE id = ?");
    $api_user->execute([$revendedor_id]);
    $dados_api = $api_user->fetch(PDO::FETCH_ASSOC);
    if ($dados_api) {
        $wa_url = $dados_api['wa_api_url'] ?? '';
        $wa_key = $dados_api['wa_api_key'] ?? '';
        $wa_inst = $dados_api['wa_instancia'] ?? '';
        $wa_status = (int)($dados_api['wa_status'] ?? 0);
    }
} catch (Exception $e) {}

// Função para envio de WhatsApp replicada nativamente para o Checkout
function enviarMsgZapCheckout($numero, $mensagem, $url, $key, $inst, $status) {
    if ($status == 0 || empty($url)) return false;
    $numero = preg_replace('/\D/', '', $numero);
    if(empty($numero)) return false;
    if (strlen($numero) == 10 || strlen($numero) == 11) { $numero = "55" . $numero; }
    $endpoint = rtrim($url, '/') . "/message/sendText/" . $inst;
    $dados = [ 
        "number" => $numero, 
        "options" => [ "delay" => 1200, "presence" => "composing" ],
        "textMessage" => [ "text" => $mensagem ]
    ];
    $ch = curl_init($endpoint);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($dados),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json", "apikey: ".$key, "Authorization: Bearer ".$key], 
        CURLOPT_TIMEOUT => 5, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false
    ]);
    $res = curl_exec($ch); curl_close($ch);
    return $res;
}

// =========================================================================
// API DE CHECAGEM INTERNA E RENOVAÇÃO EM TEMPO REAL VIA AJAX CHECKOUT
// =========================================================================
if (isset($_GET['checar_status_pix'])) {
    header('Content-Type: application/json');
    $payment_id = $_GET['checar_status_pix'];
    $gateway_type = $_GET['gateway_type'] ?? 'mp';
    $meses_plano = (int)($_GET['meses'] ?? 1);
    
    $pago = false;
    $pdo = getConexaoAtiva();
    
    // Consulta a API do Gateway correspondente para checar se o Pix entrou
    if ($gateway_type === 'asaas') {
        $stmtT = $pdo_int->prepare("SELECT asaas_api_key FROM revendedor_configuracoes WHERE revendedor_id = ?");
        $stmtT->execute([$revendedor_id]);
        $token_asaas = trim($stmtT->fetchColumn() ?? '');
        
        $ch = curl_init("https://www.asaas.com/api/v3/payments/" . $payment_id);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ["access_token: " . $token_asaas]
        ]);
        $json = json_decode(curl_exec($ch), true);
        curl_close($ch);
        
        if (isset($json['status']) && ($json['status'] === 'RECEIVED' || $json['status'] === 'CONFIRMED')) {
            $pago = true;
        }
    } else {
        $stmtT = $pdo_int->prepare("SELECT mp_access_token FROM revendedor_configuracoes WHERE revendedor_id = ?");
        $stmtT->execute([$revendedor_id]);
        $token_mp = trim($stmtT->fetchColumn() ?? '');
        
        $curl = curl_init("https://api.mercadopago.com/v1/payments/" . $payment_id);
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $token_mp]
        ]);
        $json = json_decode(curl_exec($curl), true);
        curl_close($curl);
        
        if (isset($json['status']) && $json['status'] === 'approved') {
            $pago = true;
        }
    }
    
    if ($pago) {
        // Trava para evitar processar o mesmo ID de pagamento duas vezes
        $pdo_int->exec("CREATE TABLE IF NOT EXISTS `pagamentos_processados` (`payment_id` varchar(255) PRIMARY KEY, `data_proc` timestamp DEFAULT CURRENT_TIMESTAMP)");
        $stmtVer = $pdo_int->prepare("SELECT COUNT(*) FROM pagamentos_processados WHERE payment_id = ?");
        $stmtVer->execute([$payment_id]);
        
        if ($stmtVer->fetchColumn() == 0) {
            // Detecta o modo do banco de streaming de forma inteligente
            $modo_ativo = 'interno';
            try { $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno'; } catch (Exception $e) {}
            
            $tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';
            $tabela_revendedores = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';
            $col_exp = 'exp_date';
            $col_whatsapp = ($modo_ativo === 'xui') ? 'phone' : 'whatsapp';
            
            try {
                $check_col = $pdo->query("SHOW COLUMNS FROM $tabela_clientes LIKE 'expire_date'");
                if ($check_col && $check_col->fetch()) { $col_exp = 'expire_date'; }
            } catch (Exception $e) {}
            
            // Busca o vencimento atual do cliente e a senha/whatsapp originais dele
            $stmtC = $pdo->prepare("SELECT id, password, member_id, $col_whatsapp as whatsapp, $col_exp as exp_date FROM $tabela_clientes WHERE username = ? LIMIT 1");
            $stmtC->execute([$cliente_user]);
            $cliData = $stmtC->fetch(PDO::FETCH_ASSOC);
            
            if ($cliData) {
                $revendedor_dono = (int)$cliData['member_id'];
                $pode_estender = true;
                
                // Se o dono da linha for revendedor (ID > 1), desconta créditos equivalentes (1 crédito por mês comprado)
                if ($revendedor_dono > 1) {
                    $stmtRev = $pdo->prepare("SELECT credits FROM $tabela_revendedores WHERE id = ?");
                    $stmtRev->execute([$revendedor_dono]);
                    $saldo_rev = floatval($stmtRev->fetchColumn());
                    
                    if ($saldo_rev >= $meses_plano) {
                        $pdo->prepare("UPDATE $tabela_revendedores SET credits = credits - ? WHERE id = ?")->execute([$meses_plano, $revendedor_dono]);
                        try {
                            $agora_log = date('Y-m-d H:i:s');
                            $pdo_int->prepare("INSERT INTO logs_creditos (revendedor_id, cliente_user, acao, qtd_descontada, data_hora) VALUES (?, ?, 'Renovacao Automatica via Checkout Link', ?, ?)")->execute([$revendedor_dono, $cliente_user, $meses_plano, $agora_log]);
                        } catch(Exception $e) {}
                    } else {
                        $pode_estender = false;
                    }
                }
                
                if ($pode_estender) {
                    $data_atual = ($cliData['exp_date'] == 0 || $cliData['exp_date'] < time()) ? time() : $cliData['exp_date'];
                    $nova_data = strtotime("+" . $meses_plano . " months", $data_atual);
                    
                    $pdo->prepare("UPDATE $tabela_clientes SET $col_exp = ?, enabled = 1 WHERE id = ?")->execute([$nova_data, $cliData['id']]);
                    $pdo_int->prepare("INSERT INTO pagamentos_processados (payment_id) VALUES (?)")->execute([$payment_id]);
                    
                    // =========================================================================
                    // DISPARO CIRÚRGICO DA API DO WHATSAPP APÓS APROVAÇÃO
                    // =========================================================================
                    if (!empty($cliData['whatsapp']) && $wa_status == 1) {
                        $data_formatada = date('d/m/Y', $nova_data);
                        $texto_zap = "✅ *RENOVAÇÃO CONCLUÍDA*\n\nSeu plano foi renovado automaticamente após a confirmação do pagamento!\n\n👤 *Usuário:* {$cliente_user}\n🔑 *Senha:* {$cliData['password']}\n📅 *Novo Vencimento:* {$data_formatada}\n\nObrigado pela preferência! 🚀";
                        enviarMsgZapCheckout($cliData['whatsapp'], $texto_zap, $wa_url, $wa_key, $wa_inst, $wa_status);
                    }
                }
            }
        }
        echo json_encode(['pago' => true]);
        exit;
    }
    echo json_encode(['pago' => false]);
    exit;
}

// 2. BUSCA CONFIGURAÇÕES VISUAIS DO PAINEL
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $config_painel = $pdo_int->query("SELECT nome_painel, logo_url, cor_primaria FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
        $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
        $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
    }
} catch (Exception $e) {}

// 3. BUSCA OS PLANOS EXCLUSIVOS DO REVENDEDOR (Da tabela billing_planos)
$planos = [];
try {
    $stmtPlanos = $pdo_int->prepare("SELECT id, nome_plano, meses, valor FROM billing_planos WHERE owner_id = ? ORDER BY valor ASC");
    $stmtPlanos->execute([$revendedor_id]);
    $planos = $stmtPlanos->fetchAll(PDO::FETCH_ASSOC);

    if (empty($planos)) {
        $stmtPlanosAdmin = $pdo_int->prepare("SELECT id, nome_plano, meses, valor FROM billing_planos WHERE owner_id = 1 ORDER BY valor ASC");
        $stmtPlanosAdmin->execute();
        $planos = $stmtPlanosAdmin->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {}

// 4. BUSCA AS CONFIGURAÇÕES DE CREDENCIAIS DE PAGAMENTO DO REVENDEDOR
$mp_access_token = '';
$asaas_api_key = '';

try {
    $stmtGateway = $pdo_int->prepare("SELECT mp_access_token, asaas_api_key FROM revendedor_configuracoes WHERE revendedor_id = ?");
    $stmtGateway->execute([$revendedor_id]);
    $gateway = $stmtGateway->fetch(PDO::FETCH_ASSOC);

    if ($gateway) {
        $mp_access_token = trim($gateway['mp_access_token'] ?? '');
        $asaas_api_key = trim($gateway['asaas_api_key'] ?? '');
    }

    if (empty($mp_access_token) && empty($asaas_api_key)) {
        $stmtGatewayAdmin = $pdo_int->prepare("SELECT mp_access_token, asaas_api_key FROM revendedor_configuracoes WHERE revendedor_id = 1");
        $stmtGatewayAdmin->execute();
        $gatewayAdmin = $stmtGatewayAdmin->fetch(PDO::FETCH_ASSOC);
        if ($gatewayAdmin) {
            $mp_access_token = trim($gatewayAdmin['mp_access_token'] ?? '');
            $asaas_api_key = trim($gatewayAdmin['asaas_api_key'] ?? '');
        }
    }
} catch (Exception $e) {}

// Lógica de Processamento e Integração com as APIs de Pagamento
$pix_copia_cola = '';
$pix_qr_base64 = '';
$checkout_url = '';
$generated_payment_id = '';
$generated_gateway_type = 'mp';
$generated_meses = 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['plano_id'])) {
    $plano_selecionado_id = intval($_POST['plano_id']);
    $metodo_pgto = $_POST['metodo_pagamento'] ?? 'pix';
    
    $plano_detalhes = null;
    foreach ($planos as $pl) {
        if ($pl['id'] == $plano_selecionado_id) {
            $plano_detalhes = $pl;
            break;
        }
    }

    if (!$plano_detalhes) {
        $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Plano inválido selecionado.</div>";
    } elseif (empty($mp_access_token) && empty($asaas_api_key)) {
        $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Este vendedor não possui meios de pagamento ativos no momento.</div>";
    } else {
        $valor_plano = (float) $plano_detalhes['valor'];
        $nome_plano = $plano_detalhes['nome_plano'];
        $generated_meses = (int) $plano_detalhes['meses'];
        $descricao_cobranca = "Fatura: {$nome_plano} - Usuario: {$cliente_user}";

        // --- INTEGRAÇÃO MERCADO PAGO ---
        if (!empty($mp_access_token)) {
            $generated_gateway_type = 'mp';
            if ($metodo_pgto === 'pix') {
                $ch = curl_init("https://api.mercadopago.com/v1/payments");
                $data = [
                    "transaction_amount" => $valor_plano,
                    "description" => $descricao_cobranca,
                    "payment_method_id" => "pix",
                    "payer" => [
                        "email" => $cliente_user . "@cliente.com",
                        "first_name" => "Cliente",
                        "last_name" => $cliente_user
                    ],
                    "external_reference" => $cliente_user
                ];

                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data),
                    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $mp_access_token, "Content-Type: application/json"]
                ]);

                $res = json_decode(curl_exec($ch), true);
                curl_close($ch);

                if (isset($res['point_of_interaction']['transaction_data']['qr_code'])) {
                    $pix_copia_cola = $res['point_of_interaction']['transaction_data']['qr_code'];
                    $pix_qr_base64 = $res['point_of_interaction']['transaction_data']['qr_code_base64'];
                    $generated_payment_id = $res['id'];
                    $msg_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Cobrança PIX Gerada com Sucesso!</div>";
                } else {
                    $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Erro ao gerar PIX no Mercado Pago. Contate o administrador.</div>";
                }
            } else {
                $ch = curl_init("https://api.mercadopago.com/checkout/preferences");
                $data = [
                    "items" => [[ "title" => $descricao_cobranca, "quantity" => 1, "currency_id" => "BRL", "unit_price" => $valor_plano ]],
                    "external_reference" => $cliente_user,
                    "back_urls" => [
                        "success" => "https://" . $_SERVER['HTTP_HOST'] . "/sucesso.php",
                        "pending" => "https://" . $_SERVER['HTTP_HOST'] . "/pendente.php",
                        "failure" => "https://" . $_SERVER['HTTP_HOST'] . "/erro.php"
                    ],
                    "auto_return" => "approved"
                ];

                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data),
                    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $mp_access_token, "Content-Type: application/json"]
                ]);

                $res = json_decode(curl_exec($ch), true); curl_close($ch);

                if (isset($res['init_point'])) {
                    $checkout_url = $res['init_point'];
                    header("Location: " . $checkout_url);
                    exit;
                } else {
                    $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Erro ao iniciar checkout de cartão no Mercado Pago.</div>";
                }
            }
        } 
        // --- INTEGRAÇÃO ASAAS ---
        elseif (!empty($asaas_api_key)) {
            $generated_gateway_type = 'asaas';
            // Criação do cliente com CPF aleatório válido gerado pela função
            $ch = curl_init("https://www.asaas.com/api/v3/customers");
            $data_cli = [ "name" => $cliente_user, "email" => $cliente_user . "@cliente.com", "cpfCnpj" => gerarCpfAleatorio() ];
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data_cli),
                CURLOPT_HTTPHEADER => ["access_token: " . $asaas_api_key, "Content-Type: application/json"]
            ]);
            $res_cli = json_decode(curl_exec($ch), true); curl_close($ch);

            $customer_id = $res_cli['id'] ?? '';

            if (!empty($customer_id)) {
                $metodo_asaas = ($metodo_pgto === 'pix') ? 'PIX' : 'CREDIT_CARD';
                
                $ch_pay = curl_init("https://www.asaas.com/api/v3/payments");
                $data_pay = [
                    "customer" => $customer_id, "billingType" => $metodo_asaas, "value" => $valor_plano,
                    "dueDate" => date('Y-m-d', strtotime('+3 days')), "description" => $descricao_cobranca, "externalReference" => $cliente_user
                ];

                curl_setopt_array($ch_pay, [
                    CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data_pay),
                    CURLOPT_HTTPHEADER => ["access_token: " . $asaas_api_key, "Content-Type: application/json"]
                ]);
                $res_pay = json_decode(curl_exec($ch_pay), true); curl_close($ch_pay);

                if (isset($res_pay['id'])) {
                    $payment_id = $res_pay['id'];
                    $generated_payment_id = $payment_id;

                    if ($metodo_pgto === 'pix') {
                        $ch_qr = curl_init("https://www.asaas.com/api/v3/payments/{$payment_id}/pixQrCode");
                        curl_setopt_array($ch_qr, [
                            CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["access_token: " . $asaas_api_key]
                        ]);
                        $res_qr = json_decode(curl_exec($ch_qr), true); curl_close($ch_qr);

                        if (isset($res_qr['payload'])) {
                            $pix_copia_cola = $res_qr['payload'];
                            $pix_qr_base64 = $res_qr['encodedImage'] ?? '';
                            $msg_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Cobrança PIX Gerada com Sucesso!</div>";
                        } else {
                            $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Erro ao buscar QR Code PIX no Asaas.</div>";
                        }
                    } else {
                        if (isset($res_pay['invoiceUrl'])) {
                            header("Location: " . $res_pay['invoiceUrl']);
                            exit;
                        }
                    }
                } else {
                    $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Erro ao gerar cobrança no Asaas: " . ($res_pay['errors'][0]['description'] ?? '') . "</div>";
                }
            } else {
                $msg_alerta = "<div class='alert' style='background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger);'>Erro ao vincular cliente no Asaas: " . ($res_cli['errors'][0]['description'] ?? '') . "</div>";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Checkout - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg-dark: #0f1114; --bg-card: #1e2227; --text-main: #d1d5da; --text-muted: #8a94a1; 
            --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; 
        }
        body { margin: 0; padding: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; }
        .checkout-container { width: 100%; max-width: 500px; padding: 20px; box-sizing: border-box; margin-top: 20px; margin-bottom: 40px; }
        .header-logo { text-align: center; margin-bottom: 25px; }
        .header-logo img { max-width: 180px; max-height: 60px; object-fit: contain; margin-bottom: 10px; }
        .header-logo h2 { margin: 0; color: var(--accent); font-size: 24px; }
        .user-badge { background: rgba(0, 123, 255, 0.1); border: 1px dashed var(--accent); padding: 15px; border-radius: 10px; text-align: center; margin-bottom: 25px; }
        .user-badge p { margin: 0; color: var(--text-muted); font-size: 13px; text-transform: uppercase; font-weight: bold; }
        .user-badge h3 { margin: 5px 0 0 0; color: white; font-size: 20px; letter-spacing: 1px; }
        .section-title { font-size: 14px; color: var(--text-muted); text-transform: uppercase; font-weight: bold; margin-bottom: 15px; display: block; border-bottom: 1px solid var(--border-color); padding-bottom: 8px;}
        .plan-options { display: flex; flex-direction: column; gap: 12px; margin-bottom: 25px; }
        .plan-card { background: var(--bg-card); border: 2px solid var(--border-color); border-radius: 10px; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; cursor: pointer; transition: 0.2s; position: relative;}
        .plan-card:hover { border-color: var(--text-muted); }
        .plan-card.active { border-color: var(--accent); background: rgba(0, 123, 255, 0.05); }
        .plan-card.active::before { content: '\f058'; font-family: 'Font Awesome 5 Free'; font-weight: 900; position: absolute; top: -10px; right: -10px; background: var(--accent); color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; justify-content: center; align-items: center; font-size: 14px; }
        .plan-info { display: flex; flex-direction: column; gap: 3px; }
        .plan-name { font-size: 16px; font-weight: bold; color: white; }
        .plan-duration { font-size: 12px; color: var(--text-muted); }
        .plan-price { font-size: 18px; font-weight: bold; color: var(--success); }
        .payment-methods { display: flex; gap: 10px; margin-bottom: 30px; }
        .pay-method { flex: 1; background: var(--bg-card); border: 2px solid var(--border-color); border-radius: 10px; padding: 15px; text-align: center; cursor: pointer; transition: 0.2s; color: var(--text-muted); }
        .pay-method i { font-size: 24px; display: block; margin-bottom: 8px; }
        .pay-method span { font-size: 13px; font-weight: bold; }
        .pay-method:hover { border-color: var(--text-muted); color: white; }
        .pay-method.active { border-color: var(--success); color: var(--success); background: rgba(40, 167, 69, 0.05); }
        .btn-submit { width: 100%; background: var(--accent); color: white; border: none; padding: 16px; border-radius: 8px; font-size: 16px; font-weight: bold; cursor: pointer; transition: 0.2s; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .btn-submit:hover { filter: brightness(1.1); transform: translateY(-2px); }
        .btn-submit:disabled { background: var(--border-color); color: var(--text-muted); cursor: not-allowed; transform: none; box-shadow: none; }
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; text-align: center; font-weight: bold; }
        .alert.success { background: rgba(40, 167, 69, 0.1); border: 1px solid var(--success); color: var(--success); }
        .empty-plans { text-align: center; padding: 30px; background: var(--bg-card); border-radius: 10px; color: var(--text-muted); border: 1px dashed var(--border-color); }
        .footer-note { text-align: center; margin-top: 30px; font-size: 11px; color: var(--text-muted); }
        .pix-container { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 10px; padding: 25px; text-align: center; margin-bottom: 25px; }
        .pix-qr { width: 200px; height: 200px; background: white; margin: 15px auto; padding: 10px; border-radius: 10px; display: block; }
        .pix-code { width: 100%; padding: 10px; background: #121519; border: 1px solid var(--border-color); border-radius: 5px; color: var(--text-muted); font-size: 12px; margin-bottom: 15px; box-sizing: border-box; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; }
        .btn-copy { background: var(--success); color: white; border: none; padding: 10px 20px; font-weight: bold; border-radius: 5px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s; }
        .btn-copy:hover { filter: brightness(1.1); }
    </style>
</head>
<body>

    <div class="checkout-container">
        
        <div class="header-logo">
            <?php if($logo_url): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo">
            <?php else: ?>
                <h2><?php echo htmlspecialchars($nome_painel); ?></h2>
            <?php endif; ?>
        </div>

        <?php if(isset($msg_alerta)) echo $msg_alerta; ?>

        <?php if(!empty($pix_copia_cola)): ?>
            <div class="pix-container" id="pix_status_box">
                <h3 style="color:white; margin-top:0;"><i class="fab fa-pix" style="color:var(--success);"></i> Seu QR Code PIX</h3>
                <p style="color:var(--text-muted); font-size:14px; margin-bottom: 20px;">Escaneie o QR Code abaixo ou utilize a chave copia e cola.</p>
                
                <?php if(!empty($pix_qr_base64)): ?>
                    <img class="pix-qr" src="data:image/png;base64,<?php echo $pix_qr_base64; ?>" alt="QR Code PIX">
                <?php else: ?>
                    <img class="pix-qr" src="https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=<?php echo urlencode($pix_copia_cola); ?>" alt="QR Code PIX">
                <?php endif; ?>

                <input type="text" class="pix-code" id="pixCodeInput" value="<?php echo htmlspecialchars($pix_copia_cola); ?>" readonly>
                
                <button type="button" class="btn-copy" onclick="copiarPix()">
                    <i class="fas fa-copy"></i> COPIAR CHAVE PIX
                </button>
                
                <div style="margin-top:20px; font-size:13px; color:var(--accent);" id="waiting_label">
                    <i class="fas fa-spinner fa-spin"></i> Aguardando confirmação do banco... A tela atualizará sozinha!
                </div>
            </div>
        <?php endif; ?>

        <div class="user-badge">
            <p>Renovar assinatura para o usuário</p>
            <h3><i class="fas fa-user-circle"></i> <?php echo htmlspecialchars($cliente_user); ?></h3>
        </div>

        <?php if(empty($planos)): ?>
            <div class="empty-plans">
                <i class="fas fa-box-open" style="font-size: 30px; margin-bottom:10px;"></i>
                <p>Nenhum plano disponível para compra no momento.</p>
                <p style="font-size:12px;">Entre em contato com seu vendedor.</p>
            </div>
        <?php else: ?>
            
            <form method="POST" id="checkoutForm">
                <input type="hidden" name="plano_id" id="plano_selecionado" value="">
                <input type="hidden" name="metodo_pagamento" id="metodo_selecionado" value="pix">

                <span class="section-title">1. Escolha seu Plano</span>
                <div class="plan-options">
                    <?php foreach($planos as $p): ?>
                        <div class="plan-card" onclick="selecionarPlano(this, <?php echo $p['id']; ?>)">
                            <div class="plan-info">
                                <span class="plan-name"><?php echo htmlspecialchars($p['nome_plano']); ?></span>
                                <span class="plan-duration"><i class="fas fa-calendar-alt"></i> Libera <?php echo $p['meses']; ?> Mês(es)</span>
                            </div>
                            <div class="plan-price">
                                R$ <?php echo number_format($p['valor'], 2, ',', '.'); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <span class="section-title">2. Forma de Pagamento</span>
                <div class="payment-methods">
                    <div class="pay-method active" id="btnPix" onclick="selecionarMetodo('pix')">
                        <i class="fab fa-pix"></i>
                        <span>PIX Copia e Cola</span>
                    </div>
                    <div class="pay-method" id="btnCard" onclick="selecionarMetodo('card')">
                        <i class="fas fa-credit-card"></i>
                        <span>Cartão de Crédito</span>
                    </div>
                </div>

                <button type="submit" class="btn-submit" id="btnFinalizar" disabled>
                    <i class="fas fa-lock"></i> PAGAR E RENOVAR AGORA
                </button>
            </form>

        <?php endif; ?>

        <div class="footer-note">
            <i class="fas fa-shield-alt"></i> Pagamento 100% Seguro. A liberação ocorre automaticamente após a confirmação do banco.
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let intervalStatus;
        const currentPaymentId = '<?php echo $generated_payment_id; ?>';
        const currentGatewayType = '<?php echo $generated_gateway_type; ?>';
        const currentMeses = '<?php echo $generated_meses; ?>';

        function selecionarPlano(elemento, id) {
            var cards = document.querySelectorAll('.plan-card');
            cards.forEach(c => c.classList.remove('active'));
            elemento.classList.add('active');
            
            document.getElementById('plano_selecionado').value = id;
            document.getElementById('btnFinalizar').disabled = false;
            document.getElementById('btnFinalizar').innerHTML = "<i class='fas fa-lock'></i> IR PARA O PAGAMENTO";
        }

        function selecionarMetodo(metodo) {
            document.getElementById('btnPix').classList.remove('active');
            document.getElementById('btnCard').classList.remove('active');
            if(metodo === 'pix') { document.getElementById('btnPix').add('active'); } 
            else { document.getElementById('btnCard').classList.add('active'); }
            document.getElementById('metodo_selecionado').value = metodo;
        }

        function copiarPix() {
            var copyText = document.getElementById("pixCodeInput");
            copyText.select(); copyText.setSelectionRange(0, 99999);
            document.execCommand("copy");
            
            const btn = document.querySelector('.btn-copy');
            const txtOriginal = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-check"></i> Copiado!';
            setTimeout(() => { btn.innerHTML = txtOriginal; }, 2000);
        }

        function checarStatusPagamento() {
            if (!currentPaymentId) return;
            fetch(window.location.search ? window.location.href + '&checar_status_pix=' + currentPaymentId + '&gateway_type=' + currentGatewayType + '&meses=' + currentMeses : window.location.href + '?checar_status_pix=' + currentPaymentId + '&gateway_type=' + currentGatewayType + '&meses=' + currentMeses)
            .then(res => res.json())
            .then(data => {
                if (data.pago) {
                    clearInterval(intervalStatus);
                    document.getElementById('waiting_label').innerHTML = '<i class="fas fa-check-circle" style="color:var(--success);"></i> Pagamento Aprovado!';
                    document.getElementById('pix_status_box').style.borderColor = 'var(--success)';
                    
                    Swal.fire({
                        title: '🎉 Pagamento Concluído!',
                        text: 'Sua assinatura IPTV foi renovada automaticamente com sucesso e os dados de acesso foram enviados para o seu WhatsApp cadastrado.',
                        icon: 'success',
                        background: 'var(--bg-card)', color: 'white',
                        confirmButtonColor: 'var(--accent)', confirmButtonText: 'Concluído'
                    }).then(() => {
                        window.location.href = window.location.pathname + "?r=<?php echo $hash_r; ?>&c=<?php echo $hash_c; ?>";
                    });
                }
            });
        }

        if (currentPaymentId !== '') { intervalStatus = setInterval(checarStatusPagamento, 4000); }

        document.getElementById('checkoutForm').addEventListener('submit', function(e) {
            var btn = document.getElementById('btnFinalizar');
            btn.innerHTML = "<i class='fas fa-spinner fa-spin'></i> GERANDO COBRANÇA...";
            btn.style.opacity = '0.8'; btn.style.cursor = 'wait';
        });
    </script>
</body>
</html>
