<?php
session_start();
require_once 'conexao.php';

$usuario = '';
if (isset($_GET['u']) && !empty($_GET['u'])) {
    $usuario = trim($_GET['u']);
} elseif (isset($_SESSION['logado']) && $_SESSION['logado'] === true && isset($_SESSION['usuario'])) {
    $usuario = trim($_SESSION['usuario']);
}

if (empty($usuario)) { die("<!DOCTYPE html><html lang='pt-br'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Fatura InvÃ¡lida</title><style>body{background:#151521;color:#fff;text-align:center;padding:50px;font-family:sans-serif;} .msg{background:#1e1e2d;padding:30px;border-radius:10px;border:1px solid #333;display:inline-block;}</style></head><body><div class='msg'><h2 style='color:#ea5455;'>ðŸš« Fatura nÃ£o encontrada.</h2><p style='color:#a6a6b7;'>Acesse pelo link exato enviado no seu WhatsApp ou faÃ§a login no painel.</p></div></body></html>"); }

$stmtRev = $connUser->prepare("SELECT * FROM rev WHERE usuario = ? LIMIT 1");
$stmtRev->execute([$usuario]);
$revendedor = $stmtRev->fetch(PDO::FETCH_ASSOC);

if (!$revendedor) { die("<!DOCTYPE html><html lang='pt-br'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Fatura InvÃ¡lida</title><style>body{background:#151521;color:#fff;text-align:center;padding:50px;font-family:sans-serif;} .msg{background:#1e1e2d;padding:30px;border-radius:10px;border:1px solid #333;display:inline-block;}</style></head><body><div class='msg'><h2 style='color:#ea5455;'>ðŸš« Revendedor nÃ£o encontrado.</h2></div></body></html>"); }

// Busca configuraÃ§Ã£o do Mercado Pago / Asaas
$dono = $revendedor['CadUser'];
$stmtConfig = $connUser->prepare("SELECT * FROM mp_revendedores WHERE usuario_revendedor = ? LIMIT 1");
$stmtConfig->execute([$dono]);
$configPgto = $stmtConfig->fetch(PDO::FETCH_ASSOC);

$token_mp = trim($configPgto['access_token'] ?? '');
$token_asaas = trim($configPgto['access_token_asaas'] ?? '');

// Busca o CPF Master (do Admin) que foi salvo no botÃ£o MSG Revenda
$stmtMsgConfig = $connGeral->prepare("SELECT cpf_admin FROM config_msg_rev WHERE id = 1 LIMIT 1");
$stmtMsgConfig->execute();
$confGeralMsg = $stmtMsgConfig->fetch(PDO::FETCH_ASSOC);
$cpf_admin = preg_replace('/[^0-9]/', '', $confGeralMsg['cpf_admin'] ?? '');

$mapa_perfis = [];
$res_p = $connGeral->query("SELECT id, nome FROM perfil")->fetchAll(PDO::FETCH_ASSOC);
foreach($res_p as $p) { $mapa_perfis[$p['id']] = mb_strtolower($p['nome']); }

// CORREÇÃO AQUI: Em vez de pegar só clientes da hora atual em diante, ele volta no tempo 3 dias (3 * 24 * 60 * 60 = 259200 segundos)
$agora = time();
$tres_dias_atras = $agora - (3 * 24 * 60 * 60);

$sql_conta = "SELECT perfil FROM usuario WHERE CadUser = ? AND bloqueado != 'sim' AND IF(data_premio REGEXP '^[0-9]+$', CAST(data_premio AS UNSIGNED), UNIX_TIMESTAMP(STR_TO_DATE(data_premio, '%Y-%m-%d'))) > ?";
$stmt_conta = $connUser->prepare($sql_conta);
$stmt_conta->execute([$usuario, $tres_dias_atras]);
$cli_ativos = $stmt_conta->fetchAll(PDO::FETCH_ASSOC);

$qtd_ativos = count($cli_ativos);
$total_fatura = 0;

foreach($cli_ativos as $cli) {
    $p_nome = $mapa_perfis[$cli['perfil']] ?? '';
    if (strpos($p_nome, 'net') !== false) {
        $total_fatura += (float)$revendedor['valor_net'];
    } else {
        $total_fatura += (float)$revendedor['valor_claro'];
    }
}

if ($total_fatura <= 0) { $total_fatura = 0; }

$pix_copia_cola = ""; $qr_code_base64 = ""; $erro_geracao = "";
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$url_webhook = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/webhook.php";

