<?php
include 'db.php';
include 'bot.php'; // Telegram Bot Connection

session_start(); // Session Start is must for this flow

// --- AJAX: Check Promo Code ---
if(isset($_POST['action']) && $_POST['action'] == 'check_promo') {
    header('Content-Type: application/json');
    $code = $_POST['code'];
    $stmt = $conn->prepare("SELECT * FROM promos WHERE code=?");
    $stmt->execute([$code]);
    $res = $stmt->fetch();
    
    if($res) {
        if($res['used_count'] < $res['usage_limit']) {
            echo json_encode(['status'=>'success', 'discount'=>$res['discount']]);
        } else {
            echo json_encode(['status'=>'error', 'message'=>'Promo limit exceeded!']);
        }
    } else {
        echo json_encode(['status'=>'error', 'message'=>'Invalid Promo Code!']);
    }
    exit;
}

// --- INITIALIZE PAYMENT (Redirect Logic) ---
if(isset($_POST['init_payment'])) {
    // Save payment data to session
    $_SESSION['pay_data'] = [
        'type' => $_POST['type'], // 'order' or 'deposit'
        'amount' => $_POST['amount'],
        'method' => $_POST['method'],
        // Order specific
        'pname' => $_POST['pname'] ?? null,
        'vid' => $_POST['vid'] ?? null,
        'promo' => $_POST['promo'] ?? null,
        // Deposit specific
        'redeem_code' => $_POST['redeem_code'] ?? null
    ];
    header("Location: ?page=pay");
    exit;
}

$page = $_GET['page'] ?? 'home';

// Variables
$pTitle = ""; $pMsg = ""; $showProfileBtn = false;

// Logout
if(isset($_GET['logout'])) { session_destroy(); header("Location: index.php"); exit; }

// Login & Register Logic
if(isset($_POST['login'])) {
    $u = $conn->prepare("SELECT * FROM users WHERE phone=?"); $u->execute([$_POST['phone']]); $user=$u->fetch();
    if($user && password_verify($_POST['pass'], $user['password'])) { $_SESSION['uid']=$user['id']; header("Location: index.php"); }
    else { $pTitle="Error"; $pMsg="Invalid Phone or Password!"; }
}
if(isset($_POST['reg'])) {
    try {
        $ref = bin2hex(random_bytes(3));
        $conn->prepare("INSERT INTO users (name, phone, password, ref_code, referred_by) VALUES (?,?,?,?,?)")
             ->execute([$_POST['name'], $_POST['phone'], password_hash($_POST['pass'], PASSWORD_DEFAULT), $ref, $_POST['ref_by']]);
        $pTitle="Success"; $pMsg="Account created! Please Login.";
    } catch(Exception $e) { $pTitle="Error"; $pMsg="Phone number already registered!"; }
}

$me = null;
if(isset($_SESSION['uid'])) $me = $conn->query("SELECT * FROM users WHERE id=".$_SESSION['uid'])->fetch();

