<?php
session_start();

// Trava o relógio do sistema para o horário oficial do Brasil
date_default_timezone_set('America/Sao_Paulo');

// =========================================================================
// PUXA A CONEXÃO DA PASTA OCULTA DO PAINEL
// =========================================================================
require_once '../config.php';
$pdo = getConexaoAtiva();       // Banco Principal (Streaming: Xtream UI / XUI One)
$pdo_int = getConexaoInterna(); // Banco Local (Painel: Planos, Tokens, Configurações)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// =========================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA A TABELA DE CLIENTES E VENCIMENTO
// =========================================================================
$tabela_clientes = 'users'; // Padrão Xtream UI
$col_exp = 'exp_date';      // Padrão Xtream UI

try {
    // Verifica se é XUI One (Usa a tabela 'lines')
    $check_tabela = $pdo->query("SHOW TABLES LIKE 'lines'");
    if ($check_tabela && $check_tabela->fetch()) {
        $tabela_clientes = '`lines`'; 
    }
    
    // Verifica a coluna de vencimento
    $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) {}

// TRAVA DE SEGURANÇA: Salva no Banco Interno
try {
    $pdo_int->exec("CREATE TABLE IF NOT EXISTS `pagamentos_processados` (
        `payment_id` varchar(255) PRIMARY KEY,
        `data_proc` timestamp DEFAULT CURRENT_TIMESTAMP
    )");
} catch(Exception $e) {}

// =========================================================================
// BUSCA DE PERSONALIZAÇÃO DINÂMICA (Banco Interno)
// =========================================================================
$nome_painel = 'Área do Cliente';
$logo_url = '';
$cor_primaria = '#007bff'; 

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo_int->query("SELECT * 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;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
            
            if (!empty($config_painel['logo_url'])) {
                if (preg_match('/^http/', $config_painel['logo_url'])) {
                    $logo_url = $config_painel['logo_url']; 
                } else {
                    $logo_url = '../' . $config_painel['logo_url']; 
                }
            }
        }
    }
} catch (Exception $e) {}

// =========================================================================
// LÓGICA DE LOGIN DO CLIENTE FINAL (Lê do Banco Principal)
// =========================================================================
$erro_login = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_cliente'])) {
    $user = trim($_POST['username']);
    $pass = trim($_POST['password']);

    $stmt = $pdo->prepare("SELECT id, username, $col_exp as exp_date, max_connections, member_id FROM $tabela_clientes WHERE username = ? AND password = ?");
    $stmt->execute([$user, $pass]);
    $cliente = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($cliente) {
        $_SESSION['cliente_logado'] = true;
        $_SESSION['cliente_id'] = $cliente['id'];
        $_SESSION['cliente_user'] = $cliente['username'];
        $_SESSION['dono_do_cliente'] = $cliente['member_id'];
        header("Location: ./"); 
        exit;
    } else {
        $erro_login = "Usuário ou senha incorretos!";
    }
}

if (isset($_GET['sair'])) {
    session_destroy();
    header("Location: ./");
    exit;
}

