<?php
// =================================================================
// WITHDRAW PAGE (আপনার সকল চাহিদা অনুযায়ী চূড়ান্ত সংস্করণ)
// =================================================================
session_start();
require_once '../config.php';
$conn = require_once '../db.php';

// --- বট নোটিফিকেশন পাঠানোর ফাংশন ---
function sendTelegramNotification($chat_id, $message) {
    if (!defined('BOT_TOKEN')) {
        // বটের টোকেন না থাকলে নোটিফিকেশন পাঠাবে না
        return;
    }
    $bot_token = BOT_TOKEN;
    $url = "https://api.telegram.org/bot{$bot_token}/sendMessage";
    $data = [
        'chat_id' => $chat_id,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];
    
    $options = ['http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
        'ignore_errors' => true // API error ইগনোর করতে
    ]];
    $context  = stream_context_create($options);
    file_get_contents($url, false, $context);
}

// --- উইথড্র রিকোয়েস্ট হ্যান্ডেলিং ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $chat_id = filter_input(INPUT_POST, 'chat_id', FILTER_SANITIZE_NUMBER_INT);
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    $account_number = trim(filter_input(INPUT_POST, 'account_number', FILTER_SANITIZE_STRING));
    $method = trim(filter_input(INPUT_POST, 'method', FILTER_SANITIZE_STRING));
    $response = ['success' => false, 'message' => ''];

    if (!$chat_id || !$amount || !$account_number || !$method) {
        $response['message'] = 'Please fill all required fields.';
    } elseif ($amount < 100) {
        $response['message'] = 'Minimum withdrawal amount is 100 BDT.';
    } else {
        // ব্যবহারকারীর ব্যালেন্স চেক করা (শুধুমাত্র total_balance ব্যবহার করে)
        $stmt_check = $conn->prepare("SELECT total_balance FROM users WHERE chat_id = ?");
        $stmt_check->bind_param('i', $chat_id);
        $stmt_check->execute();
        $user_balance_check = $stmt_check->get_result()->fetch_assoc();
        $current_total_balance = $user_balance_check['total_balance'] ?? 0;

        if ($current_total_balance >= $amount) {
            // `withdrawals` টেবিলে রিকোয়েস্ট যোগ করা
            $stmt = $conn->prepare("INSERT INTO withdrawals (user_id, amount, method, account_number) VALUES (?, ?, ?, ?)");
            $stmt->bind_param('idss', $chat_id, $amount, $method, $account_number);

            if ($stmt->execute()) {
                // ব্যবহারকারীর অ্যাকাউন্ট থেকে total_balance কেটে নেওয়া
                $new_balance = $current_total_balance - $amount;
                $stmt_update = $conn->prepare("UPDATE users SET total_balance = ? WHERE chat_id = ?");
                $stmt_update->bind_param('di', $new_balance, $chat_id);
                $stmt_update->execute();
                
                $response['success'] = true;
                $response['message'] = 'Your withdrawal request has been submitted successfully!';

                // বট থেকে ইউজারকে নোটিফিকেশন পাঠানো
                $notification_message = "✅ <b>Withdrawal Request Submitted!</b>\n\n";
                $notification_message .= "Your request to withdraw <b>{$amount} BDT</b> via <b>{$method}</b> to the account <b>{$account_number}</b> has been received. It will be processed soon.";
                sendTelegramNotification($chat_id, $notification_message);

            } else {
                $response['message'] = 'Database error. Please try again.';
            }
        } else {
            $response['message'] = 'You do not have enough balance to withdraw this amount.';
        }
    }
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// --- পেজ প্রদর্শনের লজিক ---
$chat_id = filter_input(INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT);
if (!$chat_id) die("সঠিক ব্যবহারকারী আইডি পাওয়া যায়নি।");

$stmt_user = $conn->prepare("SELECT * FROM users WHERE chat_id = ?");
$stmt_user->bind_param('i', $chat_id);
$stmt_user->execute();
$user = $stmt_user->get_result()->fetch_assoc();
if (!$user) die("ব্যবহারকারীকে খুঁজে পাওয়া যায়নি।");

