<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit; 
}

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// 1. Fetch User Data
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

$userBalance = $currentUser['balance'] ?? 0;

// 2. Fetch Active Investments to mark them in the grid
$activeInvestments = [];
$portfolioQuery = mysqli_query($conn, "SELECT * FROM investments WHERE user_id = $userId AND status = 'active'");
while ($row = mysqli_fetch_assoc($portfolioQuery)) {
    $activeInvestments[] = $row;
}
$activePlanNames = array_column($activeInvestments, 'plan_name');

// Define Investment Plans
$plans = [
    ['id' => 'starter', 'name' => 'Starter Plan', 'min' => 100, 'max' => 999, 'return' => 1.5, 'duration' => 7, 'icon' => 'zap', 'color' => 'blue'],
    ['id' => 'premium', 'name' => 'Premium Tier', 'min' => 1000, 'max' => 4999, 'return' => 2.5, 'duration' => 14, 'icon' => 'award', 'color' => 'emerald'],
    ['id' => 'ultra', 'name' => 'Ultra Growth', 'min' => 5000, 'max' => 19999, 'return' => 3.8, 'duration' => 30, 'icon' => 'trending-up', 'color' => 'indigo'],
    ['id' => 'vip', 'name' => 'VIP Institutional', 'min' => 20000, 'max' => 100000, 'return' => 5.0, 'duration' => 60, 'icon' => 'crown', 'color' => 'amber']
];
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    :root {
        --accent-primary: #3b82f6;
        --accent-gradient: linear-gradient(135deg, #3b82f6 0%, #2563eb 50%, #1d4ed8 100%);
        --glass-bg: rgba(255, 255, 255, 0.75);
        --bg-primary: #f0f4f8;
    }
    .dark {
        --bg-primary: #070b14;
        --glass-bg: rgba(15, 23, 42, 0.8);
    }
    body { background-color: var(--bg-primary); transition: all 0.3s; }
    .glass-card { background: var(--glass-bg); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); }
    
    /* Animation for active pulse */
    .pulse-active {
        box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4);
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
        100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
</style>

<?php include "include/nav.php"?>

<div class="flex min-h-screen">
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

      <!-- Header -->
      <div class="flex flex-col md:flex-row md:items-end justify-between gap-4 mb-10">
        <div>
          <h1 class="text-3xl font-black text-slate-900 dark:text-white">Trading Packages</h1>
          <p class="text-slate-500 dark:text-slate-400">Select a tier to activate automated trading.</p>
        </div>
        <div class="glass-card rounded-2xl px-6 py-4 flex items-center gap-4 border border-blue-100 dark:border-blue-900/30">
            <div>
                <p class="text-[10px] font-black uppercase text-slate-400">Wallet Balance</p>
                <p class="text-xl font-black text-blue-600 dark:text-blue-400">$<?= number_format($userBalance, 2) ?></p>
            </div>
        </div>
      </div>

      <!-- Plans Grid -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
        <?php foreach ($plans as $plan): 
            $isActive = in_array($plan['name'], $activePlanNames);
        ?>
          <div class="plan-card glass-card rounded-[2.5rem] p-8 flex flex-col relative overflow-hidden group <?= $isActive ? 'border-2 border-emerald-500/50' : 'border border-blue-500/10' ?>">
            
            <?php if($isActive): ?>
                <div class="absolute top-4 right-4 flex items-center gap-2 bg-emerald-500/10 text-emerald-500 px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest">
                    <span class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></span> Active
                </div>
            <?php endif; ?>

            <div class="w-14 h-14 rounded-2xl bg-<?= $plan['color'] ?>-500/10 flex items-center justify-center text-<?= $plan['color'] ?>-500 mb-6">
                <i data-lucide="<?= $plan['icon'] ?>" class="w-7 h-7"></i>
            </div>
            
            <h3 class="text-xl font-black text-slate-900 dark:text-white mb-2"><?= $plan['name'] ?></h3>
            
            <div class="mb-6">
                <span class="text-3xl font-black text-<?= $plan['color'] ?>-500"><?= $plan['return'] ?>%</span>
                <span class="text-sm text-slate-400 font-bold">/ Daily</span>
            </div>

            <ul class="space-y-3 mb-8 flex-1 text-sm font-medium text-slate-600 dark:text-slate-400">
                <li>Min: $<?= number_format($plan['min']) ?></li>
                <li>Max: $<?= number_format($plan['max']) ?></li>
                <li>Term: <?= $plan['duration'] ?> Days</li>
            </ul>

            <button onclick="openInvestModal(<?= htmlspecialchars(json_encode($plan)) ?>)" 
                    class="w-full py-4 rounded-2xl font-black text-xs uppercase tracking-widest transition-all <?= $isActive ? 'bg-slate-200 dark:bg-slate-800 text-slate-500 cursor-default' : 'bg-blue-600 hover:bg-blue-700 text-white shadow-lg shadow-blue-500/20' ?>">
                <?= $isActive ? 'Plan Running' : 'Select Plan' ?>
            </button>
          </div>
        <?php endforeach; ?>
      </div>

      <!-- Active Portfolio Section -->
      <div class="mb-12">
          <div class="flex items-center gap-3 mb-6">
              <div class="w-2 h-8 bg-blue-600 rounded-full"></div>
              <h2 class="text-2xl font-black text-slate-900 dark:text-white">Active Portfolio</h2>
          </div>

          <?php if(empty($activeInvestments)): ?>
            <div class="glass-card rounded-[2rem] p-12 text-center border border-dashed border-slate-300 dark:border-slate-800">
                <p class="text-slate-400 font-medium italic">You have no active investment plans at the moment.</p>
            </div>
          <?php else: ?>
            <div class="glass-card rounded-[2rem] overflow-hidden border border-blue-500/10">
                <table class="w-full text-left">
                    <thead class="bg-blue-500/5 text-[10px] font-black uppercase text-slate-400">
                        <tr>
                            <th class="px-8 py-4">Plan Name</th>
                            <th class="px-8 py-4">Amount</th>
                            <th class="px-8 py-4">Daily ROI</th>
                            <th class="px-8 py-4">End Date</th>
                            <th class="px-8 py-4 text-right">Status</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                        <?php foreach($activeInvestments as $invest): ?>
                            <tr class="text-sm font-bold text-slate-700 dark:text-slate-300">
                                <td class="px-8 py-6"><?= $invest['plan_name'] ?></td>
                                <td class="px-8 py-6 text-blue-600">$<?= number_format($invest['amount'], 2) ?></td>
                                <td class="px-8 py-6 text-emerald-500">+<?= $invest['daily_return'] ?>%</td>
                                <td class="px-8 py-6"><?= date('M d, Y', strtotime($invest['end_at'])) ?></td>
                                <td class="px-8 py-6 text-right">
                                    <span class="bg-emerald-500/10 text-emerald-500 px-3 py-1 rounded-full text-[10px]">ACTIVE</span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
          <?php endif; ?>
      </div>

      <!-- Profit Calculator -->
      <div class="glass-card rounded-[2.5rem] p-10 border border-blue-50 dark:border-blue-900/10">
            <h2 class="text-2xl font-black mb-8">Earning Projection</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 items-center">
                <input type="number" id="calc-amount" oninput="calculateProfit()" placeholder="Amount ($)" class="bg-slate-50 dark:bg-slate-900 border border-blue-100 dark:border-blue-900/40 rounded-2xl px-6 py-4 font-black">
                <select id="calc-plan" onchange="calculateProfit()" class="bg-slate-50 dark:bg-slate-900 border border-blue-100 dark:border-blue-900/40 rounded-2xl px-6 py-4 font-black">
                    <?php foreach($plans as $p): ?>
                        <option value="<?= $p['return'] ?>|<?= $p['duration'] ?>"><?= $p['name'] ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="bg-blue-600 rounded-2xl p-6 text-white">
                    <p class="text-[10px] font-bold opacity-70">Total Net Profit</p>
                    <p class="text-2xl font-black" id="res-profit">$0.00</p>
                </div>
            </div>
      </div>
    </div>
  </main>