// =========================================================================
// TELA DE LOGIN (SE NÃO ESTIVER LOGADO)
// =========================================================================
if (!isset($_SESSION['cliente_logado'])) {
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo htmlspecialchars($nome_painel); ?></title>
    <style>
        :root {
            --accent: <?php echo $cor_primaria; ?>;
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: #0f1114; display: flex; justify-content: center; align-items: center; height: 100vh; color: white; }
        .login-box { background: #1e2227; padding: 40px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); width: 100%; max-width: 350px; border: 1px solid #3a4149; text-align: center; }
        .logo-img { max-width: 220px; max-height: 80px; object-fit: contain; margin-bottom: 10px; }
        input { width: 100%; padding: 15px; margin-bottom: 20px; background: #121519; border: 1px solid #3a4149; color: white; border-radius: 8px; box-sizing: border-box; font-size: 15px; transition: 0.3s; }
        input:focus { border-color: var(--accent); outline: none; }
        button { width: 100%; padding: 15px; background: var(--accent); border: none; color: white; border-radius: 8px; font-weight: bold; font-size: 16px; cursor: pointer; transition: 0.3s; }
        button:hover { filter: brightness(1.15); }
        .erro { color: #ff4d4d; font-size: 14px; margin-bottom: 15px; background: rgba(220, 53, 69, 0.1); padding: 10px; border-radius: 5px; border: 1px solid #dc3545;}
    </style>
</head>
<body>
    <div class="login-box">
        <?php if(!empty($logo_url)): ?>
            <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="logo-img">
        <?php else: ?>
            <h2 style="margin-top:0; color: var(--accent);"><?php echo htmlspecialchars($nome_painel); ?></h2>
        <?php endif; ?>
        
        <p style="color: #8a94a1; font-size: 14px; margin-bottom: 30px;">Acesse para renovar sua assinatura</p>
        <?php if($erro_login) echo "<div class='erro'>$erro_login</div>"; ?>
        <form method="POST">
            <input type="hidden" name="login_cliente" value="1">
            <input type="text" name="username" placeholder="Seu Usuário" required autocomplete="off">
            <input type="password" name="password" placeholder="Sua Senha" required>
            <button type="submit">ACESSAR MEU PAINEL</button>
        </form>
    </div>
</body>
</html>
<?php
    exit;
}

// =========================================================================
// AUTO-FIX: ALINHAMENTO DE REVENDEDOR E ADMIN MASTER (Lê do Banco Interno)
// =========================================================================
$id_do_revendedor = $_SESSION['dono_do_cliente'] ?? 1;
if (empty($id_do_revendedor) || $id_do_revendedor == 0) {
    $id_do_revendedor = 1;
}

try {
    $checkPlanos = $pdo_int->prepare("SELECT COUNT(*) FROM billing_planos WHERE owner_id = ? AND ativo = 1");
    $checkPlanos->execute([$id_do_revendedor]);
    if ($checkPlanos->fetchColumn() == 0) {
        $adminMaster = $pdo_int->query("SELECT owner_id FROM billing_planos WHERE ativo = 1 ORDER BY id ASC LIMIT 1")->fetchColumn();
        if ($adminMaster) {
            $id_do_revendedor = $adminMaster;
        }
    }
} catch(Exception $e) {}

// =========================================================================
// FUNÇÃO GERADORA DE CPF ALEATÓRIO (Bypass dos erros da API)
// =========================================================================
function gerarCpfAleatorio() {
    $n = array();
    for ($i = 0; $i < 9; $i++) { $n[] = rand(0, 9); }
    $d1 = 0; for ($i = 0; $i < 9; $i++) { $d1 += $n[$i] * (10 - $i); }
    $d1 = 11 - ($d1 % 11); if ($d1 >= 10) $d1 = 0; $n[] = $d1;
    $d2 = 0; for ($i = 0; $i < 10; $i++) { $d2 += $n[$i] * (11 - $i); }
    $d2 = 11 - ($d2 % 11); if ($d2 >= 10) $d2 = 0; $n[] = $d2;
    return implode('', $n);
}

// =========================================================================
// LÓGICA DE GERAÇÃO E CHECAGEM VIA AJAX
// =========================================================================
if (isset($_POST['gerar_pix'])) {
    header('Content-Type: application/json');
    $plano_id = (int)$_POST['plano_id'];
    $gateway = $_POST['gateway'] ?? 'mp'; 
    $metodo = $_POST['metodo'] ?? 'pix'; 
    
    $cpf_falso = gerarCpfAleatorio();
    $email_falso = "cliente_" . rand(1000,99999) . "@iptvfalso.com";

    // Busca o Plano no Banco Interno
    $stmtP = $pdo_int->prepare("SELECT * FROM billing_planos WHERE id = ? AND owner_id = ?");
    $stmtP->execute([$plano_id, $id_do_revendedor]);
    $plano = $stmtP->fetch(PDO::FETCH_ASSOC);

    if (!$plano) { echo json_encode(['erro' => 'Plano inválido.']); exit; }
    
    $valor = (float)$plano['valor'];
    $referencia_externa = $_SESSION['cliente_user'] . "|||" . $plano['meses'];

    if ($gateway === 'asaas') {
        // =============== LÓGICA ASAAS ===============
        try {
            $stmtT = $pdo_int->prepare("SELECT asaas_api_key FROM revendedor_configuracoes WHERE revendedor_id = ?");
            $stmtT->execute([$id_do_revendedor]);
            $token_asaas = $stmtT->fetchColumn();
        } catch(Exception $e) { $token_asaas = ''; }

        if (empty($token_asaas)) { echo json_encode(['erro' => 'O revendedor não configurou o Asaas.']); exit; }

        $cust_data = [
            "name" => $_SESSION['cliente_user'],
            "email" => $email_falso,
            "cpfCnpj" => $cpf_falso
        ];
        
        $ch = curl_init("https://api.asaas.com/v3/customers");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($cust_data),
            CURLOPT_HTTPHEADER => ["access_token: " . $token_asaas, "Content-Type: application/json"]
        ]);
        $cust_res = json_decode(curl_exec($ch), true);
        curl_close($ch);

        $customer_id = $cust_res['id'] ?? null;
        if (!$customer_id) { echo json_encode(['erro' => 'Erro ao conectar com Asaas. A chave pode estar incorreta.']); exit; }

        if ($metodo === 'cartao') {
            $pay_data = [
                "customer" => $customer_id,
                "billingType" => "UNDEFINED", 
                "value" => $valor,
                "dueDate" => date('Y-m-d'),
                "description" => "Renovação IPTV - " . $plano['meses'] . " Mes(es)",
                "externalReference" => $referencia_externa
            ];
            
            $ch = curl_init("https://api.asaas.com/v3/payments");
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($pay_data),
                CURLOPT_HTTPHEADER => ["access_token: " . $token_asaas, "Content-Type: application/json"]
            ]);
            $pay_res = json_decode(curl_exec($ch), true);
            curl_close($ch);

            if (isset($pay_res['invoiceUrl'])) {
                echo json_encode(['sucesso' => true, 'link_cartao' => $pay_res['invoiceUrl']]);
            } else {
                echo json_encode(['erro' => 'Erro ao gerar Link do Asaas.']);
            }
            exit;

        } else {
            $pay_data = [
                "customer" => $customer_id,
                "billingType" => "PIX",
                "value" => $valor,
                "dueDate" => date('Y-m-d'),
                "description" => "Renovação IPTV - " . $plano['meses'] . " Mes(es)",
                "externalReference" => $referencia_externa
            ];
            
            $ch = curl_init("https://api.asaas.com/v3/payments");
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($pay_data),
                CURLOPT_HTTPHEADER => ["access_token: " . $token_asaas, "Content-Type: application/json"]
            ]);
            $pay_res = json_decode(curl_exec($ch), true);
            curl_close($ch);

            $payment_id = $pay_res['id'] ?? null;
            if (!$payment_id) { echo json_encode(['erro' => 'Erro ao gerar PIX no Asaas.']); exit; }

            $ch = curl_init("https://api.asaas.com/v3/payments/" . $payment_id . "/pixQrCode");
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => ["access_token: " . $token_asaas]
            ]);
            $qr_res = json_decode(curl_exec($ch), true);
            curl_close($ch);

            if (isset($qr_res['encodedImage'])) {
                echo json_encode([
                    'sucesso' => true,
                    'qr_code_base64' => str_replace('data:image/png;base64,', '', $qr_res['encodedImage']),
                    'copia_cola' => $qr_res['payload'],
                    'payment_id' => $payment_id
                ]);
            } else {
                echo json_encode(['erro' => 'Erro ao obter código PIX do Asaas.']);
            }
            exit;
        }

    } else {
        // =============== LÓGICA MERCADO PAGO ===============
        $stmtT = $pdo_int->prepare("SELECT mp_access_token FROM revendedor_configuracoes WHERE revendedor_id = ?");
        $stmtT->execute([$id_do_revendedor]);
        $token_mp = $stmtT->fetchColumn();

        if (empty($token_mp)) { echo json_encode(['erro' => 'O revendedor não configurou o Mercado Pago.']); exit; }

        if ($metodo === 'cartao') {
            $data = [
                "items" => [[
                    "title" => "Renovação IPTV - " . $plano['meses'] . " Mes(es)",
                    "quantity" => 1,
                    "unit_price" => $valor
                ]],
                "payer" => [
                    "name" => $_SESSION['cliente_user'],
                    "email" => $email_falso
                ],
                "external_reference" => $referencia_externa
            ];

            $curl = curl_init("https://api.mercadopago.com/checkout/preferences");
            curl_setopt_array($curl, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . $token_mp, "Content-Type: application/json" ],
            ]);
            $response = curl_exec($curl);
            curl_close($curl);
            
            $json = json_decode($response, true);
            if (isset($json['init_point'])) {
                echo json_encode(['sucesso' => true, 'link_cartao' => $json['init_point']]);
            } else {
                echo json_encode(['erro' => 'Erro ao gerar Link do Cartão no Mercado Pago.']);
            }
            exit;

        } else {
            $data = [
                "transaction_amount" => $valor,
                "description" => "Renovação IPTV - " . $plano['meses'] . " Mes(es)",
                "payment_method_id" => "pix",
                "payer" => [ 
                    "email" => $email_falso, 
                    "first_name" => $_SESSION['cliente_user'], 
                    "last_name" => "Cliente",
                    "identification" => [ "type" => "CPF", "number" => $cpf_falso ]
                ],
                "external_reference" => $referencia_externa 
            ];

            $curl = curl_init("https://api.mercadopago.com/v1/payments");
            curl_setopt_array($curl, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . $token_mp, "Content-Type: application/json" ],
            ]);

            $response = curl_exec($curl);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);

            $json = json_decode($response, true);

            if ($httpcode == 201 || $httpcode == 200) {
                $qr_code_base64 = $json['point_of_interaction']['transaction_data']['qr_code_base64'];
                $copia_cola = $json['point_of_interaction']['transaction_data']['qr_code'];
                $payment_id = $json['id'];
                
                echo json_encode([
                    'sucesso' => true,
                    'qr_code_base64' => $qr_code_base64,
                    'copia_cola' => $copia_cola,
                    'payment_id' => $payment_id
                ]);
            } else {
                echo json_encode(['erro' => 'Erro no Mercado Pago. Verifique seu Access Token.']);
            }
            exit;
        }
    }
}

