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

// --- CONFIGURAÇÃO DA TAXA EXTRA ---
// Mude aqui o valor que você quer cobrar a mais do cliente
$taxa_extra = 3.00; 
// ----------------------------------

// --- FUNÇÃO: GERADOR DE CPF VÁLIDO ---
function gerarCpf() {
    $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}";
}

// --- FUNÇÃO: CRIA CLIENTE NO ASAAS ---
function criarClienteAsaas($token, $nome, $email, $cpf) {
    $ch = curl_init("https://www.asaas.com/api/v3/customers?email=" . $email);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["access_token: $token"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (isset($res['data'][0]['id'])) {
        return ['success' => true, 'id' => $res['data'][0]['id']];
    }

    $dados = ["name" => $nome, "email" => $email, "cpfCnpj" => $cpf];
    
    $ch = curl_init("https://www.asaas.com/api/v3/customers");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dados));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["access_token: $token", "Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $criado = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (isset($criado['id'])) {
        return ['success' => true, 'id' => $criado['id']];
    } else {
        $erroMsg = $criado['errors'][0]['description'] ?? 'Erro desconhecido ao criar cliente.';
        return ['success' => false, 'error' => $erroMsg];
    }
}

// 1. VERIFICA LOGIN
if (!isset($_SESSION['cliente_logado'])) { header("Location: cliente_login.php"); exit; }
$user = $_SESSION['cliente_user'];

// 2. DADOS DO USUÁRIO
$stmt = $connUser->prepare("SELECT * FROM usuario WHERE usuario = ?");
$stmt->execute([$user]);
$dados = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$dados) { header("Location: cliente_login.php"); exit; }
$dono_revenda = $dados['CadUser'];

// 3. FORMATAÇÃO
$venc_original = $dados['data_premio'];
$venc_timestamp = is_numeric($venc_original) ? (int)$venc_original : strtotime($venc_original);
$data_vencimento_formatada = date('d/m/Y', $venc_timestamp);
$status_cor = ($venc_timestamp < time()) ? '#ea5455' : '#28c76f'; 
$status_texto = ($venc_timestamp < time()) ? 'Vencido' : 'Ativo';

// 4. CONFIGURAÇÃO 
$stmtRev = $connUser->prepare("SELECT access_token, dados_bancarios FROM mp_revendedores WHERE usuario_revendedor = ?");
$stmtRev->execute([$dono_revenda]);
$config_revenda = $stmtRev->fetch(PDO::FETCH_ASSOC);

if (!$config_revenda) {
    $config_revenda = [];
}

$api_key_asaas = $config_revenda['access_token'] ?? ''; 
$dados_bancarios_texto = $config_revenda['dados_bancarios'] ?? "Contate o suporte.";
$tem_asaas = !empty($api_key_asaas) && strpos(trim($api_key_asaas), '$') === 0; 

// 5. PLANOS
$planos = [];
try {
    $stmtPlanos = $connUser->prepare("SELECT * FROM planos_revenda WHERE id_revendedor = ? ORDER BY valor ASC");
    $stmtPlanos->execute([$dono_revenda]);
    $planos_db = $stmtPlanos->fetchAll(PDO::FETCH_ASSOC);
    if (count($planos_db) > 0) {
        foreach ($planos_db as $p) {
            $planos[] = ['nome' => $p['nome_plano'], 'dias' => $p['dias'], 'valor' => $p['valor'], 'logo' => $p['logo_perfil'] ?? 'iptv.png'];
        }
    } else {
        $planos[] = ['nome' => 'Renovação Mensal', 'dias' => 30, 'valor' => 25.00, 'logo' => 'iptv.png'];
    }
} catch (Exception $e) {}