// --- FINAL PAYMENT PROCESSING ---
if(isset($_POST['confirm_payment']) && $me) {
    $data = $_SESSION['pay_data'] ?? null;
    if(!$data) { header("Location: ?page=home"); exit; }

    $trx = $_POST['trx'];
    $success = false;

    // 1. ORDER PROCESSING
    if($data['type'] == 'order') {
        $price = $data['amount'];
        $method = $data['method'];
        
        // Fetch variant name for record
        $var = $conn->query("SELECT * FROM variants WHERE id=".$data['vid'])->fetch();

        if($method == 'Balance') {
            if($me['balance'] >= $price) {
                $conn->query("UPDATE users SET balance=balance-$price WHERE id={$me['id']}");
                $conn->prepare("INSERT INTO orders (user_id, product_name, variant_name, price, method, status) VALUES (?,?,?,?,?,?)")
                     ->execute([$me['id'], $data['pname'], $var['name'], $price, 'Balance', 'Pending']);
                $success = true;
            } else { $pTitle="Failed"; $pMsg="Insufficient Balance!"; }
        } else {
            // Gateway Order
            if(empty($trx)) { $pTitle="Error"; $pMsg="Transaction ID required!"; }
            else {
                $conn->prepare("INSERT INTO orders (user_id, product_name, variant_name, price, method, trx_id) VALUES (?,?,?,?,?,?)")
                     ->execute([$me['id'], $data['pname'], $var['name'], $price, $method, $trx]);
                $success = true;
            }
        }

        if($success) {
             // Update Promo
             if(!empty($data['promo'])) {
                 $conn->prepare("UPDATE promos SET used_count = used_count + 1 WHERE code=?")->execute([$data['promo']]);
             }
             // Telegram
             $msg = "<b>📦 NEW ORDER RECEIVED!</b>\n👤 User: {$me['name']} ({$me['phone']})\n🛒 Item: {$data['pname']} - {$var['name']}\n💰 Price: $ {$price}\n💳 Method: {$method}\n";
             if($method != 'Balance') $msg .= "🔢 TrxID: {$trx}\n";
             sendNotification($msg);

             $pTitle = "Success"; $pMsg = "Order Placed Successfully!"; $showProfileBtn = true;
             unset($_SESSION['pay_data']); // Clear session
        }
    } 
    // 2. DEPOSIT PROCESSING
    elseif($data['type'] == 'deposit') {
        if($data['method'] == 'Redeem Code') {
             // Logic handled in previous step or direct check here if needed, but usually redeem is instant. 
             // If we arrived here via 'pay' page, it implies Manual Deposit usually.
             // But if you want Redeem via Pay page, we need logic. Assuming Manual for 'pay' page mostly.
        } else {
            if(empty($trx)) { $pTitle="Error"; $pMsg="Transaction ID required!"; }
            else {
                $conn->prepare("INSERT INTO deposits (user_id, method, amount, trx_id) VALUES (?,?,?,?)")
                     ->execute([$me['id'], $data['method'], $data['amount'], $trx]);
                
                // Telegram
                $msg = "<b>💰 NEW DEPOSIT REQUEST!</b>\n👤 User: {$me['name']} ({$me['phone']})\n🏦 Method: {$data['method']}\n💵 Amount: $ {$data['amount']}\n🔢 TrxID: {$trx}\n";
                sendNotification($msg);

                $pTitle="Submitted"; $pMsg="Deposit request sent to admin."; $showProfileBtn = true;
                unset($_SESSION['pay_data']);
            }
        }
    }
}