$total_balance = $user['total_balance'] ?? 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Withdraw Funds</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
    <style>
        :root {
            --background-light: #F4F6F9; --white: #FFFFFF; --text-dark: #1E2022;
            --text-muted: #6A737D; --primary-color: #007BFF;
            --bg-dark: #161922; --bg-card: #252836; --footer-active: #50E3C2;
        }
        body { margin: 0; font-family: 'Poppins', sans-serif; background-color: var(--background-light); color: var(--text-dark); padding: 15px; padding-bottom: 95px; }
        a { text-decoration: none; color: inherit; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .header .title { font-size: 1.2em; font-weight: 600; margin: 0 auto; text-align: center; }
        .header .icon { font-size: 1.4em; color: var(--text-dark); width: 40px; text-align: center; }
        .user-info { display: flex; align-items: center; margin-bottom: 15px; }
        .user-info img { width: 40px; height: 40px; border-radius: 50%; margin-right: 10px; }
        .user-info .name { font-weight: 600; }
        .user-info .balance { font-size: 0.9em; color: var(--text-muted); }
        .card { background: var(--white); border-radius: 20px; padding: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .form-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .form-header h3 { margin: 0; font-size: 1.2em; }
        .balance-badge { background-color: #FFF3E0; color: #FF9800; padding: 8px 12px; border-radius: 10px; font-weight: 600; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; font-weight: 500; margin-bottom: 8px; }
        .input-wrapper { position: relative; }
        .form-group input { width: 100%; padding: 15px; border: 1px solid #e0e0e0; border-radius: 12px; font-size: 1em; font-family: 'Poppins', sans-serif; box-sizing: border-box; }
        .input-currency { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-weight: 500; }
        .helper-text { font-size: 0.8em; color: var(--text-muted); margin-top: 8px; }
        .payment-methods { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
        .payment-methods input[type="radio"] { display: none; }
        .method-box { border: 2px solid #e0e0e0; border-radius: 12px; padding: 15px; text-align: center; cursor: pointer; transition: all 0.2s ease-in-out; }
        .method-box img { max-width: 60px; height: 30px; object-fit: contain; margin-bottom: 8px; }
        .method-box span { font-weight: 500; font-size: 1em; }
        .payment-methods input[type="radio"]:checked + .method-box { border-color: var(--primary-color); background-color: #EBF5FF; transform: scale(1.05); }
        .submit-btn { width: 100%; border: none; padding: 16px; border-radius: 15px; font-size: 1.1em; font-weight: 600; color: var(--white); cursor: pointer; margin-top: 25px; background: linear-gradient(90deg, #5665E8, #7542EB); box-shadow: 0 5px 15px rgba(117, 66, 235, 0.3); transition: all 0.3s ease; }
        .submit-btn:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(117, 66, 235, 0.4); }
        footer { position: fixed; bottom: 0; left: 0; right: 0; background: var(--bg-card); display: flex; justify-content: space-around; align-items: center; padding: 10px 0; border-top-left-radius: 25px; border-top-right-radius: 25px; box-shadow: 0 -5px 20px rgba(0,0,0,0.2); }
        footer a { color: var(--text-muted); text-decoration: none; font-size: 24px; text-align: center; flex-grow: 1; }
        footer a .label { font-size: 11px; display: block; margin-top: 2px; }
        footer a.active, footer a.active .label { color: var(--footer-active); }
    </style>
</head>
<body>
    

    <div class="user-info">
        <img src="<?php echo htmlspecialchars($user['profile_photo_url'] ?? 'assets/default_avatar.png'); ?>" alt="Profile">
        <div>
            <div class="name"><?php echo htmlspecialchars($user['first_name']); ?></div>
            <div class="balance">Balance: <?php echo number_format($total_balance, 2); ?> BDT</div>
        </div>
    </div>

    <div class="card">
        <form id="withdrawForm">
            <div class="form-header">
                <h3>Withdraw Funds</h3>
                <span class="balance-badge"><i class="fas fa-coins"></i> <?php echo number_format($total_balance, 2); ?> BDT</span>
            </div>
            
            <div class="form-group">
                <label for="amount">Amount</label>
                <div class="input-wrapper">
                    <input type="number" id="amount" name="amount" placeholder="Enter amount" required>
                    <span class="input-currency">BDT</span>
                </div>
                <p class="helper-text">Minimum: 100 BDT</p>
            </div>

            <div class="form-group">
                <label for="account_number">Withdrawal Address</label>
                <input type="text" id="account_number" name="account_number" placeholder="Enter your account number" required>
                <p class="helper-text">Enter the number for your selected payment method.</p>
            </div>

            <div class="form-group">
                <label>Payment Method</label>
                <div class="payment-methods" style="grid-template-columns: repeat(4, 1fr);">
                    <label>
                        <input type="radio" name="method" value="Bkash" required>
                        <div class="method-box"><img src="assets/bkash.png" alt="Bkash"><br><span>Bkash</span></div>
                    </label>
                    <label>
                        <input type="radio" name="method" value="Nagod" required>
                        <div class="method-box"><img src="assets/nagod.png" alt="Nagod"><br><span>Nagod</span></div>
                    </label>
                    <label>
                        <input type="radio" name="method" value="Rocket" required>
                        <div class="method-box"><img src="assets/rocket.png" alt="Rocket"><br><span>Rocket</span></div>
                    </label>
                    <label>
                        <input type="radio" name="method" value="Upay" required>
                        <div class="method-box"><img src="assets/upay.png" alt="Upay"><br><span>Upay</span></div>
                    </label>
                </div>
            </div>

            <input type="hidden" name="chat_id" value="<?php echo $chat_id; ?>">
            <button type="submit" class="submit-btn">Submit Request</button>
        </form>
    </div>

    <!-- ফুটার -->
    <footer>
        <a href="index.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-home"></i><span class="label">Home</span></a>
        <a href="#"><i class="fas fa-ad"></i><span class="label">Ads Task</span></a>
        <a href="#"><i class="fas fa-tasks"></i><span class="label">TG Tasks</span></a>
        <a href="refer.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-users"></i><span class="label">Refer</span></a>
        <a href="wallet.php?user_id=<?php echo $chat_id; ?>" class="active"><i class="fas fa-wallet"></i><span class="label">Withdraw</span></a>
        <a href="profile.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-user"></i><span class="label">Profile</span></a>
    </footer>

    <script>
        const tg = window.Telegram.WebApp;
        tg.ready();
        tg.setHeaderColor('#F4F6F9');

        document.getElementById('withdrawForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const form = this;
            const totalBalance = <?php echo $total_balance; ?>;
            const amount = parseFloat(form.amount.value);

            if (isNaN(amount) || amount < 100) {
                tg.showAlert("Minimum withdrawal amount is 100 BDT.");
                return;
            }
            if (amount > totalBalance) {
                tg.showAlert("You do not have enough balance.");
                return;
            }
            const selectedMethod = form.querySelector('input[name="method"]:checked');
            if (!selectedMethod) {
                tg.showAlert("Please select a payment method.");
                return;
            }

            tg.showConfirm(`Are you sure you want to withdraw ${amount} BDT via ${selectedMethod.value}?`, async (isConfirmed) => {
                if (isConfirmed) {
                    const formData = new FormData(form);
                    tg.MainButton.setText('Processing...').show().showProgress();

                    try {
                        const response = await fetch('', { method: 'POST', body: formData });
                        const result = await response.json();
                        
                        tg.MainButton.hideProgress().hide();
                        tg.showAlert(result.message, () => {
                            if (result.success) {
                                window.location.reload();
                            }
                        });

                    } catch (error) {
                        tg.MainButton.hideProgress().hide();
                        tg.showAlert('An error occurred. Please try again.');
                    }
                }
            });
        });
    </script>
</body>
</html>
<?php
$conn->close();
?>