<?php
require_once '../app/Controllers/sessions.php';
require_once '../app/Controllers/security_access.php';
require_once '../app/models/user.php';
require_once '../app/Controllers/products.php';
require_once '../app/Controllers/checkInController.php';
require_once '../app/Controllers/controller_investments.php';
require_once '../app/Controllers/layouts.php';
ini_set("display_errors", 0);

// token anti-CSRF
if (empty($_SESSION['box3d_token'])) $_SESSION['box3d_token'] = bin2hex(random_bytes(16));
$token = $_SESSION['box3d_token'];

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

// processa abertura (POST)
$last = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['open_box']) && hash_equals($token, $_POST['token'] ?? '')) {

    // Bloqueia se não tiver spins
    if ($user['qtd_spins'] <= 0) {
        $_SESSION['toastMessage'] = 'Chaves insuficientes. Convide amigos!';
        $_SESSION['toastType'] = 'error';
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    }

    // distribuição do pagamento REAL (1..5 reais) - controlável
    $r = random_int(1, 1000);
    if ($r <= 750) $paid = 1;
    elseif ($r <= 920) $paid = 2;
    elseif ($r <= 980) $paid = 3;
    elseif ($r <= 997) $paid = 4;
    else $paid = 5;
    
    // valor visual
    $visual = random_int(1, 1000);

    // atualiza saldo com transação PDO
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("UPDATE users SET balance = balance + :v, qtd_spins = qtd_spins - 1, total_spins = total_spins + 1, awards_spins = awards_spins + :v WHERE id = :id");
        $stmt->execute([':v' => $paid, ':id' => $user['id']]);
        $q = $pdo->prepare("SELECT balance FROM users WHERE id = :id");
        $q->execute([':id' => $user['id']]);
        $newBal = $q->fetchColumn();
        $pdo->commit();

        $_SESSION['last_box3d'] = [
            'visual' => $visual,
            'paid' => $paid,
            'balance' => $newBal,
            'time' => time()
        ];

        createHistory('Baú do Tesouro: R$' . $paid . ' resgatado.');
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("chest error: " . $e->getMessage());
        $_SESSION['last_box3d'] = [
            'error' => true,
            'message' => 'Erro interno'
        ];
    }

    // PRG
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit;
}

// pega resultado recente
$last = $_SESSION['last_box3d'] ?? null;
if ($last && (time() - ($last['time'] ?? 0) > 0)) {
    unset($_SESSION['last_box3d']);
    $last = null;
}
// Variável para controlar o bloqueio do botão/interação
$is_blocked = $user['qtd_spins'] <= 0;