// Checagem de pagamento
if (isset($_GET['checar_pagamento'])) {
    header('Content-Type: application/json');
    $payment_id = $_GET['checar_pagamento'];
    $gateway = $_GET['gateway'] ?? 'mp';
    
    $status_aprovado = false;
    $referencia_externa = "";

    if ($gateway === 'asaas') {
        try {
            $stmtT = $pdo_int->prepare("SELECT asaas_api_key FROM revendedor_configuracoes WHERE revendedor_id = ?");
            $stmtT->execute([$id_do_revendedor]);
            $token_asaas = $stmtT->fetchColumn();
        } catch(Exception $e) { $token_asaas = ''; }

        $ch = curl_init("https://api.asaas.com/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')) {
            $status_aprovado = true;
            $referencia_externa = $json['externalReference'];
        }
    } else {
        $stmtT = $pdo_int->prepare("SELECT mp_access_token FROM revendedor_configuracoes WHERE revendedor_id = ?");
        $stmtT->execute([$id_do_revendedor]);
        $token_mp = $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 ],
        ]);
        $response = curl_exec($curl);
        $json = json_decode($response, true);
        curl_close($curl);

        if (isset($json['status']) && $json['status'] === 'approved') {
            $status_aprovado = true;
            $referencia_externa = $json['external_reference'];
        }
    }
    
    if ($status_aprovado) {
        $ref = explode('|||', $referencia_externa);
        $user_cli = $ref[0];
        $meses_comprados = (int)$ref[1];

        // Verifica no Banco Interno se já foi processado
        $stmtVer = $pdo_int->prepare("SELECT COUNT(*) FROM pagamentos_processados WHERE payment_id = ?");
        $stmtVer->execute([$payment_id]);
        
        if ($stmtVer->fetchColumn() == 0) {
            // Atualiza o vencimento no Banco Principal
            $stmtC = $pdo->prepare("SELECT id, $col_exp as exp_date FROM $tabela_clientes WHERE username = ?");
            $stmtC->execute([$user_cli]);
            $cliData = $stmtC->fetch(PDO::FETCH_ASSOC);

            if ($cliData) {
                $data_atual = ($cliData['exp_date'] == 0 || $cliData['exp_date'] < time()) ? time() : $cliData['exp_date'];
                $nova_data = strtotime("+" . $meses_comprados . " months", $data_atual);

                $pdo->prepare("UPDATE $tabela_clientes SET $col_exp = ?, enabled = 1 WHERE id = ?")->execute([$nova_data, $cliData['id']]);
                
                // Registra o pagamento no Banco Interno
                $pdo_int->prepare("INSERT INTO pagamentos_processados (payment_id) VALUES (?)")->execute([$payment_id]);
            }
        }
        
        echo json_encode(['pago' => true]);
        exit;
    } else {
        echo json_encode(['pago' => false]);
    }
    exit;
}

