<?php
// Verificação de sessão admin (sem importar arquivos)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

ini_set('display_errors', 0);
require '../../config/db.php';

// Verificar se admin está logado e existe
if (!isset($_SESSION['admin_session']) || empty($_SESSION['admin_session'])) {
    header('Location: ../login.php');
    exit;
}

// Verificar se o admin existe no banco
$adminPhone = $_SESSION['admin_session'];
$stmtAdmin = $pdo->prepare("SELECT * FROM admin_users WHERE phone = :phone AND status = 'active'");
$stmtAdmin->execute([':phone' => $adminPhone]);
$adminData = $stmtAdmin->fetch(PDO::FETCH_ASSOC);

if (!$adminData) {
    // Admin não existe ou está inativo - expirar sessão
    session_unset();
    session_destroy();
    header('Location: ../login.php');
    exit;
}

// Verificar timeout de sessão (63 minutos)
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > 3780) {
    session_unset();
    session_destroy();
    header('Location: ../login.php');
    exit;
}

// Atualizar last_activity
$_SESSION['last_activity'] = time();





$faturamentLiquid = ($faturament - $totalWithdrawalApprovedTaxasLiquid - $totalComissions) + $taxasLiquida;
?>

<?php
// Inclui os arquivos de conexão com o banco de dados


session_start();

// Define o diretório de upload de imagens
define('UPLOAD_DIR', __DIR__ . '/uploads/');
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0777, true);
}

// Verifica se o usuário está logado e tem permissões de administrador
// A verificação usa 'level' e 'status' da tabela 'admin_users'
// if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_level'] === '') {
//     $_SESSION['toastMessage'] = 'Acesso restrito.';
//     $_SESSION['toastType'] = 'error';
//     header('Location: ../login.php'); // Redireciona para a página de login
//     exit;
// }

// Consultar Dados da plataforma
$stmtPlataforma = $pdo->prepare("SELECT * FROM configs WHERE id = 1");
$stmtPlataforma->execute();
$dadosPlataforma = $stmtPlataforma->fetch(PDO::FETCH_ASSOC);

// Função para obter o parâmetro 'page' da URL, com um fallback para 'dashboard'
$currentPage = isset($_GET['page']) ? $_GET['page'] : 'dashboard';

// --- Paginação ---
$limit = 10;
$page = isset($_GET['paged']) ? (int)$_GET['paged'] : 1;
$offset = ($page - 1) * $limit;

// --- Variáveis para controle de modais e dados de edição ---
$showEditModal = false;
$editDataType = '';
$editData = null;

// Função genérica para redirecionar após POST para evitar reenvio de formulário
function redirectToPage($page, $params = [])
{
    $url = "?page=" . urlencode($page);
    foreach ($params as $key => $value) {
        $url .= "&" . urlencode($key) . "=" . urlencode($value);
    }
    header("Location: " . $url);
    exit();
}

// Função para fazer upload de arquivo
function handleFileUpload($fileInputName, $currentFilePath = null)
{
    if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES[$fileInputName]['tmp_name'];
        $fileName = $_FILES[$fileInputName]['name'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));
        $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
        $destPath = UPLOAD_DIR . $newFileName;
        $allowedfileExtensions = ['jpg', 'gif', 'png', 'jpeg', 'svg', 'webp'];
        if (in_array($fileExtension, $allowedfileExtensions)) {
            if (move_uploaded_file($fileTmpPath, $destPath)) {
                if ($currentFilePath && strpos($currentFilePath, '/uploads/') === 0 && file_exists(__DIR__ . $currentFilePath)) {
                    unlink(__DIR__ . $currentFilePath);
                }
                return '/uploads/' . $newFileName;
            } else {
                error_log("Erro ao mover arquivo: " . $fileTmpPath . " para " . $destPath);
                return null;
            }
        } else {
            error_log("Extensão de arquivo não permitida: " . $fileExtension);
            return null;
        }
    }
    return $currentFilePath;
}

// --- Lógica de Processamento de Formulários (POST) ---

// Processar atualização de USUÁRIO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_user') {
    $userId = $_POST['user_id'];
    $userName = $_POST['user_name'];
    $userPhone = $_POST['user_phone'];
    $userBalance = $_POST['user_balance'];
    $userPassword = $_POST['user_password'];
    $userStatus = $_POST['user_status'];
    $userProfit = $_POST['profit_investments'];
    $userGiros = $_POST['qtd_spins'];
    $userTotalLvl1 = $_POST['total_lvl1'];
    $userTotalLvl2 = $_POST['total_lvl2'];
    $userTotalLvl3 = $_POST['total_lvl3'];
    $userTotalDep = $_POST['total_indicated_deposits'];
    $userQtdInv = $_POST['qtd_investments'];
    $userAffiliateCode = $_POST['affiliate_code'];
    $userIndicatedBy = $_POST['indicated_by'];
    $userLider = $_POST['lider'];

    try {
        $sql = "UPDATE users SET name = :name, phone = :phone, balance = :balance, status = :status, profit_investments = :profit_investments, total_lvl1 = :total_lvl1, total_lvl2 = :total_lvl2, total_lvl3 = :total_lvl3, total_indicated_deposits = :total_indicated_deposits, qtd_investments = :qtd_investments, qtd_spins = :qtd_spins, affiliate_code = :affiliate_code, indicated_by = :indicated_by, lider = :lider";
        $params = [
            ':name' => $userName,
            ':phone' => $userPhone,
            ':balance' => $userBalance,
            ':status' => $userStatus,
            ':profit_investments' => $userProfit,
            ':qtd_spins' => $userGiros,
            ':total_lvl1' => $userTotalLvl1,
            ':total_lvl2' => $userTotalLvl2,
            ':total_lvl3' => $userTotalLvl3,
            ':total_indicated_deposits' => $userTotalDep,
            ':qtd_investments' => $userQtdInv,
            ':affiliate_code' => $userAffiliateCode,
            ':indicated_by' => $userIndicatedBy,
            ':lider' => $userLider,
            ':id' => $userId
        ];
        if (!empty($userPassword)) {
            $sql .= ", password = :password";
            $params[':password'] = password_hash($userPassword, PASSWORD_DEFAULT);
        }
        $sql .= " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $_SESSION['toastMessage'] = 'Usuário atualizado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('users');
    } catch (PDOException $e) {
        error_log("Erro ao atualizar usuário: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao atualizar usuário.' . $e;
        $_SESSION['toastType'] = 'error';
        redirectToPage('users');
    }
}

// Processar exclusão de USUÁRIO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_user') {
    $userId = $_POST['user_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
        $stmt->execute([':id' => $userId]);
        $_SESSION['toastMessage'] = 'Usuário excluído com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('users');
    } catch (PDOException $e) {
        error_log("Erro ao excluir usuário: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao excluir usuário.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('users');
    }
}

// Processar adição de PRODUTO DE INVESTIMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_investment_product') {
    $data = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    var_dump($data);

    $name = $data['name'];
    $value = str_replace(['.', ','], ['', '.'], $data['value']);
    $totalDays = $data['total_days'];
    $dailyReturn = str_replace([','], ['.'], $data['daily_return']);
    $limitPurchase = $data['limit_purchase'];
    $newUser = $data['new_user'];
    $description = $data['description'];
    $event = $data['event'];
    $dateExpired = ($event == '1') ? $data['data_expiracao_evento'] : null;

    file_put_contents('teste2.txt', $dateExpired . PHP_EOL, FILE_APPEND);

    $totalReturn = (floatval($dailyReturn) * intval($totalDays));
    $token = bin2hex(random_bytes(10));
    $createdAt = date('Y-m-d H:i:s');

    $img = handleFileUpload('img_file');
    if (empty($img) && !empty($data['img_url_text'])) {
        $img = $data['img_url_text'];
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO investment_products (token, name, img, description, value, total_days, daily_return, total_return, is_active, limit_purchase, new_user, created_at, type, order_product, available, event, date_expired_event, automatic_expired) VALUES (:token, :name, :img, :description, :value, :total_days, :daily_return, :total_return, :is_active, :limit_purchase, :new_user, :created_at, :type, :order_product, :available, :event, :date_expired_event, :automatic_expired)");
        $stmt->execute([
            ':token' => $token,
            ':name' => $name,
            ':img' => $img,
            ':description' => $description,
            ':value' => $value,
            ':total_days' => $totalDays,
            ':daily_return' => $dailyReturn,
            ':total_return' => $totalReturn,
            ':is_active' => 1,
            ':limit_purchase' => $limitPurchase,
            ':new_user' => $newUser,
            ':created_at' => $createdAt,
            ':type' => 'diary',
            ':order_product' => $data['order_product'],
            ':available' => $data['available'],
            ':event' => $event,
            ':date_expired_event' => $dateExpired,
            ':automatic_expired' => $data['automatic_expired']
        ]);
        $_SESSION['toastMessage'] = 'Produto de investimento adicionado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('investment-products');
    } catch (PDOException $e) {
        error_log("Erro ao adicionar produto de investimento: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao adicionar produto de investimento.' . $e->getMessage();
        $_SESSION['toastType'] = 'error';
        redirectToPage('investment-products');
    }
}

// Processar adição de PRODUTO DE INVESTIMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_investment_product_cicle') {
    $data = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    $name = $data['name'];
    $value = str_replace([','], ['.'], $data['value']);
    $valorDoResgate = str_replace(['.', ','], ['', '.'], $data['daily_return']);
    $totalDays = $data['total_days'];
    $dailyReturn = $value + $valorDoResgate;
    $limitPurchase = $data['limit_purchase'];
    $newUser = $data['new_user'];
    $description = $data['description'];

    $totalReturn = 1;
    $token = bin2hex(random_bytes(10));
    $createdAt = date('Y-m-d H:i:s');

    $img = handleFileUpload('img_file');
    if (empty($img) && !empty($data['img_url_text'])) {
        $img = $data['img_url_text'];
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO investment_products (token, name, img, description, value, total_days, daily_return, total_return, is_active, limit_purchase, new_user, created_at, type, order_product, available) VALUES (:token, :name, :img, :description, :value, :total_days, :daily_return, :total_return, :is_active, :limit_purchase, :new_user, :created_at, :type, :order_product, :available)");
        $stmt->execute([
            ':token' => $token,
            ':name' => $name,
            ':img' => $img,
            ':description' => $description,
            ':value' => $value,
            ':total_days' => $totalDays,
            ':daily_return' => $dailyReturn,
            ':total_return' => $dailyReturn,
            ':is_active' => 1,
            ':limit_purchase' => $limitPurchase,
            ':new_user' => $newUser,
            ':created_at' => $createdAt,
            ':type' => 'cicle',
            ':order_product' => $data['order_product'],
            ':available' => $data['available']
        ]);
        $_SESSION['toastMessage'] = 'Produto de investimento adicionado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('investment-products');
    } catch (PDOException $e) {
        error_log("Erro ao adicionar produto de investimento: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao adicionar produto de investimento.' . $e->getMessage();
        $_SESSION['toastType'] = 'error';
        redirectToPage('investment-products');
    }
}


// Processar atualização de PRODUTOS DE INVESTIMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_investment_product') {
    $productId = $_POST['product_id'];
    $productName = $_POST['product_name'];
    $productImg = $_POST['product_img'];
    $productDesc = $_POST['product_description'];
    $productValue = $_POST['product_value'];
    $totalDays = $_POST['total_days'];
    $dailyReturn = $_POST['daily_return'];
    $limitPurchase = $_POST['limit_purchase'];
    $newUser = $_POST['new_user'];
    $status = $_POST['is_active'];

    $currentProduct1 = $pdo->prepare("SELECT * FROM investment_products WHERE id = :id");
    $currentProduct1->execute([':id' => $productId]);
    $produto = $currentProduct1->fetch(PDO::FETCH_ASSOC);

    if ($produto['type'] === 'diary') {
        $totalReturn = (floatval($dailyReturn) * intval($totalDays));
    } else {
        $totalReturn = (float)$dailyReturn; 
    }

    try {
        $stmt = $pdo->prepare("UPDATE investment_products SET name = :name, img = :img, description = :description, value = :value, total_days = :total_days, daily_return = :daily_return, total_return = :total_return, limit_purchase = :limit_purchase, new_user = :new_user, is_active = :status, order_product = :order_product, available = :available WHERE id = :id");
        $stmt->execute([
            ':name' => $productName,
            ':img' => $productImg,
            ':description' => $productDesc,
            ':value' => $productValue,
            ':total_days' => $totalDays,
            ':daily_return' => $dailyReturn,
            ':total_return' => $totalReturn,
            ':limit_purchase' => $limitPurchase,
            ':new_user' => $newUser,
            ':status' => $status,
            ':id' => $productId,
            ':order_product' => $_POST['order_product'],
            ':available' => $_POST['available']
        ]);
        $_SESSION['toastMessage'] = 'Produto de investimento atualizado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('investment-products');
    } catch (PDOException $e) {
        error_log("Erro ao atualizar produto de investimento: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao atualizar produto de investimento.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('investment-products');
    }
}

// Processar exclusão de PRODUTO DE INVESTIMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_investment_product') {
    $productId = $_POST['product_id'];
    try {
        $stmtImg = $pdo->prepare("SELECT img FROM investment_products WHERE id = :id");
        $stmtImg->execute([':id' => $productId]);
        $imgPath = $stmtImg->fetchColumn();
        if ($imgPath && strpos($imgPath, '/uploads/') === 0 && file_exists(__DIR__ . $imgPath)) {
            unlink(__DIR__ . $imgPath);
        }
        $stmt = $pdo->prepare("DELETE FROM investment_products WHERE id = :id");
        $stmt->execute([':id' => $productId]);
        $_SESSION['toastMessage'] = 'Produto de investimento excluído com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('investment-products');
    } catch (PDOException $e) {
        error_log("Erro ao excluir produto de investimento: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao excluir produto de investimento.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('investment-products');
    }
}

// Processar atualização de SAQUE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_withdrawal') {
    $withdrawalId = $_POST['withdrawal_id'];
    $status = $_POST['status'];
    $pagoEm = ($status === 'approved') ? date('Y-m-d H:i:s') : null;
    try {
        $stmt = $pdo->prepare("UPDATE withdrawal SET status = :status, created_at = :created_at WHERE id = :id");
        $stmt->execute([
            ':status' => $status,
            ':created_at' => $pagoEm,
            ':id' => $withdrawalId
        ]);
        $_SESSION['toastMessage'] = 'Saque atualizado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('withdrawals');
    } catch (PDOException $e) {
        error_log("Erro ao atualizar saque: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao atualizar saque.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('withdrawals');
    }
}

// Processar exclusão e reembolso de SAQUE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_withdrawal_refund') {
    $withdrawalId = $_POST['withdrawal_id'];
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT user_id, value FROM withdrawal WHERE id = :id AND status = 'pending'");
        $stmt->execute([':id' => $withdrawalId]);
        $withdrawalData = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($withdrawalData) {
            $userId = $withdrawalData['user_id'];
            $amountToRefund = $withdrawalData['value'];

            $stmtUpdate = $pdo->prepare("UPDATE users SET balance = balance + :amount WHERE id = :id");
            $stmtUpdate->execute([':amount' => $amountToRefund, ':id' => $userId]);

            $stmtUpdateStatus = $pdo->prepare("UPDATE withdrawal SET status = 'recused' WHERE id = :id");
            $stmtUpdateStatus->execute([':id' => $withdrawalId]);

            $pdo->commit();
            $_SESSION['toastMessage'] = 'Saque recusado e valor reembolsado com sucesso!';
            $_SESSION['toastType'] = 'success';
        } else {
            $_SESSION['toastMessage'] = 'Saque não encontrado ou não está pendente.';
            $_SESSION['toastType'] = 'error';
        }
        redirectToPage('withdrawals');
    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log("Erro ao excluir e reembolsar saque: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao excluir e reembolsar saque.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('withdrawals');
    }
}