// 6. PROCESSAMENTO (ASAAS COM TAXA)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['plano_idx']) && $tem_asaas) {
    $idx = (int)$_POST['plano_idx'];
    $tipo_pagamento = $_POST['metodo'] == 'pix' ? 'PIX' : 'CREDIT_CARD';
    
    if (isset($planos[$idx])) {
        $plano_sel = $planos[$idx];
        
        // --- CÁLCULO DO VALOR FINAL COM TAXA ---
        $valor_original = (float)$plano_sel['valor'];
        $valor_cobrar = $valor_original + $taxa_extra;
        // ---------------------------------------

        $email_cli = $dados['email'] ?? "cli_" . $user . "@email.com";
        if (!filter_var($email_cli, FILTER_VALIDATE_EMAIL)) {
            $email_cli = "cliente_" . rand(1000,9999) . "@email.com";
        }
        
        $cpf_cli = gerarCpf(); 

        // 1. Cliente Asaas
        $resultado_cliente = criarClienteAsaas($api_key_asaas, $user, $email_cli, $cpf_cli);

        if ($resultado_cliente['success']) {
            $asaas_customer_id = $resultado_cliente['id'];

            // 2. Cria a Cobrança com Valor Aumentado e Dias do Plano
            // O segredo está aqui: Mandar "USUARIO||DIAS" no externalReference
            $dados_cobranca = [
                "customer" => $asaas_customer_id,
                "billingType" => $tipo_pagamento,
                "value" => $valor_cobrar, 
                "dueDate" => date('Y-m-d'),
                "description" => "Renovacao " . $plano_sel['nome'] . " (Inclui taxa de R$ " . number_format($taxa_extra, 2, ',', '.') . ")",
                "externalReference" => $user . "||" . $plano_sel['dias'] // <-- MODIFICAÇÃO IMPORTANTE AQUI
            ];

            $ch = curl_init("https://www.asaas.com/api/v3/payments");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dados_cobranca));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ["access_token: $api_key_asaas", "Content-Type: application/json"]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $resposta = curl_exec($ch);
            $res = json_decode($resposta, true);
            curl_close($ch);

            if (isset($res['invoiceUrl'])) {
                header("Location: " . $res['invoiceUrl']); 
                exit;
            } else {
                $erro = $res['errors'][0]['description'] ?? 'Erro ao gerar cobrança.';
                echo "<script>alert('Asaas Erro: $erro');</script>";
            }
        } else {
            $erroCli = $resultado_cliente['error'];
            echo "<script>alert('Erro no Cadastro do Cliente Asaas: $erroCli');</script>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Renovar | <?= htmlspecialchars($user) ?></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: #f0f2f5; color: #333; font-family: 'Segoe UI', sans-serif; }
        .header-app { background: linear-gradient(135deg, #0030b9 0%, #42a5f5 100%); padding: 30px 20px 80px; border-radius: 0 0 30px 30px; color: white; text-align: center; position: relative; }
        .btn-logout { position: absolute; top: 20px; right: 20px; color: white; background: rgba(0,0,0,0.2); padding: 5px 15px; border-radius: 20px; text-decoration:none; font-size: 0.9rem; }
        .user-info-card { background: rgba(255,255,255,0.15); backdrop-filter: blur(5px); border: 1px solid rgba(255,255,255,0.2); border-radius: 15px; padding: 15px; margin-top: 20px; display: inline-block; min-width: 280px; }
        .main-container { max-width: 500px; margin: -50px auto 20px; padding: 0 15px; position: relative; z-index: 10; }
        .card-plano { background: #fff; border-radius: 15px; padding: 20px; box-shadow: 0 10px 25px rgba(0,0,0,0.08); margin-bottom: 20px; border: 1px solid #eef0f7; position: relative; overflow: hidden; display:flex; flex-direction:column; align-items:center; }
        .logo-plano { width: 60px; height: 60px; object-fit: contain; margin-bottom: 10px; }
        .plano-nome { font-size: 1.1rem; color: #555; font-weight: 700; text-transform: uppercase; }
        .plano-valor { font-size: 2.2rem; font-weight: 800; color: #0030b9; margin: 5px 0 10px; }
        .badge-dias { background: #e0e0e0; color: #555; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 700; letter-spacing: 0.5px; }
        
        .btn-pix { background: #28c76f; color: white; width: 100%; border-radius: 10px; font-weight: 700; padding: 14px; border: none; margin-top: 15px; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 10px; }
        .btn-pix:hover { background: #20a059; transform: translateY(-2px); color: white; }
        
        .btn-card { background: #009ee3; color: white; width: 100%; border-radius: 10px; font-weight: 700; padding: 14px; border: none; margin-top: 10px; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 10px; }
        .btn-card:hover { background: #007bb0; transform: translateY(-2px); color: white; }

        .btn-bank { background: #6c757d; color: white; width: 100%; border-radius: 10px; font-weight: 700; padding: 14px; border: none; margin-top: 10px; transition: 0.2s; }
        .btn-disabled { background: #ccc; width: 100%; border-radius: 10px; padding: 14px; border:none; color: #fff; font-weight: 600; margin-top: 10px; cursor: not-allowed; }
        
        .aviso-taxa { font-size: 0.85rem; color: #666; margin-top: 5px; background: #f8f9fa; padding: 5px 10px; border-radius: 5px; width: 100%; text-align: center; }
    </style>
</head>
<body>

<div class="header-app">
    <a href="cliente_sair.php" class="btn-logout"><i class="fas fa-sign-out-alt"></i> Sair</a>
    <div class="user-info-card">
        <h4 class="fw-bold mb-1"><i class="fas fa-user-circle me-2"></i><?= htmlspecialchars($user) ?></h4>
        <div class="d-flex justify-content-center gap-3 mt-2 text-white small fw-bold">
            <span><i class="fas fa-calendar-alt me-1"></i> Vence: <?= $data_vencimento_formatada ?></span>
            <span style="background: white; color: <?= $status_cor ?>; padding: 2px 8px; border-radius: 4px;"><?= $status_texto ?></span>
        </div>
    </div>
</div>

<div class="main-container">
    <?php if(count($planos) > 0): ?>
        <?php foreach($planos as $idx => $plano): ?>
        <div class="card-plano">
            <img src="../img/<?= htmlspecialchars($plano['logo']) ?>" class="logo-plano" onerror="this.style.display='none'">
            <div class="plano-nome"><?= htmlspecialchars($plano['nome']) ?></div>
            
            <div class="plano-valor">
                R$ <?= number_format($plano['valor'], 2, ',', '.') ?>
            </div>
            
            <span class="badge-dias"><i class="fas fa-clock me-1"></i> <?= $plano['dias'] ?> DIAS DE ACESSO</span>
            
            <div style="width:100%">
                <?php if($tem_asaas): ?>
                
                <div class="aviso-taxa">
                    <i class="fas fa-info-circle"></i> Será adicionada taxa de R$ <?= number_format($taxa_extra, 2, ',', '.') ?> no checkout.
                </div>

                <form method="POST">
                    <input type="hidden" name="plano_idx" value="<?= $idx ?>">
                    <input type="hidden" name="metodo" value="pix">
                    <button type="submit" class="btn-pix"><i class="fa-brands fa-pix"></i> PAGAR COM PIX (R$ <?= number_format($plano['valor'] + $taxa_extra, 2, ',', '.') ?>)</button>
                </form>

                <form method="POST">
                    <input type="hidden" name="plano_idx" value="<?= $idx ?>">
                    <input type="hidden" name="metodo" value="card">
                    <button type="submit" class="btn-card"><i class="fas fa-credit-card"></i> PAGAR COM CARTÃO</button>
                </form>

                <?php else: ?>
                <button class="btn-disabled"><i class="fas fa-ban me-2"></i> Pagamento Indisponível</button>
                <?php endif; ?>
                
                <button class="btn-bank" data-bs-toggle="modal" data-bs-target="#modalBank"><i class="fas fa-university me-2"></i> DEPÓSITO MANUAL</button>
            </div>
        </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="alert alert-warning text-center">Nenhum plano disponível no momento.</div>
    <?php endif; ?>
</div>

<div class="modal fade" id="modalBank" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
            <div class="modal-header bg-success text-white"><h5 class="modal-title fw-bold">Dados Bancários</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4 bg-light"><div class="p-3 bg-white border rounded shadow-sm"><pre style="white-space: pre-wrap; font-family: sans-serif; color: #444;"><?= $dados_bancarios_texto ?></pre></div></div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