// =========================================================================
// HISTÓRICO DINÂMICO DE GANHOS
// =========================================================================
function generateRandomPrize() {
    $min_id = 1;
    $max_id = 100000;
    $id = random_int($min_id, $max_id);
    $r = random_int(1, 100);
    if ($r <= 70) { 
        $prize = random_int(5000, 15000) / 100;
    } elseif ($r <= 95) { 
        $prize = random_int(15100, 40000) / 100;
    } else { 
        $prize = random_int(40100, 100000) / 100;
    }
    $id_str = sprintf('%05d', $id);
    $hidden_id = 'USER#' . substr($id_str, 0, -2) . '**';
    return ['id' => $hidden_id, 'prize' => number_format($prize, 2, ',', '.')];
}
$dynamic_history_count = random_int(5, 8);
$dynamic_history = [];
for ($i = 0; $i < $dynamic_history_count; $i++) {
    $dynamic_history[] = generateRandomPrize();
}
?>
<?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>Baú do Tesouro 宝箱 - <?= 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 src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.2/dist/confetti.browser.min.js"></script>

    <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)',
            }
          }
        }
      };
    </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: 90px;
      }

      /* 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);
      }

      /* Card Principal (Palco) */
      .draw-stage-card {
        background: #FFF;
        border: 1px solid #E5E7EB;
        margin: 20px;
        padding: 40px 20px;
        position: relative;
        text-align: center;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.05);
        overflow: visible;
      }
      
      /* ===========================
         CSS TREASURE CHEST
         =========================== */
      .chest-container {
        width: 160px;
        height: 140px;
        margin: 0 auto 30px;
        position: relative;
        perspective: 1000px;
        cursor: pointer;
        z-index: 20;
      }

      .chest {
        width: 100%;
        height: 100%;
        position: relative;
        transform-style: preserve-3d;
        animation: chestFloat 3s ease-in-out infinite;
      }

      @keyframes chestFloat {
        0%, 100% { transform: translateY(0); }
        50% { transform: translateY(-10px); }
      }

      /* Parte de Baixo (Corpo) - Mantido Vermelho/Dourado por ser "Lucky" */
      .chest-body {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 80px;
        background: linear-gradient(to bottom, #E53935, #B71C1C);
        border: 4px solid #FFD700;
        border-radius: 0 0 10px 10px;
        box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .chest-body::before { /* Detalhe lateral esquerdo */
        content: ''; position: absolute; left: 15px; width: 10px; height: 100%; background: #FFD700; opacity: 0.8;
      }
      .chest-body::after { /* Detalhe lateral direito */
        content: ''; position: absolute; right: 15px; width: 10px; height: 100%; background: #FFD700; opacity: 0.8;
      }

      /* Tampa (Lid) */
      .chest-lid {
        position: absolute;
        top: 0;
        left: -4px; /* Ajuste da borda */
        width: calc(100% + 8px);
        height: 70px;
        background: linear-gradient(to bottom, #EF5350, #C62828);
        border: 4px solid #FFD700;
        border-radius: 40px 40px 0 0;
        transform-origin: bottom;
        transition: transform 0.6s cubic-bezier(0.4, 0.0, 0.2, 1);
        z-index: 10;
        box-shadow: inset 0 5px 10px rgba(255, 255, 255, 0.2);
      }
      
      .chest-lid::after { /* Listra central da tampa */
        content: ''; position: absolute; left: 50%; transform: translateX(-50%);
        width: 20px; height: 100%; background: #FFD700;
      }

      /* Fechadura */
      .chest-lock {
        position: absolute;
        bottom: -15px;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 30px;
        background: #FFD700;
        border: 2px solid #DAA520;
        border-radius: 50%;
        z-index: 20;
        box-shadow: 0 2px 5px rgba(0,0,0,0.3);
      }

      /* Brilho Interior */
      .chest-glow {
        position: absolute;
        top: 20px; left: 10px; right: 10px; bottom: 10px;
        background: radial-gradient(circle, #FFF700, #FF7E67, transparent);
        opacity: 0;
        transition: opacity 0.5s;
        z-index: 5;
        filter: blur(10px);
        transform: scale(0.5);
      }

      /* ESTADO: ABRINDO */
      .chest-container.opening .chest {
        animation: chestShake 0.5s linear;
      }
      .chest-container.opened .chest-lid {
        transform: rotateX(-110deg);
      }
      .chest-container.opened .chest-glow {
        opacity: 1;
        transform: scale(1.5) translateY(-40px);
        transition: all 0.5s ease-out 0.2s;
      }

      @keyframes chestShake {
        0% { transform: rotate(0deg); }
        25% { transform: rotate(5deg); }
        50% { transform: rotate(-5deg); }
        75% { transform: rotate(5deg); }
        100% { transform: rotate(0deg); }
      }

      /* Botão Ação Salmon */
      .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;
        border-radius: 8px;
        transition: all 0.2s;
        display: flex; justify-content: center; align-items: center; gap: 8px;
        box-shadow: 0 5px 15px rgba(255, 126, 103, 0.3);
        cursor: pointer;
      }
      .btn-salmon:active { transform: scale(0.98); background: #FFA090; }
      .btn-salmon:disabled {
        background: #E5E7EB; color: #9CA3AF; box-shadow: none; cursor: not-allowed;
      }

      /* Ticker Light */
      .ticker-container {
        background: #F9FAFB;
        border: 1px solid #E5E7EB;
        margin-top: 20px;
        padding: 10px;
        height: 120px;
        overflow: hidden;
        position: relative;
        border-radius: 8px;
      }
      .ticker-item {
        display: flex; justify-content: space-between; align-items: center;
        padding: 8px 5px;
        border-bottom: 1px dashed #E5E7EB;
        font-family: 'Oswald', sans-serif;
        font-size: 11px;
        color: #6B7280;
        opacity: 0;
        transform: translateY(10px);
        transition: all 0.5s;
      }
      .ticker-prize { color: #43A047; font-weight: bold; }

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

      /* Partículas */
      .money-particle {
        position: absolute;
        font-family: 'Oswald', sans-serif;
        color: #FFD700;
        font-weight: bold;
        pointer-events: none;
        z-index: 50;
        text-shadow: 0 0 5px rgba(0,0,0,0.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">
            <i data-lucide="arrow-left" class="w-4 h-4"></i>
         </a>
         <h1 class="text-sm font-bold text-vip-salmon uppercase tracking-[2px]">Baú do Tesouro 宝箱</h1>
         <div class="w-8"></div>
      </div>

      <div class="draw-stage-card">
         
         <div class="chest-container" id="chestContainer">
            <div class="chest">
                <div class="chest-lid">
                    <div class="chest-lock"></div>
                </div>
                <div class="chest-glow"></div>
                <div class="chest-body"></div>
            </div>
         </div>

         <div class="relative z-20">
            <div class="flex items-center justify-center gap-2 mb-4">
               <span class="text-[10px] text-gray-400 uppercase tracking-widest font-bold">Chaves Disponíveis 钥匙:</span>
               <span class="text-2xl font-mono text-gray-800 font-bold <?= $is_blocked ? 'text-gray-300' : 'text-vip-salmon' ?>">
                  <?= number_format($user['qtd_spins'], 0) ?>
               </span>
            </div>

            <div id="winText" class="text-vip-green font-mono font-bold text-lg mb-4 hidden animate-pulse uppercase">
               VOCÊ GANHOU!
            </div>

            <form method="POST" id="openForm">
               <input type="hidden" name="open_box" value="1">
               <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
               
               <button type="button" id="openBtn" class="btn-salmon" <?= $is_blocked ? 'disabled' : '' ?>>
                  <?= $is_blocked ? 'SEM CHAVES 无钥匙' : 'ABRIR BAÚ 开启' ?>
                  <i data-lucide="<?= $is_blocked ? 'lock' : 'key' ?>" class="w-4 h-4"></i>
               </button>
            </form>

            <?php if ($is_blocked): ?>
               <div class="mt-4 border border-vip-red/20 bg-red-50 p-2 rounded-lg">
                  <p class="text-[10px] text-vip-red font-mono uppercase font-bold">
                     <i class="fa-solid fa-triangle-exclamation mr-1"></i> Convide amigos para ganhar chaves 邀请好友
                  </p>
               </div>
            <?php else: ?>
               <p class="text-[9px] text-gray-400 mt-3 font-mono uppercase font-bold">Crédito imediato no saldo.</p>
            <?php endif; ?>
         </div>

         <div class="ticker-container">
            <div class="flex items-center justify-between border-b border-gray-200 pb-1 mb-1">
               <span class="text-[9px] text-vip-salmon uppercase font-bold">Ganhadores Recentes 最新中奖</span>
               <i data-lucide="activity" class="w-3 h-3 text-gray-400"></i>
            </div>
            <div id="dynamicFeed">
               <?php foreach ($dynamic_history as $item): ?>
                  <div class="ticker-item">
                     <span class="text-gray-800 font-bold"><?= htmlspecialchars($item['id']) ?></span>
                     <span class="text-gray-400">ganhou</span>
                     <span class="ticker-prize">R$ <?= htmlspecialchars($item['prize']) ?></span>
                  </div>
               <?php endforeach; ?>
            </div>
         </div>

      </div>

      <div class="mx-5 mb-8 bg-white border border-gray-200 p-4 rounded-lg flex justify-between items-center shadow-sm">
         <div>
            <p class="text-[9px] text-gray-400 font-bold uppercase tracking-widest">Total Ganho 累计奖金</p>
            <p class="text-xl font-mono text-gray-800 font-bold">R$ <?= number_format($user['awards_spins'], 2, ',', '.') ?></p>
         </div>
         <div class="w-10 h-10 border border-vip-salmon bg-vip-salmon/10 flex items-center justify-center text-vip-salmon rounded-full">
            <i data-lucide="trophy" class="w-5 h-5"></i>
         </div>
      </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-triangle' : 'check-circle'}" class="w-4 h-4 ${iconColor}"></i>
                <span class="font-mono text-xs uppercase tracking-wide font-bold">${msg}</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; ?>

        // Feed Animation
        const dynamicFeed = document.getElementById('dynamicFeed');
        const feedItems = Array.from(document.getElementsByClassName('ticker-item'));

        if (dynamicFeed && feedItems.length > 0) {
            let currentIndex = 0;
            
            feedItems.forEach((item, index) => {
                setTimeout(() => {
                    item.style.opacity = 1;
                    item.style.transform = 'translateY(0)';
                }, index * 200);
            });

            function rotateFeed() {
                const itemToMove = feedItems[currentIndex];
                itemToMove.style.opacity = 0;
                itemToMove.style.transform = 'translateY(-10px)';

                setTimeout(() => {
                    itemToMove.style.transition = 'none';
                    itemToMove.style.transform = 'translateY(10px)';
                    dynamicFeed.appendChild(itemToMove);

                    setTimeout(() => {
                        itemToMove.style.transition = 'all 0.5s ease';
                        itemToMove.style.opacity = 1;
                        itemToMove.style.transform = 'translateY(0)';
                    }, 50);

                    currentIndex = (currentIndex + 1) % feedItems.length;
                }, 500);

                setTimeout(rotateFeed, 2500);
            }
            setTimeout(rotateFeed, 2000);
        }

        // Chest Logic
        const chestContainer = document.getElementById('chestContainer');
        const openBtn = document.getElementById('openBtn');
        const winText = document.getElementById('winText');
        let isOpening = false;
        const isBlocked = <?= json_encode($is_blocked) ?>;

        function triggerOpen() {
            if (isOpening || isBlocked) {
                if(isBlocked) showToast('Sem chaves disponíveis.', 'error');
                return;
            }
            isOpening = true;
            
            // 1. Shake
            chestContainer.classList.add('opening');
            
            // 2. Open Lid & Glow after small delay
            setTimeout(() => {
                chestContainer.classList.remove('opening');
                chestContainer.classList.add('opened');
                
                // Confetti Explosion
                if (typeof confetti === 'function') {
                    // Centro
                    confetti({ particleCount: 100, spread: 70, origin: { y: 0.6 }, colors: ['#FFD700', '#FF7E67'] });
                    // Lados
                    setTimeout(() => {
                        confetti({ particleCount: 50, angle: 60, spread: 55, origin: { x: 0 }, colors: ['#FF7E67', '#FFD700'] });
                        confetti({ particleCount: 50, angle: 120, spread: 55, origin: { x: 1 }, colors: ['#FF7E67', '#FFD700'] });
                    }, 200);
                }

                // 3. Submit Form
                setTimeout(() => {
                    document.getElementById('openForm').submit();
                }, 1500);

            }, 500);
        }

        openBtn.addEventListener('click', triggerOpen);
        chestContainer.addEventListener('click', triggerOpen);

        <?php if ($last && empty($last['error'])): ?>
            // Se acabou de ganhar, mostra o baú aberto
            (function() {
                chestContainer.classList.add('opened');
                winText.textContent = "GANHOU R$ <?= number_format($last['paid'], 2, ',', '.') ?>";
                winText.classList.remove('hidden');
                showToast("Prêmio resgatado!", "success");
                if (typeof confetti === 'function') {
                    confetti({ particleCount: 150, spread: 100, origin: { y: 0.6 }, colors: ['#FF7E67', '#FFD700'] });
                }
            })();
        <?php endif; ?>

    </script>
  </body>
  </html>
<?php endif; ?>