// Processar atualização de CONTA PIX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_account_pix') {
    $accountId = $_POST['account_id'];
    $typePix = $_POST['type_pix'];
    $keyBeneficiary = $_POST['key_beneficiary'];
    $status = $_POST['status'];
    try {
        $stmt = $pdo->prepare("UPDATE accounts_pix SET type_pix = :type_pix, key_beneficiary = :key_beneficiary, status = :status WHERE id = :id");
        $stmt->execute([
            ':type_pix' => $typePix,
            ':key_beneficiary' => $keyBeneficiary,
            ':status' => $status,
            ':id' => $accountId
        ]);
        $_SESSION['toastMessage'] = 'Conta PIX atualizada com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('accounts-pix');
    } catch (PDOException $e) {
        error_log("Erro ao atualizar conta pix: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao atualizar conta PIX.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('accounts-pix');
    }
}

// Processar exclusão de CONTA PIX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_account_pix') {
    $accountId = $_POST['account_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM accounts_pix WHERE id = :id");
        $stmt->execute([':id' => $accountId]);
        $_SESSION['toastMessage'] = 'Conta PIX excluída com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('accounts-pix');
    } catch (PDOException $e) {
        error_log("Erro ao excluir conta pix: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao excluir conta PIX.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('accounts-pix');
    }
}

// Processar atualização de CONFIGURAÇÕES
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_configs') {
    $nomeSite = $_POST['name_platform'];
    $corPrincipal = $_POST['color_primary'];
    $minWith = $_POST['min_with'];
    $maxWith = $_POST['max_with'];
    $minDep = $_POST['min_dep'];
    $taxaSaq = $_POST['taxa_saq'];
    $percentageLvl1 = $_POST['percentage_lvl1'];
    $percentageLvl2 = $_POST['percentage_lvl2'];
    $percentageLvl3 = $_POST['percentage_lvl3'];
    $supportLink = $_POST['support_link'];
    $supportLink2 = $_POST['support_link2'];
    $supportLink3 = $_POST['support_link3'];
    $canalLink = $_POST['canal_link'];
    $textLogin = $_POST['text_login'];
    $textPass = $_POST['text_pass'];

    $currentConfigs = $pdo->query("SELECT logo, favicon FROM configs WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    $logo = handleFileUpload('logo_file', $currentConfigs['logo']);
    $favicon = handleFileUpload('favicon_file', $currentConfigs['favicon']);
    if (empty($logo) && !empty($_POST['logo_url_text'])) {
        $logo = $_POST['logo_url_text'];
    }
    if (empty($favicon) && !empty($_POST['favicon_url_text'])) {
        $favicon = $_POST['favicon_url_text'];
    }

    try {
        $stmt = $pdo->prepare("UPDATE configs SET name_platform = :name_platform, color_primary = :color_primary, min_with = :min_with, max_with = :max_with, min_dep = :min_dep, taxa_saq = :taxa_saq, percentage_lvl1 = :percentage_lvl1, percentage_lvl2 = :percentage_lvl2, percentage_lvl3 = :percentage_lvl3, support_link = :support_link, support_link2 = :support_link2, support_link3 = :support_link3, canal_link = :canal_link, text_login = :text_login, text_pass = :text_pass, logo = :logo, favicon = :favicon WHERE id = 1");
        $stmt->execute([
            ':name_platform' => $nomeSite,
            ':color_primary' => $corPrincipal,
            ':min_with' => $minWith,
            ':max_with' => $maxWith,
            ':min_dep' => $minDep,
            ':taxa_saq' => $taxaSaq,
            ':percentage_lvl1' => $percentageLvl1,
            ':percentage_lvl2' => $percentageLvl2,
            ':percentage_lvl3' => $percentageLvl3,
            ':support_link' => $supportLink,
            ':support_link2' => $supportLink2,
            ':support_link3' => $supportLink3,
            ':canal_link' => $canalLink,
            ':text_login' => $textLogin,
            ':text_pass' => $textPass,
            ':logo' => $logo,
            ':favicon' => $favicon
        ]);
        $_SESSION['toastMessage'] = 'Configurações atualizadas com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('settings');
    } catch (PDOException $e) {
        error_log("Erro ao atualizar configurações: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao atualizar configurações.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('settings');
    }
}

// Processar atualização de cupom
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_coupon') {
    $couponId = $_POST['coupon_id'];
    $code = $_POST['code'];
    $expireAt = $_POST['expire_at'];
    $status = $_POST['status'];
    try {
        $stmt = $pdo->prepare("UPDATE cupons SET code = :code, expire_at = :expire_at, status = :status WHERE id = :id");
        $stmt->execute([
            ':code' => $code,
            ':expire_at' => $expireAt,
            ':status' => $status,
            ':id' => $couponId
        ]);
        $_SESSION['toastMessage'] = 'Cupom atualizado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('coupons');
    } catch (PDOException $e) {
        error_log("Erro ao atualizar cupom: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao atualizar cupom.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('coupons');
    }
}

// Processar exclusão de cupom
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_coupon') {
    $couponId = $_POST['coupon_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM cupons WHERE id = :id");
        $stmt->execute([':id' => $couponId]);
        $_SESSION['toastMessage'] = 'Cupom excluído com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('coupons');
    } catch (PDOException $e) {
        error_log("Erro ao excluir cupom: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao excluir cupom.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('coupons');
    }
}

// Processar adição de cupom
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_coupon') {
    $code = $_POST['code'];
    $expireAt = $_POST['expire_at'];
    $status = $_POST['status'];
    $createdAt = date('Y-m-d H:i:s');

    if ($_POST['type'] === 'aleatory') {
        $value = rand(50, 150) / 100;
    } else {
        $value = str_replace([','], ['.'], $_POST['value']);
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO cupons (code, created_at, expire_at, status, value, limit_purchase_user, limit_purchase_geral, type) VALUES (:code, :created_at, :expire_at, :status, :value, :limit_purchase_user, :limit_purchase_geral, :type)");
        $stmt->execute([
            ':code' => $code,
            ':created_at' => $createdAt,
            ':expire_at' => $expireAt,
            ':status' => $status,
            ':value' => $value,
            ':limit_purchase_user' => $_POST['rescue'],
            ':limit_purchase_geral' => $_POST['rescue_geral'],
            ':type' => $_POST['type']
        ]);
        $_SESSION['toastMessage'] = 'Cupom adicionado com sucesso!';
        $_SESSION['toastType'] = 'success';
        redirectToPage('coupons');
    } catch (PDOException $e) {
        error_log("Erro ao adicionar cupom: " . $e->getMessage());
        $_SESSION['toastMessage'] = 'Falha ao adicionar cupom.' . $e->getMessage();
        $_SESSION['toastType'] = 'error';
        redirectToPage('coupons');
    }
}

// --- Lógica para buscar dados para preencher modais de edição (GET) ---
if (isset($_GET['edit_user_id']) && $currentPage === 'users') {
    $userId = $_GET['edit_user_id'];
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->execute([':id' => $userId]);
    $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($editData) {
        $showEditModal = true;
        $editDataType = 'user';
    }
}

if (isset($_GET['edit_product_id']) && $currentPage === 'investment-products') {
    $productId = $_GET['edit_product_id'];
    $stmt = $pdo->prepare("SELECT * FROM investment_products WHERE id = :id");
    $stmt->execute([':id' => $productId]);
    $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($editData) {
        $showEditModal = true;
        $editDataType = 'investment_product';
    }
}

if (isset($_GET['edit_withdrawal_id']) && $currentPage === 'withdrawals') {
    $withdrawalId = $_GET['edit_withdrawal_id'];
    $stmt = $pdo->prepare("SELECT w.*, u.name as user_name FROM withdrawal w JOIN users u ON w.user_id = u.id WHERE w.id = :id");
    $stmt->execute([':id' => $withdrawalId]);
    $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($editData) {
        $showEditModal = true;
        $editDataType = 'withdrawal';
    }
}

if (isset($_GET['edit_account_id']) && $currentPage === 'accounts-pix') {
    $accountId = $_GET['edit_account_id'];
    $stmt = $pdo->prepare("SELECT * FROM accounts_pix WHERE id = :id");
    $stmt->execute([':id' => $accountId]);
    $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($editData) {
        $showEditModal = true;
        $editDataType = 'account_pix';
    }
}

if (isset($_GET['edit_coupon_id']) && $currentPage === 'coupons') {
    $couponId = $_GET['edit_coupon_id'];
    $stmt = $pdo->prepare("SELECT * FROM cupons WHERE id = :id");
    $stmt->execute([':id' => $couponId]);
    $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($editData) {
        $showEditModal = true;
        $editDataType = 'coupon';
    }
}

// Dados para a página de perfil de usuário
if ($currentPage === 'user-profile' && isset($_GET['user_id'])) {
    $userId = $_GET['user_id'];
    $userProfile = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $userProfile->execute([':id' => $userId]);
    $profileData = $userProfile->fetch(PDO::FETCH_ASSOC);

    if ($profileData) {
        $totalAffiliates = $pdo->prepare("SELECT COUNT(*) FROM users WHERE indicated_by = :code");
        $totalAffiliates->execute([':code' => $profileData['affiliate_code']]);
        $totalAffiliates = $totalAffiliates->fetchColumn();

        $totalInvestments = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE user_id = :id");
        $totalInvestments->execute([':id' => $userId]);
        $totalInvestments = $totalInvestments->fetchColumn();

        $totalDeposited = $pdo->prepare("SELECT SUM(value) FROM transactions WHERE user_id = :id AND status = 'paid'");
        $totalDeposited->execute([':id' => $userId]);
        $totalDeposited = $totalDeposited->fetchColumn();

        $totalWithdrawn = $pdo->prepare("SELECT SUM(value) FROM withdrawal WHERE user_id = :id AND status = 'approved'");
        $totalWithdrawn->execute([':id' => $userId]);
        $totalWithdrawn = $totalWithdrawn->fetchColumn();

        $lastInvestment = $pdo->prepare("SELECT name, invested_amount, created_at FROM investments WHERE user_id = :id ORDER BY created_at DESC LIMIT 1");
        $lastInvestment->execute([':id' => $userId]);
        $lastInvestment = $lastInvestment->fetch(PDO::FETCH_ASSOC);

        // Histórico de transações do usuário
        $transactionsHistorySql = "SELECT * FROM transactions WHERE user_id = :id ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
        $transactionsHistory = $pdo->prepare($transactionsHistorySql);
        $transactionsHistory->bindParam(':id', $userId, PDO::PARAM_INT);
        $transactionsHistory->bindParam(':limit', $limit, PDO::PARAM_INT);
        $transactionsHistory->bindParam(':offset', $offset, PDO::PARAM_INT);
        $transactionsHistory->execute();
        $userTransactions = $transactionsHistory->fetchAll(PDO::FETCH_ASSOC);
        $totalUserTransactions = $pdo->prepare("SELECT COUNT(*) FROM transactions WHERE user_id = :id");
        $totalUserTransactions->bindParam(':id', $userId, PDO::PARAM_INT);
        $totalUserTransactions->execute();
        $totalPagesUserTransactions = ceil($totalUserTransactions->fetchColumn() / $limit);

        // Histórico de saques do usuário
        $withdrawalsHistorySql = "SELECT * FROM withdrawal WHERE user_id = :id ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
        $withdrawalsHistory = $pdo->prepare($withdrawalsHistorySql);
        $withdrawalsHistory->bindParam(':id', $userId, PDO::PARAM_INT);
        $withdrawalsHistory->bindParam(':limit', $limit, PDO::PARAM_INT);
        $withdrawalsHistory->bindParam(':offset', $offset, PDO::PARAM_INT);
        $withdrawalsHistory->execute();
        $userWithdrawals = $withdrawalsHistory->fetchAll(PDO::FETCH_ASSOC);
        $totalUserWithdrawals = $pdo->prepare("SELECT COUNT(*) FROM withdrawal WHERE user_id = :id");
        $totalUserWithdrawals->bindParam(':id', $userId, PDO::PARAM_INT);
        $totalUserWithdrawals->execute();
        $totalPagesUserWithdrawals = ceil($totalUserWithdrawals->fetchColumn() / $limit);

        // Histórico de atividades do usuário
        $activityHistorySql = "SELECT * FROM history WHERE user_id = :id ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
        $activityHistory = $pdo->prepare($activityHistorySql);
        $activityHistory->bindParam(':id', $userId, PDO::PARAM_INT);
        $activityHistory->bindParam(':limit', $limit, PDO::PARAM_INT);
        $activityHistory->bindParam(':offset', $offset, PDO::PARAM_INT);
        $activityHistory->execute();
        $userActivity = $activityHistory->fetchAll(PDO::FETCH_ASSOC);
        $totalUserActivity = $pdo->prepare("SELECT COUNT(*) FROM history WHERE user_id = :id");
        $totalUserActivity->bindParam(':id', $userId, PDO::PARAM_INT);
        $totalUserActivity->execute();
        $totalPagesUserActivity = ceil($totalUserActivity->fetchColumn() / $limit);
    } else {
        $_SESSION['toastMessage'] = 'Usuário não encontrado.';
        $_SESSION['toastType'] = 'error';
        redirectToPage('users');
    }
}


// --- Funções para buscar dados para as listagens e dashboard ---
$totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalInvested = $pdo->query("SELECT SUM(invested_amount) FROM investments WHERE is_active = 1")->fetchColumn();
$totalPendingWithdrawals = $pdo->query("SELECT SUM(value) FROM withdrawal WHERE status = 'pending'")->fetchColumn();
$totalDepositsToday = $pdo->query("SELECT SUM(value) FROM transactions WHERE status = 'paid' AND DATE(date_payment) = CURDATE()")->fetchColumn();
$totalWithdrawalsToday = $pdo->query("SELECT SUM(value) FROM withdrawal WHERE status = 'approved' AND DATE(created_at) = CURDATE()")->fetchColumn();
$totalCommissionPaid = $pdo->query("SELECT SUM(liquid_affiliate) FROM comission_affiliates")->fetchColumn();
$totalBalance = $pdo->query("SELECT SUM(balance) FROM users")->fetchColumn();

// Dados para a página de Usuários
$searchQueryUsers = isset($_GET['busca_users']) ? $_GET['busca_users'] : '';
$totalUsersCount = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalPagesUsers = ceil($totalUsersCount / $limit);
$geralUsuariosSql = "SELECT * FROM users";
if (!empty($searchQueryUsers)) {
    $geralUsuariosSql .= " WHERE name LIKE :busca OR id LIKE :busca OR phone LIKE :busca OR affiliate_code LIKE :busca";
}
$geralUsuariosSql .= " LIMIT :limit OFFSET :offset";
$geralUsuarios = $pdo->prepare($geralUsuariosSql);
$geralUsuarios->bindParam(':limit', $limit, PDO::PARAM_INT);
$geralUsuarios->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryUsers)) {
    $geralUsuarios->bindValue(':busca', '%' . $searchQueryUsers . '%', PDO::PARAM_STR);
}
$geralUsuarios->execute();
$usuariosGerais = $geralUsuarios->fetchAll(PDO::FETCH_ASSOC);

