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

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

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

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

// 2. Fetch Withdrawal History
$history = [];
$getHistory = mysqli_query($conn, "SELECT * FROM transactions WHERE user_id = $userId AND type = 'withdrawal' ORDER BY created_at DESC");
while ($row = mysqli_fetch_assoc($getHistory)) {
    $history[] = $row;
}

// 3. Define Withdrawal Methods
$methods = [
    ['id' => 'bank', 'name' => 'Bank Transfer', 'icon' => 'landmark', 'color' => 'blue'],
    ['id' => 'usdt_trc20', 'name' => 'USDT (TRC20)', 'icon' => 'coins', 'color' => 'emerald'],
    ['id' => 'btc', 'name' => 'Bitcoin', 'icon' => 'bitcoin', 'color' => 'amber']
];
?>

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

<!-- SweetAlert2 & Alpine.js -->
<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-btn {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 2px solid transparent;
    }
    .method-btn.selected {
        border-color: var(--accent-blue);
        background: rgba(59, 130, 246, 0.05);
    }

    /* Fix for large balances: Auto-scaling text */
    .balance-display {
        font-size: clamp(1.25rem, 5vw, 1.875rem); /* Minimum 20px, scales with screen, max 30px */
        line-height: 1.2;
        word-break: break-all;
    }
</style>

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

