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

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

<?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>Conta de Saque 提现账户 - <?= 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=Share+Tech+Mono&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', '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 */
      .vip-header {
        padding: 20px;
        background: rgba(255, 255, 255, 0.95);
        border-bottom: 1px solid #E5E7EB;
        display: flex; justify-content: space-between; align-items: center;
        position: sticky; top: 0; z-index: 50; backdrop-filter: blur(10px);
        box-shadow: 0 2px 10px rgba(0,0,0,0.03);
      }

      /* Status Bar Clean */
      .status-ribbon {
        margin: 20px;
        padding: 15px;
        background: #FFF;
        border-radius: 12px;
        border: 1px solid #E5E7EB;
        box-shadow: 0 4px 15px rgba(0,0,0,0.03);
        display: flex; justify-content: center; align-items: center; gap: 10px;
      }
      .status-dot {
        width: 8px; height: 8px; border-radius: 50%;
        box-shadow: 0 0 5px currentColor;
      }

      /* --- CARTÃO PIX (SALMÃO) --- */
      .pix-card-container {
        perspective: 1000px;
        margin: 0 20px 30px 20px;
      }

      .pix-card {
        background: linear-gradient(135deg, #FF7E67 0%, #FF6B50 100%);
        border-radius: 16px;
        padding: 24px;
        position: relative;
        overflow: hidden;
        box-shadow: var(--card-float);
        min-height: 200px;
        display: flex; flex-direction: column; justify-content: space-between;
        color: white;
        transition: transform 0.3s;
      }
      .pix-card:hover { transform: translateY(-5px); }

      .pix-card::after {
        content: ''; position: absolute; inset: 0;
        background: radial-gradient(circle at top right, rgba(255,255,255,0.2) 0%, transparent 60%);
        pointer-events: none;
      }

      .card-logo {
        font-family: 'Oswald', sans-serif; font-size: 16px; color: #FFF;
        display: flex; align-items: center; gap: 8px; font-weight: bold;
        letter-spacing: 1px;
      }
      
      .card-chip {
        width: 45px; height: 32px;
        background: rgba(255,255,255,0.2);
        border-radius: 6px; border: 1px solid rgba(255,255,255,0.3);
        margin-top: 15px;
      }

      .card-key {
        font-family: 'Share Tech Mono', monospace;
        font-size: 18px; color: #fff; letter-spacing: 1px;
        margin-top: auto; margin-bottom: 15px;
        word-break: break-all;
        text-shadow: 0 1px 2px rgba(0,0,0,0.1);
      }

      .card-holder {
        font-family: 'Inter', sans-serif;
        font-size: 10px; color: rgba(255,255,255,0.8); text-transform: uppercase; letter-spacing: 1px;
      }
      .card-holder-name {
        font-family: 'Inter', sans-serif;
        font-size: 13px; color: #FFF; font-weight: 700; text-transform: uppercase;
      }

      .card-type {
        position: absolute; bottom: 25px; right: 25px;
        font-size: 10px; color: #FF7E67; font-weight: bold;
        padding: 4px 10px; border-radius: 20px; background: #FFF;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
      }

      /* --- FORMULÁRIO CLEAN --- */
      .form-card {
        margin: 0 20px;
        background: #FFF;
        border-radius: 16px;
        border: 1px solid #E5E7EB;
        padding: 25px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.05);
      }

      .field-group { margin-bottom: 20px; position: relative; }
      
      .field-label {
        font-family: 'Inter', sans-serif; font-size: 11px; color: #9CA3AF;
        text-transform: uppercase; letter-spacing: 0.5px;
        margin-bottom: 8px; display: block; font-weight: 600;
      }

      .field-input {
        width: 100%;
        background: #F9FAFB;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        padding: 12px 15px;
        color: #333;
        font-family: 'Inter', sans-serif; font-size: 14px;
        transition: all 0.3s;
      }
      .field-input:focus {
        border-color: #FF7E67;
        background: #FFF;
        outline: none;
        box-shadow: 0 0 0 3px rgba(255, 126, 103, 0.1);
      }
      .field-input::placeholder { color: #D1D5DB; }

      .select-wrapper { position: relative; }
      .select-arrow {
        position: absolute; right: 15px; top: 40px; color: #9CA3AF; pointer-events: none;
      }

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

      /* Aviso de Segurança */
      .security-warning {
        font-size: 11px; color: #6B7280; text-align: center;
        margin-bottom: 25px; font-family: 'Inter', sans-serif;
        background: #FEF2F2; border: 1px dashed #FECACA;
        padding: 10px; border-radius: 8px;
      }
      .security-warning strong { color: #E53935; }

      /* 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>

    <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="text-gray-400 hover:text-vip-salmon transition">
            <i data-lucide="arrow-left" class="w-6 h-6"></i>
        </a>
        <h1 class="text-lg font-bold text-vip-salmon font-mono tracking-widest uppercase">
            Dados de Saque 提现信息
        </h1>
        <div class="w-6"></div> 
      </div>

      <div class="status-ribbon">
         <?php if ($stmtConsultPixAccount->rowCount() > 0) : ?>
             <div class="status-dot bg-vip-green shadow-[0_0_5px_rgba(67,160,71,0.5)]"></div>
             <span class="text-xs text-vip-green uppercase tracking-wide font-bold">Conta Verificada 已验证</span>
         <?php else: ?>
             <div class="status-dot bg-vip-red shadow-[0_0_5px_rgba(229,57,53,0.5)]"></div>
             <span class="text-xs text-vip-red uppercase tracking-wide font-bold">Configuração Necessária 需设置</span>
         <?php endif; ?>
      </div>

      <div class="pb-20">

        <?php if ($stmtConsultPixAccount->rowCount() > 0) : ?>
          <div class="pix-card-container">
             <div class="pix-card">
                <div class="card-logo">
                   <i class="fa-brands fa-pix"></i>
                   <span>PIX KEY</span>
                </div>
                
                <div class="card-chip"></div>

                <div class="card-key">
                   <?= htmlspecialchars($stmtResultPix['key_beneficiary']) ?>
                </div>

                <div class="flex justify-between items-end">
                   <div>
                      <p class="card-holder">Titular Autorizado 持有人</p>
                      <p class="card-holder-name"><?= htmlspecialchars($stmtResultPix['name_beneficiary']) ?></p>
                   </div>
                   <div class="card-type">
                      <?= htmlspecialchars($stmtResultPix['type_pix']) ?>
                   </div>
                </div>
             </div>
          </div>

          <div class="px-5">
             <a href="withdrawal.php" class="btn-salmon">
                Solicitar Saque 申请提现
             </a>
          </div>

        <?php else: ?>
          <div class="form-card">
             
             <div class="security-warning">
                <i class="fa-solid fa-shield-halved mr-1 text-vip-red"></i>
                <strong>SEGURANÇA 安全提示:</strong> O CPF deve ser o mesmo do titular da conta para evitar fraudes.
             </div>

             <form method="POST" id="myForm">
                
                <div class="field-group">
                   <label class="field-label">Nome Completo 姓名</label>
                   <input name="name_beneficiary" type="text" placeholder="DIGITE SEU NOME" class="field-input" required />
                </div>

                <div class="field-group">
                   <label class="field-label">Documento (CPF) 证件号</label>
                   <input id="cpf_beneficiary" name="cpf_beneficiary" value="<?= htmlspecialchars($user['document'] ?? '') ?>" type="text" placeholder="000.000.000-00" class="field-input" required />
                   <p id="cpfFeedback" class="text-[10px] text-right mt-1 text-gray-400 font-mono uppercase font-bold">Aguardando...</p>
                </div>

                <div class="grid grid-cols-3 gap-4">
                   <div class="field-group col-span-1 select-wrapper">
                      <label class="field-label">Tipo 类型</label>
                      <select name="type_pix" class="field-input appearance-none cursor-pointer" required>
                         <option value="" disabled selected>Selecione</option>
                         <option value="CPF">CPF</option>
                         <option value="PHONE">TEL</option>
                         <option value="EMAIL">EMAIL</option>
                      </select>
                      <i class="fa-solid fa-chevron-down select-arrow"></i>
                   </div>
                   
                   <div class="field-group col-span-2">
                      <label class="field-label">Chave Pix 键</label>
                      <input name="key_beneficiary" type="text" placeholder="SUA CHAVE" class="field-input" required />
                   </div>
                </div>

                <button name="add_pix" type="submit" class="btn-salmon mt-2">
                   Salvar Chave 保存账户
                </button>

             </form>
          </div>
        <?php endif; ?>

      </div>

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

    </div>

    <script>
      lucide.createIcons();

      // --- TOAST LIGHT ---
      function showToast(msg, type) {
         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-octagon' : 'check-circle'}" class="w-5 h-5 ${iconColor}"></i>
            <div>
               <p class="text-[10px] font-bold text-vip-salmon uppercase mb-0.5">${isError ? 'ERRO' : 'SUCESSO'}</p>
               <span class="font-mono text-xs uppercase tracking-wide text-gray-600">${msg}</span>
            </div>
         `;
         
         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; ?>

      // --- VALIDAÇÃO CPF (ADAPTADO PARA LIGHT) ---
      (function() {
        const input = document.getElementById('cpf_beneficiary');
        const feedback = document.getElementById('cpfFeedback');
        const form = document.getElementById('myForm');

        if(!input) return;

        const onlyDigits = str => (str || '').replace(/\D+/g, '');

        function cpfMask(value) {
          const v = onlyDigits(value).slice(0, 11);
          if (v.length <= 3) return v;
          if (v.length <= 6) return v.replace(/^(\d{3})(\d+)/, '$1.$2');
          if (v.length <= 9) return v.replace(/^(\d{3})(\d{3})(\d+)/, '$1.$2.$3');
          return v.replace(/^(\d{3})(\d{3})(\d{3})(\d{1,2})/, '$1.$2.$3-$4');
        }

        function isValidCPF(cpf) {
          cpf = onlyDigits(cpf);
          if (cpf.length !== 11) return false;
          if (/^(\d)\1{10}$/.test(cpf)) return false;

          let sum = 0;
          for (let i = 0; i < 9; i++) sum += parseInt(cpf.charAt(i), 10) * (10 - i);
          let rem = sum % 11;
          let dig1 = (rem < 2) ? 0 : 11 - rem;
          if (dig1 !== parseInt(cpf.charAt(9), 10)) return false;

          sum = 0;
          for (let i = 0; i < 10; i++) sum += parseInt(cpf.charAt(i), 10) * (11 - i);
          rem = sum % 11;
          let dig2 = (rem < 2) ? 0 : 11 - rem;
          if (dig2 !== parseInt(cpf.charAt(10), 10)) return false;

          return true;
        }

        function updateUI() {
          const raw = input.value;
          const masked = cpfMask(raw);
          input.value = masked;

          const digits = onlyDigits(masked);
          if (digits.length < 11) {
            input.style.borderColor = '#E5E7EB';
            feedback.textContent = 'DIGITE 11 NÚMEROS...';
            feedback.style.color = '#9CA3AF';
            return;
          }

          if (isValidCPF(digits)) {
            input.style.borderColor = '#43A047';
            feedback.textContent = 'DOCUMENTO VÁLIDO OK';
            feedback.style.color = '#43A047';
          } else {
            input.style.borderColor = '#E53935';
            feedback.textContent = 'CPF INVÁLIDO';
            feedback.style.color = '#E53935';
          }
        }

        input.addEventListener('input', updateUI);
        
        form && form.addEventListener('submit', (e) => {
          const digits = onlyDigits(input.value);
          if (!isValidCPF(digits)) {
            e.preventDefault();
            input.focus();
            input.style.borderColor = '#E53935';
            showToast('CPF Inválido. Verifique os números.', 'error');
          }
        });

        if (input.value) updateUI();
      })();
    </script>
  </body>
  </html>
<?php endif; ?>