// --- Spin Logic ---
$spinAllowed = false; $timeLeft = "";
if($me) {
    $last = $me['last_spin_time'];
    if(!$last) { $spinAllowed = true; } 
    else {
        $diff = (new DateTime())->diff(new DateTime($last));
        if($diff->days < 1) {
            $target = (new DateTime($last))->modify('+1 day');
            $timeLeft = (new DateTime())->diff($target)->format('%h Hours %i Minutes');
            $spinAllowed = false;
        } else { $spinAllowed = true; }
    }
}
if(isset($_POST['spin']) && $me) {
    if($spinAllowed) {
        $win = mt_rand(1, 50) / 10; 
        $conn->query("UPDATE users SET balance=balance+$win, last_spin_time=NOW() WHERE id={$me['id']}");
        $me['balance'] += $win; $spinRes = $win; $spinAllowed = false; $timeLeft = "23 Hours 59 Minutes"; 
    } else { $pTitle="Sorry"; $pMsg="Please wait $timeLeft for next spin!"; }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Shop</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --bg: #0f172a; --card: #1e293b; --text: #ffffff; --primary: #e11d48; --bkash: #e2136e; --nagad: #ec1c24; }
        body { margin:0; background:var(--bg); color:var(--text); font-family:'Segoe UI', sans-serif; padding-bottom:70px; }
        
        .header { background:var(--card); padding:15px; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #333; }
        .user-avatar { width:45px; height:45px; border-radius:50%; background:#333; display:flex; align-items:center; justify-content:center; border:2px solid var(--primary); font-size:20px; }
        .bal-trigger { font-size:12px; color:var(--primary); cursor:pointer; background:rgba(225,29,72,0.1); padding:2px 8px; border-radius:10px; margin-top:2px; display:inline-block; }
        .bal-amt { font-weight:bold; color:#4ade80; display:none; animation:fadeIn 0.5s; }
        @keyframes fadeIn { from{opacity:0;} to{opacity:1;} }
        
        .grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:10px; padding:15px; }
        .card { background:var(--card); border-radius:12px; padding:10px; text-align:center; overflow:hidden; }
        .card img { width:100%; aspect-ratio:1/1; object-fit:cover; border-radius:8px; }
        .btn { background:var(--primary); color:white; border:none; padding:12px; width:100%; border-radius:8px; margin-top:10px; font-weight:bold; cursor:pointer; }
        input, select { width:100%; padding:12px; background:#334155; border:1px solid #475569; border-radius:8px; color:white; margin:5px 0; box-sizing:border-box; }
        .hidden { display:none !important; }

        .modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); align-items:center; justify-content:center; z-index:100; overflow-y: auto; }
        .modal-box { background:white; color:#333; padding:15px; border-radius:15px; width:90%; max-width:350px; text-align:center; position:relative; }
        .close-btn { position:absolute; top:10px; right:15px; font-size:20px; cursor:pointer; color:#666; z-index: 101;}

        /* --- Payment Gateway Design --- */
        .gateway-container { width: 95%; max-width: 400px; margin: 20px auto; border-radius: 15px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.3); }
        .gateway-header { background: #fff; padding: 20px; font-size: 24px; font-weight: bold; color: #333; text-align: center; border-bottom: 1px solid #eee; }
        .gateway-body { padding: 30px 20px; color: white; text-align: left; }
        .bkash-theme .gateway-body { background: var(--bkash); }
        .nagad-theme .gateway-body { background: var(--nagad); }
        .gateway-input { background: white; border: none; padding: 15px; border-radius: 8px; width: 100%; margin-top: 10px; color: #333; font-size: 16px; text-align: center; }
        .gateway-btn { width: 100%; padding: 15px; border: none; border-radius: 8px; font-size: 18px; font-weight: bold; margin-top: 25px; cursor: pointer; background: rgba(0,0,0,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); transition: 0.3s; }
        .gateway-btn:hover { background: rgba(0,0,0,0.4); }
        .back-btn { width: 100%; padding: 12px; margin-top: 10px; background: transparent; color: rgba(255,255,255,0.8); border: none; cursor: pointer; font-size: 14px; text-decoration: underline; }

        .instruction-list { list-style: none; padding: 0; margin: 20px 0; font-size: 14px; line-height: 1.8; }
        .instruction-list li { margin-bottom: 10px; position: relative; padding-left: 20px; }
        .instruction-list li::before { content: '•'; position: absolute; left: 0; font-weight: bold; font-size: 20px; }
        .copy-box { background: rgba(0,0,0,0.15); padding: 5px 12px; border-radius: 6px; display: inline-flex; align-items: center; gap: 8px; cursor: pointer; border: 1px dashed rgba(255,255,255,0.4); font-weight: bold; font-size: 16px; margin-top: 5px; }
        
        /* Custom Toast */
        .toast-msg { visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: center; border-radius: 5px; padding: 16px; position: fixed; z-index: 1000; left: 50%; bottom: 30px; transform: translateX(-50%); font-size: 15px; box-shadow: 0 4px 10px rgba(0,0,0,0.5); opacity: 0; transition: opacity 0.5s, bottom 0.5s; }
        .toast-msg.show { visibility: visible; opacity: 1; bottom: 50px; }

        .nav { position:fixed; bottom:0; width:100%; background:var(--card); display:flex; justify-content:space-around; padding:12px 0; border-top:1px solid #333; z-index:50; }
        .nav a { color:#94a3b8; text-decoration:none; text-align:center; font-size:11px; }
        .nav a.active { color:var(--primary); }
        .nav i { font-size:20px; display:block; margin-bottom:4px; }
        .status-Completed, .status-Approved { color:#4ade80; } .status-Pending { color:#facc15; } .status-Rejected { color:#f87171; }

        /* Spin Wheel */
        .wheel-container { position:relative; width:280px; height:280px; margin:30px auto; }
        .wheel { width: 100%; height: 100%; border-radius: 50%; border: 4px solid #fff; position: relative; background: conic-gradient(#ef4444 0% 12.5%, #f97316 12.5% 25%, #eab308 25% 37.5%, #22c55e 37.5% 50%, #06b6d4 50% 62.5%, #3b82f6 62.5% 75%, #a855f7 75% 87.5%, #ec4899 87.5% 100%); transition: transform 4s cubic-bezier(0.25, 1, 0.5, 1); box-shadow: 0 0 15px rgba(0,0,0,0.5); }
        .marker { position:absolute; top:-20px; left:50%; transform:translateX(-50%); width:0; height:0; border-left: 15px solid transparent; border-right: 15px solid transparent; border-top: 30px solid white; z-index:10; }
        .wheel-item { position: absolute; top: 50%; left: 50%; width: 40px; height: 40px; font-size: 24px; display: flex; align-items: center; justify-content: center; transform: translate(-50%, -50%) rotate(calc(var(--i) * 45deg + 22.5deg)) translateY(-90px) rotate(calc((var(--i) * 45deg + 22.5deg) * -1)); }
    </style>
</head>
<body>
    
    <!-- Custom Toast -->
    <div id="toast" class="toast-msg">Number Copied!</div>

    <!-- Popup Msg -->
    <div id="popup" class="modal">
        <div class="modal-box">
            <h2 id="pTitle" style="color:var(--primary)"></h2>
            <p id="pMsg" style="margin-bottom:20px;"></p>
            <?php if($showProfileBtn): ?><button onclick="window.location='?page=profile'" class="btn" style="background:#059669; margin-bottom:5px;">Go to Profile</button><?php endif; ?>
            <button onclick="document.getElementById('popup').style.display='none'" class="btn" style="background:#333;">Close</button>
        </div>
    </div>

    <?php if(!$me): ?>
        <!-- Login & Registration (Hidden for brevity, same as before) -->
        <div style="padding:30px; text-align:center; margin-top:50px;">
            <h1 style="color:var(--primary)">PANEL SHOP</h1>
            <div id="loginForm">
                <form method="post"><input name="phone" placeholder="Phone Number" required><input type="password" name="pass" placeholder="Password" required><button name="login" class="btn">Login</button></form>
                <p style="margin-top:20px; color:#94a3b8;">Don't have an account? <span onclick="toggleAuth('reg')" style="color:var(--primary); cursor:pointer; font-weight:bold;">Register</span></p>
            </div>
            <div id="regForm" class="hidden">
                <form method="post"><input name="name" placeholder="Full Name" required><input name="phone" placeholder="Phone Number" required><input type="password" name="pass" placeholder="Password" required><input name="ref_by" placeholder="Referral Code (Optional)"><button name="reg" class="btn">Create Account</button></form>
                <p style="margin-top:20px; color:#94a3b8;">Already have an account? <span onclick="toggleAuth('login')" style="color:var(--primary); cursor:pointer; font-weight:bold;">Back to Login</span></p>
            </div>
        </div>
        <script>function toggleAuth(t){document.getElementById(t==='reg'?'loginForm':'regForm').classList.add('hidden');document.getElementById(t==='reg'?'regForm':'loginForm').classList.remove('hidden');}</script>
    <?php else: ?>

    <!-- Header -->
    <?php if($page != 'pay'): ?>
    <div class="header">
        <div style="display:flex; align-items:center; gap:10px;">
            <div class="user-avatar"><i class="fas fa-user"></i></div>
            <div>
                <b style="font-size:16px;"><?php echo $me['name']; ?></b><br>
                <span class="bal-trigger" id="balBtn" onclick="toggleBalance()"><i class="fas fa-wallet"></i> Tap to View</span>
                <span class="bal-amt" id="balAmt">$ <?php echo number_format($me['balance'], 2); ?></span>
            </div>
        </div>
        <a href="?logout=true" style="color:#f87171; font-size:20px;"><i class="fas fa-sign-out-alt"></i></a>
    </div>
    <?php endif; ?>

    <div style="padding-bottom:20px;">
        <?php if($page == 'home'): ?>
            <div class="grid">
                <?php $p=$conn->query("SELECT * FROM products"); while($row=$p->fetch()): ?>
                <div class="card" onclick="window.location='?page=view&id=<?php echo $row['id']; ?>'">
                    <img src="uploads/<?php echo $row['image']; ?>">
                    <div style="margin-top:8px; font-size:13px; font-weight:bold;"><?php echo $row['name']; ?></div>
                </div>
                <?php endwhile; ?>
            </div>

        <?php elseif($page == 'view'): $prod = $conn->query("SELECT * FROM products WHERE id=".$_GET['id'])->fetch(); ?>
            <div style="padding:20px;">
                <h2 style="text-align:center; margin-bottom:20px;"><?php echo $prod['name']; ?></h2>
                <div style="background:var(--card); padding:20px; border-radius:15px;">
                    <label>Select Package</label>
                    <select id="varSelect">
                        <?php $v=$conn->query("SELECT * FROM variants WHERE product_id=".$prod['id']); 
                        while($r=$v->fetch()) echo "<option value='{$r['id']}' data-name='{$r['name']}' data-price='{$r['price']}'>{$r['name']} - $ {$r['price']}</option>"; ?>
                    </select>
                    <button class="btn" onclick="openPaymentModal()">Pay Now</button>
                </div>
            </div>

            <!-- Order Modal -->
            <div id="paymentModal" class="modal">
                <div class="modal-box">
                    <span class="close-btn" onclick="document.getElementById('paymentModal').style.display='none'">&times;</span>
                    
                    <h3 style="margin-top:0; color:var(--primary);">Confirm Order</h3>
                    <p>Package: <b id="dispName"></b></p>
                    <p>Price: <b style="color:var(--primary)">$ <span id="dispPrice"></span></b></p>
                    
                    <div style="font-size:12px; color:var(--primary); cursor:pointer; margin-bottom:5px;" onclick="document.getElementById('promoSection').classList.toggle('hidden')">Do you have Promo Code?</div>
                    <div id="promoSection" class="hidden">
                        <div class="promo-wrapper"><input id="promoInput" placeholder="Enter Code"><button type="button" class="apply-btn" onclick="applyPromo()">Apply</button></div>
                        <small id="promoMsg" style="display:block; margin-bottom:5px;"></small>
                    </div>
                    <div id="priceSummary" class="price-summary" style="display:none;"><div>Discount: <b id="discountAmt">$0</b></div><div>Total: <b id="finalPayable"></b></div></div>

                    <label>Select Payment Method</label>
                    <select id="payMethod">
                        <option value="Balance">My Balance ($ <?php echo $me['balance']; ?>)</option>
                        <option value="Bkash">Bkash</option>
                        <option value="Nagad">Nagad</option>
                    </select>
                    <button class="btn" onclick="proceedToPay()">Next Step</button>
                </div>
            </div>
            
            <script>
                let originalPrice = 0, currentPrice = 0, promoCode = "";
                function openPaymentModal() {
                    let sel = document.getElementById('varSelect'); let opt = sel.options[sel.selectedIndex];
                    document.getElementById('dispName').innerText = opt.getAttribute('data-name');
                    originalPrice = parseFloat(opt.getAttribute('data-price')); currentPrice = originalPrice;
                    document.getElementById('dispPrice').innerText = originalPrice;
                    document.getElementById('paymentModal').style.display = 'flex';
                }
                function applyPromo() {
                    let code = document.getElementById('promoInput').value; let msg = document.getElementById('promoMsg');
                    if(!code) return;
                    let formData = new FormData(); formData.append('action', 'check_promo'); formData.append('code', code);
                    fetch('index.php', { method: 'POST', body: formData }).then(r => r.json()).then(d => {
                        if(d.status === 'success') {
                            let discount = parseFloat(d.discount); currentPrice = originalPrice - discount; if(currentPrice < 0) currentPrice = 0;
                            msg.innerText = "Applied!"; msg.style.color = "green";
                            document.getElementById('priceSummary').style.display = 'block'; document.getElementById('discountAmt').innerText = "- $ " + discount; document.getElementById('finalPayable').innerText = "$ " + currentPrice;
                            promoCode = code;
                        } else { msg.innerText = d.message; msg.style.color = "red"; }
                    });
                }
                function proceedToPay() {
                    let method = document.getElementById('payMethod').value;
                    let sel = document.getElementById('varSelect'); let vid = sel.value;
                    
                    // Post form to redirect to pay page
                    let f = document.createElement('form'); f.method = 'POST';
                    
                    // For balance, we can process directly or via confirm.
                    // For consistency, let's send everything to INIT Logic
                    if(method === 'Balance') {
                        if(!confirm("Pay with Balance?")) return;
                    }

                    f.innerHTML = `
                        <input type="hidden" name="init_payment" value="1">
                        <input type="hidden" name="type" value="order">
                        <input type="hidden" name="pname" value="<?php echo $prod['name']; ?>">
                        <input type="hidden" name="vid" value="${vid}">
                        <input type="hidden" name="amount" value="${currentPrice}">
                        <input type="hidden" name="method" value="${method}">
                        <input type="hidden" name="promo" value="${promoCode}">
                    `;
                    document.body.appendChild(f); f.submit();
                }
            </script>

        <?php elseif($page == 'pay'): 
            $pay = $_SESSION['pay_data'] ?? null;
            if(!$pay) echo "<script>window.location='?page=home'</script>";
            
            // If Balance, it should have been processed, but if logic brings here
            if($pay['method'] == 'Balance') {
                 // Auto submit balance payment
                 echo "<form method='post' id='autoBal'><input type='hidden' name='confirm_payment' value='1'><input type='hidden' name='trx' value='balance'></form><script>document.getElementById('autoBal').submit();</script>";
            }

            // Setup Details
            $themeClass = ($pay['method'] == 'Bkash') ? 'bkash-theme' : 'nagad-theme';
            $targetNum = ($pay['method'] == 'Bkash') ? '01996805508' : '01406245880';
            $dialCode = ($pay['method'] == 'Bkash') ? '*247#' : '*167#';
        ?>
            <!-- DEDICATED PAYMENT PAGE -->
            <div class="<?php echo $themeClass; ?>">
                <div class="gateway-container">
                    <div class="gateway-header">৳ <?php echo $pay['amount']; ?></div>
                    <div class="gateway-body">
                        <div style="text-align:center; margin-bottom:15px; font-weight:bold; font-size:18px;">ট্রানজেকশন আইডি দিন</div>
                        
                        <form method="post">
                            <input name="trx" class="gateway-input" placeholder="ট্রানজেকশন আইডি দিন" required>
                            
                            <ul class="instruction-list">
                                <li><?php echo $dialCode; ?> ডায়াল করে আপনার <?php echo strtoupper($pay['method']); ?> মোবাইল মেনুতে যান অথবা অ্যাপে যান।</li>
                                <li>"Send Money" -এ ক্লিক করুন।</li>
                                <li>প্রাপক নম্বর হিসেবে এই নম্বরটি লিখুন:
                                    <br>
                                    <div class="copy-box" onclick="copyToClip('<?php echo $targetNum; ?>')">
                                        <?php echo $targetNum; ?> <i class="far fa-copy"></i> Copy
                                    </div>
                                </li>
                                <li>টাকার পরিমাণ: <b><?php echo $pay['amount']; ?></b></li>
                                <li>Reference: <b><?php echo $me['id']; ?></b></li>
                                <li>সবকিছু ঠিক থাকলে নিশ্চিত করুন।</li>
                                <li>এখন উপরের বক্সে Transaction ID দিন এবং নিচের VERIFY বাটনে ক্লিক করুন।</li>
                            </ul>

                            <button name="confirm_payment" class="gateway-btn">VERIFY</button>
                        </form>
                        <button onclick="window.history.back()" class="back-btn">Cancel / Back</button>
                    </div>
                </div>
            </div>

            <script>
                function copyToClip(text) {
                    navigator.clipboard.writeText(text).then(() => { 
                        var x = document.getElementById("toast");
                        x.innerHTML = "Number Copied: " + text;
                        x.className = "toast-msg show";
                        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
                    });
                }
            </script>

        <?php elseif($page == 'spin'): ?>
            <!-- Spin Wheel Code -->
            <div style="text-align:center; padding-top:20px;">
                <h2 style="color:var(--primary)">LUCKY SPIN</h2>
                <div class="wheel-container">
                    <div class="marker"></div>
                    <div class="wheel" id="wheel"><?php for($i=0; $i<8; $i++): ?><div class="wheel-item" style="--i:<?php echo $i; ?>">🎁</div><?php endfor; ?></div>
                </div>
                <form method="post">
                    <?php if($spinAllowed): ?><button name="spin" class="btn" style="width:200px; border-radius:30px;">SPIN NOW</button>
                    <?php else: ?><button type="button" class="btn" style="width:200px; border-radius:30px; background:#64748b; cursor:not-allowed;" disabled>Wait: <?php echo $timeLeft; ?></button><?php endif; ?>
                </form>
            </div>
            <?php if(isset($spinRes)): ?><script>setTimeout(()=>{document.getElementById('wheel').style.transform="rotate("+(1800+Math.random()*360)+"deg)";setTimeout(()=>{document.getElementById('popup').style.display='flex';document.getElementById('pTitle').innerText='Won!';document.getElementById('pMsg').innerText='You won $ <?php echo $spinRes; ?>';setTimeout(()=>{window.location.href='?page=spin';},3000);},4000);},100);</script><?php endif; ?>

        <?php elseif($page == 'refer'): ?>
             <div class="card" style="margin:20px;">
                <i class="fas fa-gift" style="font-size:50px; color:var(--primary); margin:10px;"></i>
                <h3>Refer & Earn</h3>
                <p>Invite friends and get 5% bonus.</p>
                <div style="background:#334155; padding:15px; border:2px dashed #475569; margin:20px 0; font-size:22px; font-weight:bold; letter-spacing:2px;"><?php echo $me['ref_code']; ?></div>
                <?php $refCount = $conn->query("SELECT COUNT(*) FROM users WHERE referred_by='{$me['ref_code']}'")->fetchColumn(); ?>
                <p>Total Referred: <b><?php echo $refCount; ?></b></p>
            </div>
            
            <h3 style="margin:20px 0 10px 20px;">Bonus History</h3>
            <div style="padding:0 20px;">
                <?php $bonusHist = $conn->query("SELECT d.amount, d.date, u.name FROM deposits d JOIN users u ON d.user_id = u.id WHERE u.referred_by = '{$me['ref_code']}' AND d.status = 'Approved' ORDER BY d.id DESC");
                if($bonusHist->rowCount() == 0) echo "<p style='color:#666; font-size:12px;'>No bonus history yet.</p>";
                while($b = $bonusHist->fetch()): $bonusAmt = $b['amount'] * 0.05; ?>
                <div class="card" style="margin-bottom:10px; text-align:left; display:flex; justify-content:space-between; align-items:center;">
                    <div><div style="font-size:13px;">From: <b><?php echo $b['name']; ?></b></div><div style="font-size:11px; color:#94a3b8;"><?php echo $b['date']; ?></div></div>
                    <div style="text-align:right;"><div style="font-weight:bold; color:#4ade80;">+ $ <?php echo $bonusAmt; ?></div><div style="font-size:10px; color:#94a3b8;">(5% of <?php echo $b['amount']; ?>)</div></div>
                </div>
                <?php endwhile; ?>
            </div>

        <?php elseif($page == 'profile'): ?>
             <div class="card" style="margin:20px;"><h3><?php echo $me['name']; ?></h3><p style="color:#94a3b8"><?php echo $me['phone']; ?></p></div>
             
             <!-- Deposit Section -->
             <div class="card" style="margin:20px;">
                <h4>Add Funds</h4>
                
                <div id="depStep1">
                    <select id="depMethodSelect">
                        <option value="">Select Method</option>
                        <option value="Bkash">Bkash</option>
                        <option value="Nagad">Nagad</option>
                        <option value="Redeem Code">Redeem Code</option>
                    </select>
                    
                    <div id="redeemInput" class="hidden"><input id="codeVal" placeholder="Enter Gift Code"></div>
                    <div id="amountInput"><input type="number" id="amtVal" placeholder="Amount"></div>

                    <button class="btn" onclick="processDeposit()">Next Step</button>
                </div>
            </div>

            <script>
                document.getElementById('depMethodSelect').addEventListener('change', function() {
                    let m = this.value;
                    if(m === 'Redeem Code') {
                        document.getElementById('redeemInput').classList.remove('hidden');
                        document.getElementById('amountInput').classList.add('hidden');
                    } else {
                        document.getElementById('redeemInput').classList.add('hidden');
                        document.getElementById('amountInput').classList.remove('hidden');
                    }
                });

                function processDeposit() {
                    let m = document.getElementById('depMethodSelect').value;
                    if(!m) return alert("Select Method");

                    if(m === 'Redeem Code') {
                        let c = document.getElementById('codeVal').value;
                        if(!c) return alert("Enter Code");
                        // Submit Redeem Immediately
                        let f = document.createElement('form'); f.method='POST';
                        f.innerHTML = `<input type="hidden" name="deposit" value="1"><input type="hidden" name="method" value="Redeem Code"><input type="hidden" name="redeem_code" value="${c}">`;
                        document.body.appendChild(f); f.submit();
                    } else {
                        let a = document.getElementById('amtVal').value;
                        if(!a) return alert("Enter Amount");
                        
                        // Submit to Init Payment
                        let f = document.createElement('form'); f.method='POST';
                        f.innerHTML = `
                            <input type="hidden" name="init_payment" value="1">
                            <input type="hidden" name="type" value="deposit">
                            <input type="hidden" name="amount" value="${a}">
                            <input type="hidden" name="method" value="${m}">
                        `;
                        document.body.appendChild(f); f.submit();
                    }
                }
            </script>
            
            <h3 style="margin:20px 0 10px 20px;">Recent Orders</h3>
            <div style="padding:0 20px;">
                <?php $h=$conn->query("SELECT * FROM orders WHERE user_id={$me['id']} ORDER BY id DESC LIMIT 5"); while($o=$h->fetch()): ?>
                <div class="card" style="margin-bottom:10px; text-align:left;">
                    <div style="display:flex; justify-content:space-between;"><b><?php echo $o['product_name']; ?></b><span class="status-<?php echo $o['status']; ?>"><?php echo $o['status']; ?></span></div>
                </div>
                <?php endwhile; ?>
            </div>
            <h3 style="margin:20px 0 10px 20px;">Deposit History</h3>
            <div style="padding:0 20px;">
                <?php $d=$conn->query("SELECT * FROM deposits WHERE user_id={$me['id']} ORDER BY id DESC LIMIT 5"); if($d->rowCount()==0) echo "<p style='color:#666; font-size:12px;'>No deposits yet.</p>"; while($row=$d->fetch()): ?>
                <div class="card" style="margin-bottom:10px; text-align:left; display:flex; justify-content:space-between; align-items:center;">
                    <div><div style="font-weight:bold; font-size:14px;"><?php echo $row['method']; ?></div><div style="font-size:11px; color:#94a3b8;"><?php echo $row['date']; ?></div></div>
                    <div style="text-align:right;"><div style="font-weight:bold;">$ <?php echo $row['amount']; ?></div><span class="status-<?php echo $row['status']; ?>" style="font-size:11px;"><?php echo $row['status']; ?></span></div>
                </div>
                <?php endwhile; ?>
            </div>
        <?php endif; ?>
    </div>

    <?php if($page != 'pay'): ?>
    <div class="nav"><a href="?page=home" class="<?php echo $page=='home'?'active':''; ?>"><i class="fas fa-home"></i>Home</a><a href="?page=spin" class="<?php echo $page=='spin'?'active':''; ?>"><i class="fas fa-gamepad"></i>Spin</a><a href="?page=refer" class="<?php echo $page=='refer'?'active':''; ?>"><i class="fas fa-share-alt"></i>Refer</a><a href="?page=profile" class="<?php echo $page=='profile'?'active':''; ?>"><i class="fas fa-user"></i>Profile</a></div>
    <?php endif; ?>
    
    <script>function toggleBalance() { let btn = document.getElementById('balBtn'); let amt = document.getElementById('balAmt'); btn.style.display = 'none'; amt.style.display = 'inline-block'; setTimeout(() => { amt.style.display = 'none'; btn.style.display = 'inline-block'; }, 3000); } let title = "<?php echo $pTitle; ?>"; let msg = "<?php echo $pMsg; ?>"; if(title) { document.getElementById('popup').style.display = 'flex'; document.getElementById('pTitle').innerText = title; document.getElementById('pMsg').innerText = msg; }</script>

    <?php endif; ?>
</body>
</html>