// =========================================================================
// DASHBOARD DO CLIENTE (HTML)
// =========================================================================
// Busca o cliente no Banco Principal
$stmt = $pdo->prepare("SELECT *, $col_exp as exp_date FROM $tabela_clientes WHERE id = ?");
$stmt->execute([$_SESSION['cliente_id']]);
$dados_cliente = $stmt->fetch(PDO::FETCH_ASSOC);

// Busca os tokens no Banco Interno
$tem_mp = false;
$tem_asaas = false;
try {
    $stmtChaves = $pdo_int->prepare("SELECT * FROM revendedor_configuracoes WHERE revendedor_id = ?");
    $stmtChaves->execute([$id_do_revendedor]);
    $chaves_rev = $stmtChaves->fetch(PDO::FETCH_ASSOC);
    if ($chaves_rev) {
        if (!empty($chaves_rev['mp_access_token'])) $tem_mp = true;
        if (isset($chaves_rev['asaas_api_key']) && !empty($chaves_rev['asaas_api_key'])) $tem_asaas = true;
    }
} catch(Exception $e) {}

// Busca os Planos no Banco Interno
$planos = [];
try {
    $stmtP = $pdo_int->prepare("SELECT * FROM billing_planos WHERE ativo = 1 AND owner_id = ? ORDER BY meses ASC");
    $stmtP->execute([$id_do_revendedor]);
    $planos = $stmtP->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

$vencimento = ($dados_cliente['exp_date'] == 0) ? "Ilimitado" : date('d/m/Y H:i', $dados_cliente['exp_date']);
$status = ($dados_cliente['exp_date'] < time() && $dados_cliente['exp_date'] != 0) ? "<span style='color:#dc3545;'>VENCIDO</span>" : "<span style='color:#28a745;'>ATIVO</span>";

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel - <?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 {
            --accent: <?php echo $cor_primaria; ?>;
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: #0f1114; color: #d1d5da; }
        .header { background: #1e2227; padding: 20px; text-align: center; border-bottom: 1px solid #3a4149; }
        .logo-img-dash { max-width: 180px; max-height: 50px; object-fit: contain; }
        .container { max-width: 900px; margin: 30px auto; padding: 0 20px; }
        
        .info-card { background: #272c33; padding: 25px; border-radius: 12px; border: 1px solid #3a4149; margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px; }
        .info-box { text-align: center; flex: 1; min-width: 150px; }
        .info-box span { display: block; font-size: 12px; color: #8a94a1; text-transform: uppercase; margin-bottom: 5px; }
        .info-box strong { font-size: 20px; color: white; }
        
        .planos-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
        .plano-card { background: #1e2227; border: 1px solid #3a4149; border-radius: 12px; padding: 25px; text-align: center; transition: 0.3s; position: relative; overflow: hidden; }
        .plano-card:hover { border-color: var(--accent); transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.4); }
        .plano-nome { font-size: 18px; font-weight: bold; color: white; margin-bottom: 10px; }
        .plano-valor { font-size: 32px; font-weight: bold; color: #28a745; margin-bottom: 20px; }
        .btn-renovar { background: var(--accent); color: white; border: none; padding: 12px; width: 100%; border-radius: 8px; font-weight: bold; font-size: 14px; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px;}
        .btn-renovar:hover { filter: brightness(1.15); }
        
        .btn-sair { background: rgba(220, 53, 69, 0.1); border: 1px solid #dc3545; color: #dc3545; padding: 6px 12px; border-radius: 5px; text-decoration: none; font-size: 13px; font-weight: bold; transition: 0.2s;}
        .btn-sair:hover { background: #dc3545; color: white; }

        /* MODAL PIX */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.8); align-items: center; justify-content: center; }
        .modal-content { background: #1e2227; padding: 30px; border-radius: 12px; border: 1px solid var(--accent); text-align: center; max-width: 350px; width: 90%; }
        .qr-code-img { width: 200px; height: 200px; border-radius: 8px; margin: 15px 0; border: 5px solid white; }
        .copia-cola { background: #121519; color: #28a745; padding: 10px; border-radius: 6px; border: 1px dashed #28a745; font-family: monospace; font-size: 12px; word-break: break-all; margin-bottom: 15px; }
        .btn-copiar { background: #28a745; color: white; border: none; padding: 10px; width: 100%; border-radius: 6px; font-weight: bold; cursor: pointer; margin-bottom: 10px; }
        .loader { border: 4px solid #3a4149; border-top: 4px solid var(--accent); border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 0 auto 15px auto; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>

    <div class="header">
        <?php if(!empty($logo_url)): ?>
            <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="logo-img-dash">
        <?php else: ?>
            <h2 style="margin:0; color:white;"><i class="fas fa-user-circle" style="color:var(--accent);"></i> <?php echo htmlspecialchars($nome_painel); ?></h2>
        <?php endif; ?>
        
        <div style="margin-top:15px; display:flex; justify-content:center; align-items:center; gap: 15px;">
            <span style="font-size: 14px;">Olá, <strong style="color:white;"><?php echo htmlspecialchars($dados_cliente['username']); ?></strong>!</span>
            <a href="?sair=1" class="btn-sair"><i class="fas fa-sign-out-alt"></i> SAIR</a>
        </div>
    </div>

    <div class="container">
        <h3 style="color:white; margin-top:0;"><i class="fas fa-info-circle" style="color:var(--accent);"></i> Detalhes da sua Conta</h3>
        <div class="info-card">
            <div class="info-box"><span>Status</span><strong><?php echo $status; ?></strong></div>
            <div class="info-box" style="border-left: 1px solid #3a4149; border-right: 1px solid #3a4149;"><span>Vencimento</span><strong><?php echo $vencimento; ?></strong></div>
            <div class="info-box"><span>Telas Liberadas</span><strong><?php echo $dados_cliente['max_connections']; ?> Conexão(ões)</strong></div>
        </div>

        <h3 style="color:white; border-bottom: 1px solid #3a4149; padding-bottom: 10px; margin-bottom: 20px;"><i class="fas fa-bolt" style="color:var(--accent);"></i> Renovar Assinatura</h3>
        
        <div class="planos-grid">
            <?php if(empty($planos) || (!$tem_mp && !$tem_asaas)): ?>
                <div style="grid-column: 1 / -1; background: rgba(243, 156, 18, 0.1); border: 1px solid #f39c12; color: #f39c12; padding: 20px; border-radius: 8px; text-align:center;">Seu provedor ainda não configurou o pagamento automático. Entre em contato com o suporte!</div>
            <?php else: foreach($planos as $p): ?>
                <div class="plano-card">
                    <div class="plano-nome"><?php echo htmlspecialchars($p['nome_plano']); ?></div>
                    <div style="color: #8a94a1; font-size: 14px; margin-bottom: 15px;">Adiciona +<?php echo $p['meses']; ?> Mês(es) de acesso</div>
                    <div class="plano-valor">R$ <?php echo number_format($p['valor'], 2, ',', '.'); ?></div>
                    
                    <div style="display: flex; flex-direction: column; gap: 8px;">
                        <?php if($tem_mp): ?>
                            <div style="display:flex; gap:8px;">
                                <button class="btn-renovar" style="background:#009ee3; flex:1; font-size:12px;" onclick="gerarPagamento(<?php echo $p['id']; ?>, 'mp', 'pix')"><i class="fas fa-qrcode"></i> PIX (MP)</button>
                                <button class="btn-renovar" style="background:#0071a1; flex:1; font-size:12px;" onclick="gerarPagamento(<?php echo $p['id']; ?>, 'mp', 'cartao')"><i class="fas fa-credit-card"></i> Cartão</button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if($tem_asaas): ?>
                            <div style="display:flex; gap:8px;">
                                <button class="btn-renovar" style="background:#001e60; flex:1; font-size:12px;" onclick="gerarPagamento(<?php echo $p['id']; ?>, 'asaas', 'pix')"><i class="fas fa-qrcode"></i> PIX (Asaas)</button>
                                <button class="btn-renovar" style="background:#00123a; flex:1; font-size:12px;" onclick="gerarPagamento(<?php echo $p['id']; ?>, 'asaas', 'cartao')"><i class="fas fa-credit-card"></i> Cartão</button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

    <div id="pixModal" class="modal">
        <div class="modal-content" id="modalBox">
            <div id="loadingView">
                <div class="loader"></div>
                <h3 style="color:white;">Processando...</h3>
                <p style="color:#8a94a1; font-size:14px;">Conectando com o sistema bancário.</p>
            </div>
            
            <div id="pixView" style="display:none;">
                <h3 style="color:#28a745; margin-top:0;"><i class="fas fa-check-circle"></i> PIX Gerado!</h3>
                <p style="color:white; font-size:14px;">Escaneie o QR Code abaixo com o app do seu banco para pagar e liberar seu acesso na hora.</p>
                <img id="imgQrCode" class="qr-code-img" src="">
                
                <p style="color:#8a94a1; font-size:12px; margin-bottom:5px;">Ou use o Copia e Cola:</p>
                <div class="copia-cola" id="txtCopiaCola"></div>
                <button class="btn-copiar" onclick="copiarChave()"><i class="fas fa-copy"></i> COPIAR CHAVE PIX</button>
                
                <div style="margin-top: 15px; font-size:12px; color:var(--accent);">
                    <i class="fas fa-spinner fa-spin"></i> Aguardando pagamento... A tela irá atualizar sozinha.
                </div>
                <button onclick="fecharModal()" style="background:transparent; border:none; color:#dc3545; margin-top:15px; cursor:pointer;">Cancelar</button>
            </div>

            <div id="sucessoView" style="display:none;">
                <i class="fas fa-check-circle" style="color:#28a745; font-size:60px; margin-bottom:15px;"></i>
                <h2 style="color:white; margin:0;">PAGAMENTO APROVADO!</h2>
                <p style="color:#28a745; font-weight:bold;">Sua conta foi renovada com sucesso.</p>
                <button onclick="window.location.reload()" style="background:var(--accent); color:white; border:none; padding:12px; width:100%; border-radius:6px; font-weight:bold; cursor:pointer; margin-top:15px;">ATUALIZAR PAINEL</button>
            </div>
        </div>
    </div>

    <script>
        let checkInterval;
        let pagamentoAtual = '';
        let gatewayAtual = '';

        function gerarPagamento(planoId, gateway, metodo) {
            document.getElementById('pixModal').style.display = 'flex';
            document.getElementById('loadingView').style.display = 'block';
            document.getElementById('pixView').style.display = 'none';
            document.getElementById('sucessoView').style.display = 'none';

            let formData = new FormData();
            formData.append('gerar_pix', '1'); // O backend recebe isso como gatilho principal
            formData.append('plano_id', planoId);
            formData.append('gateway', gateway);
            formData.append('metodo', metodo); // 'pix' ou 'cartao'

            fetch('', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.sucesso) {
                    if (data.link_cartao) {
                        // Se for Cartão, a API devolve um Link (Preference no MP ou Invoice no Asaas)
                        window.location.href = data.link_cartao;
                    } else {
                        // Se for PIX, exibe o QR Code
                        document.getElementById('imgQrCode').src = "data:image/png;base64," + data.qr_code_base64;
                        document.getElementById('txtCopiaCola').innerText = data.copia_cola;
                        pagamentoAtual = data.payment_id;
                        gatewayAtual = gateway;
                        
                        document.getElementById('loadingView').style.display = 'none';
                        document.getElementById('pixView').style.display = 'block';

                        checkInterval = setInterval(checarPagamento, 5000);
                    }
                } else {
                    alert(data.erro);
                    fecharModal();
                }
            })
            .catch(() => {
                alert("Erro ao conectar com o banco. O provedor configurou corretamente a chave de API?");
                fecharModal();
            });
        }

        function checarPagamento() {
            if(!pagamentoAtual) return;
            fetch(`?checar_pagamento=${pagamentoAtual}&gateway=${gatewayAtual}`)
            .then(res => res.json())
            .then(data => {
                if (data.pago) {
                    clearInterval(checkInterval);
                    document.getElementById('pixView').style.display = 'none';
                    document.getElementById('sucessoView').style.display = 'block';
                    document.getElementById('modalBox').style.borderColor = '#28a745';
                }
            });
        }

        function copiarChave() {
            const texto = document.getElementById('txtCopiaCola').innerText;
            navigator.clipboard.writeText(texto).then(() => {
                alert("Chave Copia e Cola copiada para a área de transferência!");
            });
        }

        function fecharModal() {
            document.getElementById('pixModal').style.display = 'none';
            if (checkInterval) clearInterval(checkInterval);
        }
    </script>
</body>
</html>
