<?php
session_start();
if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit(); }

try {
    $db = new PDO('sqlite:trading_platform.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $user_id = $_SESSION['user_id'];

    // --- অটোমেটিক ডাটাবেস কলাম চেক (Auto Migration) ---
    $withdrawCols = $db->query("PRAGMA table_info(withdrawals)")->fetchAll(PDO::FETCH_ASSOC);
    $existingCols = array_column($withdrawCols, 'name');
    if (!in_array('method', $existingCols)) { $db->exec("ALTER TABLE withdrawals ADD COLUMN method TEXT"); }
    if (!in_array('address', $existingCols)) { $db->exec("ALTER TABLE withdrawals ADD COLUMN address TEXT"); }

    // ১. একটিভ পেমেন্ট মেথড আনা
    $active_methods = $db->query("SELECT * FROM payment_methods WHERE status = 1")->fetchAll(PDO::FETCH_ASSOC);

    // ২. ইউজারের বর্তমান ব্যালেন্স চেক
    $stmt = $db->prepare("SELECT main_balance FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user_balance = $stmt->fetchColumn();

    $msg = ""; $error = "";

    // ৩. ডিপোজিট প্রসেস (পেন্ডিং থাকবে)
    if (isset($_POST['submit_deposit'])) {
        $amount = (float)$_POST['amount'];
        $method = htmlspecialchars($_POST['method']);
        $tid = htmlspecialchars($_POST['transaction_id']);

        if($amount >= 0.5) {
            $ins = $db->prepare("INSERT INTO deposits (user_id, amount, method, status, created_at) VALUES (?, ?, ?, 'Pending', datetime('now'))");
            $ins->execute([$user_id, $amount, "$method (TID: $tid)"]);
            $msg = "Deposit request submitted! Assets will be added after review.";
        } else { $error = "Minimum deposit is $0.5"; }
    }

    // ৪. উইথড্র প্রসেস (সাথে সাথে ব্যালেন্স কাটা হবে)
    if (isset($_POST['submit_withdraw'])) {
        $amount = (float)$_POST['amount'];
        $method = htmlspecialchars($_POST['method']);
        $address = htmlspecialchars($_POST['address']);

        if ($amount < 1) {
            $error = "Minimum withdrawal is $1";
        } elseif ($user_balance >= $amount) {
            // ১. ডাটাবেস থেকে টাকা কেটে নেওয়া
            $deduct = $db->prepare("UPDATE users SET main_balance = main_balance - ? WHERE id = ?");
            $deduct->execute([$amount, $user_id]);

            // ২. রিকোয়েস্ট সেভ করা
            $ins = $db->prepare("INSERT INTO withdrawals (user_id, amount, method, address, status, created_at) VALUES (?, ?, ?, ?, 'Pending', datetime('now'))");
            $ins->execute([$user_id, $amount, $method, $address]);

            // ৩. বর্তমান পেজের ভেরিয়েবল আপডেট করা
            $user_balance -= $amount;
            $msg = "Withdrawal request sent! $".$amount." deducted from assets.";
        } else { 
            $error = "Insufficient balance!"; 
        }
    }

} catch (PDOException $e) { die("System Error: " . $e->getMessage()); }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Ziber Wallet - Assets</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
        body { background: #0b0e11; color: white; font-family: 'Plus Jakarta Sans', sans-serif; padding-bottom: 100px; }
        .glass-panel { background: #161a21; border: 1px solid rgba(255,255,255,0.05); }
        .tab-active { background: #2fb474; color: black; font-weight: 800; border: none; }
        .input-dark { background: #0b0e11; border: 1px solid #2d3648; color: white; outline: none; }
        .input-dark:focus { border-color: #2fb474; }
    </style>
</head>
<body class="p-4">

    <div class="max-w-md mx-auto">
        <div class="glass-panel p-6 rounded-[32px] mb-8 relative overflow-hidden">
            <p class="text-[10px] text-gray-500 uppercase font-black tracking-widest">Total Assets</p>
            <h2 class="text-4xl font-black text-[#2fb474] mt-1">$<?php echo number_format($user_balance, 2); ?></h2>
            <div class="mt-4 flex space-x-2">
                <span class="text-[9px] bg-[#2fb474]/10 text-[#2fb474] px-2 py-1 rounded-md font-bold uppercase tracking-tighter italic">Secured Wallet</span>
            </div>
            <i class="fas fa-coins absolute -bottom-4 -right-4 text-7xl text-white/5 transform rotate-12"></i>
        </div>

        <?php if($msg) echo "<div class='bg-[#2fb474]/10 text-[#2fb474] p-4 rounded-2xl mb-6 text-xs font-bold border border-[#2fb474]/20 text-center uppercase'>$msg</div>"; ?>
        <?php if($error) echo "<div class='bg-red-500/10 text-red-500 p-4 rounded-2xl mb-6 text-xs font-bold border border-red-500/20 text-center uppercase'>$error</div>"; ?>

        <div class="flex space-x-2 mb-8 bg-[#161a21] p-1.5 rounded-2xl border border-white/5">
            <button onclick="switchTab('deposit')" id="dep-btn" class="tab-active flex-1 py-3 rounded-xl text-[10px] uppercase font-black tracking-widest">Deposit</button>
            <button onclick="switchTab('withdraw')" id="wd-btn" class="flex-1 py-3 rounded-xl text-[10px] text-gray-500 uppercase font-black tracking-widest">Withdraw</button>
        </div>

        <div id="deposit-sec" class="space-y-6">
            <div class="glass-panel p-6 rounded-[32px]">
                <label class="text-[10px] font-black text-gray-500 uppercase ml-1">Payment Method</label>
                <select id="dep-method" onchange="updateDepDetails()" class="input-dark w-full p-4 rounded-2xl mt-2 font-bold text-sm">
                    <?php foreach($active_methods as $m): ?>
                        <option value="<?php echo $m['method_name']; ?>" data-address="<?php echo $m['address']; ?>" data-rate="<?php echo $m['rate']; ?>">
                            <?php echo strtoupper($m['method_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <div class="mt-6 p-4 bg-black/40 rounded-2xl border border-white/5">
                    <p class="text-[9px] text-[#2fb474] uppercase font-black mb-2">Target Address</p>
                    <div class="flex items-center justify-between">
                        <p id="target-number" class="text-sm font-mono truncate mr-2">---</p>
                        <button onclick="copyAddr()" class="bg-[#2fb474] text-black px-3 py-1.5 rounded-lg text-[9px] font-black uppercase">Copy</button>
                    </div>
                </div>

                <form method="POST" class="mt-6 space-y-4">
                    <input type="hidden" name="method" id="form-method-dep">
                    <input type="number" name="amount" id="dep-amount" oninput="calcDep()" placeholder="Deposit Amount ($)" step="0.01" required class="input-dark w-full p-4 rounded-2xl text-lg font-black">
                    <p id="total-pay" class="text-[10px] text-yellow-500 font-bold uppercase text-right tracking-tighter"></p>
                    <input type="text" name="transaction_id" placeholder="Enter Transaction ID" required class="input-dark w-full p-4 rounded-2xl font-mono text-sm uppercase">
                    <button type="submit" name="submit_deposit" class="w-full bg-[#2fb474] text-black font-black py-4 rounded-2xl uppercase tracking-widest mt-2 active:scale-95 transition">Submit Payment</button>
                </form>
            </div>
        </div>

        <div id="withdraw-sec" class="hidden space-y-6">
            <div class="glass-panel p-6 rounded-[32px]">
                <form method="POST" class="space-y-4">
                    <label class="text-[10px] font-black text-gray-500 uppercase ml-1">Withdraw Gateway</label>
                    <select name="method" class="input-dark w-full p-4 rounded-2xl font-bold text-sm">
                        <?php foreach($active_methods as $m): ?>
                            <option value="<?php echo $m['method_name']; ?>"><?php echo strtoupper($m['method_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input type="number" name="amount" placeholder="Withdraw Amount ($)" step="0.01" required class="input-dark w-full p-4 rounded-2xl text-lg font-black">
                    <input type="text" name="address" placeholder="Your Wallet / Number" required class="input-dark w-full p-4 rounded-2xl font-mono text-sm">
                    <button type="submit" name="submit_withdraw" class="w-full bg-white text-black font-black py-4 rounded-2xl uppercase tracking-widest mt-2 active:scale-95 transition">Withdraw Now</button>
                </form>
            </div>
        </div>
    </div>

    <?php include 'navbar.php'; ?>

    <script>
        function switchTab(t) {
            document.getElementById('deposit-sec').classList.toggle('hidden', t !== 'deposit');
            document.getElementById('withdraw-sec').classList.toggle('hidden', t !== 'withdraw');
            document.getElementById('dep-btn').classList.toggle('tab-active', t === 'deposit');
            document.getElementById('wd-btn').classList.toggle('tab-active', t === 'withdraw');
            if(t === 'withdraw') document.getElementById('dep-btn').classList.add('text-gray-500');
            else document.getElementById('wd-btn').classList.add('text-gray-500');
        }

        function updateDepDetails() {
            const s = document.getElementById('dep-method');
            if(!s.options[s.selectedIndex]) return;
            const o = s.options[s.selectedIndex];
            document.getElementById('target-number').innerText = o.getAttribute('data-address');
            document.getElementById('form-method-dep').value = s.value;
            calcDep();
        }

        function calcDep() {
            const a = document.getElementById('dep-amount').value;
            const s = document.getElementById('dep-method');
            if(!s.options[s.selectedIndex]) return;
            const r = s.options[s.selectedIndex].getAttribute('data-rate');
            document.getElementById('total-pay').innerText = a > 0 ? "You need to pay: " + (a * r).toFixed(2) + " Units" : "";
        }

        function copyAddr() {
            const text = document.getElementById('target-number').innerText;
            navigator.clipboard.writeText(text).then(() => alert('Copied: ' + text));
        }
        window.onload = updateDepDetails;
    </script>
</body>
</html>