</div>

<!-- Modal remains the same but with added styling -->
<div id="investModal" class="fixed inset-0 z-[100] hidden flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" onclick="closeModal()"></div>
    <div class="relative w-full max-w-md glass-card rounded-[2.5rem] p-8 border border-white/20 shadow-2xl">
        <h3 id="modalPlanName" class="text-2xl font-black text-center mb-6 text-slate-900 dark:text-white">---</h3>
        <form action="process/purchase_plan.php" method="POST" class="space-y-6">
            <input type="hidden" name="plan_id" id="modalPlanId">
            <input type="number" name="amount" id="investAmount" required step="any" class="w-full bg-slate-50 dark:bg-slate-900 border border-blue-100 dark:border-blue-900/40 rounded-2xl px-6 py-4 font-black text-lg text-center outline-none">
            <button type="submit" class="w-full py-5 bg-blue-600 text-white font-black rounded-2xl shadow-xl shadow-blue-500/20 uppercase tracking-widest text-xs">Confirm Investment</button>
            <button type="button" onclick="closeModal()" class="w-full text-slate-400 text-xs font-bold">Cancel</button>
        </form>
    </div>
</div>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    lucide.createIcons();
    function calculateProfit() {
        const amount = parseFloat(document.getElementById('calc-amount').value) || 0;
        const [rate, days] = document.getElementById('calc-plan').value.split('|').map(parseFloat);
        const profit = (amount * (rate / 100)) * days;
        document.getElementById('res-profit').innerText = '$' + profit.toLocaleString(undefined, {minimumFractionDigits: 2});
    }
    function openInvestModal(plan) {
        document.getElementById('investModal').classList.remove('hidden');
        document.getElementById('modalPlanName').innerText = plan.name;
        document.getElementById('modalPlanId').value = plan.id;
        document.getElementById('investAmount').value = plan.min;
    }
    function closeModal() { document.getElementById('investModal').classList.add('hidden'); }
</script>

<?php if (isset($_SESSION['success'])): ?>
<script>
    Swal.fire({
        title: 'Activated!',
        text: '<?= $_SESSION['success']; ?>',
        icon: 'success',
        background: document.documentElement.classList.contains('dark') ? '#0f172a' : '#ffffff',
        color: document.documentElement.classList.contains('dark') ? '#f1f5f9' : '#0f172a',
        confirmButtonColor: '#3b82f6',
        customClass: { popup: 'rounded-[2rem]' }
    });
</script>
<?php unset($_SESSION['success']); endif; ?>

<?php include "include/buttom-nav.php"?>