<?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';
require '../app/Controllers/layouts.php';

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

$stmtInvestments2 = $pdo->prepare("SELECT * FROM investments WHERE user_id = :user_id ORDER BY is_active DESC");
$stmtInvestments2->execute([
    ':user_id' => $user['id'],
]);
$resultInvestments2 = $stmtInvestments2->fetchAll(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) : ?>
    <?php
    // Lógica PHP Mantida
    $consultHistoryRescues = $pdo->prepare('SELECT * FROM investments_rescues WHERE user_id = :user_id ORDER BY created_at DESC');
    $consultHistoryRescues->execute([':user_id' => $user['id']]);
    $rescues = $consultHistoryRescues->fetchAll(PDO::FETCH_ASSOC);

    $totalColetado = 0;
    foreach ($rescues as $r) {
        $totalColetado += $r['value'];
    }
    ?>
  <!DOCTYPE html>
  <html lang="pt-BR">

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Histórico de Coletas 收益记录 - <?= 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)',
            }
          }
        }
      };
    </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);
      }

      /* Painel de Resumo */
      .stats-panel {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1px;
        background: #E5E7EB;
        border-bottom: 1px solid #E5E7EB;
        margin-bottom: 20px;
      }
      
      .stat-item {
        background: #FFF;
        padding: 20px;
        text-align: center;
      }

      /* Card de Transação (Lista Clean) */
      .tx-card {
        background: #FFF;
        border: 1px solid #E5E7EB;
        margin-bottom: 10px;
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.2s;
        border-radius: 12px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.02);
      }
      .tx-card:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.05); }

      /* Status Styles */
      .status-dot {
        width: 6px; height: 6px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 5px;
      }
      
      .st-received { color: #43A047; }
      .st-received .status-dot { background: #43A047; box-shadow: 0 0 5px rgba(67, 160, 71, 0.5); }
      .bg-icon-received { background: rgba(255, 126, 103, 0.1); color: #FF7E67; border: 1px solid rgba(255, 126, 103, 0.2); }

      /* Ícone Quadrado */
      .tx-icon-box {
        width: 40px; height: 40px;
        display: flex; align-items: center; justify-content: center;
        flex-shrink: 0;
        border-radius: 8px;
      }

      /* 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="profile.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]">Histórico de Coletas 收益记录</h1>
         <div class="w-8"></div> 
      </div>

      <div class="stats-panel">
         <div class="stat-item">
            <p class="text-[9px] text-gray-400 uppercase tracking-widest mb-1 font-bold">Total Coletas 数量</p>
            <p class="text-xl font-mono text-gray-800 font-bold"><?= count($rescues) ?></p>
         </div>
         <div class="stat-item">
            <p class="text-[9px] text-gray-400 uppercase tracking-widest mb-1 font-bold">Lucro Total 总收益</p>
            <p class="text-xl font-mono text-vip-green font-bold">+R$ <?= number_format($totalColetado, 2, ',', '.') ?></p>
         </div>
      </div>

      <div class="px-5 pb-20">
         <h3 class="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-4 border-b border-gray-200 pb-2 flex items-center gap-2">
            <i data-lucide="trending-up" class="w-3 h-3"></i> Registro de Lucros 收益明细
         </h3>

         <div class="flex flex-col">
            <?php if (empty($rescues)) : ?>
               <div class="text-center py-12 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="piggy-bank" class="w-6 h-6"></i>
                  </div>
                  <p class="text-xs text-gray-400 font-mono font-bold">NENHUM LUCRO REGISTRADO / 无收益</p>
               </div>
            <?php else : ?>

               <?php foreach ($rescues as $resgate) : 
                   // Assumindo que registros na tabela são sucessos
                   $statusText = 'RECEBIDO 已到账';
                   $statusClass = 'st-received';
                   $iconClass = 'bg-icon-received';
                   $icon = 'coins';
               ?>

                   <div class="tx-card group">
                       <div class="flex items-center gap-3">
                           <div class="tx-icon-box <?= $iconClass ?>">
                               <i data-lucide="<?= $icon ?>" class="w-5 h-5"></i>
                           </div>
                           <div>
                               <div class="flex items-center gap-2 mb-0.5">
                                  <span class="text-xs font-bold font-mono text-gray-800">Lucro de Investimento 投资收益</span>
                               </div>
                               <p class="text-[9px] text-gray-400 font-mono uppercase font-bold"><?= date('Y-m-d H:i', strtotime($resgate['created_at'])) ?></p>
                           </div>
                       </div>

                       <div class="text-right">
                           <p class="text-sm font-mono font-bold text-vip-green mb-1">+ R$ <?= number_format($resgate['value'], 2, ',', '.') ?></p>
                           <span class="text-[9px] font-bold uppercase tracking-wide <?= $statusClass ?>">
                               <span class="status-dot"></span><?= $statusText ?>
                           </span>
                       </div>
                   </div>
               <?php endforeach; ?>

            <?php endif; ?>
         </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; ?>
    </script>
  </body>
  </html>
<?php endif; ?>