<?php
require_once '../app/Controllers/sessions.php';
require_once '../app/Controllers/security_access.php';
require_once '../app/models/user.php';
require_once '../app/Controllers/checkInController.php';
require_once '../app/Controllers/controller_investments.php'; // Essencial para esta tela
require '../app/Controllers/layouts.php';

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

// Garante que variáveis de visualização existam
$tempo_restante_segundos = $tempo_restante_segundos ?? 0;
?>
<?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" />
    <title>Meus Investimentos 我的投资 - <?= 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 10px 30px -5px rgba(0,0,0,0.05)'
            }
          }
        }
      };
    </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);
      }

      /* Cards de Resumo */
      .stat-card {
        background: #FFF;
        border: 1px solid #E5E7EB;
        padding: 16px;
        border-radius: 12px;
        position: relative;
        overflow: hidden;
        box-shadow: 0 4px 10px rgba(0,0,0,0.03);
      }
      
      /* Painel de Coleta */
      .collect-panel {
        background: #FFF;
        border: 1px solid #E5E7EB;
        border-left: 4px solid #FF7E67;
        margin: 20px;
        padding: 20px;
        position: relative;
        border-radius: 12px;
        box-shadow: 0 10px 20px rgba(0,0,0,0.05);
      }

      /* Botão Coleta Salmon */
      .btn-collect-salmon {
        background: #FF7E67;
        color: #FFF;
        font-family: 'Oswald', sans-serif;
        text-transform: uppercase;
        font-weight: bold;
        letter-spacing: 1px;
        border: none;
        border-radius: 8px;
        transition: all 0.2s;
        box-shadow: 0 5px 15px rgba(255, 126, 103, 0.3);
      }
      .btn-collect-salmon:active { transform: scale(0.98); }
      .btn-collect-salmon:disabled {
        background: #E5E7EB;
        color: #9CA3AF;
        box-shadow: none;
        cursor: not-allowed;
      }

      /* Card de Investimento (Lista Clean) */
      .invest-item {
        background: #FFF;
        border: 1px solid #E5E7EB;
        margin-bottom: 15px;
        border-radius: 12px;
        transition: transform 0.2s, box-shadow 0.2s;
        box-shadow: 0 2px 5px rgba(0,0,0,0.02);
      }
      .invest-item:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.05); }

      .details-panel {
        background: #F9FAFB;
        border-top: 1px solid #E5E7EB;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s ease-out, padding 0.3s;
        border-radius: 0 0 12px 12px;
      }
      .details-panel.open {
        max-height: 500px;
        padding: 16px;
      }

      /* Barra de Progresso Light */
      .progress-track {
        background: #F3F4F6;
        height: 6px;
        width: 100%;
        margin: 12px 0;
        border-radius: 3px;
        overflow: hidden;
      }
      .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #FF7E67, #FFA090);
        border-radius: 3px;
        box-shadow: 0 0 8px rgba(255, 126, 103, 0.3);
      }

      /* 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">
            Meus Ativos 资产
        </h1>
        <div class="w-6"></div> 
      </div>

      <div class="grid grid-cols-2 gap-4 px-5 mt-5">
         <div class="stat-card">
            <div class="flex items-center gap-2 mb-2">
                <div class="w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center text-gray-500">
                    <i data-lucide="wallet" class="w-3 h-3"></i>
                </div>
                <p class="text-[10px] text-gray-500 uppercase tracking-widest font-bold">Total Investido 总投入</p>
            </div>
            <p class="text-xl font-mono text-gray-800 font-bold">R$ <?= number_format($totalInvested ?? 0, 2, ',', '.') ?></p>
         </div>
         <div class="stat-card">
            <div class="flex items-center gap-2 mb-2">
                <div class="w-6 h-6 rounded-full bg-vip-salmon/10 flex items-center justify-center text-vip-salmon">
                    <i data-lucide="trending-up" class="w-3 h-3"></i>
                </div>
                <p class="text-[10px] text-vip-salmon uppercase tracking-widest font-bold">Lucro Total 总收益</p>
            </div>
            <p class="text-xl font-mono text-vip-salmon font-bold">R$ <?= number_format($totalPaid ?? 0, 2, ',', '.') ?></p>
         </div>
      </div>

      <div class="collect-panel">
         <div class="flex items-center justify-between mb-4">
            <h2 class="text-xs font-bold text-gray-700 uppercase flex items-center gap-2">
               <i data-lucide="hourglass" class="w-4 h-4 text-vip-salmon"></i>
               Coleta de Lucros 收益提取
            </h2>
            <div id="timerContainer" style="display:none;">
               <span id="timer-rendimento-countdown" class="font-mono text-sm text-vip-salmon font-bold bg-vip-salmon/10 px-3 py-1 rounded-full border border-vip-salmon/20">--:--:--</span>
            </div>
         </div>

         <?php if (!empty($resultInvestments2)) : ?>
            <form method="POST">
               <button id="btnVerify" type="submit" name="send-verify" class="btn-collect-salmon w-full py-4 flex items-center justify-center gap-2 shadow-lg shadow-salmon/30">
                  <i class="fa-solid fa-bolt"></i>
                  <span>RECEBER TUDO 一键领取</span>
               </button>
            </form>
         <?php else: ?>
            <button disabled class="btn-collect-salmon w-full py-4 opacity-50 flex items-center justify-center gap-2">
               <i class="fa-solid fa-ban"></i>
               SEM LUCRO PENDENTE
            </button>
         <?php endif; ?>
      </div>

      <div class="px-5 pb-24">
         <h3 class="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-3 border-b border-gray-200 pb-2 flex justify-between">
            <span>Ativos em Execução 运行中资产</span>
            <span><?= count($resultInvestments2) ?> ITENS</span>
         </h3>

         <?php if (empty($resultInvestments2)) : ?>
            <div class="py-12 text-center border border-dashed border-gray-200 rounded-lg bg-white">
               <div class="w-12 h-12 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-3 text-gray-300">
                   <i data-lucide="package-open" class="w-6 h-6"></i>
               </div>
               <p class="text-gray-400 font-mono text-xs mb-3">NENHUM ATIVO ENCONTRADO</p>
               <a href="index.php" class="text-xs text-vip-salmon hover:underline font-bold">COMEÇAR A INVESTIR &rarr;</a>
            </div>
         <?php else : ?>
            
            <div class="flex flex-col">
               <?php foreach ($resultInvestments2 as $inv2) :
                  $dias = $inv2['duration_days'];
                  $total = $inv2['total_return'];
                  $recebido = $inv2['total_paid'];
                  $renda_dia = $dias > 0 ? $total / $dias : 0;
                  $faltando = $total - $recebido;
                  $modalId = "details-" . preg_replace('/[^a-zA-Z0-9_-]/', '', $inv2['id']);
                  $isDiary = ($inv2['type'] === 'diary');
                  $isActive = ($inv2['is_active'] == 1);
                  $statusLabel = $isActive ? 'EM EXECUÇÃO 运行中' : 'FINALIZADO 已结束';
                  $statusClass = $isActive ? 'bg-green-100 text-green-600 border-green-200' : 'bg-gray-100 text-gray-500 border-gray-200';
                  $percentualDiario = $total > 0 && $isDiary ? round(($renda_dia / $total) * 100, 2) : 0;
                  $progressPercent = $total > 0 ? min(100, ($recebido / $total) * 100) : 0;
               ?>
               
               <div class="invest-item group">
                  <div class="p-4 cursor-pointer" onclick="toggleDetails('<?= $modalId ?>')">
                     
                     <div class="flex justify-between items-start mb-2">
                        <div>
                           <div class="flex items-center gap-2 mb-1">
                              <?php if($isDiary): ?>
                                 <span class="bg-vip-salmon/10 text-vip-salmon text-[9px] px-1.5 py-0.5 rounded border border-vip-salmon/20 font-bold font-mono">DIÁRIO</span>
                              <?php else: ?>
                                 <span class="bg-blue-50 text-blue-500 text-[9px] px-1.5 py-0.5 rounded border border-blue-100 font-bold font-mono">CICLO</span>
                              <?php endif; ?>
                              <h4 class="text-sm font-bold text-gray-800 truncate w-40"><?= htmlspecialchars($inv2['name']) ?></h4>
                           </div>
                           <span class="text-[9px] px-2 py-0.5 rounded-full border <?= $statusClass ?> font-bold uppercase tracking-wide"><?= $statusLabel ?></span>
                        </div>
                        <div class="text-right">
                           <p class="text-[9px] text-gray-400 uppercase font-bold">Retorno Total</p>
                           <p class="text-sm font-mono text-gray-800 font-bold">R$ <?= number_format($total, 2, ',', '.') ?></p>
                        </div>
                     </div>

                     <div class="progress-track">
                        <div class="progress-fill transition-all duration-500" style="width: <?= $progressPercent ?>%"></div>
                     </div>
                     
                     <div class="flex justify-between items-end mt-1">
                        <p class="text-[10px] text-gray-500 font-mono font-bold">PAGO: <span class="text-vip-green">R$ <?= number_format($recebido, 2, ',', '.') ?></span></p>
                        <div class="flex items-center text-[10px] text-vip-salmon font-bold uppercase hover:underline">
                            Detalhes <i data-lucide="chevron-down" class="w-3 h-3 ml-1"></i>
                        </div>
                     </div>
                  </div>

                  <div id="<?= $modalId ?>" class="details-panel">
                     <div class="grid grid-cols-2 gap-3 mb-4 font-mono text-xs">
                        <div class="bg-white p-3 border border-gray-200 rounded-lg">
                           <p class="text-gray-400 mb-1 font-bold">DURAÇÃO</p>
                           <p class="text-gray-800 font-bold"><?= $dias ?> DIAS</p>
                        </div>
                        <div class="bg-white p-3 border border-gray-200 rounded-lg">
                           <p class="text-gray-400 mb-1 font-bold">RESTANTE</p>
                           <p class="text-gray-800 font-bold">R$ <?= number_format($faltando, 2, ',', '.') ?></p>
                        </div>
                        <?php if ($isDiary) : ?>
                        <div class="bg-white p-3 border border-gray-200 rounded-lg col-span-2 flex justify-between items-center">
                           <div>
                              <p class="text-gray-400 mb-1 font-bold">LUCRO DIÁRIO</p>
                              <p class="text-vip-salmon font-bold">R$ <?= number_format($renda_dia, 2, ',', '.') ?></p>
                           </div>
                           <span class="text-[10px] text-gray-400 bg-gray-50 px-2 py-1 rounded font-bold"><?= $percentualDiario ?>% / dia</span>
                        </div>
                        <?php endif; ?>
                     </div>
                     
                     <a href="investment_product.php?ref=<?= urlencode($inv2['token'] ?? '') ?>" class="block text-center text-[10px] text-gray-500 hover:text-vip-salmon uppercase tracking-widest border-t border-gray-200 pt-3 font-bold">
                        Ver Lógica do Produto 查看详情 &rarr;
                     </a>
                  </div>
               </div>
               <?php endforeach; ?>
            </div>

         <?php endif; ?>
      </div>

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

    </div>

    <script>
      lucide.createIcons();

      // --- CRONÔMETRO DE RENDIMENTO ---
      let tempoRestanteRendimentoSegundos = <?= $tempo_restante_segundos ?>;
      let btnVerify = document.getElementById('btnVerify');
      let timerRendimentoDisplay = document.getElementById('timer-rendimento-countdown');
      let timerRendimentoContainer = document.getElementById('timerContainer');

      function formatarTempo(segundos) {
          const h = String(Math.floor(segundos / 3600)).padStart(2, '0');
          const m = String(Math.floor((segundos % 3600) / 60)).padStart(2, '0');
          const s = String(segundos % 60).padStart(2, '0');
          return `${h}:${m}:${s}`;
      }

      function iniciarCronometroRendimento() {
          btnVerify = document.getElementById('btnVerify');
          timerRendimentoDisplay = document.getElementById('timer-rendimento-countdown');
          timerRendimentoContainer = document.getElementById('timerContainer');

          if (!btnVerify || !timerRendimentoDisplay || !timerRendimentoContainer) return;

          function atualizar() {
              if (tempoRestanteRendimentoSegundos <= 0) {
                  btnVerify.style.display = 'flex';
                  timerRendimentoContainer.style.display = 'none';
                  btnVerify.disabled = false;
                  btnVerify.classList.remove('opacity-50', 'cursor-not-allowed');
                  clearInterval(intervalo);
                  return;
              }

              btnVerify.style.display = 'none';
              timerRendimentoContainer.style.display = 'block';
              
              timerRendimentoDisplay.textContent = formatarTempo(tempoRestanteRendimentoSegundos);
              tempoRestanteRendimentoSegundos--;
          }

          if (tempoRestanteRendimentoSegundos > 0) {
              btnVerify.style.display = 'none';
              timerRendimentoContainer.style.display = 'block';
          } else {
              btnVerify.style.display = 'flex';
              timerRendimentoContainer.style.display = 'none';
              btnVerify.disabled = false;
              btnVerify.classList.remove('opacity-50', 'cursor-not-allowed');
          }

          atualizar(); 
          const intervalo = setInterval(atualizar, 1000);
      }

      document.addEventListener('DOMContentLoaded', iniciarCronometroRendimento);

      // --- Lógica de Detalhes ---
      function toggleDetails(id) {
        const el = document.getElementById(id);
        if (!el) return;
        
        document.querySelectorAll('.details-panel.open').forEach(opened => {
           if(opened !== el) opened.classList.remove('open');
        });

        el.classList.toggle('open');
      }

      // --- Toast Light Style ---
      function showToast(msg) {
         const container = document.getElementById('toast-container');
         const toast = document.createElement('div');
         
         toast.className = 'toast-custom pointer-events-auto';
         toast.innerHTML = `
            <i data-lucide="check-circle" class="w-4 h-4 text-vip-green"></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) ?>'));
      <?php endif; ?>
    </script>
  </body>
  </html>
<?php endif; ?>