// =========================================================================
// 5. GERAÇÃO DO PIX API
// =========================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $gateway = $_POST['gateway'] ?? '';
    
    // ----------- MERCADO PAGO -----------
    if ($gateway === 'mp' && !empty($token_mp)) {
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://api.mercadopago.com/v1/payments',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode([
                "transaction_amount" => (float)$total_fatura,
                "description" => "Renovacao Painel " . $usuario,
                "payment_method_id" => "pix",
                "notification_url" => $url_webhook, 
                "payer" => [
                    "email" => $usuario . "@revenda.com",
                    "first_name" => $revendedor['nome'] ?: $usuario
                ]
            ]),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $token_mp,
                'X-Idempotency-Key: ' . uniqid()
            ],
        ]);
        
        $response = curl_exec($curl); curl_close($curl);
        $resp_obj = json_decode($response);
        
        if (isset($resp_obj->id) && isset($resp_obj->point_of_interaction)) {
            $id_pagamento = $resp_obj->id;
            $pix_copia_cola = $resp_obj->point_of_interaction->transaction_data->qr_code;
            $qr_code_base64 = $resp_obj->point_of_interaction->transaction_data->qr_code_base64;
            
            $stmtInsert = $connUser->prepare("INSERT INTO pagamentos (id_pagamento_mp, usuario_id, status, valor) VALUES (?, ?, 'pending', ?)");
            $stmtInsert->execute([$id_pagamento, $usuario, $total_fatura]);
        } else {
            $erro_geracao = "Erro ao gerar PIX no Mercado Pago. Verifique seu Access Token.";
        }
    } 
    // ----------- ASAAS -----------
    elseif ($gateway === 'asaas' && !empty($token_asaas)) {
        
        if (empty($cpf_admin) || strlen($cpf_admin) !== 11) {
            $erro_geracao = "O Administrador ainda não configurou o CPF Mestre (para o Asaas) nas configurações do painel.";
        } else {
            // 1. Criar ou puxar Cliente no Asaas usando o NOME do revendedor, mas o SEU CPF MESTRE!
            $curl_cus = curl_init();
            curl_setopt_array($curl_cus, [
                CURLOPT_URL => "https://api.asaas.com/v3/customers",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode(["name" => $revendedor['nome'] ?: $usuario, "cpfCnpj" => $cpf_admin]),
                CURLOPT_HTTPHEADER => ["Content-Type: application/json", "access_token: " . $token_asaas],
            ]);
            $resp_cus = json_decode(curl_exec($curl_cus)); curl_close($curl_cus);

            $customer_id = $resp_cus->id ?? null;

            if ($customer_id) {
                // 2. Criar CobranÃ§a PIX
                $curl_pay = curl_init();
                curl_setopt_array($curl_pay, [
                    CURLOPT_URL => "https://api.asaas.com/v3/payments",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => json_encode([
                        "customer" => $customer_id,
                        "billingType" => "PIX",
                        "value" => (float)$total_fatura,
                        "dueDate" => date('Y-m-d'),
                        "description" => "Renovacao Painel " . $usuario
                    ]),
                    CURLOPT_HTTPHEADER => ["Content-Type: application/json", "access_token: " . $token_asaas],
                ]);
                $resp_pay = json_decode(curl_exec($curl_pay)); curl_close($curl_pay);

                $pay_id = $resp_pay->id ?? null;

                if ($pay_id) {
                    // 3. Pegar o QR Code dessa cobranÃ§a
                    $curl_qr = curl_init();
                    curl_setopt_array($curl_qr, [
                        CURLOPT_URL => "https://api.asaas.com/v3/payments/".$pay_id."/pixQrCode",
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_HTTPHEADER => ["access_token: " . $token_asaas],
                    ]);
                    $resp_qr = json_decode(curl_exec($curl_qr)); curl_close($curl_qr);

                    $pix_copia_cola = $resp_qr->payload ?? '';
                    $qr_code_base64 = $resp_qr->encodedImage ?? '';

                    if (!empty($pix_copia_cola)) {
                        $stmtInsert = $connUser->prepare("INSERT INTO pagamentos (id_pagamento_mp, usuario_id, status, valor) VALUES (?, ?, 'pending', ?)");
                        $stmtInsert->execute([$pay_id, $usuario, $total_fatura]);
                    } else {
                        $erro_geracao = "Cobrança gerada, mas houve erro ao puxar o código PIX do Asaas.";
                    }
                } else {
                    $erro_geracao = "Erro ao gerar cobrança no Asaas. " . ($resp_pay->errors[0]->description ?? '');
                }
            } else {
                $erro_geracao = "Erro ao validar o CPF Mestre no Asaas. " . ($resp_cus->errors[0]->description ?? '');
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fatura | <?= htmlspecialchars($usuario) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background-color: #151521; color: #fff; font-family: 'Segoe UI', sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; padding: 15px; }
        .card-fatura { background: #1e1e2d; border: 1px solid #2b2b40; border-radius: 15px; width: 100%; max-width: 450px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); overflow: hidden; }
        .header-fatura { background: linear-gradient(90deg, #1e1e2d 0%, #7367f0 100%); padding: 25px 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .valor-destaque { font-size: 2.5rem; font-weight: 800; color: #28c76f; text-shadow: 0 2px 5px rgba(40, 199, 111, 0.3); }
        .box-info { background: #151521; border-radius: 8px; padding: 15px; border: 1px solid #333; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center; }
        .btn-mp { background-color: #009ee3; color: white; border: none; }
        .btn-mp:hover { background-color: #0080b7; color: white; }
        .btn-asaas { background-color: #002d62; color: white; border: none; }
        .btn-asaas:hover { background-color: #001a3a; color: white; }
        .qr-code-box img { max-width: 200px; border-radius: 10px; border: 4px solid #fff; margin: 15px 0; }
        .copia-cola-input { background: #111 !important; border: 1px dashed #7367f0 !important; color: #0f0 !important; font-family: monospace; font-size: 0.85rem; text-align: center; }
    </style>
</head>
<body>

<div class="card-fatura">
    <div class="header-fatura">
        <h4 class="mb-0 fw-bold"><i class="fas fa-file-invoice-dollar me-2"></i> Renovação de Painel</h4>
        <div class="small text-white-50 mt-1">Revendedor: <?= htmlspecialchars($usuario) ?></div>
    </div>
    
    <div class="p-4">
        <?php if ($total_fatura <= 0): ?>
            <div class="text-center py-4">
                <i class="fas fa-check-circle text-success" style="font-size: 4rem;"></i>
                <h4 class="mt-3 fw-bold">Tudo Certo!</h4>
                <p class="text-white-50">Você não tem clientes ativos ou custos pendentes para esta renovação.</p>
            </div>
        <?php else: ?>
        
            <?php if (!empty($erro_geracao)): ?>
                <div class="alert alert-danger border-0 small"><i class="fas fa-exclamation-triangle me-2"></i><?= $erro_geracao ?></div>
            <?php endif; ?>

            <?php if (empty($pix_copia_cola)): ?>
                <div class="text-center mb-4">
                    <div class="text-white-50 small fw-bold text-uppercase">Total da Fatura</div>
                    <div class="valor-destaque">R$ <?= number_format($total_fatura, 2, ',', '.') ?></div>
                </div>

                <div class="box-info">
                    <div>
                        <div class="text-white-50 small fw-bold">Clientes Ativos</div>
                        <div class="fw-bold fs-5"><?= $qtd_ativos ?> <i class="fas fa-users text-primary ms-1"></i></div>
                    </div>
                    <div class="text-end">
                        <div class="text-white-50 small fw-bold">Vencimento Atual</div>
                        <div class="fw-bold text-warning"><?= date('d/m/Y', (int)$revendedor['data_premio']) ?></div>
                    </div>
                </div>

                <div class="mt-4">
                    <h6 class="fw-bold text-center mb-3">Escolha como pagar:</h6>
                    
                    <?php if(!empty($token_mp)): ?>
                    <form method="POST" class="mb-3">
                        <input type="hidden" name="gateway" value="mp">
                        <button type="submit" class="btn btn-mp w-100 fw-bold py-3 shadow"><i class="fas fa-handshake me-2"></i> PAGAR COM MERCADO PAGO</button>
                    </form>
                    <?php endif; ?>

                    <?php if(!empty($token_asaas)): ?>
                    <form method="POST">
                        <input type="hidden" name="gateway" value="asaas">
                        <button type="submit" class="btn btn-asaas w-100 fw-bold py-3 shadow"><i class="fas fa-money-check-alt me-2"></i> PAGAR COM ASAAS</button>
                    </form>
                    <?php endif; ?>
                    
                    <?php if(empty($token_mp) && empty($token_asaas)): ?>
                        <div class="alert alert-warning text-center border-0 mt-3 small"><i class="fas fa-exclamation-circle me-1"></i> Nenhuma chave PIX automÃ¡tica foi configurada.</div>
                    <?php endif; ?>
                </div>

            <?php else: ?>
                <div class="text-center">
                    <h5 class="text-success fw-bold"><i class="fas fa-check-circle me-2"></i> PIX Gerado!</h5>
                    <p class="text-white-50 small mb-0">Abra o app do seu banco e escaneie o código ou copie a chave abaixo.</p>
                    
                    <div class="qr-code-box">
                        <img src="data:image/jpeg;base64,<?= $qr_code_base64 ?>" alt="QR Code PIX">
                    </div>
                    
                    <label class="small fw-bold text-white-50 mt-2 mb-1">PIX Copia e Cola:</label>
                    <input type="text" id="pixCode" class="form-control copia-cola-input p-3 mb-3" value="<?= $pix_copia_cola ?>" readonly>
                    
                    <button onclick="copiarPix()" class="btn btn-primary w-100 fw-bold py-3 shadow-sm mb-3"><i class="fas fa-copy me-2"></i> COPIAR CÓDIGO PIX</button>
                    
                    <div class="alert alert-info border-0 small text-start" style="background: rgba(0, 207, 232, 0.1);">
                        <i class="fas fa-robot me-2 text-info"></i> O seu painel será¡ <b>renovado automaticamente</b> assim que o pagamento for confirmado. Não envie comprovante!
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<script>
    function copiarPix() {
        var copyText = document.getElementById("pixCode");
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(copyText.value).then(() => {
            alert("CÃ³digo PIX copiado com sucesso!");
        });
    }
</script>
</body>
</html>