<div class="flex min-h-screen" x-data="{ 
    selectedMethod: 'bank', 
    amount: '', 
    balance: <?= $userBalance ?>,
    get isOverBalance() { return parseFloat(this.amount) > this.balance }
}">
  
  <?php include "include/sidebar.php" ?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

      <div class="mb-10">
        <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">Withdraw Funds</h1>
        <p class="text-slate-500 dark:text-slate-400 mt-1">Authorize a secure payout from your trading account.</p>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        <!-- Left: Withdrawal Form -->
        <div class="lg:col-span-7">
            <form id="withdrawalForm" action="process/init_withdrawal.php" method="POST" class="glass-card rounded-[2.5rem] p-8 md:p-10 border border-blue-500/10 shadow-2xl">
                
                <!-- Balance Display (With overflow fix) -->
                <div class="flex items-center justify-between mb-10 bg-blue-500/5 p-6 rounded-3xl border border-blue-500/10 overflow-hidden">
                    <div class="min-w-0 flex-1">
                        <p class="text-[10px] font-black uppercase text-slate-400 tracking-widest">Available Balance</p>
                        <p class="balance-display font-black text-blue-600 dark:text-blue-400">
                            $<?= number_format($userBalance, 2) ?>
                        </p>
                    </div>
                    <div class="w-12 h-12 bg-blue-500/10 rounded-2xl flex items-center justify-center text-blue-500 ml-4 flex-shrink-0">
                        <i data-lucide="shield-check" class="w-6 h-6"></i>
                    </div>
                </div>

                <!-- Hidden Security Fields -->
                <input type="hidden" name="withdrawal_pin" id="hidden_pin">
                <input type="hidden" name="admin_auth_code" id="hidden_auth">

                <!-- Step 1: Amount -->
                <div class="mb-8">
                    <label class="text-[10px] font-black uppercase text-slate-400 mb-2 block px-2">1. Enter Payout Amount</label>
                    <div class="relative">
                        <span class="absolute left-6 top-1/2 -translate-y-1/2 text-xl font-black text-slate-400">$</span>
                        <input type="number" name="amount" x-model="amount" required step="any" placeholder="0.00"
                            class="w-full bg-slate-100 dark:bg-slate-900/50 border-none rounded-2xl py-6 pl-12 pr-6 text-2xl font-black focus:ring-4 focus:ring-blue-500/10 outline-none"
                            :class="isOverBalance ? 'text-rose-500' : 'text-slate-900 dark:text-white'">
                    </div>
                    <p x-show="isOverBalance" class="text-[10px] font-bold text-rose-500 mt-2 px-2 uppercase">Insufficient funds.</p>
                </div>

                <!-- Step 2: Method Selection -->
                <div class="mb-8">
                    <label class="text-[10px] font-black uppercase text-slate-400 mb-4 block px-2">2. Payout Method</label>
                    <div class="grid grid-cols-3 gap-3">
                        <?php foreach($methods as $m): ?>
                            <button type="button" @click="selectedMethod = '<?= $m['id'] ?>'"
                                :class="selectedMethod === '<?= $m['id'] ?>' ? 'selected' : 'border-slate-200 dark:border-slate-800'"
                                class="method-btn glass-card rounded-2xl p-4 text-center group">
                                <div class="w-10 h-10 rounded-xl bg-<?= $m['color'] ?>-500/10 text-<?= $m['color'] ?>-500 flex items-center justify-center mx-auto mb-2">
                                    <i data-lucide="<?= $m['icon'] ?>" class="w-5 h-5"></i>
                                </div>
                                <span class="text-[10px] font-black uppercase text-slate-600 dark:text-slate-400"><?= $m['name'] ?></span>
                                <input type="radio" name="method" value="<?= $m['id'] ?>" class="hidden" :checked="selectedMethod === '<?= $m['id'] ?>'">
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Step 3: Dynamic Destination Details -->
                <div class="mb-10 p-6 bg-slate-50 dark:bg-slate-900/30 rounded-[2rem] border border-slate-200 dark:border-slate-800">
                    <label class="text-[10px] font-black uppercase text-slate-400 mb-4 block">3. Destination Information</label>
                    
                    <div x-show="selectedMethod === 'bank'" x-transition class="space-y-4">
                        <input type="text" name="bank_name" placeholder="Bank Name" class="w-full bg-white dark:bg-slate-900 border-none rounded-xl py-4 px-6 text-sm font-bold outline-none focus:ring-2 focus:ring-blue-500/20">
                        <input type="text" name="acc_number" placeholder="Account Number" class="w-full bg-white dark:bg-slate-900 border-none rounded-xl py-4 px-6 text-sm font-bold outline-none focus:ring-2 focus:ring-blue-500/20">
                        <input type="text" name="acc_name" placeholder="Account Name" class="w-full bg-white dark:bg-slate-900 border-none rounded-xl py-4 px-6 text-sm font-bold outline-none focus:ring-2 focus:ring-blue-500/20">
                    </div>

                    <div x-show="selectedMethod !== 'bank'" x-transition>
                        <input type="text" name="wallet_address" :placeholder="'Your ' + selectedMethod.toUpperCase() + ' Wallet Address'" class="w-full bg-white dark:bg-slate-900 border-none rounded-xl py-4 px-6 text-sm font-bold outline-none focus:ring-2 focus:ring-blue-500/20">
                    </div>
                </div>

                <button type="button" onclick="startSecuritySequence()" :disabled="isOverBalance || !amount"
                    class="w-full py-6 bg-blue-600 hover:bg-blue-700 disabled:bg-slate-300 disabled:cursor-not-allowed text-white font-black rounded-2xl text-xs uppercase tracking-[0.2em] transition-all shadow-xl shadow-blue-600/20">
                    Initialize Payout
                </button>
            </form>
        </div>

        <!-- Right: Recent Activity -->
        <div class="lg:col-span-5">
            <div class="glass-card rounded-[2.5rem] p-8 border border-blue-500/10 min-h-[500px]">
                <h3 class="text-sm font-black uppercase text-slate-400 tracking-widest mb-8 px-2">History</h3>
                <div class="space-y-4">
                    <?php if(empty($history)): ?>
                        <div class="text-center py-20 opacity-20">
                            <i data-lucide="history" class="w-10 h-10 mx-auto mb-4"></i>
                            <p class="text-xs font-bold uppercase">No records</p>
                        </div>
                    <?php else: ?>
                        <?php foreach($history as $h): ?>
                            <div class="flex items-center justify-between p-4 bg-slate-50 dark:bg-slate-900/40 rounded-2xl border border-slate-200 dark:border-slate-800/50">
                                <div>
                                    <p class="text-xs font-black text-slate-900 dark:text-white">$<?= number_format($h['amount'], 2) ?></p>
                                    <p class="text-[9px] font-bold text-slate-400 uppercase tracking-widest"><?= date('M d', strtotime($h['created_at'])) ?></p>
                                </div>
                                <span class="px-3 py-1 rounded-full text-[9px] font-black uppercase <?= $h['status'] == 'completed' ? 'text-emerald-500 bg-emerald-500/10' : 'text-amber-500 bg-amber-500/10' ?>">
                                    <?= $h['status'] ?>
                                </span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

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

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

    async function startSecuritySequence() {
        // STEP 1: PIN
        const { value: pin } = await Swal.fire({
            title: 'Security PIN',
            text: 'Authorized personnel only. Please verify your 4-digit PIN.',
            input: 'password',
            inputAttributes: { maxlength: 6, autofocus: 'true', textAlign: 'center' },
            showCancelButton: true,
            confirmButtonColor: '#3b82f6',
            background: document.documentElement.classList.contains('dark') ? '#0f172a' : '#fff',
            color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
        });

        if (pin) {
            Swal.fire({
                title: 'Verifying Owner...',
                allowOutsideClick: false,
                didOpen: () => { Swal.showLoading(); }
            });

            // STEP 2: ADMIN AUTH (Simulated delay for "security check" feel)
            setTimeout(async () => {
                const { value: authCode } = await Swal.fire({
                    title: 'Admin Authorization',
                    text: 'Account ownership verified. Enter the Admin-issued Auth Code to complete.',
                    input: 'text',
                    inputPlaceholder: 'AUTH-XXXX',
                    showCancelButton: true,
                    confirmButtonColor: '#10b981',
                    background: document.documentElement.classList.contains('dark') ? '#0f172a' : '#fff',
                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                });

                if (authCode) {
                    document.getElementById('hidden_pin').value = pin;
                    document.getElementById('hidden_auth').value = authCode;
                    
                    Swal.fire({
                        title: 'Authorized',
                        text: 'Finalizing transaction...',
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    });

                    setTimeout(() => {
                        document.getElementById('withdrawalForm').submit();
                    }, 1500);
                }
            }, 800);
        }
    }

    // Success/Error Alerts from Session
    <?php if (isset($_SESSION['success'])): ?>
    Swal.fire({ icon: 'success', title: 'Success', text: '<?= $_SESSION['success'] ?>', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['success']); endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
    Swal.fire({ icon: 'error', title: 'Error', text: '<?= $_SESSION['error'] ?>', confirmButtonColor: '#ef4444' });
    <?php unset($_SESSION['error']); endif; ?>
</script>
<?php include "include/footer.php"?>
</body>
</html>