<?php
require_once '../app/Controllers/sessions.php';
require_once '../app/Controllers/security_access.php';
require_once '../app/models/user.php';
require '../app/Controllers/layouts.php';
require '../app/Controllers/updateProfile.php';
require_once '../app/Controllers/checkInController.php';
require_once '../app/Controllers/controller_investments.php';

$toastMessage = $_SESSION['toastMessage'] ?? null;
$toastType = $_SESSION['toastType'] ?? null;
unset($_SESSION['toastMessage'], $_SESSION['toastType']);

// Consultar taxa saque
$consultTaxa = $pdo->prepare("SELECT taxa_saq FROM configs");
$consultTaxa->execute();
$resultTaxa = $consultTaxa->fetch(PDO::FETCH_ASSOC);
?>
<?php if ($stmtThemesPlatformResult['theme_actual'] === 'brasileira') : ?>
  <script>window.location.href = '?theme=gringa2';</script>
<?php elseif ($stmtThemesPlatformResult['theme_actual'] === 'gringa') : ?>
   <script>window.location.href = '?theme=gringa2';</script>
<?php elseif ($stmtThemesPlatformResult['theme_actual'] === 'gringa2' || true) : ?>
  <!DOCTYPE html>
  <html lang="pt-BR">

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Resgate Imediato 提现 - <?= htmlspecialchars($stmtConfigsPlatformResult["name_platform"]) ?></title>

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;500;700&family=Inter:wght@300;400;600;700;800&family=Noto+Sans+SC:wght@400;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">

    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              vip: {
                bg: '#F8F9FA',      // Fundo claro
                card: '#FFFFFF',    // Card branco
                text: '#333333',    // Texto escuro
                border: '#E5E7EB',  // Borda cinza claro
                salmon: '#FF7E67',  // Cor Principal (Salmão)
                salmonlight: '#FFA090',
                red: '#E53935',
                green: '#43A047',
                gray: '#9CA3AF'
              }
            },
            fontFamily: {
              sans: ['Inter', 'Noto Sans SC', 'sans-serif'],
              mono: ['Oswald', 'sans-serif'],
              tech: ['"Share Tech Mono"', 'monospace']
            },
            boxShadow: {
              'soft': '0 4px 20px rgba(0, 0, 0, 0.05)',
              'glow-salmon': '0 0 15px rgba(255, 126, 103, 0.4)',
              'card-float': '0 15px 35px -5px rgba(255, 126, 103, 0.5)'
            }
          }
        }
      };
    </script>

    <style>
      body {
        background-color: #F8F9FA;
        /* Grade cinza sutil */
        background-image: 
            linear-gradient(#E5E7EB 1px, transparent 1px),
            linear-gradient(90deg, #E5E7EB 1px, transparent 1px);
        background-size: 40px 40px;
        color: #333;
        -webkit-font-smoothing: antialiased;
        padding-bottom: 100px;
      }

      /* Header Clean */
      .vip-header {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-bottom: 1px solid #E5E7EB;
        padding: 15px 20px;
        position: sticky;
        top: 0;
        z-index: 50;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 2px 10px rgba(0,0,0,0.03);
      }

      /* Painel de Saldo (Estilo Cofre Clean) */
      .vault-panel {
        background: linear-gradient(135deg, #FF7E67 0%, #FF6B50 100%);
        border-radius: 16px;
        margin: 20px;
        padding: 24px;
        position: relative;
        text-align: center;
        box-shadow: 0 10px 30px -5px rgba(255, 126, 103, 0.4);
        color: white;
      }
      .vault-panel::after {
        content: '';
        position: absolute;
        top: -50%; left: -50%; width: 200%; height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 60%);
        pointer-events: none;
      }

      /* Input de Valor */
      .amount-display {
        background: #FFF;
        border: 1px solid #E5E7EB;
        border-radius: 12px;
        padding: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(0,0,0,0.02);
      }
      .amount-display:focus-within {
        border-color: #FF7E67;
        box-shadow: 0 0 0 3px rgba(255, 126, 103, 0.1);
      }
      
      .currency-symbol {
        color: #FF7E67;
        font-family: 'Oswald', sans-serif;
        font-size: 24px;
        font-weight: bold;
        padding-right: 10px;
        border-right: 1px solid #E5E7EB;
      }
      
      .custom-input {
        background: transparent;
        border: none;
        outline: none;
        color: #333;
        font-family: 'Oswald', sans-serif;
        font-size: 28px;
        width: 100%;
        font-weight: bold;
      }
      .custom-input::placeholder { color: #D1D5DB; }

      /* Botões Rápidos */
      .quick-btn {
        background: #F3F4F6;
        border: 1px solid #E5E7EB;
        color: #6B7280;
        font-family: 'Oswald', sans-serif;
        font-size: 12px;
        padding: 10px 0;
        transition: all 0.2s;
        text-transform: uppercase;
        border-radius: 8px;
        font-weight: bold;
      }
      .quick-btn:hover {
        border-color: #FF7E67;
        color: #FF7E67;
        background: #FFF;
      }
      .quick-btn:active { transform: scale(0.95); }

      /* Botão Principal */
      .btn-salmon {
        background: #FF7E67;
        color: #FFF;
        font-family: 'Oswald', sans-serif;
        font-weight: bold;
        text-transform: uppercase;
        letter-spacing: 1px;
        padding: 16px;
        width: 100%;
        border: none;
        margin-top: 20px;
        border-radius: 8px;
        transition: all 0.2s;
        display: flex; justify-content: center; align-items: center; gap: 10px;
        box-shadow: 0 5px 15px rgba(255, 126, 103, 0.3);
      }
      .btn-salmon:hover { background: #FFA090; transform: translateY(-2px); }
      .btn-salmon:active { transform: scale(0.98); }
      .btn-salmon:disabled {
        background: #E5E7EB;
        color: #9CA3AF;
        cursor: not-allowed;
        box-shadow: none;
      }

      /* Card Bloqueio */
      .lock-card {
        background: #FFF;
        border: 1px dashed #E53935;
        padding: 30px 20px;
        text-align: center;
        margin-top: 20px;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(229, 57, 53, 0.05);
      }

      /* Regras */
      .rules-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px;
        border-bottom: 1px dashed #E5E7EB;
        background: #FFF;
      }
      .rules-item:first-child { border-radius: 12px 12px 0 0; }
      .rules-item:last-child { border-radius: 0 0 12px 12px; border-bottom: none; }

      .rules-icon {
        width: 24px; height: 24px;
        background: #F9FAFB;
        border: 1px solid #E5E7EB;
        display: flex; align-items: center; justify-content: center;
        color: #9CA3AF;
        font-size: 10px;
        border-radius: 6px;
      }

      /* Toast Light */
      .toast-custom {
        background: #FFF; border: 1px solid #E5E7EB; border-left: 3px solid #FF7E67;
        color: #333; padding: 12px 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        display: flex; align-items: center; gap: 10px;
        animation: slideInTop 0.4s forwards;
      }
      @keyframes slideInTop { from { transform: translateY(-100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
    </style>
  </head>

  <body class="font-sans text-gray-800">

    <div id="toast-container" class="fixed top-4 left-0 right-0 z-[100] flex justify-center pointer-events-none"></div>

    <div class="max-w-[480px] mx-auto min-h-screen relative border-x border-gray-100 shadow-xl">

        <div class="vip-header">
            <a href="index.php" class="w-8 h-8 flex items-center justify-center border border-gray-200 bg-white text-gray-500 hover:text-vip-salmon transition rounded-full shadow-sm">
                <i data-lucide="arrow-left" class="w-4 h-4"></i>
            </a>
            <h1 class="text-sm font-bold text-vip-salmon uppercase tracking-[2px]">Resgate Imediato 提现</h1>
            <a href="<?= htmlspecialchars($stmtConfigsPlatformResult['support_link']) ?>" class="w-8 h-8 flex items-center justify-center border border-gray-200 bg-white text-gray-500 hover:text-vip-salmon transition rounded-full shadow-sm">
                <i data-lucide="headset" class="w-4 h-4"></i>
            </a>
        </div>

        <div class="vault-panel">
            <p class="text-[10px] text-white/80 uppercase tracking-[3px] mb-2 font-bold">Saldo Disponível 可用余额</p>
            <div class="flex items-baseline justify-center gap-1">
                <span class="text-xl text-white font-mono">R$</span>
                <h2 class="text-5xl font-mono text-white font-bold tracking-tighter drop-shadow-sm">
                   <?= number_format($user['balance'] ?? 0, 2, ',', '.') ?>
                </h2>
            </div>
            <div class="absolute bottom-3 right-3">
                <span class="bg-white/20 backdrop-blur-sm border border-white/30 text-white text-[9px] px-2 py-0.5 rounded font-bold uppercase shadow-sm">
                    VIP <?= htmlspecialchars($user['vip_level'] ?? '0') ?>
                </span>
            </div>
        </div>

        <div class="px-5 pb-24">

            <?php if (!$stmtResultPix) : ?>
                <div class="lock-card">
                    <div class="w-16 h-16 bg-red-50 border border-red-200 rounded-full flex items-center justify-center mx-auto mb-4 text-vip-red">
                        <i data-lucide="shield-alert" class="w-8 h-8"></i>
                    </div>
                    <h3 class="text-sm font-bold text-gray-800 uppercase tracking-widest mb-2">Chave Pix Necessária</h3>
                    <p class="text-xs text-gray-500 mb-6 leading-relaxed px-4 font-bold">
                        Cofre Bloqueado. Configure sua chave PIX para habilitar saques.
                    </p>
                    <a href="add_bank_create.php" class="btn-salmon shadow-lg shadow-salmon/30">
                        CONFIGURAR AGORA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                    </a>
                </div>

            <?php else: ?>
                <form method="POST" id="formSaque">

                    <label for="valorSaque" class="text-[10px] text-gray-400 uppercase tracking-widest mb-2 block ml-1 font-bold">
                        Valor do Saque 提现金额
                    </label>

                    <div class="amount-display">
                        <span class="currency-symbol">R$</span>
                        <input id="valorSaque" name="value_withdrawal" type="text" placeholder="0,00" class="custom-input" oninput="formatarMoeda(this, '<?= htmlspecialchars($stmtConfigsPlatformResult['taxa_saq']) ?>')" required autocomplete="off" />
                    </div>

                    <div class="grid grid-cols-4 gap-2 mb-4">
                        <?php
                        $min_with = floatval(str_replace(',', '.', $stmtConfigsPlatformResult['min_with']));
                        $max_with = floatval(str_replace(',', '.', $stmtConfigsPlatformResult['max_with']));
                        $user_bal = floatval($user['balance'] ?? 0);
                        
                        $quick_values = [
                            $min_with,
                            $min_with * 2,
                            $min_with * 5,
                            min($user_bal, $max_with)
                        ];
                        
                        $quick_values = array_unique(array_filter($quick_values, function($v) use ($user_bal) {
                            return $v > 0 && $v <= $user_bal;
                        }));
                        
                        if(empty($quick_values)) {
                             $quick_values = [$min_with, $min_with*2, $min_with*5, $max_with];
                        }

                        $count = 0;
                        foreach ($quick_values as $val) :
                            if ($count >= 4) break;
                            $isMax = ($val == $user_bal || $val == $max_with);
                            $label = $isMax ? 'MAX' : 'R$ ' . number_format($val, 0, ',', '.');
                        ?>
                            <button type="button" class="quick-btn" onclick="setQuickValue(<?= $val ?>)">
                                <?= $label ?>
                            </button>
                        <?php $count++; endforeach; ?>
                    </div>

                    <div class="flex justify-between items-center text-[10px] bg-gray-50 p-3 border border-gray-200 rounded-lg mb-6 font-mono font-bold" id="taxaInfo">
                        <span class="text-gray-500">TAXA REDE: <?= htmlspecialchars($stmtConfigsPlatformResult['taxa_saq']) ?>%</span>
                        <span class="text-gray-400">--</span>
                    </div>

                    <button id="btnSaque" name="send_withdrawal" type="submit" class="btn-salmon shadow-lg shadow-salmon/30" disabled>
                        <i data-lucide="check-circle" class="w-5 h-5"></i>
                        CONFIRMAR SAQUE 确认提现
                    </button>

                </form>

                <div class="mt-8 bg-white border border-gray-200 rounded-xl shadow-sm">
                    <h3 class="text-[10px] font-bold text-gray-400 uppercase tracking-widest p-3 border-b border-gray-100 bg-gray-50 rounded-t-xl">Regras de Saque 规则</h3>
                    <div class="space-y-0">
                        <div class="rules-item">
                            <div class="rules-icon"><i class="fa-solid fa-wallet"></i></div>
                            <div>
                                <p class="text-[9px] text-gray-400 uppercase font-bold">Destino</p>
                                <p class="text-xs text-gray-700 font-bold">Chave PIX Cadastrada</p>
                            </div>
                        </div>
                        <div class="rules-item">
                            <div class="rules-icon"><i class="fa-solid fa-sliders"></i></div>
                            <div>
                                <p class="text-[9px] text-gray-400 uppercase font-bold">Limites</p>
                                <p class="text-xs text-gray-700 font-mono font-bold">
                                    Min R$<?= htmlspecialchars($stmtConfigsPlatformResult['min_with']) ?> / Max R$<?= htmlspecialchars($stmtConfigsPlatformResult['max_with']) ?>
                                </p>
                            </div>
                        </div>
                        <div class="rules-item border-none">
                            <div class="rules-icon"><i class="fa-regular fa-clock"></i></div>
                            <div>
                                <p class="text-[9px] text-gray-400 uppercase font-bold">Horário Processamento</p>
                                <p class="text-xs text-gray-700 font-bold">10:00 - 16:00 (Seg-Sex)</p>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

        </div>

        <?php include 'partials/menu-bottom.php'; ?>

    </div>

    <script>
        // Init Icons
        lucide.createIcons();

        // Toast Light
        function showToast(message, type = 'success') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            const isError = type === 'error';
            const iconColor = isError ? 'text-vip-red' : 'text-vip-green';
            const borderColor = isError ? 'border-l-vip-red' : 'border-l-vip-salmon';

            toast.className = `toast-custom pointer-events-auto ${borderColor}`;
            toast.innerHTML = `
            <i data-lucide="${isError ? 'alert-triangle' : 'check-circle'}" class="w-4 h-4 ${iconColor}"></i>
            <span class="font-mono text-xs uppercase tracking-wide font-bold">${message}</span>
        `;

            container.appendChild(toast);
            lucide.createIcons();

            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(-20px)';
                toast.style.transition = 'all 0.3s';
                setTimeout(() => toast.remove(), 400);
            }, 3000);
        }

        <?php if ($toastMessage) : ?>
            window.addEventListener('load', () => showToast('<?= htmlspecialchars($toastMessage) ?>', '<?= $toastType ?>'));
        <?php endif; ?>

        // Logic
        const minWith = parseFloat('<?= str_replace(',', '.', htmlspecialchars($stmtConfigsPlatformResult['min_with'])) ?>');
        const maxWith = parseFloat('<?= str_replace(',', '.', htmlspecialchars($stmtConfigsPlatformResult['max_with'])) ?>');
        const taxaSaque = '<?= htmlspecialchars($stmtConfigsPlatformResult['taxa_saq']) ?>';
        const userBalance = parseFloat('<?= number_format($user['balance'] ?? 0, 2, '.', '') ?>');

        function formatarMoeda(campo, taxaSaque) {
            let valor = campo.value.replace(/\D/g, "");
            valor = (parseInt(valor, 10) / 100).toFixed(2).replace(".", ",");
            campo.value = valor;

            const taxa = parseFloat(taxaSaque) / 100;
            const valorNumerico = parseFloat(valor.replace(',', '.'));
            const btn = document.getElementById("btnSaque");
            const infoBox = document.getElementById("taxaInfo");

            if (!isNaN(valorNumerico) && valorNumerico > 0) {
                const valorTaxa = valorNumerico * taxa;
                const valorLiquido = valorNumerico - valorTaxa;
                let isValid = true;
                let infoHTML = `<span class="text-gray-500">TAXA: R$ ${valorTaxa.toFixed(2)}</span> <span class="font-bold text-vip-salmon">LÍQUIDO: R$ ${valorLiquido.toFixed(2)}</span>`;

                if (valorNumerico < minWith) {
                    infoHTML = `<span class="text-vip-red font-bold uppercase text-[9px]">Mínimo Req: R$ ${minWith.toFixed(2)}</span>`;
                    isValid = false;
                } else if (valorNumerico > maxWith) {
                    infoHTML = `<span class="text-vip-red font-bold uppercase text-[9px]">Limite Máx: R$ ${maxWith.toFixed(2)}</span>`;
                    isValid = false;
                } else if (valorNumerico > userBalance) {
                    infoHTML = `<span class="text-vip-red font-bold uppercase text-[9px]">Saldo Insuficiente</span>`;
                    isValid = false;
                }

                infoBox.innerHTML = infoHTML;
                btn.disabled = !isValid;
                if(isValid) {
                    btn.classList.remove('opacity-50', 'cursor-not-allowed');
                } else {
                    btn.classList.add('opacity-50', 'cursor-not-allowed');
                }
            } else {
                infoBox.innerHTML = `<span class="text-gray-500">TAXA REDE: ${taxaSaque}%</span><span class="text-gray-400">--</span>`;
                btn.disabled = true;
                btn.classList.add('opacity-50', 'cursor-not-allowed');
            }
        }

        function setQuickValue(value) {
            const input = document.getElementById("valorSaque");
            input.value = value.toFixed(2).replace('.', ',');
            formatarMoeda(input, taxaSaque);
        }
    </script>
</body>

</html>
<?php endif; ?>