<?php
// ১. এরর রিপোর্টিং
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';

try {
    if (file_exists($db_path)) {
        require $db_path;
    } else {
        $conn = new mysqli('localhost', 'root', '', 'bajipari');
    }
} catch (Exception $e) {
    die("Database Connection Error: " . $e->getMessage());
}

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

$uid = $_SESSION['user_id'];
$message = "";
$msg_type = "";

try {
    // 3. Fetch User Data (এজেন্ট আইডি সহ)
    $user_q = $conn->query("SELECT u.*, p.kyc_real_name FROM users u LEFT JOIN player_profiles p ON u.id = p.user_id WHERE u.id=$uid");
    $user = $user_q->fetch_assoc();

    // Verification Check
    $has_name = !empty($user['kyc_real_name']);
    $is_verified = $has_name;

    // 4. HANDLE ADD NEW WALLET
    if (isset($_POST['add_wallet'])) {
        $new_method = $_POST['new_method'];
        $new_number = $_POST['new_number'];
        
        if (!empty($new_method) && !empty($new_number)) {
            $chk = $conn->query("SELECT id FROM player_wallets WHERE user_id=$uid AND wallet_number='$new_number' AND method='$new_method'");
            if ($chk->num_rows == 0) {
                $stmt = $conn->prepare("INSERT INTO player_wallets (user_id, method, wallet_number) VALUES (?, ?, ?)");
                $stmt->bind_param("iss", $uid, $new_method, $new_number);
                $stmt->execute();
                $message = "নতুন ওয়ালেট সফলভাবে যুক্ত হয়েছে!";
                $msg_type = "success";
            } else {
                $message = "এই ওয়ালেটটি ইতিমধ্যে যুক্ত আছে।";
                $msg_type = "error";
            }
        }
    }

    // 5. HANDLE WITHDRAW REQUEST
    if (isset($_POST['submit_withdraw'])) {
        $amount = floatval($_POST['amount']);
        $wallet_id = isset($_POST['selected_wallet']) ? intval($_POST['selected_wallet']) : 0;

        // WAGER CHECK
        $target_turnover = floatval($user['turnover_target'] ?? 0);
        $bet_q = $conn->query("SELECT SUM(bet_amount) as total_bet FROM game_bet_history WHERE user_id=$uid");
        $bet_row = $bet_q->fetch_assoc();
        $total_played = floatval($bet_row['total_bet'] ?? 0);
        $wager_remaining = max(0, $target_turnover - $total_played);

        // VALIDATION
        if ($amount < 100) {
            $message = "সর্বনিম্ন উইথড্র অ্যামাউন্ট ১০০ টাকা।";
            $msg_type = "error";
        } elseif ($amount > 25000) {
            $message = "একবারে সর্বোচ্চ ২৫,০০০ টাকার বেশি উত্তোলন সম্ভব নয়।";
            $msg_type = "error";
        } elseif ($amount > $user['balance']) {
            $message = "আপনার পর্যাপ্ত ব্যালেন্স নেই।";
            $msg_type = "error";
        } elseif ($wager_remaining > 0) {
            $message = "উইথড্র করতে আরও ৳" . number_format($wager_remaining, 2) . " টাকার গেম খেলতে হবে।";
            $msg_type = "error";
        } elseif ($wallet_id == 0) {
            $message = "অনুগ্রহ করে একটি ওয়ালেট সিলেক্ট করুন।";
            $msg_type = "error";
        } else {
            // PROCESS WITHDRAW
            $w_res = $conn->query("SELECT * FROM player_wallets WHERE id=$wallet_id AND user_id=$uid");
            if ($w_res && $w_res->num_rows > 0) {
                $wallet = $w_res->fetch_assoc();
                $method_str = ucfirst($wallet['method']) . " (" . $wallet['wallet_number'] . ")";
                
                $target_agent_id = 0; 
                if (!empty($user['agent_id']) && $user['agent_id'] > 0) {
                    $target_agent_id = intval($user['agent_id']);
                }

                $conn->query("UPDATE users SET balance = balance - $amount WHERE id=$uid");
                
                $stmt = $conn->prepare("INSERT INTO transactions_fake (user_id, type, amount, method, status, created_at, agent_id) VALUES (?, 'withdraw', ?, ?, 'pending', NOW(), ?)");
                $stmt->bind_param("idsi", $uid, $amount, $method_str, $target_agent_id);
                
                if ($stmt->execute()) {
                    $message = "উইথড্র রিকুয়েস্ট সফল হয়েছে!";
                    $msg_type = "success";
                    $user['balance'] -= $amount; 
                } else {
                    $conn->query("UPDATE users SET balance = balance + $amount WHERE id=$uid");
                    $message = "সার্ভার এরর, অনুগ্রহ করে আবার চেষ্টা করুন।";
                    $msg_type = "error";
                }
            }
        }
    }

    $wallets = $conn->query("SELECT * FROM player_wallets WHERE user_id=$uid ORDER BY id DESC");

} catch (Exception $e) {
    die("<div style='color:white; background:red; padding:10px; text-align:center;'>System Error: " . $e->getMessage() . "</div>");
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Withdraw Money</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">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <style>
        body { background-color: #111518; color: #d1d5db; font-family: 'Roboto', sans-serif; padding-bottom: 100px; }
        .tab-active { background-color: #eab308; color: black; font-weight: bold; }
        .tab-inactive { background-color: #1c2227; color: white; }
        .wallet-card {
            background-color: #1c2227; border: 1px solid #2f3840; border-radius: 8px; padding: 12px;
            display: flex; justify-content: space-between; align-items: center; cursor: pointer; transition: 0.2s;
        }
        .wallet-card.selected { border-color: #eab308; background-color: #2a2a2a; }
        .wallet-icon { width: 40px; height: 40px; object-fit: contain; }
        #addWalletModal { z-index: 200; }
        .text-error { color: #ef4444; font-size: 12px; margin-top: 5px; display: none; font-weight: bold; }
        .btn-submit { 
            background-color: #eab308; color: black; width: 100%; padding: 12px; 
            border-radius: 6px; font-weight: bold; font-size: 16px; border: none; cursor: pointer;
        }
        .btn-submit:hover { opacity: 0.9; }
        .verify-alert { background: #1c2227; border-left: 4px solid #ef4444; padding: 15px; margin-bottom: 20px; border-radius: 4px; }
        
        /* প্রিমেইড বক্স স্টাইল */
        .prepaid-box {
            background: #1c2227; border: 1px solid #2f3840; color: white;
            padding: 8px; text-align: center; border-radius: 4px; font-size: 14px; cursor: pointer;
        }
        .prepaid-box:active { background: #eab308; color: black; }
    </style>
</head>
<body>

    <div class="bg-[#15191d] p-3 pb-2 sticky top-0 z-50 shadow-md">
        <div class="flex justify-between items-center mb-3">
            <h2 class="text-white text-lg font-medium mx-auto">উত্তোলন (Withdraw)</h2>
            <button onclick="window.location.href='index.php'" class="absolute right-3 text-gray-400"><i class="fas fa-times text-xl"></i></button>
        </div>
        <div class="flex rounded-md overflow-hidden">
            <a href="deposit.php" class="flex-1 text-center py-2.5 text-sm tab-inactive">ডিপোজিট</a>
            <div class="flex-1 text-center py-2.5 text-sm tab-active">উত্তোলন</div>
        </div>
    </div>

    <div class="px-4 mt-4">
        
        <div class="mb-5 text-center">
            <p class="text-xs text-gray-400 mb-1">বর্তমান ব্যালেন্স</p>
            <h1 class="text-3xl font-bold text-white">৳ <?php echo number_format($user['balance'], 2); ?></h1>
        </div>

        <?php if(!$is_verified): ?>
        <div class="verify-alert">
            <div class="flex gap-3">
                <i class="fas fa-user-lock text-red-500 text-xl mt-1"></i>
                <div>
                    <h4 class="text-white font-bold text-sm">ভেরিফিকেশন প্রয়োজন</h4>
                    <p class="text-xs text-gray-400 mt-1">টাকা উত্তোলনের জন্য আপনার আসল নাম (Real Name) প্রোফাইলে সেট করতে হবে।</p>
                    <a href="personal_info.php" class="inline-block mt-2 bg-red-600 text-white text-xs px-3 py-1 rounded">ভেরিফাই করুন</a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if($message): ?>
        <div class="p-3 mb-4 rounded text-sm font-bold <?php echo $msg_type == 'success' ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300'; ?>">
            <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <form method="POST" id="withdrawForm" onsubmit="return validateSubmission()">
            
            <div class="mb-6">
                <label class="block text-gray-400 text-sm mb-2">টাকার পরিমাণ (সীমা: ১০০ - ২৫০০০)</label>
                <div class="relative">
                    <span class="absolute left-3 top-3 text-gray-400 text-lg">৳</span>
                    <input type="number" name="amount" id="amountInput" placeholder="0.00" min="100" max="25000" class="w-full bg-[#1c2227] border border-[#2f3840] rounded-lg p-3 pl-8 text-white focus:border-[#eab308] outline-none text-lg font-bold" required>
                </div>
                <div class="flex justify-between mt-1">
                    <p class="text-[10px] text-gray-500 font-bold">সীমা: 100 - 25000</p>
                </div>

                <div class="grid grid-cols-5 gap-2 mt-3">
                    <div class="prepaid-box" onclick="setAmount(500)">500</div>
                    <div class="prepaid-box" onclick="setAmount(1000)">1000</div>
                    <div class="prepaid-box" onclick="setAmount(5000)">5000</div>
                    <div class="prepaid-box" onclick="setAmount(10000)">10000</div>
                    <div class="prepaid-box" onclick="setAmount(25000)">25000</div>
                </div>

                <p id="amountError" class="text-error"><i class="fas fa-exclamation-circle"></i> ১০০ - ২৫,০০০ টাকার মধ্যে ইনপুট দিন।</p>
                <p id="balanceError" class="text-error"><i class="fas fa-exclamation-circle"></i> পর্যাপ্ত ব্যালেন্স নেই।</p>
            </div>

            <div class="mb-6">
                <div class="flex justify-between items-center mb-3">
                    <label class="text-gray-400 text-sm">উত্তোলনের মাধ্যম</label>
                    <button type="button" onclick="openModal()" class="text-[#eab308] text-xs font-bold border border-[#eab308] px-2 py-1 rounded hover:bg-[#eab308] hover:text-black transition">
                        + নতুন যুক্ত করুন
                    </button>
                </div>

                <div class="space-y-3">
                    <?php if($wallets->num_rows > 0): ?>
                        <?php while($w = $wallets->fetch_assoc()): ?>
                        <label class="wallet-card group relative">
                            <input type="radio" name="selected_wallet" value="<?php echo $w['id']; ?>" class="absolute opacity-0 w-full h-full cursor-pointer" onchange="selectWallet(this)">
                            <div class="flex items-center gap-3">
                                <?php 
                                    $img = 'https://freelogopng.com/images/all_img/1656234745bkash-app-logo-png.png'; 
                                    $m = strtolower($w['method']);
                                    if($m == 'nagad') $img = 'https://freelogopng.com/images/all_img/1679248828Nagad-Logo-PNG.png';
                                    elseif($m == 'rocket') $img = 'https://seeklogo.com/images/D/dutch-bangla-rocket-logo-B4D1CC458D-seeklogo.com.png';
                                    elseif($m == 'upay') $img = 'https://images.seeklogo.com/logo-png/64/1/upay-logo-png_seeklogo-642533.png';
                                ?>
                                <img src="<?php echo $img; ?>" class="wallet-icon rounded bg-white p-0.5">
                                <div>
                                    <p class="text-white font-bold capitalize"><?php echo $w['method']; ?></p>
                                    <p class="text-gray-400 text-xs"><?php echo $w['wallet_number']; ?></p>
                                </div>
                            </div>
                            <div class="w-5 h-5 rounded-full border border-gray-500 flex items-center justify-center check-circle group-hover:border-[#eab308]">
                                <div class="w-3 h-3 bg-[#eab308] rounded-full hidden inner-circle"></div>
                            </div>
                        </label>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="text-center py-6 border border-dashed border-gray-600 rounded bg-[#1c2227]">
                            <p class="text-gray-500 text-sm">কোনো ওয়ালেট যুক্ত নেই।</p>
                            <p class="text-xs text-gray-600">উপরে "+ নতুন যুক্ত করুন" বাটনে ক্লিক করুন।</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="fixed bottom-20 left-0 w-full px-4">
                <button type="submit" name="submit_withdraw" id="submitBtn" class="btn-submit">
                    উত্তোলন নিশ্চিত করুন
                </button>
            </div>

        </form>
    </div>

    <div id="addWalletModal" class="fixed inset-0 hidden bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
        <div class="bg-[#1c2227] w-full max-w-sm rounded-lg border border-gray-600 shadow-2xl p-5 relative">
            <button onclick="closeModal()" class="absolute top-3 right-3 text-gray-400 hover:text-white"><i class="fas fa-times text-lg"></i></button>
            <h3 class="text-white font-bold text-lg mb-4">নতুন ওয়ালেট যুক্ত করুন</h3>
            <form method="POST">
                <div class="mb-3">
                    <label class="text-xs text-gray-400 mb-1 block">মেথড সিলেক্ট করুন</label>
                    <div class="grid grid-cols-2 gap-2">
                        <label class="cursor-pointer">
                            <input type="radio" name="new_method" value="bkash" class="peer hidden" checked>
                            <div class="bg-[#111518] border border-gray-600 p-2 rounded text-center text-sm text-gray-300 peer-checked:border-[#eab308] peer-checked:text-[#eab308] font-bold">bKash</div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="new_method" value="nagad" class="peer hidden">
                            <div class="bg-[#111518] border border-gray-600 p-2 rounded text-center text-sm text-gray-300 peer-checked:border-[#eab308] peer-checked:text-[#eab308] font-bold">Nagad</div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="new_method" value="rocket" class="peer hidden">
                            <div class="bg-[#111518] border border-gray-600 p-2 rounded text-center text-sm text-gray-300 peer-checked:border-[#eab308] peer-checked:text-[#eab308] font-bold">Rocket</div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="new_method" value="upay" class="peer hidden">
                            <div class="bg-[#111518] border border-gray-600 p-2 rounded text-center text-sm text-gray-300 peer-checked:border-[#eab308] peer-checked:text-[#eab308] font-bold">Upay</div>
                        </label>
                    </div>
                </div>
                <div class="mb-4">
                    <label class="text-xs text-gray-400 mb-1 block">ফোন নম্বর</label>
                    <input type="number" name="new_number" placeholder="017xxxxxxxx" class="w-full bg-[#111518] border border-gray-600 rounded p-2 text-white focus:border-[#eab308] outline-none" required>
                </div>
                <button type="submit" name="add_wallet" class="w-full bg-[#eab308] text-black font-bold py-2 rounded">সেভ করুন</button>
            </form>
        </div>
    </div>

    <div class="fixed bottom-0 left-0 w-full h-[60px] bg-black border-t border-[#222] z-50 flex justify-between items-center px-6">
        <a href="index.php" class="flex flex-col items-center justify-center text-gray-500">
            <i class="fas fa-home text-lg mb-1"></i><span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center text-gray-500">
            <i class="fas fa-gift text-lg mb-1"></i><span class="text-[10px]">Promotions</span>
        </a>
        <a href="deposit.php" class="flex flex-col items-center justify-center text-gray-500">
            <i class="fas fa-wallet text-lg mb-1"></i><span class="text-[10px]">Deposit</span>
        </a>
        <a href="account.php" class="flex flex-col items-center justify-center text-[#eab308]">
            <i class="fas fa-user text-lg mb-1"></i><span class="text-[10px]">My Account</span>
        </a>
    </div>

    <script>
        const userBalance = <?php echo $user['balance'] ?? 0; ?>;
        
        function setAmount(amt) {
            document.getElementById('amountInput').value = amt;
        }

        function openModal() { document.getElementById('addWalletModal').classList.remove('hidden'); }
        function closeModal() { document.getElementById('addWalletModal').classList.add('hidden'); }

        function selectWallet(radio) {
            document.querySelectorAll('.wallet-card').forEach(el => {
                el.classList.remove('selected');
                el.querySelector('.inner-circle').classList.add('hidden');
            });
            radio.closest('.wallet-card').classList.add('selected');
            radio.closest('.wallet-card').querySelector('.inner-circle').classList.remove('hidden');
        }

        function validateSubmission() {
            const amountVal = parseFloat(document.getElementById('amountInput').value);
            const walletSelected = document.querySelector('input[name="selected_wallet"]:checked');
            
            document.getElementById('amountError').style.display = 'none';
            document.getElementById('balanceError').style.display = 'none';

            if (isNaN(amountVal) || amountVal < 100 || amountVal > 25000) {
                document.getElementById('amountError').style.display = 'block';
                return false;
            }
            if (amountVal > userBalance) {
                document.getElementById('balanceError').style.display = 'block';
                return false;
            }
            if (!walletSelected) {
                alert("অনুগ্রহ করে একটি ওয়ালেট সিলেক্ট করুন।");
                return false;
            }
            
            return true;
        }
    </script>

</body>
</html>