<?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'];

    // ১. অ্যাডমিন সেটিংস থেকে মেথডগুলো আনা
    $method_query = $db->query("SELECT * FROM payment_methods WHERE status = 1");
    $active_methods = $method_query->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! Verification in progress.";
        } else { $error = "Min deposit is $0.5"; }
    }

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

        if ($user_balance >= $amount && $amount >= 1) {
            $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]);
            $msg = "Withdrawal request submitted successfully!";
        } else { $error = "Insufficient balance or invalid amount!"; }
    }

} catch (PDOException $e) { die("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</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-color: #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 !important; }
        .input-dark { background: #0b0e11; border: 1px solid #2d3648; color: white; outline: none; }
        .input-dark:focus { border-color: #2fb474; }
        /* ড্রপডাউন ফোনের নেটিভ মেনু ডার্ক করার চেষ্টা */
        select option { background: #161a21; color: white; }
    </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">Active Node</span>
            </div>
            <i class="fas fa-shield-alt 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 tracking-widest transition-all">Deposit</button>
            <button onclick="switchTab('withdraw')" id="wd-btn" class="flex-1 py-3 rounded-xl text-[10px] text-gray-500 uppercase tracking-widest transition-all">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 tracking-widest ml-1">Select Network</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-5 bg-[#2fb474]/5 border border-[#2fb474]/10 rounded-2xl">
                    <p class="text-[9px] text-[#2fb474] uppercase font-black tracking-[2px]">Deposit Address</p>
                    <div class="flex items-center justify-between mt-2">
                        <p id="target-number" class="text-[13px] font-mono font-bold text-white truncate mr-2">---</p>
                        <button onclick="copyAddr()" class="bg-[#2fb474] text-black px-3 py-1.5 rounded-lg text-[9px] font-black uppercase whitespace-nowrap">
                            Copy <i class="fas fa-copy ml-1"></i>
                        </button>
                    </div>
                </div>

                <form method="POST" class="mt-6 space-y-4">
                    <input type="hidden" name="method" id="form-method-dep">
                    <div>
                        <label class="text-[10px] font-black text-gray-500 uppercase tracking-widest ml-1">Amount ($)</label>
                        <input type="number" name="amount" id="dep-amount" oninput="calcDep()" placeholder="Min $0.5" step="0.01" required class="input-dark w-full p-4 rounded-2xl mt-1 text-lg font-black">
                        <p id="total-pay" class="text-[10px] text-yellow-500 mt-2 font-black uppercase text-right tracking-tighter"></p>
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-500 uppercase tracking-widest ml-1">Transaction ID</label>
                        <input type="text" name="transaction_id" placeholder="Enter TxID / TrxID" required class="input-dark w-full p-4 rounded-2xl mt-1 font-mono uppercase text-sm">
                    </div>
                    <button type="submit" name="submit_deposit" class="w-full bg-[#2fb474] text-black font-black py-4 rounded-2xl uppercase tracking-widest mt-4 shadow-lg shadow-[#2fb474]/20 active:scale-95 transition">Confirm Deposit</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">
                    <div>
                        <label class="text-[10px] font-black text-gray-500 uppercase tracking-widest ml-1">Withdraw Method</label>
                        <select name="method" 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']; ?>"><?php echo strtoupper($m['method_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-500 uppercase tracking-widest ml-1">Withdraw Amount ($)</label>
                        <input type="number" name="amount" placeholder="Min $1" step="0.01" required class="input-dark w-full p-4 rounded-2xl mt-1 text-lg font-black">
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-500 uppercase tracking-widest ml-1">Your Wallet / Number</label>
                        <input type="text" name="address" placeholder="Address or Number" required class="input-dark w-full p-4 rounded-2xl mt-1 font-mono text-sm">
                    </div>
                    <button type="submit" name="submit_withdraw" class="w-full bg-white text-black font-black py-4 rounded-2xl uppercase tracking-widest mt-4 active:scale-95 transition">Execute Withdraw</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        function switchTab(type) {
            const depBtn = document.getElementById('dep-btn');
            const wdBtn = document.getElementById('wd-btn');
            const depSec = document.getElementById('deposit-sec');
            const wdSec = document.getElementById('withdraw-sec');

            if(type === 'deposit') {
                depSec.classList.remove('hidden');
                wdSec.classList.add('hidden');
                depBtn.classList.add('tab-active');
                wdBtn.classList.remove('tab-active');
                wdBtn.classList.add('text-gray-500');
            } else {
                wdSec.classList.remove('hidden');
                depSec.classList.add('hidden');
                wdBtn.classList.add('tab-active');
                wdBtn.classList.remove('text-gray-500');
                depBtn.classList.remove('tab-active');
                depBtn.classList.add('text-gray-500');
            }
        }

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

        function copyAddr() {
            const text = document.getElementById('target-number').innerText;
            navigator.clipboard.writeText(text).then(() => {
                alert('Copied to Clipboard!');
            });
        }

        function calcDep() {
            const amount = document.getElementById('dep-amount').value;
            const select = document.getElementById('dep-method');
            if(!select.options[select.selectedIndex]) return;

            const rate = select.options[select.selectedIndex].getAttribute('data-rate');
            const display = document.getElementById('total-pay');

            if(amount > 0) {
                const total = (amount * rate).toLocaleString();
                display.innerText = "Send Exactly: " + total + " Units/BDT";
            } else { display.innerText = ""; }
        }

        window.onload = updateDepDetails;
    </script>
</body>
</html>