// Função para buscar a árvore de afiliados de um usuário
function getAffiliateTree($pdo, $affiliateCode, $level = 1, $maxLevel = 3)
{
    if ($level > $maxLevel || empty($affiliateCode)) {
        return [];
    }
    $stmt = $pdo->prepare("SELECT u.id, u.name, u.phone, u.affiliate_code, u.indicated_by, 
                            (SELECT MAX(created_at) FROM investments WHERE user_id = u.id) as last_investment_date,
                            (SELECT name FROM investments WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) as last_investment_name,
                            (SELECT invested_amount FROM investments WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) as last_investment_amount
                            FROM users u WHERE u.indicated_by = :affiliate_code");
    $stmt->execute([':affiliate_code' => $affiliateCode]);
    $directAffiliates = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $tree = [];
    foreach ($directAffiliates as $affiliate) {
        $affiliate['level'] = $level;
        $affiliate['children'] = getAffiliateTree($pdo, $affiliate['affiliate_code'], $level + 1, $maxLevel);
        $tree[] = $affiliate;
    }
    return $tree;
}


// Dados para a página de Produtos de Investimento
$searchQueryProducts = isset($_GET['busca_products']) ? $_GET['busca_products'] : '';
$totalProductsCount = $pdo->query("SELECT COUNT(*) FROM investment_products")->fetchColumn();
$totalPagesProducts = ceil($totalProductsCount / $limit);
$productsSql = "SELECT * FROM investment_products";
if (!empty($searchQueryProducts)) {
    $productsSql .= " WHERE name LIKE :busca OR token LIKE :busca";
}
$productsSql .= " LIMIT :limit OFFSET :offset";
$products = $pdo->prepare($productsSql);
$products->bindParam(':limit', $limit, PDO::PARAM_INT);
$products->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryProducts)) {
    $products->bindValue(':busca', '%' . $searchQueryProducts . '%', PDO::PARAM_STR);
}
$products->execute();
$productsGerais = $products->fetchAll(PDO::FETCH_ASSOC);

// Dados para a página de Investimentos Ativos
$searchQueryInvestments = isset($_GET['busca_investments']) ? $_GET['busca_investments'] : '';
$totalInvestmentsCount = $pdo->query("SELECT COUNT(*) FROM investments")->fetchColumn();
$totalPagesInvestments = ceil($totalInvestmentsCount / $limit);
$investmentsSql = "SELECT i.*, u.name as user_name, u.phone as user_phone FROM investments i JOIN users u ON i.user_id = u.id";
if (!empty($searchQueryInvestments)) {
    $investmentsSql .= " WHERE i.name LIKE :busca OR u.name LIKE :busca OR u.phone LIKE :busca";
}
$investmentsSql .= " LIMIT :limit OFFSET :offset";
$investments = $pdo->prepare($investmentsSql);
$investments->bindParam(':limit', $limit, PDO::PARAM_INT);
$investments->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryInvestments)) {
    $investments->bindValue(':busca', '%' . $searchQueryInvestments . '%', PDO::PARAM_STR);
}
$investments->execute();
$investmentsGerais = $investments->fetchAll(PDO::FETCH_ASSOC);

// Dados para a página de Saques
$searchQueryWithdrawals = isset($_GET['busca_saques']) ? $_GET['busca_saques'] : '';
$filterStatusWithdrawals = isset($_GET['status_saques']) ? $_GET['status_saques'] : 'all';
$withdrawalsSql = "SELECT w.*, u.name as user_name FROM withdrawal w JOIN users u ON w.user_id = u.id";
$whereClausesWithdrawals = [];
if (!empty($searchQueryWithdrawals)) {
    $whereClausesWithdrawals[] = "(w.reference_id LIKE :busca OR w.user_id LIKE :busca OR u.name LIKE :busca OR u.phone LIKE :busca)";
}
if ($filterStatusWithdrawals !== 'all') {
    $whereClausesWithdrawals[] = "w.status = :status";
}
if (!empty($whereClausesWithdrawals)) {
    $withdrawalsSql .= " WHERE " . implode(" AND ", $whereClausesWithdrawals);
}
$countSql = "SELECT COUNT(*) FROM withdrawal w JOIN users u ON w.user_id = u.id";
if (!empty($whereClausesWithdrawals)) {
    $countSql .= " WHERE " . implode(" AND ", $whereClausesWithdrawals);
}
$totalWithdrawalsCountStmt = $pdo->prepare($countSql);
if (!empty($searchQueryWithdrawals)) {
    $totalWithdrawalsCountStmt->bindValue(':busca', '%' . $searchQueryWithdrawals . '%', PDO::PARAM_STR);
}
if ($filterStatusWithdrawals !== 'all') {
    $totalWithdrawalsCountStmt->bindValue(':status', $filterStatusWithdrawals, PDO::PARAM_STR);
}
$totalWithdrawalsCountStmt->execute();
$totalWithdrawalsCount = $totalWithdrawalsCountStmt->fetchColumn();
$totalPagesWithdrawals = ceil($totalWithdrawalsCount / $limit);
$withdrawalsSql .= " ORDER BY w.created_at DESC LIMIT :limit OFFSET :offset";
$withdrawals = $pdo->prepare($withdrawalsSql);
$withdrawals->bindParam(':limit', $limit, PDO::PARAM_INT);
$withdrawals->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryWithdrawals)) {
    $withdrawals->bindValue(':busca', '%' . $searchQueryWithdrawals . '%', PDO::PARAM_STR);
}
if ($filterStatusWithdrawals !== 'all') {
    $withdrawals->bindValue(':status', $filterStatusWithdrawals, PDO::PARAM_STR);
}
$withdrawals->execute();
$withdrawalsGerais = $withdrawals->fetchAll(PDO::FETCH_ASSOC);

// Dados para a página de Transações
$searchQueryTransactions = isset($_GET['busca_transacoes']) ? $_GET['busca_transacoes'] : '';
$totalTransactionsCount = $pdo->query("SELECT COUNT(*) FROM transactions")->fetchColumn();
$totalPagesTransactions = ceil($totalTransactionsCount / $limit);
$transactionsSql = "SELECT t.*, u.name as user_name FROM transactions t JOIN users u ON t.user_id = u.id";
if (!empty($searchQueryTransactions)) {
    $transactionsSql .= " WHERE t.reference_id LIKE :busca OR user_id LIKE :busca OR t.idTransaction LIKE :busca OR u.name LIKE :busca OR u.phone LIKE :busca";
}
$transactionsSql .= " ORDER BY t.created_at DESC LIMIT :limit OFFSET :offset";
$transactions = $pdo->prepare($transactionsSql);
$transactions->bindParam(':limit', $limit, PDO::PARAM_INT);
$transactions->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryTransactions)) {
    $transactions->bindValue(':busca', '%' . $searchQueryTransactions . '%', PDO::PARAM_STR);
}
$transactions->execute();
$transactionsGerais = $transactions->fetchAll(PDO::FETCH_ASSOC);

// Dados para a página de Contas PIX
$searchQueryAccounts = isset($_GET['busca_accounts']) ? $_GET['busca_accounts'] : '';
$totalAccountsCount = $pdo->query("SELECT COUNT(*) FROM accounts_pix")->fetchColumn();
$totalPagesAccounts = ceil($totalAccountsCount / $limit);
$accountsSql = "SELECT ap.*, u.name as user_name FROM accounts_pix ap JOIN users u ON ap.phone_user = u.phone";
if (!empty($searchQueryAccounts)) {
    $accountsSql .= " WHERE ap.key_beneficiary LIKE :busca OR u.name LIKE :busca OR u.phone LIKE :busca";
}
$accountsSql .= " LIMIT :limit OFFSET :offset";
$accounts = $pdo->prepare($accountsSql);
$accounts->bindParam(':limit', $limit, PDO::PARAM_INT);
$accounts->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryAccounts)) {
    $accounts->bindValue(':busca', '%' . $searchQueryAccounts . '%', PDO::PARAM_STR);
}
$accounts->execute();
$accountsGerais = $accounts->fetchAll(PDO::FETCH_ASSOC);

// Dados para a página de Comissões de Afiliados
$searchQueryCommissions = isset($_GET['busca_commissions']) ? $_GET['busca_commissions'] : '';
$totalCommissionsCount = $pdo->query("SELECT COUNT(*) FROM comission_affiliates")->fetchColumn();
$totalPagesCommissions = ceil($totalCommissionsCount / $limit);
$commissionsSql = "SELECT ca.*, u.name as affiliate_name FROM comission_affiliates ca JOIN users u ON ca.affiliate_id = u.id";
if (!empty($searchQueryCommissions)) {
    $commissionsSql .= " WHERE ca.affiliate_id LIKE :busca OR ca.indicated_phone LIKE :busca OR ca.investment_name LIKE :busca";
}
$commissionsSql .= " ORDER BY ca.created_at DESC LIMIT :limit OFFSET :offset";
$commissions = $pdo->prepare($commissionsSql);
$commissions->bindParam(':limit', $limit, PDO::PARAM_INT);
$commissions->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryCommissions)) {
    $commissions->bindValue(':busca', '%' . $searchQueryCommissions . '%', PDO::PARAM_STR);
}
$commissions->execute();
$commissionsGerais = $commissions->fetchAll(PDO::FETCH_ASSOC);


// Dados para a página de Cupons
$searchQueryCoupons = isset($_GET['busca_coupons']) ? $_GET['busca_coupons'] : '';
$totalCouponsCount = $pdo->query("SELECT COUNT(*) FROM cupons")->fetchColumn();
$totalPagesCoupons = ceil($totalCouponsCount / $limit);
$couponsSql = "SELECT * FROM cupons";
if (!empty($searchQueryCoupons)) {
    $couponsSql .= " WHERE code LIKE :busca";
}
$couponsSql .= " LIMIT :limit OFFSET :offset";
$coupons = $pdo->prepare($couponsSql);
$coupons->bindParam(':limit', $limit, PDO::PARAM_INT);
$coupons->bindParam(':offset', $offset, PDO::PARAM_INT);
if (!empty($searchQueryCoupons)) {
    $coupons->bindValue(':busca', '%' . $searchQueryCoupons . '%', PDO::PARAM_STR);
}
$coupons->execute();
$couponsGerais = $coupons->fetchAll(PDO::FETCH_ASSOC);

