<?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);
    
    // ইউজারের ব্যালেন্স চেক
    $stmt = $db->prepare("SELECT main_balance FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user_balance = $stmt->fetchColumn();

    $msg = "";
    $rate = 130; // $1 = 130 BDT

    // ডিপোজিট রিকোয়েস্ট হ্যান্ডলিং
    if (isset($_POST['submit_deposit'])) {
        $amount = $_POST['amount'];
        $method = $_POST['method'];
        $tid = $_POST['transaction_id'];

        $ins = $db->prepare("INSERT INTO deposits (user_id, amount, method, status, created_at) VALUES (?, ?, ?, 'Pending', datetime('now'))");
        $ins->execute([$_SESSION['user_id'], $amount, "$method (TID: $tid)"]);
        $msg = "Deposit request submitted! Wait for approval.";
    }

    // উইথড্র রিকোয়েস্ট হ্যান্ডলিং
    if (isset($_POST['submit_withdraw'])) {
        $amount = $_POST['amount'];
        $method = $_POST['method'];
        $address = $_POST['address'];

        if ($user_balance >= $amount && $amount >= 1) {
            $ins = $db->prepare("INSERT INTO withdrawals (user_id, amount, status, created_at) VALUES (?, ?, 'Pending', datetime('now'))");
            $ins->execute([$_SESSION['user_id'], $amount]);
            $msg = "Withdrawal request submitted!";
        } else {
            $msg = "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">
    <title>Ziber - Transactions</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background-color: #0b0e11; color: white; font-family: 'Inter', sans-serif; }
        .glass-box { background: #161a21; border: 1px solid rgba(255,255,255,0.05); }
        .tab-btn.active { background: #2fb474; color: black; }
        .input-box { background: #0b0e11; border: 1px solid #2d3648; color: white; }
    </style>
</head>
<body class="p-6">

    <div class="max-w-md mx-auto">
        <h2 class="text-2xl font-bold mb-8 text-center uppercase tracking-tighter">Ziber Wallet</h2>

        <?php if($msg) echo "<div class='bg-green-600/20 text-green-500 p-4 rounded-xl mb-6 text-center text-sm font-bold border border-green-500/20'>$msg</div>"; ?>

        <div class="flex space-x-2 mb-8 bg-[#161a21] p-1 rounded-2xl">
            <button onclick="switchTab('deposit')" id="dep-btn" class="tab-btn active flex-1 py-3 rounded-xl font-bold text-sm transition">DEPOSIT</button>
            <button onclick="switchTab('withdraw')" id="wd-btn" class="tab-btn flex-1 py-3 rounded-xl font-bold text-sm text-gray-400 transition">WITHDRAW</button>
        </div>

        <div id="deposit-sec" class="space-y-6">
            <div class="glass-box p-6 rounded-3xl">
                <label class="text-xs font-bold text-gray-500 uppercase">Select Method</label>
                <select id="dep-method" onchange="updateDetails()" class="input-box w-full p-4 rounded-xl mt-2 outline-none">
                    <option value="Bkash">Bkash Personal</option>
                    <option value="Nagad">Nagad Personal</option>
                    <option value="Binance">Binance (USDT TRC20)</option>
                </select>

                <div id="payment-info" class="mt-6 p-4 bg-green-500/10 border border-green-500/20 rounded-xl">
                    <p class="text-xs text-green-500 uppercase font-bold">Send Money to:</p>
                    <p id="target-number" class="text-lg font-black mt-1">017XXXXXXXX</p>
                    <p class="text-[10px] text-gray-400 mt-2 italic">* $1 = <?php echo $rate; ?> BDT. Send the exact amount.</p>
                </div>

                <form method="POST" class="mt-6 space-y-4">
                    <input type="hidden" name="method" id="form-method" value="Bkash">
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase">Amount ($)</label>
                        <input type="number" name="amount" id="dep-amount" oninput="calcTotal()" placeholder="Min $1" required class="input-box w-full p-4 rounded-xl mt-1">
                        <p id="total-pay" class="text-[10px] text-yellow-500 mt-2 font-bold uppercase"></p>
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase">Transaction ID</label>
                        <input type="text" name="transaction_id" placeholder="Enter TrxID" required class="input-box w-full p-4 rounded-xl mt-1">
                    </div>
                    <button type="submit" name="submit_deposit" class="w-full bg-[#2fb474] text-black font-black py-4 rounded-xl uppercase tracking-widest mt-4">Submit Deposit</button>
                </form>
            </div>
        </div>

        <div id="withdraw-sec" class="hidden space-y-6">
            <div class="glass-box p-6 rounded-3xl">
                <p class="text-center text-gray-500 text-sm mb-4">Available: <span class="text-white font-bold">$<?php echo number_format($user_balance, 2); ?></span></p>
                
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase">Select Method</label>
                        <select name="method" class="input-box w-full p-4 rounded-xl mt-2 outline-none">
                            <option value="Bkash">Bkash</option>
                            <option value="Nagad">Nagad</option>
                            <option value="Binance">Binance (USDT)</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase">Withdraw Amount ($)</label>
                        <input type="number" name="amount" placeholder="Min $5" required class="input-box w-full p-4 rounded-xl mt-1">
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase">Wallet Address / Number</label>
                        <input type="text" name="address" placeholder="Enter Number/Address" required class="input-box w-full p-4 rounded-xl mt-1">
                    </div>
                    <button type="submit" name="submit_withdraw" class="w-full bg-white text-black font-black py-4 rounded-xl uppercase tracking-widest mt-4">Confirm Withdraw</button>
                </form>
            </div>
        </div>
    </div>

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

    <script>
        function switchTab(type) {
            if(type === 'deposit') {
                document.getElementById('deposit-sec').classList.remove('hidden');
                document.getElementById('withdraw-sec').classList.add('hidden');
                document.getElementById('dep-btn').classList.add('active');
                document.getElementById('wd-btn').classList.remove('active');
            } else {
                document.getElementById('deposit-sec').classList.add('hidden');
                document.getElementById('withdraw-sec').classList.remove('hidden');
                document.getElementById('wd-btn').classList.add('active');
                document.getElementById('dep-btn').classList.remove('active');
            }
        }

        function updateDetails() {
            const method = document.getElementById('dep-method').value;
            const target = document.getElementById('target-number');
            document.getElementById('form-method').value = method;

            if(method === 'Bkash') target.innerText = '01700000000'; // আপনার বিকাশ নাম্বার
            else if(method === 'Nagad') target.innerText = '01900000000'; // আপনার নগদ নাম্বার
            else target.innerText = 'TYK4xP...yourTRC20address'; // আপনার বাইনেন্স এড্রেস
            
            calcTotal();
        }

        function calcTotal() {
            const amount = document.getElementById('dep-amount').value;
            const rate = <?php echo $rate; ?>;
            const method = document.getElementById('dep-method').value;
            const display = document.getElementById('total-pay');

            if(amount > 0) {
                if(method === 'Binance') {
                    display.innerText = "Total to Pay: " + amount + " USDT";
                } else {
                    display.innerText = "Total to Pay: ৳" + (amount * rate);
                }
            } else {
                display.innerText = "";
            }
        }
    </script>
</body>
</html>