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

// --- CONFIGURAÇÃO DA TAXA EXTRA ---
$taxa_extra = 3.00; 
// ----------------------------------

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}";
}

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 { return ['success' => false, 'error' => $criado['errors'][0]['description'] ?? 'Erro desconhecido ao criar cliente.']; }
}

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

// 2. BUSCA DADOS DO CLIENTE (Ou Teste) NO BANCO
$stmt = $connUser->prepare("SELECT * FROM usuario WHERE usuario = ?");
$stmt->execute([$user]);
$dados = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$dados) {
    $stmtT = $connUser->prepare("SELECT * FROM teste WHERE usuario = ?");
    $stmtT->execute([$user]);
    $dados = $stmtT->fetch(PDO::FETCH_ASSOC);
}

// Se não achar o cliente (foi deletado), desloga.
if(!$dados) { 
    session_destroy();
    header("Location: ./"); 
    exit; 
}

$dono_revenda = $dados['CadUser'];
$id_perfil_cliente = $dados['perfil'] ?? null;

// 3. FORMATAÇÃO DE VENCIMENTO
$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';

// =========================================================================
// 3.5 BUSCAR DADOS DO SERVIDOR E OPERADORA
// =========================================================================
$op_nome = "Operadora";
$op_url = "Não configurado";
$op_porta = "00000";
$op_img = "";

$status_servidor_real = false;
$cliente_usa_claro = false; // Sinalizador
$cliente_usa_net = false;   // Sinalizador

if ($id_perfil_cliente) {
    // Tenta achar o perfil específico do cliente
    $stOp = $connGeral->prepare("SELECT nome, url, porta FROM perfil WHERE id = ? LIMIT 1");
    $stOp->execute([$id_perfil_cliente]);
    $perfil_db = $stOp->fetch(PDO::FETCH_ASSOC);
    
    if ($perfil_db) {
        $op_nome = $perfil_db['nome'];
        $op_url = $perfil_db['url'];
        $op_porta = $perfil_db['porta'];
        
        $nome_low = strtolower($op_nome);
        if (strpos($nome_low, 'claro') !== false) {
            $cliente_usa_claro = true;
            $op_img = '<img src="../img/claro.png" style="height: 20px; vertical-align: middle; filter: drop-shadow(0 0 2px rgba(255,255,255,0.5));">';
        } elseif (strpos($nome_low, 'net') !== false) {
            $cliente_usa_net = true;
            $op_img = '<img src="../img/net.png" style="height: 20px; vertical-align: middle; filter: drop-shadow(0 0 2px rgba(255,255,255,0.5));">';
        }

        // Testar Status do Servidor deste perfil
        if (!empty($op_url) && !empty($op_porta)) {
            $ip_clean = str_replace(['http://', 'https://', '/'], '', $op_url);
            $con = @fsockopen($ip_clean, $op_porta, $errCode, $errStr, 1);
            if ($con) {
                $status_servidor_real = true;
                fclose($con);
            }
        }
    }
}

