<?php
session_start();
require_once "include/db.php";

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

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

// Fetch User Data for Balance Display
$userQuery = mysqli_query($conn, "SELECT balance FROM users WHERE id = $userId LIMIT 1");
$userData = mysqli_fetch_assoc($userQuery);
$userBalance = $userData['balance'] ?? 0;

// NEW: Fetch available payment methods from the database
$methods = [];
$getMethods = mysqli_query($conn, "SELECT * FROM payment_details");
while ($row = mysqli_fetch_assoc($getMethods)) {
    // We map icons/colors based on the slug for UI consistency
    $ui_meta = [
        'usdt_trc20' => ['icon' => 'coins', 'color' => 'emerald', 'desc' => 'Fastest & Low Fee'],
        'bank'       => ['icon' => 'landmark', 'color' => 'blue', 'desc' => 'Local Bank Deposit'],
        'btc'        => ['icon' => 'bitcoin', 'color' => 'amber', 'desc' => 'Standard Crypto'],
        'eth'        => ['icon' => 'circle-dot', 'color' => 'indigo', 'desc' => 'ERC20 Network']
    ];
    
    $slug = $row['method_slug'];
    $methods[] = [
        'id'    => $slug,
        'name'  => $row['method_name'],
        'icon'  => $ui_meta[$slug]['icon'] ?? 'credit-card',
        'color' => $ui_meta[$slug]['color'] ?? 'slate',
        'desc'  => $ui_meta[$slug]['desc'] ?? 'Secure Payment'
    ];
}

// Set a default selected method for Alpine.js
$defaultMethod = !empty($methods) ? $methods[0]['id'] : 'usdt_trc20';
?>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

<style>
    :root {
        --accent-blue: #3b82f6;
        --glass-bg: rgba(255, 255, 255, 0.75);
    }
    .dark { --glass-bg: rgba(15, 23, 42, 0.8); }
    .glass-card { background: var(--glass-bg); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); }
    
    .method-card {
        border: 2px solid transparent;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .method-card.selected {
        border-color: var(--accent-blue);
        background: rgba(59, 130, 246, 0.05);
        transform: translateY(-4px);
    }
</style>

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

<!-- Alpine.js handles the UI state -->
<div class="flex min-h-screen transition-colors duration-300" x-data="{ selectedMethod: '<?= $defaultMethod ?>', amount: '' }">
  
  <?php include "include/sidebar.php" ?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

      <!-- Page Header -->
      <div class="mb-10">
        <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">Fund Account</h1>
        <p class="text-slate-500 dark:text-slate-400 mt-1">Select your preferred method and enter the amount to deposit.</p>
      </div>

      <form action="process/init_deposit.php" method="POST" class="space-y-8">
        
        <!-- Balance Preview -->
        <div class="glass-card rounded-[2rem] p-8 border border-blue-500/10 flex items-center justify-between shadow-sm">
            <div>
                <p class="text-[10px] font-black uppercase text-slate-400 mb-1 tracking-widest">Available Balance</p>
                <p class="text-3xl font-black text-blue-600 dark:text-blue-400">$<?= number_format($userBalance, 2) ?></p>
            </div>
            <div class="w-14 h-14 bg-blue-500/10 rounded-2xl flex items-center justify-center text-blue-500">
                <i data-lucide="wallet" class="w-7 h-7"></i>
            </div>
        </div>

        <!-- Payment Methods (Fetched from DB) -->
        <div>
            <label class="text-sm font-black text-slate-400 uppercase tracking-widest mb-4 block px-2">1. Choose Payment Method</label>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <?php foreach($methods as $m): ?>
                    <div 
                        @click="selectedMethod = '<?= $m['id'] ?>'"
                        :class="selectedMethod === '<?= $m['id'] ?>' ? 'selected' : 'border-slate-200 dark:border-slate-800'"
                        class="method-card glass-card rounded-3xl p-6 cursor-pointer relative overflow-hidden group"
                    >
                        <div class="w-12 h-12 rounded-2xl bg-<?= $m['color'] ?>-500/10 text-<?= $m['color'] ?>-500 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
                            <i data-lucide="<?= $m['icon'] ?>" class="w-6 h-6"></i>
                        </div>
                        <h3 class="font-black text-slate-900 dark:text-white"><?= $m['name'] ?></h3>
                        <p class="text-[10px] text-slate-400 font-bold uppercase mt-1"><?= $m['desc'] ?></p>

                        <!-- Hidden Radio for Form Submission -->
                        <input type="radio" name="payment_method" value="<?= $m['id'] ?>" class="hidden" :checked="selectedMethod === '<?= $m['id'] ?>'">
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Amount Input Card -->
        <div class="glass-card rounded-[2.5rem] p-10 border border-blue-500/10 shadow-lg">
            <div class="max-w-md mx-auto text-center space-y-6">
                <label class="text-sm font-black text-slate-400 uppercase tracking-widest">2. Enter Deposit Amount</label>
                
                <div class="relative">
                    <span class="absolute left-8 top-1/2 -translate-y-1/2 text-3xl font-black text-blue-500/30">$</span>
                    <input 
                        type="number" 
                        name="amount" 
                        x-model="amount"
                        required 
                        placeholder="0.00"
                        step="any"
                        class="w-full bg-slate-100 dark:bg-slate-900/50 border-none rounded-[2.5rem] py-10 pl-16 pr-8 text-5xl font-black text-center focus:ring-4 focus:ring-blue-500/20 transition-all outline-none text-slate-900 dark:text-white"
                    >
                </div>

                <!-- Quick Select Amounts -->
                <div class="flex flex-wrap justify-center gap-3">
                    <template x-for="val in [100, 500, 1000, 5000]">
                        <button 
                            type="button" 
                            @click="amount = val"
                            class="px-5 py-2.5 rounded-full bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 text-xs font-black hover:border-blue-500 hover:text-blue-500 transition-all shadow-sm"
                            x-text="'+ $' + val.toLocaleString()"
                        ></button>
                    </template>
                </div>
            </div>
        </div>

        <!-- Submit Button -->
        <div class="space-y-4">
            <button 
                type="submit" 
                class="w-full py-7 bg-blue-600 hover:bg-blue-700 text-white font-black rounded-[2.5rem] text-sm uppercase tracking-[0.25em] transition-all shadow-2xl shadow-blue-600/40 active:scale-[0.97] flex items-center justify-center gap-3"
            >
                Proceed to Payment <i data-lucide="chevron-right" class="w-5 h-5"></i>
            </button>
            <p class="text-center text-[10px] text-slate-400 font-bold uppercase tracking-widest">
                <i data-lucide="shield-check" class="w-3 h-3 inline-block mr-1 text-emerald-500"></i> Secure 256-bit Encrypted Transaction
            </p>
        </div>

      </form>
    </div>
  </main>
</div>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    lucide.createIcons();

    // SweetAlert Listeners for Errors
    <?php if (isset($_SESSION['error'])): ?>
    Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        text: '<?= $_SESSION['error'] ?>',
        background: document.documentElement.classList.contains('dark') ? '#0f172a' : '#fff',
        color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
        confirmButtonColor: '#3b82f6',
        customClass: { popup: 'rounded-[2rem]' }
    });
    <?php unset($_SESSION['error']); endif; ?>
</script>
<?php include "include/buttom-nav.php"?>
</body>
</html>