// Dados para a página de Settings
$configs = $pdo->query("SELECT * FROM configs WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
$gateways = $pdo->query("SELECT * FROM gateways")->fetchAll(PDO::FETCH_ASSOC);
$themes = $pdo->query("SELECT * FROM themes")->fetchAll(PDO::FETCH_ASSOC);
$admins = $pdo->query("SELECT * FROM admin_users")->fetchAll(PDO::FETCH_ASSOC);


// Dados para Dashboard
$faturament = $pdo->query("SELECT SUM(value) AS total_paids FROM transactions WHERE status = 'paid'")->fetch(PDO::FETCH_ASSOC)['total_paids'] ?? 0;
$totalWithdrawalApproved = $pdo->query("SELECT SUM(value) AS total_withdrawal_paid FROM withdrawal WHERE status = 'approved'")->fetch(PDO::FETCH_ASSOC)['total_withdrawal_paid'] ?? 0;
$totalComissions = $pdo->query("SELECT SUM(liquid_affiliate) AS total_comissions FROM comission_affiliates")->fetch(PDO::FETCH_ASSOC)['total_comissions'] ?? 0;
$totalWithdrawalApprovedTaxas = $pdo->query("SELECT SUM(value_taxa) AS total_withdrawal_taxa_paid FROM withdrawal WHERE status = 'approved'")->fetch(PDO::FETCH_ASSOC)['total_withdrawal_taxa_paid'] ?? 0;
$faturamentLiquid = ($faturament - $totalWithdrawalApprovedTaxasLiquid - $totalComissions) + $taxasLiquida;
$resultTotalProductsActive = $pdo->query("SELECT COUNT(*) FROM investment_products WHERE is_active = '1'")->fetchColumn();
$totalPendingDeposits = $pdo->query("SELECT SUM(value) FROM transactions WHERE status = 'awaiting'")->fetchColumn();

?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="<?= htmlspecialchars(ltrim($dadosPlataforma['favicon'], '/')) ?>" type="image/x-icon">
    <title>Painel de Administração - <?= htmlspecialchars($dadosPlataforma['name_platform']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        ::-webkit-scrollbar {
            width: 12px;
            height: 12px;
            background-color: #1a1a1a;
        }

        ::-webkit-scrollbar-track {
            background-color: #2c2c2c;
            border-radius: 10px;
            border: 1px solid #444;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #666;
            border-radius: 10px;
            border: 2px solid #2c2c2c;
        }

        ::-webkit-scrollbar-thumb:hover {
            background-color: #888;
        }

        .container-scroll {
            scrollbar-width: thin;
            scrollbar-color: #666 #2c2c2c;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: #000;
            color: #f8f9fa;
        }

        .sidebar {
            background-color: #1a1a1a;
            transition: transform 0.3s ease, width 0.3s ease;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.5);
            z-index: 20;
            border-right: 1px solid #333;
        }

        .sidebar:not(.collapsed) {
            width: 16rem;
        }

        .sidebar.collapsed {
            width: 5rem;
        }

        .main-content {
            flex-grow: 1;
            margin-left: 16rem;
            transition: margin-left 0.3s ease;
        }

        .main-content.collapsed {
            margin-left: 5rem;
        }

        .nav-text {
            transition: opacity 0.3s ease;
        }

        .sidebar.collapsed .nav-text {
            opacity: 0;
            width: 0;
            overflow: hidden;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: 100vh;
                position: fixed;
                top: 0;
                left: 0;
                transform: translateX(-100%);
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .main-content.collapsed {
                margin-left: 0;
            }
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            border-radius: 0.5rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .sidebar-item.active,
        .sidebar-item:hover {
            background-color: #333;
        }

        .stats-card,
        .content-panel {
            background-color: #1a1a1a;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 1rem;
            border: 1px solid #333;
        }

        .stats-card-value {
            font-size: 1.5rem;
            font-weight: 700;
        }

        .stats-card-label {
            font-size: 0.75rem;
            color: #a0aec0;
        }

        .chart-container {
            position: relative;
            height: 200px;
        }

        .user-table th,
        .user-table td {
            padding: 0.75rem 1rem;
            text-align: left;
        }

        .user-table th {
            color: #a0aec0;
            font-weight: 600;
            border-bottom: 2px solid #333;
        }

        .user-table td {
            border-bottom: 1px solid #333;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.75);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 30;
            visibility: hidden;
            opacity: 0;
            transition: visibility 0s, opacity 0.3s linear;
        }

        .modal-overlay.open {
            visibility: visible;
            opacity: 1;
        }

        .modal-content {
            background-color: #1a1a1a;
            border-radius: 0.5rem;
            padding: 2rem;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
            transform: scale(0.9);
            transition: transform 0.3s ease;
            border: 1px solid #333;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-overlay.open .modal-content {
            transform: scale(1);
        }

        .mobile-menu-toggle {
            display: block;
        }

        .desktop-sidebar-toggle {
            display: none;
        }

        @media (min-width: 769px) {
            .mobile-menu-toggle {
                display: none;
            }

            .desktop-sidebar-toggle {
                display: block;
            }

            .sidebar.collapsed {
                width: 5rem;
            }

            .sidebar:not(.collapsed) {
                transform: translateX(0);
            }
        }

        .filament-button {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            transition: background-color 0.2s ease, box-shadow 0.2s ease;
            cursor: pointer;
            border: 1px solid transparent;
        }

        .filament-button.primary {
            background-color: #dba424ff;
            color: #000;
        }

        .filament-button.primary:hover {
            background-color: #d09a1d;
        }

        .filament-button.danger {
            background-color: #dc2626;
            color: #fff;
        }

        .filament-button.danger:hover {
            background-color: #b91c1c;
        }

        .filament-button.secondary {
            background-color: #4b5563;
            color: #fff;
        }

        .filament-button.secondary:hover {
            background-color: #374151;
        }

        .filament-input,
        .filament-select {
            background-color: #0E0E0E;
            border: 1px solid #4b556383;
            color: #f8f9fa;
            border-radius: 0.375rem;
            padding: 0.75rem;
            width: 100%;
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .filament-input:focus,
        .filament-select:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
        }

        .image-preview-thumb {
            max-width: 50px;
            max-height: 50px;
            object-fit: cover;
            border-radius: 0.25rem;
            margin-right: 0.5rem;
        }

        /* Estilos para a Árvore de Afiliados */
        .affiliate-tree {
            list-style-type: none;
            padding-left: 1rem;
        }

        .affiliate-tree-item {
            position: relative;
            padding: 0.5rem 0;
        }

        .affiliate-tree-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 1px;
            height: 100%;
            background: #4b5563;
        }

        .affiliate-tree-item-content {
            display: flex;
            align-items: center;
            padding-left: 1rem;
            color: #f8f9fa;
        }

        .affiliate-tree-item-content::before {
            content: '';
            position: absolute;
            left: 0;
            top: 1rem;
            width: 1rem;
            height: 1px;
            background: #4b5563;
        }
    </style>
</head>

<body class="flex min-h-screen">

    <?php if (isset($_SESSION['toastType'], $_SESSION['toastMessage'])): ?>
        <section style="z-index:9999" id="toast" class="fixed top-6 right-6 z-50" style="width: 356px;">
            <div
                id="toastItem"
                class="flex items-center gap-3 px-4 py-3 border rounded-md shadow-lg animate-slideDownFade <?= ($_SESSION['toastType']) === 'success' ? 'bg-[#0D3A0E] border-[#36D957] text-[#B9FFBE]' : 'bg-[#8B0000] border-[#660000] text-[#FFB6B6]' ?> font-medium text-sm"
                role="alert">
                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="w-5 h-5" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
                </svg>
                <span id="toastText"><?= htmlspecialchars($_SESSION['toastMessage']) ?></span>
            </div>
        </section>

        <style>
            @keyframes slideDownFade {
                0% {
                    opacity: 0;
                    transform: translateY(-30px);
                }

                100% {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            .animate-slideDownFade {
                animation: slideDownFade 0.4s ease-out;
                transition: opacity 0.5s ease-in;
            }
        </style>

        <script>
            setTimeout(() => {
                const toast = document.getElementById('toastItem');
                if (toast) {
                    toast.style.opacity = '0';
                    toast.style.transition = 'opacity 0.5s ease-in';
                    setTimeout(() => toast.remove(), 500);
                }
            }, 3000);
        </script>
        <?php unset($_SESSION['toastType'], $_SESSION['toastMessage']); ?>
    <?php endif; ?>

    <aside id="sidebar" class="sidebar h-full w-64 fixed top-0 left-0 flex flex-col p-4">
        <div class="flex items-center justify-between mb-8">
            <h1 class="text-2xl font-bold nav-text"><?= htmlspecialchars($dadosPlataforma['name_platform']) ?></h1>
            <button id="mobile-sidebar-close" class="mobile-menu-toggle text-white focus:outline-none p-1 rounded hover:bg-gray-700">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
            <button id="desktop-sidebar-toggle" class="desktop-sidebar-toggle text-white focus:outline-none p-1 rounded hover:bg-gray-700">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                </svg>
            </button>
        </div>
        <nav class="flex-grow">
            <ul>
                <li class="mb-2"><a href="?page=dashboard" id="link-dashboard" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                        </svg>
                        <span class="nav-text">Painel de Controle</span>
                    </a></li>
                <li class="mb-2"><a href="?page=users" id="link-users" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                        </svg>
                        <span class="nav-text">Usuários</span>
                    </a></li>
                <li class="mb-2"><a href="?page=affiliate-network" id="link-affiliate-network" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.5 16.5h-3m3 0a.75.75 0 01-.75.75h-3a.75.75 0 01-.75-.75m3 0v-1.5m0 1.5l1.5-1.5V12m-1.5 4.5l-1.5-1.5m1.5 1.5h-.75m-4.5 0a.75.75 0 01-.75.75h-3a.75.75 0 01-.75-.75m-1.5-1.5v3h3v-3h-3zm9 0a.75.75 0 01.75-.75h3a.75.75 0 01.75.75m-3-1.5h-1.5v3m-3-3h1.5v3m-4.5-1.5h1.5v3m-1.5-3h1.5v3m-1.5-3h1.5v3" />
                        </svg>
                        <span class="nav-text">Árvore de Afiliados</span>
                    </a></li>
                <li class="mb-2"><a href="?page=investment-products" id="link-investment-products" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.592 1M12 8V4m0 4h.01M12 12h.01M12 16h.01M12 20h.01M6.5 12a.5.5 0 11-1 0 .5.5 0 011 0z" />
                        </svg>
                        <span class="nav-text">Produtos de Investimento</span>
                    </a></li>
                <li class="mb-2"><a href="?page=investments" id="link-investments" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                        </svg>
                        <span class="nav-text">Investimentos Ativos</span>
                    </a></li>
                <li class="mb-2"><a href="?page=withdrawals" id="link-withdrawals" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                        </svg>
                        <span class="nav-text">Saques</span>
                    </a></li>
                <li class="mb-2"><a href="?page=transactions" id="link-transactions" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M3 14h18m-9-4v8m-7 0h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
                        </svg>
                        <span class="nav-text">Transações</span>
                    </a></li>
                <li class="mb-2"><a href="?page=accounts-pix" id="link-accounts-pix" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4a8 8 0 100 16 8 8 0 000-16zm-7.5 8c0-3.866 3.134-7 7-7s7 3.134 7 7-3.134 7-7 7-7-3.134-7-7zM12 9a.5.5 0 110-1 .5.5 0 010 1zM12 15a.5.5 0 110-1 .5.5 0 010 1z" />
                        </svg>
                        <span class="nav-text">Contas PIX</span>
                    </a></li>
                <li class="mb-2"><a href="?page=coupons" id="link-coupons" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 14l6-6m-6 0h.01M9 14h.01m-1 7h8a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 01-2-2m2 4v-2m2 2h2a2 2 0 012 2v10a2 2 0 01-2 2H9a2 2 0 01-2-2v-6a2 2 0 01-2-2z" />
                        </svg>
                        <span class="nav-text">Cupons</span>
                    </a></li>
                <li class="mb-2"><a href="?page=settings" id="link-settings" class="sidebar-item">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                        <span class="nav-text">Configurações</span>
                    </a></li>
            </ul>
        </nav>
        <div class="flex items-center p-3 mt-auto border-t border-gray-600">
            <?php if (!empty($dadosPlataforma['logo'])): ?>
                <img src="<?= htmlspecialchars(ltrim($dadosPlataforma['logo'], '/')) ?>" alt="Logo" class="max-h-8 max-w-[100px] mr-3">
            <?php else: ?>
                <img src="https://placehold.co/40x40/4a5568/a0aec0?text=U" alt="User Profile" class="rounded-full mr-3">
            <?php endif; ?>
            <div class="nav-text">
                <span class="block text-sm font-semibold">Admin</span>
                <span class="block text-xs text-gray-400">Online</span>
            </div>
        </div>
    </aside>

    <main id="main-content" class="main-content p-8 bg-[#0E0E0E] transition-all duration-300">
        <header class="flex items-center justify-between mb-8">
            <h2 id="page-title" class="text-2xl font-bold">Painel de Controle</h2>
            <div class="flex items-center space-x-4">
                <button id="mobile-menu-toggle" class="mobile-menu-toggle text-white focus:outline-none p-1 rounded hover:bg-gray-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                    </svg>
                </button>
                <div class="relative hidden md:block">
                    <input type="text" placeholder="Buscar..." class="bg-gray-700 text-white placeholder-gray-400 rounded-full px-4 py-2 pl-10 focus:outline-none focus:ring-2 focus:ring-blue-500 w-full">
                    <svg class="h-5 w-5 absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                    </svg>
                </div>
            </div>
        </header>

        <div id="content-area"></div>
    </main>

    <!-- Modal de Edição Genérico -->
    <div id="edit-modal" class="modal-overlay <?= $showEditModal ? 'open' : '' ?>">
        <div class="modal-content">
            <h3 class="text-xl font-bold mb-4" id="modal-title">Editar Item</h3>
            <form id="edit-form" method="POST" action="?page=<?= htmlspecialchars($currentPage) ?>" enctype="multipart/form-data">
                <input type="hidden" name="action" id="modal-action" value="update_<?= htmlspecialchars($editDataType) ?>">
                <?php if ($editDataType === 'user' && $editData): ?>
                    <input type="hidden" name="user_id" value="<?= htmlspecialchars($editData['id']) ?>">
                    <div class="mb-4"><label for="user-name" class="block text-sm font-medium mb-2">Nome</label><input type="text" id="user-name" name="user_name" class="filament-input" value="<?= htmlspecialchars($editData['name']) ?>"></div>
                    <div class="mb-4"><label for="user-phone" class="block text-sm font-medium mb-2">Telefone</label><input type="text" id="user-phone" name="user_phone" class="filament-input" value="<?= htmlspecialchars($editData['phone']) ?>"></div>
                    <div class="mb-4"><label for="user-balance" class="block text-sm font-medium mb-2">Saldo</label><input type="number" step="0.01" id="user-balance" name="user_balance" class="filament-input" value="<?= htmlspecialchars($editData['balance']) ?>"></div>
                    <div class="mb-4"><label for="profit_investments" class="block text-sm font-medium mb-2">Lucro de Investimentos</label><input type="number" step="0.01" id="profit_investments" name="profit_investments" class="filament-input" value="<?= htmlspecialchars($editData['profit_investments']) ?>"></div>
                    <div class="mb-4"><label for="qtd_spins" class="block text-sm font-medium mb-2">Giros Disponíveis</label><input type="number" id="qtd_spins" name="qtd_spins" class="filament-input" value="<?= htmlspecialchars($editData['qtd_spins']) ?>"></div>
                    <div class="mb-4"><label for="total_lvl1" class="block text-sm font-medium mb-2">Total Nível 1</label><input type="number" step="0.01" id="total_lvl1" name="total_lvl1" class="filament-input" value="<?= htmlspecialchars($editData['total_lvl1']) ?>"></div>
                    <div class="mb-4"><label for="total_lvl2" class="block text-sm font-medium mb-2">Total Nível 2</label><input type="number" step="0.01" id="total_lvl2" name="total_lvl2" class="filament-input" value="<?= htmlspecialchars($editData['total_lvl2']) ?>"></div>
                    <div class="mb-4"><label for="total_lvl3" class="block text-sm font-medium mb-2">Total Nível 3</label><input type="number" step="0.01" id="total_lvl3" name="total_lvl3" class="filament-input" value="<?= htmlspecialchars($editData['total_lvl3']) ?>"></div>
                    <div class="mb-4"><label for="total_indicated_deposits" class="block text-sm font-medium mb-2">Total Depósitos Indicados</label><input type="number" step="0.01" id="total_indicated_deposits" name="total_indicated_deposits" class="filament-input" value="<?= htmlspecialchars($editData['total_indicated_deposits']) ?>"></div>
                    <div class="mb-4"><label for="qtd_investments" class="block text-sm font-medium mb-2">Qtd Investimentos</label><input type="number" id="qtd_investments" name="qtd_investments" class="filament-input" value="<?= htmlspecialchars($editData['qtd_investments']) ?>"></div>
                    <div class="mb-4"><label for="affiliate_code" class="block text-sm font-medium mb-2">Código Afiliado</label><input type="text" id="affiliate_code" name="affiliate_code" class="filament-input" value="<?= htmlspecialchars($editData['affiliate_code']) ?>"></div>
                    <div class="mb-4"><label for="indicated_by" class="block text-sm font-medium mb-2">Indicado Por</label><input type="text" id="indicated_by" name="indicated_by" class="filament-input" value="<?= htmlspecialchars($editData['indicated_by']) ?>"></div>
                    <div class="mb-4"><label for="lider" class="block text-sm font-medium mb-2">Líder</label>
                        <select id="lider" name="lider" class="filament-select">
                            <option value="no" <?= ($editData['lider'] == 'no') ? 'selected' : '' ?>>Não</option>
                            <option value="yes" <?= ($editData['lider'] == 'yes') ? 'selected' : '' ?>>Sim</option>
                        </select>
                    </div>
                    <div class="mb-4"><label for="user-password" class="block text-sm font-medium mb-2">Nova Senha</label><input type="text" id="user-password" name="user_password" class="filament-input"></div>
                    <div class="mb-4"><label for="user-status" class="block text-sm font-medium mb-2">Status</label>
                        <select id="user-status" name="user_status" class="filament-select">
                            <option value="active" <?= ($editData['status'] == 'active') ? 'selected' : '' ?>>Ativo</option>
                            <option value="banned" <?= ($editData['status'] == 'banned') ? 'selected' : '' ?>>Banido</option>
                        </select>
                    </div>
                <?php elseif ($editDataType === 'investment_product' && $editData): ?>
                    <input type="hidden" name="product_id" value="<?= htmlspecialchars($editData['id']) ?>">
                    <p class="block text-lg font-medium mb-4">Tipo Projeto: (<?= ($editData['type'] === 'diary') ? 'Diário' : 'Ciclo' ?>)</p>
                    <div class="mb-4"><label for="product-name" class="block text-sm font-medium mb-2">Nome</label><input type="text" id="product-name" name="product_name" class="filament-input" value="<?= htmlspecialchars($editData['name']) ?>"></div>
                    <div class="mb-4"><label for="product-img" class="block text-sm font-medium mb-2">Imagem</label><input type="text" id="product-img" name="product_img" class="filament-input" value="<?= htmlspecialchars($editData['img']) ?>"></div>
                    <div class="mb-4"><label for="product-description" class="block text-sm font-medium mb-2">Descrição</label><textarea id="product-description" name="product_description" class="filament-input" rows="3"><?= htmlspecialchars($editData['description']) ?></textarea></div>
                    <div class="mb-4"><label for="product-value" class="block text-sm font-medium mb-2">Valor</label><input type="number" step="0.01" id="product-value" name="product_value" class="filament-input" value="<?= htmlspecialchars($editData['value']) ?>"></div>
                    <div class="mb-4"><label for="total-days" class="block text-sm font-medium mb-2">Total de Dias</label><input type="number" id="total-days" name="total_days" class="filament-input" value="<?= htmlspecialchars($editData['total_days']) ?>"></div>
                    <div class="mb-4"><label for="daily-return" class="block text-sm font-medium mb-2"> <?= ($editData['type'] === 'diary') ? 'Retorno Diário (R$)' : 'Recompensa Final' ?></label><input type="number" step="0.01" id="daily-return" name="daily_return" class="filament-input" value="<?= htmlspecialchars($editData['daily_return']) ?>"></div>
                    <div class="mb-4"><label for="limit-purchase" class="block text-sm font-medium mb-2">Limite de Compra</label><input type="number" id="limit-purchase" name="limit_purchase" class="filament-input" value="<?= htmlspecialchars($editData['limit_purchase']) ?>"></div>
                    <div class="mb-4"><label for="new_user" class="block text-sm font-medium mb-2">Apenas novos usuários ?</label>
                        <select id="new_user" name="new_user" class="filament-select">
                            <option value="0" <?= ($editData['new_user'] == '1') ? 'selected' : '' ?>>Não</option>
                            <option value="1" <?= ($editData['new_user'] == '0') ? 'selected' : '' ?>>Sim</option>
                        </select>
                    </div>
                    <div class="mb-4"><label for="position" class="block text-sm font-medium mb-2">Posição de Apresentação</label><select id="position" name="order_product" value="<?= htmlspecialchars($editData['order_product']) ?>" class="filament-input"><option value="1">1º Lugar</option><option value="2">2º Lugar</option><option value="3">3º Lugar</option><option value="4">4º Lugar</option><option value="5">5º Lugar</option><option value="6">6º Lugar</option><option value="7">7º Lugar</option><option value="8">8º Lugar</option><option value="9">9º Lugar</option><option value="10">10º Lugar</option><option value="11">11º Lugar</option><option value="12">12º Lugar</option><option value="13">13º Lugar</option><option value="14">14º Lugar</option><option value="15">15º Lugar</option><option value="16">16º Lugar</option><option value="17">17º Lugar</option><option value="18">18º Lugar</option><option value="19">19º Lugar</option><option value="20">20º Lugar</option></select></div>
                                        <div class="mb-4"><label for="und" class="block text-sm font-medium mb-2">Unidades Disponíveis para Compra</label><input type="number" id="und" name="available" class="filament-input" value="<?= htmlspecialchars($editData['available']) ?>" required></div>
                    <div class="mb-4"><label for="is-active" class="block text-sm font-medium mb-2">Status</label>
                        <select id="is-active" name="is_active" class="filament-select">
                            <option value="1" <?= ($editData['is_active'] == '1') ? 'selected' : '' ?>>Ativo</option>
                            <option value="0" <?= ($editData['is_active'] == '0') ? 'selected' : '' ?>>Inativo</option>
                        </select>
                    </div>
                <?php elseif ($editDataType === 'withdrawal' && $editData): ?>
                    <input type="hidden" name="withdrawal_id" value="<?= htmlspecialchars($editData['id']) ?>">
                    <div class="mb-4"><strong>ID do Saque:</strong> <?= htmlspecialchars($editData['id']) ?></div>
                    <div class="mb-4"><strong>Usuário:</strong> <?= htmlspecialchars($editData['user_name']) ?></div>
                    <div class="mb-4"><strong>Telefone:</strong> <?= htmlspecialchars($editData['phone']) ?></div>
                    <div class="mb-4"><strong>Valor Solicitado:</strong> R$ <?= number_format($editData['value'], 2, ',', '.') ?></div>
                    <div class="mb-4"><strong>Valor Líquido:</strong> R$ <?= number_format($editData['with_liquid'], 2, ',', '.') ?></div>
                    <div class="mb-4"><label for="withdrawal-status" class="block text-sm font-medium mb-2">Status</label>
                        <select id="withdrawal-status" name="status" class="filament-select">
                            <option value="pending" <?= ($editData['status'] == 'pending') ? 'selected' : '' ?>>Pendente</option>
                            <option value="approved" <?= ($editData['status'] == 'approved') ? 'selected' : '' ?>>Aprovado</option>
                            <option value="recused" <?= ($editData['status'] == 'recused') ? 'selected' : '' ?>>Recusado</option>
                        </select>
                    </div>
                <?php elseif ($editDataType === 'account_pix' && $editData): ?>
                    <input type="hidden" name="account_id" value="<?= htmlspecialchars($editData['id']) ?>">
                    <div class="mb-4"><label for="type_pix" class="block text-sm font-medium mb-2">Tipo de Chave</label>
                        <select id="type_pix" name="type_pix" class="filament-select">
                            <option value="CPF" <?= ($editData['type_pix'] == 'CPF') ? 'selected' : '' ?>>CPF</option>
                            <option value="EMAIL" <?= ($editData['type_pix'] == 'EMAIL') ? 'selected' : '' ?>>EMAIL</option>
                            <option value="PHONE" <?= ($editData['type_pix'] == 'PHONE') ? 'selected' : '' ?>>PHONE</option>
                        </select>
                    </div>
                    <div class="mb-4"><label for="key_beneficiary" class="block text-sm font-medium mb-2">Chave PIX</label><input type="text" id="key_beneficiary" name="key_beneficiary" class="filament-input" value="<?= htmlspecialchars($editData['key_beneficiary']) ?>"></div>
                    <div class="mb-4"><label for="account_status" class="block text-sm font-medium mb-2">Status</label>
                        <select id="account_status" name="status" class="filament-select">
                            <option value="active" <?= ($editData['status'] == 'active') ? 'selected' : '' ?>>Ativo</option>
                            <option value="inative" <?= ($editData['status'] == 'inative') ? 'selected' : '' ?>>Inativo</option>
                        </select>
                    </div>
                <?php elseif ($editDataType === 'coupon' && $editData): ?>
                    <input type="hidden" name="coupon_id" value="<?= htmlspecialchars($editData['id']) ?>">
                    <div class="mb-4"><label for="coupon-code" class="block text-sm font-medium mb-2">Código</label><input type="text" id="coupon-code" name="code" class="filament-input" value="<?= htmlspecialchars($editData['code']) ?>"></div>
                    <div class="mb-4"><label for="coupon-expire-at" class="block text-sm font-medium mb-2">Expira em</label><input type="datetime-local" id="coupon-expire-at" name="expire_at" class="filament-input" value="<?= date('Y-m-d\TH:i', strtotime($editData['expire_at'])) ?>"></div>
                    <div class="mb-4"><label for="coupon-status" class="block text-sm font-medium mb-2">Status</label>
                        <select id="coupon-status" name="status" class="filament-select">
                            <option value="active" <?= ($editData['status'] == 'active') ? 'selected' : '' ?>>Ativo</option>
                            <option value="disabled" <?= ($editData['status'] == 'disabled') ? 'selected' : '' ?>>Inativo</option>
                            <option value="expired" <?= ($editData['status'] == 'expired') ? 'selected' : '' ?>>Expirado</option>
                        </select>
                    </div>
                <?php endif; ?>
                <div class="flex justify-end space-x-4 mt-6">
                    <button type="button" id="close-modal" class="filament-button secondary">Cancelar</button>
                    <button type="submit" class="filament-button primary">Salvar</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('main-content');
            const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
            const mobileSidebarClose = document.getElementById('mobile-sidebar-close');
            const desktopSidebarToggle = document.getElementById('desktop-sidebar-toggle');
            const contentArea = document.getElementById('content-area');
            const navLinks = document.querySelectorAll('.sidebar-item');
            const pageTitle = document.getElementById('page-title');

            // Modal elements
            const editModal = document.getElementById('edit-modal');
            const closeModalBtn = document.getElementById('close-modal');
            const editForm = document.getElementById('edit-form');
            const modalTitle = document.getElementById('modal-title');

            // Funções para controle da sidebar
            const toggleSidebar = () => {
                sidebar.classList.toggle('collapsed');
                mainContent.classList.toggle('collapsed');
            };
            desktopSidebarToggle.addEventListener('click', toggleSidebar);
            mobileMenuToggle.addEventListener('click', () => {
                sidebar.classList.add('active');
            });
            mobileSidebarClose.addEventListener('click', () => {
                sidebar.classList.remove('active');
            });

            // Função para obter parâmetro da URL
            const getURLParameter = (name) => {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                const regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
                const results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            };

            // Função para desenhar o gráfico SVG
            const drawChart = () => {
                const canvas = document.getElementById('finance-chart');
                if (!canvas) return;
                const width = canvas.offsetWidth;
                const height = canvas.offsetHeight;
                canvas.innerHTML = '';
                const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                svg.setAttribute("width", width);
                svg.setAttribute("height", height);
                svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
                canvas.appendChild(svg);
                const padding = 20;
                const chartWidth = width - padding * 2;
                const chartHeight = height - padding * 2;
                const mockData = {
                    labels: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun'],
                    deposits: [5000, 7000, 6500, 8000, 7500, 9000],
                    withdrawals: [2000, 3500, 3000, 4500, 4000, 5000]
                };
                const maxVal = Math.max(...mockData.deposits, ...mockData.withdrawals);
                const getPoints = (data) => data.map((val, i) => `${padding + (chartWidth / (data.length - 1)) * i},${height - padding - (chartHeight / maxVal) * val}`).join(' ');
                const createLine = (points, color) => {
                    const line = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
                    line.setAttribute("points", points);
                    line.setAttribute("fill", "none");
                    line.setAttribute("stroke-width", "2");
                    line.setAttribute("stroke", color);
                    svg.appendChild(line);
                };
                createLine(getPoints(mockData.deposits), '#34d399');
                createLine(getPoints(mockData.withdrawals), '#f87171');
            };

            const renderPage = (page) => {
                let html = '';
                navLinks.forEach(item => item.classList.remove('active'));
                const activeLink = document.getElementById(`link-${page}`);
                if (activeLink) activeLink.classList.add('active');
                const currentUrl = new URL(window.location.href);
                currentUrl.searchParams.set('page', page);
                ['edit_user_id', 'edit_product_id', 'edit_withdrawal_id', 'edit_account_id', 'edit_coupon_id'].forEach(param => currentUrl.searchParams.delete(param));
                history.pushState(null, '', currentUrl.toString());

                switch (page) {
                    case 'dashboard':
                        pageTitle.textContent = 'Painel de Controle';
                        html = `
                            <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
                            <section class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Faturamento</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold">R$ <?= number_format($faturament, 2, ',', '.') ?></h4>
                                        <div class="text-green-500"><i class="bx bx-dollar-circle text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Faturamento Líquido</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold">R$ <?= number_format($faturamentLiquid, 2, ',', '.') ?></h4>
                                        <div class="text-blue-400"><i class="bx bx-line-chart-down text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Usuários</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold"><?= htmlspecialchars($totalUsers) ?></h4>
                                        <div class="text-white"><i class="bx bx-user text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Produtos Ativos</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold"><?= htmlspecialchars($resultTotalProductsActive) ?></h4>
                                        <div class="text-yellow-400"><i class="bx bx-briefcase text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Total Comissões</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold">R$ <?= number_format($totalComissions, 2, ',', '.') ?></h4>
                                        <div class="text-purple-400"><i class="bx bx-group text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Taxas Recebidas (Saques)</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold">R$ <?= number_format($taxasLiquida, 2, ',', '.') ?></h4>
                                        <div class="text-orange-400"><i class="bx bx-line-chart text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Total Saq. Aprovados</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold">R$ <?= number_format($totalWithdrawalApprovedTaxasLiquid, 2, ',', '.') ?></h4>
                                        <div class="text-red-400"><i class="bx bx-credit-card-front text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Total Dep. Pendentes</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold">R$ <?= number_format($totalPendingDeposits, 2, ',', '.') ?></h4>
                                        <div class="text-lime-400"><i class="bx bx-wallet-alt text-2xl"></i></div>
                                    </div>
                                </div>
                                <div class="stats-card p-4">
                                    <h3 class="card-category text-sm font-medium text-gray-400">Total Acessos</h3>
                                    <div class="flex items-end justify-between mt-2">
                                        <h4 class="card-title text-xl font-bold"><?= htmlspecialchars($resultVisitors['total_visitas']) ?></h4>
                                        <div class="text-red-400"><i class="bx bx-group text-2xl"></i></div>
                                    </div>
                                </div>
                            </section>
                            <section class="content-panel p-6">
                                <h3 class="text-xl font-bold mb-4">Dados Financeiros (Mock)</h3>
                                <div id="finance-chart" class="chart-container"></div>
                            </section>
                        `;
                        setTimeout(drawChart, 100);
                        break;
                    case 'users':
                        pageTitle.textContent = 'Gerenciamento de Usuários';
                        html = `
                            <section>
                                <form method="GET" action="?page=users" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_users" type="text" placeholder="Pesquise por nome, telefone ou código..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryUsers) ?>" />
                                    <input type="hidden" name="page" value="users" />
                                    <button type="submit" name="send-search" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">Nome</th>
                                                <th class="px-4 py-3">Telefone</th>
                                                <th class="px-4 py-3">Saldo</th>
                                                <th class="px-4 py-3">Cód. Afiliado</th>
                                                <th class="px-4 py-3">Indicado Por</th>
                                                <th class="px-4 py-3">Status</th>
                                                <th class="px-4 py-3">Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                            <?php if (empty($usuariosGerais)): ?>
                                                <tr><td colspan="8" class="px-4 py-4 text-center text-gray-500">Nenhum usuário encontrado.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($usuariosGerais as $usuario) : ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($usuario['id']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($usuario['name']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($usuario['phone']) ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($usuario['balance'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2 text-xs"><?= htmlspecialchars($usuario['affiliate_code']) ?></td>
                                                    <td class="px-4 py-2 text-xs"><?= htmlspecialchars($usuario['indicated_by'] ?? 'N/A') ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full <?= ($usuario['status'] == 'active') ? 'bg-green-500' : 'bg-red-500' ?> text-white"><?= htmlspecialchars(ucfirst($usuario['status'])) ?></span></td>
                                                    <td class="px-4 py-2 flex flex-wrap gap-2">
                                                        <a href="?page=users&edit_user_id=<?= htmlspecialchars($usuario['id']) ?>" class="filament-button primary text-xs">Editar</a>
                                                        <a href="?page=user-profile&user_id=<?= htmlspecialchars($usuario['id']) ?>" class="filament-button secondary text-xs">Ver Perfil</a>
                                                        <form method="POST" action="?page=users" onsubmit="return confirm('Tem certeza que deseja excluir este usuário?');" style="display:inline;">
                                                            <input type="hidden" name="action" value="delete_user">
                                                            <input type="hidden" name="user_id" value="<?= htmlspecialchars($usuario['id']) ?>">
                                                            <button type="submit" class="filament-button danger text-xs">Excluir</button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=users&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesUsers ?></span>
                                    <?php if ($page < $totalPagesUsers): ?>
                                        <a href="?page=users&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'user-profile':
                        pageTitle.textContent = 'Perfil do Usuário: <?= htmlspecialchars($profileData['name']) ?>';
                        html = `
                            <section>
                                <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Informações do Usuário</h3>
                                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Saldo</p>
                                            <span class="stats-card-value">R$ <?= number_format($profileData['balance'], 2, ',', '.') ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Lucro de Investimentos</p>
                                            <span class="stats-card-value">R$ <?= number_format($profileData['profit_investments'], 2, ',', '.') ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Giros Disponíveis</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['qtd_spins']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Lucro Afiliado</p>
                                            <span class="stats-card-value">R$ <?= number_format($profileData['total_lvl1'] + $profileData['total_lvl2'] + $profileData['total_lvl3'], 2, ',', '.') ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Visitas (Link Afiliado)</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['visits_affiliate_link']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Código de Afiliado</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['affiliate_code']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Indicado Por</p>
                                            <span class="stats-card-value"><?= htmlspecialchars(($profileData['indicated_by'] == null) ? 'Ninguém' : $profileData['indicated_by'] ) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Investimentos</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($totalInvestments) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Último Investimento</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['last_investment']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Depositado</p>
                                            <span class="stats-card-value">R$ <?= number_format($totalDeposited, 2, ',', '.') ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Sacado</p>
                                            <span class="stats-card-value">R$ <?= number_format($totalWithdrawn, 2, ',', '.') ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Nível VIP</p>
                                            <span class="stats-card-value">VIP<?= htmlspecialchars($profileData['vip_level']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Bônus VIP (Recebido)</p>
                                            <span class="stats-card-value">R$ <?= number_format($profileData['awards_vip'], 2, ',', '.') ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Giros Disponíveis</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['qtd_spins']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Giros Usados</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['total_spins']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Recebido (Envelope Dourado)</p>
                                            <span class="stats-card-value">R$ <?= htmlspecialchars($profileData['awards_spins']) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Data Cadastro</p>
                                            <span class="stats-card-value"><?= htmlspecialchars(date('d/m/Y', strtotime($profileData['date']))) ?> ás <?= htmlspecialchars(date('H:i:s', strtotime($profileData['date']))) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Último Login</p>
                                            <span class="stats-card-value"><?= htmlspecialchars(date('d/m/Y', strtotime($profileData['last_login']))) ?> ás <?= htmlspecialchars(date('H:i:s', strtotime($profileData['last_login']))) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Último Checkin</p>
                                            <span class="stats-card-value"><?= htmlspecialchars(date('d/m/Y', strtotime($profileData['last_checkin']))) ?> ás <?= htmlspecialchars(date('H:i:s', strtotime($profileData['last_checkin']))) ?></span>
                                        </div>
                                        <div class="stats-card p-4">
                                            <p class="stats-card-label">Total Checkins</p>
                                            <span class="stats-card-value"><?= htmlspecialchars($profileData['count_checkin']) ?></span>
                                        </div>
                                    </div>
                                </div>

                                <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Árvore de Afiliados</h3>
                                    <?php
                                    function renderAffiliateTree($pdo, $affiliateCode, $level = 1, $maxLevel = 3)
                                    {
                                        if ($level > $maxLevel || empty($affiliateCode)) return;
                                        $stmt = $pdo->prepare("SELECT u.id, u.name, u.phone, u.affiliate_code,
                                                                (SELECT name FROM investments WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) as last_investment_name,
                                                                (SELECT invested_amount FROM investments WHERE user_id = u.id ORDER BY created_at DESC LIMIT 1) as last_investment_amount
                                                                FROM users u WHERE u.indicated_by = :affiliate_code");
                                        $stmt->execute([':affiliate_code' => $affiliateCode]);
                                        $directAffiliates = $stmt->fetchAll(PDO::FETCH_ASSOC);

                                        if (empty($directAffiliates)) return;

                                        echo '<ul class="affiliate-tree ml-4">';
                                        foreach ($directAffiliates as $affiliate) {
                                            $lastInvestmentInfo = "Nenhum investimento";
                                            if ($affiliate['last_investment_name']) {
                                                $lastInvestmentInfo = "Último Investimento: " . htmlspecialchars($affiliate['last_investment_name']) . " (R$ " . number_format($affiliate['last_investment_amount'], 2, ',', '.') . ")";
                                            }

                                            echo '<li class="affiliate-tree-item">';
                                            echo '<div class="affiliate-tree-item-content">';
                                            echo '<span class="text-sm font-medium">Nível ' . $level . ':</span>';
                                            echo '<span class="ml-2">' . htmlspecialchars($affiliate['name']) . ' (' . htmlspecialchars($affiliate['phone']) . ') - Cód: ' . htmlspecialchars($affiliate['affiliate_code']) . '</span>';
                                            echo '<span class="ml-4 text-xs text-gray-400">' . $lastInvestmentInfo . '</span>';
                                            echo '</div>';
                                            renderAffiliateTree($pdo, $affiliate['affiliate_code'], $level + 1, $maxLevel);
                                            echo '</li>';
                                        }
                                        echo '</ul>';
                                    }
                                    echo '<div class="affiliate-tree-item">';
                                    echo '<div class="affiliate-tree-item-content font-bold">Usuário Principal: ' . htmlspecialchars($profileData['name']) . ' (Cód: ' . htmlspecialchars($profileData['affiliate_code']) . ')</div>';
                                    renderAffiliateTree($pdo, $profileData['affiliate_code']);
                                    echo '</div>';
                                    ?>
                                </div>
                                
                                <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Depósitos do Usuário</h3>
                                    <div class="overflow-x-auto rounded-lg border border-gray-700">
                                        <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                            <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                                <tr>
                                                    <th class="px-4 py-3">ID</th>
                                                    <th class="px-4 py-3">Valor</th>
                                                    <th class="px-4 py-3">Status</th>
                                                    <th class="px-4 py-3">Data</th>
                                                </tr>
                                            </thead>
                                            <tbody class="divide-y divide-gray-700 stats-card">
                                                <?php if (empty($userTransactions)): ?>
                                                    <tr><td colspan="4" class="px-4 py-4 text-center text-gray-500">Nenhum depósito encontrado.</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($userTransactions as $transaction) : ?>
                                                    <tr>
                                                        <td class="px-4 py-2"><?= htmlspecialchars($transaction['id']) ?></td>
                                                        <td class="px-4 py-2">R$ <?= number_format($transaction['value'], 2, ',', '.') ?></td>
                                                        <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full <?= ($transaction['status'] == 'paid') ? 'bg-green-500' : 'bg-orange-500' ?> text-white"><?= htmlspecialchars(ucfirst($transaction['status'])) ?></span></td>
                                                        <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($transaction['created_at'])) ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-4 flex justify-between items-center">
                                        <?php if ($page > 1): ?>
                                            <a href="?page=user-profile&user_id=<?= $userId ?>&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                        <?php endif; ?>
                                        <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesUserTransactions ?></span>
                                        <?php if ($page < $totalPagesUserTransactions): ?>
                                            <a href="?page=user-profile&user_id=<?= $userId ?>&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Saques do Usuário</h3>
                                    <div class="overflow-x-auto rounded-lg border border-gray-700">
                                        <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                            <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                                <tr>
                                                    <th class="px-4 py-3">ID</th>
                                                    <th class="px-4 py-3">Valor</th>
                                                    <th class="px-4 py-3">Status</th>
                                                    <th class="px-4 py-3">Data</th>
                                                </tr>
                                            </thead>
                                            <tbody class="divide-y divide-gray-700 stats-card">
                                                <?php if (empty($userWithdrawals)): ?>
                                                    <tr><td colspan="4" class="px-4 py-4 text-center text-gray-500">Nenhum saque encontrado.</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($userWithdrawals as $withdrawal) : ?>
                                                    <tr>
                                                        <td class="px-4 py-2"><?= htmlspecialchars($withdrawal['id']) ?></td>
                                                        <td class="px-4 py-2">R$ <?= number_format($withdrawal['value'], 2, ',', '.') ?></td>
                                                        <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full 
                                                            <?php if ($withdrawal['status'] == 'approved') echo 'bg-green-500';
                                                            elseif ($withdrawal['status'] == 'pending') echo 'bg-orange-500';
                                                            else echo 'bg-red-500'; ?> text-white"><?= htmlspecialchars(ucfirst($withdrawal['status'])) ?></span></td>
                                                        <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($withdrawal['created_at'])) ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-4 flex justify-between items-center">
                                        <?php if ($page > 1): ?>
                                            <a href="?page=user-profile&user_id=<?= $userId ?>&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                        <?php endif; ?>
                                        <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesUserWithdrawals ?></span>
                                        <?php if ($page < $totalPagesUserWithdrawals): ?>
                                            <a href="?page=user-profile&user_id=<?= $userId ?>&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="content-panel p-6">
                                    <h3 class="text-xl font-bold mb-4">Histórico de Atividades do Usuário</h3>
                                    <div class="overflow-x-auto rounded-lg border border-gray-700">
                                        <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                            <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                                <tr>
                                                    <th class="px-4 py-3">ID</th>
                                                    <th class="px-4 py-3">Ação</th>
                                                    <th class="px-4 py-3">Data</th>
                                                </tr>
                                            </thead>
                                            <tbody class="divide-y divide-gray-700 stats-card">
                                                <?php if (empty($userActivity)): ?>
                                                    <tr><td colspan="3" class="px-4 py-4 text-center text-gray-500">Nenhuma atividade encontrada.</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($userActivity as $activity) : ?>
                                                    <tr>
                                                        <td class="px-4 py-2"><?= htmlspecialchars($activity['id']) ?></td>
                                                        <td class="px-4 py-2"><?= htmlspecialchars($activity['action']) ?></td>
                                                        <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($activity['created_at'])) ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-4 flex justify-between items-center">
                                        <?php if ($page > 1): ?>
                                            <a href="?page=user-profile&user_id=<?= $userId ?>&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                        <?php endif; ?>
                                        <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesUserActivity ?></span>
                                        <?php if ($page < $totalPagesUserActivity): ?>
                                            <a href="?page=user-profile&user_id=<?= $userId ?>&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </section>
                        `;
                        break;

                    case 'affiliate-network':
                        pageTitle.textContent = 'Árvore de Afiliados';
                        html = `
                            <section>
                                <div class="content-panel p-6">
                                    <h3 class="text-xl font-bold mb-4">Visualizar Rede de Afiliados</h3>
                                    <form method="GET" action="?page=affiliate-network" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                        <input name="affiliate_code" type="text" placeholder="Código de afiliação do usuário principal" class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($_GET['affiliate_code'] ?? '') ?>" />
                                        <input type="hidden" name="page" value="affiliate-network" />
                                        <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar Rede</button>
                                    </form>
                                    <?php if (isset($_GET['affiliate_code'])): ?>
                                        <div class="mt-8">
                                            <h4 class="text-lg font-bold">Árvore para o Afiliado: <?= htmlspecialchars($_GET['affiliate_code']) ?></h4>
                                            <?php
                                            function renderAffiliateTree($pdo, $tree)
                                            {
                                                if (empty($tree)) return;
                                                echo '<ul class="affiliate-tree">';
                                                foreach ($tree as $affiliate) {
                                                    $lastInvestmentInfo = "Nenhum investimento";
                                                    if ($affiliate['last_investment_name']) {
                                                        $lastInvestmentInfo = "Último Investimento: " . htmlspecialchars($affiliate['last_investment_name']) . " (R$ " . number_format($affiliate['last_investment_amount'], 2, ',', '.') . ") em " . date('d/m/y', strtotime($affiliate['last_investment_date']));
                                                    }

                                                    echo '<li class="affiliate-tree-item">';
                                                    echo '<div class="affiliate-tree-item-content">';
                                                    echo '<span class="text-sm font-medium">Nível ' . $affiliate['level'] . ':</span>';
                                                    echo '<span class="ml-2">' . htmlspecialchars($affiliate['name']) . ' (' . htmlspecialchars($affiliate['phone']) . ') - Cód: ' . htmlspecialchars($affiliate['affiliate_code']) . '</span>';
                                                    echo '<span class="ml-4 text-xs text-gray-400">' . $lastInvestmentInfo . '</span>';
                                                    echo '</div>';
                                                    if (!empty($affiliate['children'])) {
                                                        renderAffiliateTree($pdo, $affiliate['children']);
                                                    }
                                                    echo '</li>';
                                                }
                                                echo '</ul>';
                                            }
                                            $affiliateTree = getAffiliateTree($pdo, $_GET['affiliate_code']);
                                            if (!empty($affiliateTree)) {
                                                renderAffiliateTree($pdo, $affiliateTree);
                                            } else {
                                                echo '<p class="text-gray-500 mt-2">Nenhum afiliado encontrado para este código.</p>';
                                            }
                                            ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'investment-products':
                        pageTitle.textContent = 'Gerenciamento de Produtos de Investimento';
                        html = `
                            <section>
                                <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Adicionar Novo Produto (Rendimento Diário)</h3>
                                    <form method="POST" action="?page=investment-products" enctype="multipart/form-data" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <input type="hidden" name="action" value="add_investment_product">
                                        <div><label for="new-product-name" class="block text-sm font-medium mb-2">Nome</label><input type="text" id="new-product-name" name="name" class="filament-input" required></div>
                                        <div><label for="new-product-value" class="block text-sm font-medium mb-2">Valor</label><input type="number" step="0.01" id="new-product-value" name="value" class="filament-input" required></div>
                                        <div><label for="new-total-days" class="block text-sm font-medium mb-2">Total de Dias</label><input type="number" id="new-total-days" name="total_days" class="filament-input" required></div>
                                        <div><label for="new-daily-return" class="block text-sm font-medium mb-2">Retorno Diário (R$)</label><input type="number" step="0.01" id="new-daily-return" name="daily_return" class="filament-input" required></div>
                                        <div><label for="new-limit-purchase" class="block text-sm font-medium mb-2">Limite de Compra (por usuário)</label><input type="number" id="new-limit-purchase" name="limit_purchase" class="filament-input" value="1" required></div>
                                        <div class="mb-4"><label for="new_user" class="block text-sm font-medium mb-2">Apenas novos usuários ?</label>
                        <select id="new_user" name="new_user" class="filament-select">
                            <option value="0" <?= ($editData['new_user'] == '1') ? 'selected' : '' ?>>Não</option>
                            <option value="1" <?= ($editData['new_user'] == '0') ? 'selected' : '' ?>>Sim</option>
                        </select>
                    </div>
                                        <div><label for="position" class="block text-sm font-medium mb-2">Posição de Apresentação</label><select id="position" name="order_product" class="filament-input"><option value="1">1º Lugar</option><option value="2">2º Lugar</option><option value="3">3º Lugar</option><option value="4">4º Lugar</option><option value="5">5º Lugar</option><option value="6">6º Lugar</option><option value="7">7º Lugar</option><option value="8">8º Lugar</option><option value="9">9º Lugar</option><option value="10">10º Lugar</option><option value="11">11º Lugar</option><option value="12">12º Lugar</option><option value="13">13º Lugar</option><option value="14">14º Lugar</option><option value="15">15º Lugar</option><option value="16">16º Lugar</option><option value="17">17º Lugar</option><option value="18">18º Lugar</option><option value="19">19º Lugar</option><option value="20">20º Lugar</option></select></div>
                                        <div><label for="und" class="block text-sm font-medium mb-2">Unidades Disponíveis para Compra</label><input type="number" id="und" name="available" class="filament-input" value="1" required></div>
                                        <div class="md:col-span-2"><label for="new-product-description" class="block text-sm font-medium mb-2">Descrição (Opcional)</label><textarea id="new-product-description" name="description" class="filament-input" rows="3"></textarea></div>
                                        <div class="md:col-span-2"><label for="new-product-img-file" class="block text-sm font-medium mb-2">Imagem do Produto (URL)</label><input required type="url" id="new-product-img-file" name="img_url_text" class="filament-input"></div>
                                        
                                        <div><h2 class="text-xl font-semibold mb-4 text-yellow-500 mt-8">Produto de Evento?</h2><label for="und" class="block text-sm font-medium mb-2">Esse produto será usado em evento?</label> <select name="event" class="filament-input"><option selected value="0">Näo informado</option><option value="1">Sim</option><option value="0">Näo</option></select> <label for="und2" class="block text-sm font-medium mb-2 mt-4">Se sim, defina data de expiraçäo do evento</label> <input id="und2" class="filament-input" type="datetime-local" name="data_expiracao_evento"/>
                                        <label for="und" class="block text-sm font-medium mb-2 mt-4">Expiraçäo automática</label> <select name="automatic_expired" class="filament-input"><option selected value="0">Näo informado</option><option value="1">Ativada</option><option value="0">Desativada</option></select></div>
                                        <div class="md:col-span-2 flex justify-end"><button type="submit" class="filament-button primary">Adicionar Produto</button></div>
                                    </form>
                                </div>
                                
                                    <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Adicionar Novo Produto (Rendimento por Ciclo)</h3>
                                    <form method="POST" action="?page=investment-products" enctype="multipart/form-data" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <input type="hidden" name="action" value="add_investment_product_cicle">
                                        <div><label for="new-product-name" class="block text-sm font-medium mb-2">Nome</label><input type="text" id="new-product-name" name="name" class="filament-input" required></div>
                                        <div><label for="new-product-value" class="block text-sm font-medium mb-2">Valor</label><input type="number" step="0.01" id="new-product-value" name="value" class="filament-input" required></div>
                                        <div><label for="new-total-days" class="block text-sm font-medium mb-2">Total de Dias</label><input type="number" id="new-total-days" name="total_days" class="filament-input" required></div>
                                        <div><label for="new-daily-return" class="block text-sm font-medium mb-2">Retorno Diário (R$)</label><input type="number" step="0.01" id="new-daily-return" name="daily_return" class="filament-input" required></div>
                                        <div><label for="new-limit-purchase" class="block text-sm font-medium mb-2">Limite de Compra</label><input type="number" id="new-limit-purchase" name="limit_purchase" class="filament-input" value="1" required></div>
                                          <div class="mb-4"><label for="new_user" class="block text-sm font-medium mb-2">Apenas novos usuários ?</label>
                        <select id="new_user" name="new_user" class="filament-select">
                            <option value="0" <?= ($editData['new_user'] == '1') ? 'selected' : '' ?>>Não</option>
                            <option value="1" <?= ($editData['new_user'] == '0') ? 'selected' : '' ?>>Sim</option>
                        </select>
                    </div>
                                         <div><label for="position" class="block text-sm font-medium mb-2">Posição de Apresentação</label><select id="position" name="order_product" class="filament-input"><option value="1">1º Lugar</option><option value="2">2º Lugar</option><option value="3">3º Lugar</option><option value="4">4º Lugar</option><option value="5">5º Lugar</option><option value="6">6º Lugar</option><option value="7">7º Lugar</option><option value="8">8º Lugar</option><option value="9">9º Lugar</option><option value="10">10º Lugar</option><option value="11">11º Lugar</option><option value="12">12º Lugar</option><option value="13">13º Lugar</option><option value="14">14º Lugar</option><option value="15">15º Lugar</option><option value="16">16º Lugar</option><option value="17">17º Lugar</option><option value="18">18º Lugar</option><option value="19">19º Lugar</option><option value="20">20º Lugar</option></select></div>
                                        <div><label for="und" class="block text-sm font-medium mb-2">Unidades Disponíveis para Compra</label><input type="number" id="und" name="available" class="filament-input" value="1" required></div>
                                        <div class="md:col-span-2"><label for="new-product-description" class="block text-sm font-medium mb-2">Descrição (Opcional)</label><textarea id="new-product-description" name="description" class="filament-input" rows="3"></textarea></div>
                                        <div class="md:col-span-2"><label for="new-product-img-file" class="block text-sm font-medium mb-2">Imagem do Produto (URL)</label><input type="url" id="new-product-img-file" name="img_url_text" class="filament-input"></div>

                                        <div><h2 class="text-xl font-semibold mb-4 text-orange-500 mt-8">Produto de Evento?</h2><label for="und" class="block text-sm font-medium mb-2">Esse produto será usado em evento?</label> <select name="event" class="filament-input"><option selected>Näo informado</option><option value="sim">Sim</option><option value="nao">Näo</option></select> <label for="und" class="block text-sm font-medium mb-2 mt-4">Se sim, defina data de expiraçäo do evento</label> <input class="filament-input text-white" type="datetime-local" name="data_expiracao_evento"/>
                                        <label for="und" class="block text-sm font-medium mb-2 mt-4">Expiraçäo automática</label> <select name="evento_expiracao" class="filament-input"><option selected>Näo informado</option><option value="sim">Ativada</option><option value="nao">Desativada</option></select></div>
                                        <div class="md:col-span-2 flex justify-end"><button type="submit" class="filament-button primary">Adicionar Produto</button></div>
                                    </form>
                                </div>
                                
                                <h3 class="text-xl font-bold mb-4">Lista de Produtos de Investimento</h3>
                                <form method="GET" action="?page=investment-products" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_products" type="text" placeholder="Pesquise por nome ou token..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryProducts) ?>" />
                                    <input type="hidden" name="page" value="investment-products" />
                                    <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">Ordem</th>
                                                <th class="px-4 py-3">Nome</th>
                                                <th class="px-4 py-3">Valor</th>
                                                <th class="px-4 py-3">Renda Diária</th>
                                                <th class="px-4 py-3">Total Retorno</th>
                                                <th class="px-4 py-3">Qtd Dias</th>
                                                <th class="px-4 py-3">Limite (Usuário)</th>
                                                <th class="px-4 py-3">Unidades Disponíveis</th>
                                                <th class="px-4 py-3">Status</th>
                                                <th class="px-4 py-3">Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                            <?php if (empty($productsGerais)): ?>
                                                <tr><td colspan="9" class="px-4 py-4 text-center text-gray-500">Nenhum produto encontrado.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($productsGerais as $product) : ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($product['id']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($product['order_product']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($product['name']) ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($product['value'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($product['daily_return'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($product['total_return'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($product['total_days']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($product['limit_purchase']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($product['available']) ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full <?= ($product['is_active'] == '1') ? 'bg-green-500' : 'bg-red-500' ?> text-white"><?= htmlspecialchars($product['is_active'] == '1' ? 'Ativo' : 'Inativo') ?></span></td>
                                                    <td class="px-4 py-2 flex flex-wrap gap-2">
                                                        <a href="?page=investment-products&edit_product_id=<?= htmlspecialchars($product['id']) ?>" class="filament-button primary text-xs">Editar</a>
                                                        <form method="POST" action="?page=investment-products" onsubmit="return confirm('Tem certeza que deseja excluir este produto?');" style="display:inline;">
                                                            <input type="hidden" name="action" value="delete_investment_product">
                                                            <input type="hidden" name="product_id" value="<?= htmlspecialchars($product['id']) ?>">
                                                            <button type="submit" class="filament-button danger text-xs">Excluir</button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=investment-products&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesProducts ?></span>
                                    <?php if ($page < $totalPagesProducts): ?>
                                        <a href="?page=investment-products&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'investments':
                        pageTitle.textContent = 'Gerenciamento de Investimentos Ativos';
                        html = `
                            <section>
                                <h3 class="text-xl font-bold mb-4">Lista de Investimentos Ativos</h3>
                                <form method="GET" action="?page=investments" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_investments" type="text" placeholder="Pesquise por nome do produto ou usuário..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryInvestments) ?>" />
                                    <input type="hidden" name="page" value="investments" />
                                    <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">Produto</th>
                                                <th class="px-4 py-3">Usuário</th>
                                                <th class="px-4 py-3">Valor Investido</th>
                                                <th class="px-4 py-3">Retorno Total</th>
                                                <th class="px-4 py-3">Data Início</th>
                                                <th class="px-4 py-3">Status</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                            <?php if (empty($investmentsGerais)): ?>
                                                <tr><td colspan="7" class="px-4 py-4 text-center text-gray-500">Nenhum investimento encontrado.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($investmentsGerais as $investment) : ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($investment['id']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($investment['name']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($investment['user_id']) ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($investment['invested_amount'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($investment['total_return'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($investment['created_at'])) ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full <?= ($investment['is_active'] == '1') ? 'bg-green-500' : 'bg-red-500' ?> text-white"><?= htmlspecialchars($investment['is_active'] == '1' ? 'Ativo' : 'Finalizado') ?></span></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=investments&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesInvestments ?></span>
                                    <?php if ($page < $totalPagesInvestments): ?>
                                        <a href="?page=investments&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'withdrawals':
                        pageTitle.textContent = 'Gerenciamento de Saques';
                        html = `
                            <section>
                                <h3 class="text-xl font-bold mb-4">Lista de Saques</h3>
                                <form method="GET" action="?page=withdrawals" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_saques" type="text" placeholder="Pesquise por nome, telefone ou ID..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryWithdrawals) ?>" />
                                    <select name="status_saques" class="filament-select w-full sm:w-auto px-4 py-2 border stats-card border-gray-600 rounded-md text-white">
                                        <option value="all" <?= ($filterStatusWithdrawals == 'all') ? 'selected' : '' ?>>Todos os Status</option>
                                        <option value="pending" <?= ($filterStatusWithdrawals == 'pending') ? 'selected' : '' ?>>Pendentes</option>
                                        <option value="approved" <?= ($filterStatusWithdrawals == 'approved') ? 'selected' : '' ?>>Aprovados</option>
                                        <option value="recused" <?= ($filterStatusWithdrawals == 'recused') ? 'selected' : '' ?>>Recusados</option>
                                    </select>
                                    <input type="hidden" name="page" value="withdrawals" />
                                    <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">Usuário</th>
                                                <th class="px-4 py-3">Telefone</th>
                                                <th class="px-4 py-3">Valor</th>
                                                <th class="px-4 py-3">Valor Líquido</th>
                                                <th class="px-4 py-3">Status</th>
                                                <th class="px-4 py-3">Data</th>
                                                <th class="px-4 py-3">Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                            <?php if (empty($withdrawalsGerais)): ?>
                                                <tr><td colspan="8" class="px-4 py-4 text-center text-gray-500">Nenhum saque encontrado.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($withdrawalsGerais as $withdrawal) : ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($withdrawal['id']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($withdrawal['user_name']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($withdrawal['phone']) ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($withdrawal['value'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($withdrawal['with_liquid'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full 
                                                        <?php if ($withdrawal['status'] == 'approved') echo 'bg-green-500';
                                                        elseif ($withdrawal['status'] == 'pending') echo 'bg-orange-500';
                                                        else echo 'bg-red-500'; ?> text-white"><?= htmlspecialchars(ucfirst($withdrawal['status'])) ?></span>
                                                    </td>
                                                    <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($withdrawal['created_at'])) ?></td>
                                                    <td class="px-4 py-2 flex flex-wrap gap-2">
                                                        <a href="?page=withdrawals&edit_withdrawal_id=<?= htmlspecialchars($withdrawal['id']) ?>" class="filament-button primary text-xs">Editar</a>
                                                        <?php if ($withdrawal['status'] == 'pending'): ?>
                                                            <form method="POST" style="display:inline;">
                                                                <input type="hidden" name="id_with" value="<?= $withdrawal['id'] ?>">
                                                                <button name="payment_pix" type="submit" class="filament-button primary text-xs">Aprovar</button>
                                                            </form>
                                                            <form method="POST" action="?page=withdrawals" onsubmit="return confirm('Tem certeza que deseja EXCLUIR e REEMBOLSAR este saque?');" style="display:inline;">
                                                                <input type="hidden" name="action" value="delete_withdrawal_refund">
                                                                <input type="hidden" name="withdrawal_id" value="<?= htmlspecialchars($withdrawal['id']) ?>">
                                                                <button type="submit" class="filament-button danger text-xs">Excluir e Reembolsar</button>
                                                            </form>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=withdrawals&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesWithdrawals ?></span>
                                    <?php if ($page < $totalPagesWithdrawals): ?>
                                        <a href="?page=withdrawals&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'transactions':
                        pageTitle.textContent = 'Gerenciamento de Transações (Depósitos)';
                        html = `
                            <section>
                                <h3 class="text-xl font-bold mb-4">Lista de Transações</h3>
                                <form method="GET" action="?page=transactions" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_transacoes" type="text" placeholder="Pesquise por ID, referência ou usuário..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryTransactions) ?>" />
                                    <input type="hidden" name="page" value="transactions" />
                                    <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">ID Transação</th>
                                                <th class="px-4 py-3">Usuário</th>
                                                <th class="px-4 py-3">Valor</th>
                                                <th class="px-4 py-3">Status</th>
                                                <th class="px-4 py-3">Data</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                           <?php if (empty($transactionsGerais)): ?>
                                                <tr><td colspan="6" class="px-4 py-4 text-center text-gray-500">Nenhuma transação encontrada.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($transactionsGerais as $transaction) : ?>
                                                    <?php
                                                    $phoneWpp = str_replace([' ', '(', ')', '-'], '', $transaction['phone']);
                                                    ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($transaction['id']) ?></td>
                                                    <td class="px-4 py-2 text-xs"><?= htmlspecialchars($transaction['idTransaction']) ?></td>
                                                    <td class="px-4 py-2 flex items-center gap-2"><?= htmlspecialchars($transaction['phone']) ?></td>
                                                     <td class="px-4 py-2 flex items-center gap-2"> <a target="_BLANK" href="https://api.whatsapp.com/send/?phone=%2B55<?= $phoneWpp ?>&text&type=phone_number&app_absent=0"> <img class="h-6 w-6" src="uploads/icons8-whatsapp-48.png" /> </a> <a target="_BLANK" href="https://t.me/+55<?= $phoneWpp ?>"> <img class="h-6 w-6" src="uploads/icons8-aplicação-telegrama-48.png" /> </a></td>
                                                    <td class="px-4 py-2">R$ <?= number_format($transaction['value'], 2, ',', '.') ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full <?= ($transaction['status'] == 'paid') ? 'bg-green-500' : 'bg-orange-500' ?> text-white"><?= htmlspecialchars(ucfirst($transaction['status'])) ?></span></td>
                                                    <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($transaction['created_at'])) ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=transactions&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesTransactions ?></span>
                                    <?php if ($page < $totalPagesTransactions): ?>
                                        <a href="?page=transactions&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'accounts-pix':
                        pageTitle.textContent = 'Gerenciamento de Contas PIX';
                        html = `
                            <section>
                                <h3 class="text-xl font-bold mb-4">Lista de Contas PIX</h3>
                                <form method="GET" action="?page=accounts-pix" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_accounts" type="text" placeholder="Pesquise por chave PIX, nome ou telefone..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryAccounts) ?>" />
                                    <input type="hidden" name="page" value="accounts-pix" />
                                    <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">Usuário</th>
                                                <th class="px-4 py-3">Tipo PIX</th>
                                                <th class="px-4 py-3">Chave PIX</th>
                                                <th class="px-4 py-3">Status</th>
                                                <th class="px-4 py-3">Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                            <?php if (empty($accountsGerais)): ?>
                                                <tr><td colspan="6" class="px-4 py-4 text-center text-gray-500">Nenhum conta PIX encontrada.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($accountsGerais as $account) : ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($account['id']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($account['phone_user']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($account['type_pix']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($account['key_beneficiary']) ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full <?= ($account['status'] == 'active') ? 'bg-green-500' : 'bg-red-500' ?> text-white"><?= htmlspecialchars(ucfirst($account['status'])) ?></span></td>
                                                    <td class="px-4 py-2 flex flex-wrap gap-2">
                                                        <a href="?page=accounts-pix&edit_account_id=<?= htmlspecialchars($account['id']) ?>" class="filament-button primary text-xs">Editar</a>
                                                        <form method="POST" action="?page=accounts-pix" onsubmit="return confirm('Tem certeza que deseja excluir esta conta PIX?');" style="display:inline;">
                                                            <input type="hidden" name="action" value="delete_account_pix">
                                                            <input type="hidden" name="account_id" value="<?= htmlspecialchars($account['id']) ?>">
                                                            <button type="submit" class="filament-button danger text-xs">Excluir</button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=accounts-pix&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesAccounts ?></span>
                                    <?php if ($page < $totalPagesAccounts): ?>
                                        <a href="?page=accounts-pix&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'coupons':
                        pageTitle.textContent = 'Gerenciamento de Cupons';
                        html = `
                            <section>
                                <div class="content-panel p-6 mb-6">
                                    <h3 class="text-xl font-bold mb-4">Adicionar Novo Cupom</h3>
                                    <form method="POST" action="?page=coupons" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <input type="hidden" name="action" value="add_coupon">
                                        <div><label for="new-coupon-code" class="block text-sm font-medium mb-2">Código do Cupom</label><input type="text" id="new-coupon-code" name="code" class="filament-input" required></div>
                                        <div><label for="new-coupon-expire-at" class="block text-sm font-medium mb-2">Data de Expiração</label><input type="datetime-local" id="new-coupon-expire-at" name="expire_at" class="filament-input" required></div>
                                       <div><label for="new-coupon-value" class="block text-sm font-medium mb-2">Valor do Cupom (Deixe em branco caso seja Aleatório)</label><input type="text" id="new-coupon-value" name="value" class="filament-input" required></div>
                                       <div><label for="new-coupon-rescue" class="block text-sm font-medium mb-2">Qtd uso por Usuário</label><input type="number" id="new-coupon-rescue" name="rescue" class="filament-input" required></div>
                                       <div><label for="new-coupon-rescue_geral" class="block text-sm font-medium mb-2">Qtd uso Geral</label><input type="number" id="new-coupon-rescue_geral" name="rescue_geral" class="filament-input" required></div>
                                        <div class="md:col-span-2"><label for="new-coupon-type" class="block text-sm font-medium mb-2">Tipo</label>
                                            <select id="new-coupon-type" name="type" class="filament-select">
                                                <option value="aleatory">Valor Aleatório</option>
                                                <option value="fixed">Valor Fixo</option>
                                            </select>
                                        </div>
                                        <div class="md:col-span-2"><label for="new-coupon-status" class="block text-sm font-medium mb-2">Status</label>
                                            <select id="new-coupon-status" name="status" class="filament-select">
                                                <option value="active">Ativo</option>
                                                <option value="disabled">Desativado</option>
                                            </select>
                                        </div>
                                        <div class="md:col-span-2 flex justify-end"><button type="submit" class="filament-button primary">Adicionar Cupom</button></div>
                                    </form>
                                </div>
                                <h3 class="text-xl font-bold mb-4">Lista de Cupons</h3>
                                <form method="GET" action="?page=coupons" class="mb-4 flex flex-col sm:flex-row gap-2 sm:items-center">
                                    <input name="busca_coupons" type="text" placeholder="Pesquise por código..." class="w-full sm:w-80 px-4 py-2 border stats-card border-gray-600 rounded-md text-white placeholder:text-gray-400" value="<?= htmlspecialchars($searchQueryCoupons) ?>" />
                                    <input type="hidden" name="page" value="coupons" />
                                    <button type="submit" class="px-4 py-2 filament-button primary text-xs text-white rounded-md hover:opacity-90 transition">Buscar</button>
                                </form>
                                <div class="overflow-x-auto rounded-lg border border-gray-700">
                                    <table class="w-full text-sm text-left text-gray-300 whitespace-nowrap">
                                        <thead class="bg-gray-800 text-xs uppercase text-gray-400">
                                            <tr>
                                                <th class="px-4 py-3">ID</th>
                                                <th class="px-4 py-3">Código</th>
                                                <th class="px-4 py-3">Criado em</th>
                                                <th class="px-4 py-3">Expira em</th>
                                                <th class="px-4 py-3">Status</th>
                                                <th class="px-4 py-3">Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-700 stats-card">
                                            <?php if (empty($couponsGerais)): ?>
                                                <tr><td colspan="6" class="px-4 py-4 text-center text-gray-500">Nenhum cupom encontrado.</td></tr>
                                            <?php else: ?>
                                                <?php foreach ($couponsGerais as $coupon) : ?>
                                                <tr>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($coupon['id']) ?></td>
                                                    <td class="px-4 py-2"><?= htmlspecialchars($coupon['code']) ?></td>
                                                    <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($coupon['created_at'])) ?></td>
                                                    <td class="px-4 py-2"><?= date('d/m/y H:i', strtotime($coupon['expire_at'])) ?></td>
                                                    <td class="px-4 py-2"><span class="text-xs font-semibold px-2 py-1 rounded-full 
                                                        <?php if ($coupon['status'] == 'active') echo 'bg-green-500';
                                                        elseif ($coupon['status'] == 'disabled') echo 'bg-red-500';
                                                        else echo 'bg-yellow-500'; ?> text-white"><?= htmlspecialchars(ucfirst($coupon['status'])) ?></span></td>
                                                    <td class="px-4 py-2 flex flex-wrap gap-2">
                                                        <a href="?page=coupons&edit_coupon_id=<?= htmlspecialchars($coupon['id']) ?>" class="filament-button primary text-xs">Editar</a>
                                                        <form method="POST" action="?page=coupons" onsubmit="return confirm('Tem certeza que deseja excluir este cupom?');" style="display:inline;">
                                                            <input type="hidden" name="action" value="delete_coupon">
                                                            <input type="hidden" name="coupon_id" value="<?= htmlspecialchars($coupon['id']) ?>">
                                                            <button type="submit" class="filament-button danger text-xs">Excluir</button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-4 flex justify-between items-center">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=coupons&paged=<?= $page - 1 ?>" class="filament-button secondary">Anterior</a>
                                    <?php endif; ?>
                                    <span class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPagesCoupons ?></span>
                                    <?php if ($page < $totalPagesCoupons): ?>
                                        <a href="?page=coupons&paged=<?= $page + 1 ?>" class="filament-button secondary">Próxima</a>
                                    <?php endif; ?>
                                </div>
                            </section>
                        `;
                        break;

                    case 'settings':
                        pageTitle.textContent = 'Configurações do Sistema';
                        html = `
                            <section class="content-panel p-6 mb-6">
                                <h3 class="text-xl font-bold mb-4">Configurações Gerais do Site</h3>
                                <form method="POST" action="?page=settings" enctype="multipart/form-data">
                                    <input type="hidden" name="action" value="update_configs">
                                    <div class="mb-4"><label for="site-name" class="block text-sm font-medium mb-2">Nome da Plataforma</label><input type="text" id="site-name" name="name_platform" class="filament-input" value="<?= htmlspecialchars($configs['name_platform'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="color-primary" class="block text-sm font-medium mb-2">Cor Principal (Hex)</label><input type="color" id="color-primary" name="color_primary" class="filament-input" value="<?= htmlspecialchars($configs['color_primary'] ?? '#FFFFFF') ?>"></div>
                                    <div class="mb-4"><label for="min-dep" class="block text-sm font-medium mb-2">Depósito Mínimo</label><input type="number" step="0.01" id="min-dep" name="min_dep" class="filament-input" value="<?= htmlspecialchars($configs['min_dep'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="min-with" class="block text-sm font-medium mb-2">Saque Mínimo</label><input type="number" step="0.01" id="min-with" name="min_with" class="filament-input" value="<?= htmlspecialchars($configs['min_with'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="max-with" class="block text-sm font-medium mb-2">Saque Máximo</label><input type="number" step="0.01" id="max-with" name="max_with" class="filament-input" value="<?= htmlspecialchars($configs['max_with'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="taxa-saq" class="block text-sm font-medium mb-2">Taxa de Saque (%)</label><input type="number" id="taxa-saq" name="taxa_saq" class="filament-input" value="<?= htmlspecialchars($configs['taxa_saq'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="percentage-lvl1" class="block text-sm font-medium mb-2">Comissão Nível 1 (%)</label><input type="number" id="percentage-lvl1" name="percentage_lvl1" class="filament-input" value="<?= htmlspecialchars($configs['percentage_lvl1'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="percentage-lvl2" class="block text-sm font-medium mb-2">Comissão Nível 2 (%)</label><input type="number" id="percentage-lvl2" name="percentage_lvl2" class="filament-input" value="<?= htmlspecialchars($configs['percentage_lvl2'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="percentage-lvl3" class="block text-sm font-medium mb-2">Comissão Nível 3 (%)</label><input type="number" id="percentage-lvl3" name="percentage_lvl3" class="filament-input" value="<?= htmlspecialchars($configs['percentage_lvl3'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="support-link" class="block text-sm font-medium mb-2">Link de Suporte</label><input type="url" id="support-link" name="support_link" class="filament-input" value="<?= htmlspecialchars($configs['support_link'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="support-link2" class="block text-sm font-medium mb-2">Link de Suporte 2</label><input type="url" id="support-link2" name="support_link2" class="filament-input" value="<?= htmlspecialchars($configs['support_link2'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="support-link" class="block text-sm font-medium mb-2">Link de Suporte 3</label><input type="url" id="support-link3" name="support_link3" class="filament-input" value="<?= htmlspecialchars($configs['support_link3'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="canal-link" class="block text-sm font-medium mb-2">Link do Canal</label><input type="url" id="canal-link" name="canal_link" class="filament-input" value="<?= htmlspecialchars($configs['canal_link'] ?? '') ?>"></div>
                                    <div class="mb-4"><label for="text-login" class="block text-sm font-medium mb-2">Texto Modal Home</label><textarea id="text-login" name="text_login" class="filament-input" rows="3"><?= htmlspecialchars($configs['text_login'] ?? '') ?></textarea></div>
                                    <div class="mb-4"><label for="text-pass" class="block text-sm font-medium mb-2">Link Imagem Modal Home</label><input type="text" value="<?= htmlspecialchars($configs['text_pass'] ?? '') ?>" id="text-pass" name="text_pass" class="filament-input" rows="3"></div>
                                    <div class="mb-4"><label for="logo-file" class="block text-sm font-medium mb-2">Upload Logo</label><input type="file" id="logo-file" name="logo_file" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-gray-700 file:text-gray-200 hover:file:bg-gray-600">
                                        <label for="logo-url-text" class="block text-sm font-medium mb-2 mt-2">Ou URL da Logo</label><input type="text" id="logo-url-text" name="logo_url_text" class="filament-input" value="<?= htmlspecialchars($configs['logo'] ?? '') ?>">
                                        <?php if (!empty($configs['logo'])): ?><img src="<?= htmlspecialchars(ltrim($configs['logo'], '/')) ?>" alt="Logo Atual" class="mt-2 max-w-[100px] max-h-[50px] rounded" id="logo-preview"><?php endif; ?>
                                    </div>
                                    <div class="mb-4"><label for="favicon-file" class="block text-sm font-medium mb-2">Upload Favicon</label><input type="file" id="favicon-file" name="favicon_file" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-gray-700 file:text-gray-200 hover:file:bg-gray-600">
                                        <label for="favicon-url-text" class="block text-sm font-medium mb-2 mt-2">Ou URL do Favicon</label><input type="text" id="favicon-url-text" name="favicon_url_text" class="filament-input" value="<?= htmlspecialchars($configs['favicon'] ?? '') ?>">
                                        <?php if (!empty($configs['favicon'])): ?><img src="<?= htmlspecialchars(ltrim($configs['favicon'], '/')) ?>" alt="Favicon Atual" class="mt-2 max-w-[50px] max-h-[50px] rounded" id="favicon-preview"><?php endif; ?>
                                    </div>
                                    <div class="flex justify-end"><button type="submit" class="filament-button primary">Salvar Configurações</button></div>
                                </form>
                            </section>
                        `;
                        break;

                    default:
                        html = `<div class="p-6">Página não encontrada.</div>`;
                }
                contentArea.innerHTML = html;

                if (page === 'dashboard') {
                    setTimeout(drawChart, 100);
                }
                if (page === 'settings') {
                    setTimeout(() => {
                        const setupImagePreview = (fileInputId, urlInputId, previewImgId) => {
                            const fileInput = document.getElementById(fileInputId);
                            const urlInput = document.getElementById(urlInputId);
                            const previewImg = document.getElementById(previewImgId);
                            const updatePreview = (src) => {
                                if (src) {
                                    previewImg.src = src;
                                    previewImg.classList.remove('hidden');
                                } else {
                                    previewImg.src = '';
                                    previewImg.classList.add('hidden');
                                }
                            };
                            if (fileInput) {
                                fileInput.addEventListener('change', (event) => {
                                    const file = event.target.files[0];
                                    if (file) {
                                        const reader = new FileReader();
                                        reader.onload = (e) => {
                                            updatePreview(e.target.result);
                                        };
                                        reader.readAsDataURL(file);
                                        if (urlInput) urlInput.value = '';
                                    } else if (!urlInput || !urlInput.value) {
                                        updatePreview('');
                                    }
                                });
                            }
                            if (urlInput) {
                                urlInput.addEventListener('input', (event) => {
                                    updatePreview(event.target.value);
                                    if (fileInput) fileInput.value = '';
                                });
                            }
                        };
                        setupImagePreview('logo-file', 'logo-url-text', 'logo-preview');
                        setupImagePreview('favicon-file', 'favicon-url-text', 'favicon-preview');
                    }, 100);
                }
            };

            closeModalBtn.addEventListener('click', () => {
                editModal.classList.remove('open');
                const url = new URL(window.location.href);
                url.searchParams.delete('edit_user_id');
                url.searchParams.delete('edit_product_id');
                url.searchParams.delete('edit_withdrawal_id');
                url.searchParams.delete('edit_account_id');
                url.searchParams.delete('edit_coupon_id');
                history.pushState(null, '', url.toString());
            });

            navLinks.forEach(link => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    const pageId = link.id.replace('link-', '');
                    renderPage(pageId);
                    if (window.innerWidth <= 768) {
                        sidebar.classList.remove('active');
                    }
                });
            });
            const initialPage = getURLParameter('page') || 'dashboard';
            renderPage(initialPage);
            window.addEventListener('resize', () => {
                if (pageTitle.textContent === 'Painel de Controle') {
                    drawChart();
                }
            });
        });
    </script>
</body>

</html>