// SE ELE NÃO TIVER PERFIL (OU DEU ERRO), PUXA UM GENÉRICO DA CLARO E NET
$op_generica_html = "";
if (empty($op_url) || $op_url == "Não configurado") {
    $op_claro = $connGeral->query("SELECT url, porta FROM perfil WHERE LOWER(nome) LIKE '%claro%' AND (bloqueado IS NULL OR bloqueado != 'sim') LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $op_net = $connGeral->query("SELECT url, porta FROM perfil WHERE LOWER(nome) LIKE '%net%' AND (bloqueado IS NULL OR bloqueado != 'sim') LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    
    if ($op_claro) {
        $op_generica_html .= "
        <div style='margin-bottom: 5px;'>
            <img src='../img/claro.png' style='height: 18px; vertical-align: middle;'> 
            <span style='color:#a6a6b7; font-size:0.85rem; font-family:monospace;'>URL: {$op_claro['url']} | Porta: {$op_claro['porta']}</span>
        </div>";
    }
    if ($op_net) {
        $op_generica_html .= "
        <div>
            <img src='../img/net.png' style='height: 18px; vertical-align: middle;'> 
            <span style='color:#a6a6b7; font-size:0.85rem; font-family:monospace;'>URL: {$op_net['url']} | Porta: {$op_net['porta']}</span>
        </div>";
    }
    if(empty($op_generica_html)) {
        $op_generica_html = "<span style='color:#ea5455; font-size:0.85rem;'>Nenhuma operadora configurada no painel.</span>";
    }
}

// =========================================================================
// 4. VERIFICA QUEM É O DONO (ADMIN OU REVENDEDOR)
// =========================================================================
$isAdminOwner = false;
$stmtAdmin = $connUser->prepare("SELECT id FROM admin WHERE usuario = ?");
$stmtAdmin->execute([$dono_revenda]);
if ($stmtAdmin->rowCount() > 0 || strtolower($dono_revenda) === 'admin') {
    $isAdminOwner = true;
}

// =========================================================================
// 5. PUXAR CONFIGURAÇÕES FINANCEIRAS (PIX / ASAAS)
// =========================================================================
$config_revenda = [];

if ($isAdminOwner) {
    $stmtRev = $connUser->prepare("SELECT access_token, dados_bancarios FROM mp_revendedores WHERE usuario_revendedor = ? LIMIT 1");
    $stmtRev->execute([$dono_revenda]);
    $config_revenda = $stmtRev->fetch(PDO::FETCH_ASSOC);

    if(!$config_revenda){
         $stmtFallback = $connUser->query("SELECT access_token, dados_bancarios FROM mp_revendedores LIMIT 1");
         $config_revenda = $stmtFallback->fetch(PDO::FETCH_ASSOC);
    }
} else {
    $stmtRev = $connUser->prepare("SELECT access_token, dados_bancarios FROM mp_revendedores WHERE usuario_revendedor = ? LIMIT 1");
    $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 para realizar o pagamento.";
$tem_asaas = !empty($api_key_asaas) && strlen($api_key_asaas) > 10; 

// =========================================================================
// 6. PUXAR OS PLANOS CORRETOS E APLICAR O FILTRO
// =========================================================================
$planos = [];
try {
    if ($isAdminOwner) {
        $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) {
            $stmtPlanosFb = $connUser->query("SELECT p.* FROM planos_revenda p JOIN admin a ON p.id_revendedor = a.usuario ORDER BY p.valor ASC");
            $planos_db = $stmtPlanosFb->fetchAll(PDO::FETCH_ASSOC);
            if(count($planos_db) == 0){
                $stmtAll = $connUser->query("SELECT * FROM planos_revenda ORDER BY valor ASC LIMIT 4");
                $planos_db = $stmtAll->fetchAll(PDO::FETCH_ASSOC);
            }
        }
    } else {
        $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) {
            $nome_do_plano = strtolower($p['nome_plano']);
            
            // FILTRO: Se o cliente for Claro, esconde planos que mencionem "Net"
            if ($cliente_usa_claro && strpos($nome_do_plano, 'net') !== false) {
                continue;
            }
            // FILTRO: Se o cliente for Net, esconde planos que mencionem "Claro"
            if ($cliente_usa_net && strpos($nome_do_plano, 'claro') !== false) {
                continue;
            }

            $planos[] = [
                'nome' => $p['nome_plano'], 
                'dias' => $p['dias'], 
                'valor' => $p['valor'], 
                'logo' => $p['logo_perfil'] ?? 'iptv.png'
            ];
        }
    }
    
    // Se o array de planos ficar vazio após o filtro ou não houver cadastro
    if (count($planos) == 0) {
        $planos[] = ['nome' => 'Renovação Padrão', 'dias' => 30, 'valor' => 30.00, 'logo' => 'iptv.png'];
    }
} catch (Exception $e) {}


// =========================================================================
// 7. PROCESSAMENTO DO PAGAMENTO (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];
        $valor_cobrar = (float)$plano_sel['valor'] + $taxa_extra;
        $nome_cli = $dados['nome'] ?? $user;

        $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(); 

        $resultado_cliente = criarClienteAsaas($api_key_asaas, $nome_cli, $email_cli, $cpf_cli);

        if ($resultado_cliente['success']) {
            $dados_cobranca = [
                "customer" => $resultado_cliente['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']
            ];

            $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 {
                echo "<script>alert('Asaas Erro: " . ($res['errors'][0]['description'] ?? 'Erro') . "');</script>";
            }
        } else {
            echo "<script>alert('Erro no Cadastro do Cliente: {$resultado_cliente['error']}');</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; }
        
        .server-status-card { background: rgba(0,0,0,0.2); border-radius: 10px; padding: 10px 15px; margin-top: 15px; text-align: left; border: 1px solid rgba(255,255,255,0.1); }

        .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($dados['nome'] ?? $user) ?></h4>
        <p class="mb-2 text-white-50 small">User: <?= htmlspecialchars($user) ?></p>
        <div class="d-flex justify-content-center gap-3 mt-2 text-white small fw-bold mb-3">
            <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 class="server-status-card">
            <?php if (!empty($op_url) && $op_url != "Não configurado"): ?>
                <div class="d-flex justify-content-between align-items-center border-bottom border-secondary pb-2 mb-2">
                    <span class="small fw-bold">Operadora:</span>
                    <span>
                        <?= $op_img ?> <span class="ms-1 small"><?= htmlspecialchars($op_nome) ?></span>
                    </span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span class="small text-white-50">URL / DNS:</span>
                    <span class="small fw-bold" style="font-family: monospace; color: #00cfe8;"><?= htmlspecialchars($op_url) ?></span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span class="small text-white-50">Porta:</span>
                    <span class="small fw-bold" style="font-family: monospace; color: #ff9f43;"><?= htmlspecialchars($op_porta) ?></span>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <span class="small text-white-50">Status do Servidor:</span>
                    <?php if ($status_servidor_real): ?>
                        <span class="badge bg-success" style="font-size: 0.7rem;">ONLINE</span>
                    <?php else: ?>
                        <span class="badge bg-danger" style="font-size: 0.7rem;">OFFLINE</span>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="text-center pb-2 mb-2 border-bottom border-secondary small fw-bold">Operadoras Disponíveis</div>
                <?= $op_generica_html ?>
            <?php endif; ?>
        </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>
