<?php
// ১. সেশন নোটিশ এড়ানোর জন্য চেক
if (session_status() === PHP_SESSION_NONE) { 
    session_start(); 
}

require 'config/db.php';

// ২. লগইন চেক
if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit(); 
}
$user_id = $_SESSION['user_id'];

$msg = "";
$msg_type = "";

// ৩. ডাটা ফেচ করা (সেটিংস, ইউজার ব্যালেন্স এবং পেমেন্ট মেথড)
try {
    // সেটিংস থেকে কারেন্সি এবং মিনিমাম উইথড্র আনা
    $stmt_set = $pdo->query("SELECT * FROM settings WHERE id = 1");
    $settings = $stmt_set->fetch(PDO::FETCH_ASSOC);
    $currency = $settings['currency'] ?? '৳';
    $min_withdraw = $settings['min_withdraw'] ?? 50; 

    // ইউজার ব্যালেন্স আনা
    $stmt_user = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt_user->execute([$user_id]);
    $user = $stmt_user->fetch(PDO::FETCH_ASSOC);
    $current_balance = $user['balance'] ?? 0;

    // পেমেন্ট মেথড টেবিল থেকে মেথডগুলো আনা (যেগুলো Withdraw সাপোর্ট করে)
    $method_stmt = $pdo->query("SELECT * FROM payment_methods WHERE type IN ('Withdraw', 'Both') ORDER BY id ASC");
    $all_methods = $method_stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) { 
    error_log($e->getMessage());
    $current_balance = 0; 
    $currency = '৳';
    $min_withdraw = 50;
    $all_methods = [];
}

// ৪. উইথড্র সাবমিশন লজিক
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_withdraw'])) {
    $method = htmlspecialchars($_POST['method'] ?? '');
    $amount = floatval($_POST['amount'] ?? 0);
    $account_number = htmlspecialchars($_POST['account_number'] ?? '');

    if ($amount < $min_withdraw) {
        $msg = "Minimum withdraw amount is " . $currency . $min_withdraw;
        $msg_type = "red";
    } elseif ($amount > $current_balance) {
        $msg = "Insufficient balance!";
        $msg_type = "red";
    } elseif (empty($account_number) || empty($method)) {
        $msg = "Please fill all fields!";
        $msg_type = "red";
    } else {
        try {
            $pdo->beginTransaction();

            // ৪.১ ব্যালেন্স আপডেট
            $new_balance = $current_balance - $amount;
            $update_stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
            $update_stmt->execute([$new_balance, $user_id]);

            // ৪.২ উইথড্র রিকোয়েস্ট সেভ
            $stmt = $pdo->prepare("INSERT INTO withdraws (user_id, method, amount, account_number, status, created_at) VALUES (?, ?, ?, ?, 'Pending', NOW())");
            
            if ($stmt->execute([$user_id, $method, $amount, $account_number])) {
                $pdo->commit();
                $msg = "Withdraw request submitted successfully!";
                $msg_type = "green";
                $current_balance = $new_balance; 
            } else {
                $pdo->rollBack();
                $msg = "Transaction failed!";
                $msg_type = "red";
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $msg = "Error processing request.";
            $msg_type = "red";
        }
    }
}
?>

<!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>Withdraw - Ludo Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body { background: #020617; color: #f1f5f9; font-family: 'Rajdhani', sans-serif; background-image: radial-gradient(circle at 50% 0%, #1e1b4b 0%, #020617 70%); min-height: 100vh; }
        .glass-card { background: rgba(30, 41, 59, 0.4); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.05); }
        .method-radio:checked + div { border-color: #ef4444; background: rgba(239, 68, 68, 0.1); box-shadow: 0 0 15px rgba(239, 68, 68, 0.2); }
        input { background: rgba(0,0,0,0.3) !important; border: 1px solid rgba(255,255,255,0.1) !important; color: white !important; outline: none; }
    </style>
</head>
<body class="pb-10 antialiased">

    <header class="p-5 flex justify-between items-center sticky top-0 z-40 bg-[#020617]/80 backdrop-blur-md border-b border-white/5">
        <button onclick="location.href='wallet.php'" class="w-10 h-10 rounded-xl glass-card flex items-center justify-center text-slate-300 active:scale-95">
            <i class="fas fa-chevron-left"></i>
        </button>
        <h2 class="text-xl font-bold tracking-widest uppercase">Withdraw</h2>
        <div class="w-10"></div>
    </header>

    <div class="max-w-md mx-auto px-5 space-y-6 mt-4">

        <div class="glass-card rounded-[2rem] p-6 text-center border-t-4 border-red-500 shadow-2xl shadow-red-500/10">
            <p class="text-[10px] text-slate-400 font-bold uppercase tracking-widest">Withdrawable Balance</p>
            <h1 class="text-4xl font-black text-white mt-1"><?= $currency ?><?= number_format($current_balance, 2) ?></h1>
        </div>

        <?php if($msg): ?>
            <script>
                Swal.fire({
                    icon: '<?= $msg_type == "green" ? "success" : "error" ?>',
                    title: '<?= $msg_type == "green" ? "Success" : "Error" ?>',
                    text: '<?= $msg ?>',
                    background: '#1e293b', color: '#fff', confirmButtonColor: '#ef4444'
                });
            </script>
        <?php endif; ?>

        <form method="POST" class="space-y-6">
            
            <div class="space-y-3">
                <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest px-1">Receive via</label>
                <div class="grid grid-cols-3 gap-3">
                    <?php 
                    $isFirst = true;
                    if (!empty($all_methods)):
                        foreach($all_methods as $m): 
                            $logo = "https://cdn-icons-png.flaticon.com/512/4341/4341764.png";
                            if(stripos($m['name'], 'bkash') !== false) $logo = "https://freelogopng.com/images/all_img/1656234745bkash-app-logo-png.png";
                            elseif(stripos($m['name'], 'nagad') !== false) $logo = "https://freelogopng.com/images/all_img/1679248787Nagad-Logo-PNG.png";
                            elseif(stripos($m['name'], 'rocket') !== false) $logo = "https://logowik.com/content/uploads/images/rocket4947.logowik.com.webp";
                    ?>
                    <label class="cursor-pointer group">
                        <input type="radio" name="method" value="<?= htmlspecialchars($m['name']) ?>" class="hidden method-radio" <?= $isFirst ? 'checked' : '' ?>>
                        <div class="glass-card p-4 rounded-2xl flex flex-col items-center gap-2 border-2 border-transparent transition group-active:scale-95 h-full justify-center">
                            <img src="<?= $logo ?>" class="h-6 object-contain">
                            <span class="text-[10px] font-bold uppercase text-slate-400 group-hover:text-white"><?= htmlspecialchars($m['name']) ?></span>
                        </div>
                    </label>
                    <?php $isFirst = false; endforeach; 
                    else: echo "<p class='col-span-3 text-center text-xs text-red-500'>No methods available.</p>"; endif; ?>
                </div>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest px-1 ml-1">Account Number</label>
                    <div class="relative mt-1">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500"><i class="fas fa-phone-alt text-xs"></i></span>
                        <input type="text" name="account_number" class="w-full py-4 pl-10 pr-4 rounded-2xl text-sm font-bold" placeholder="Your Number" required>
                    </div>
                </div>

                <div>
                    <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest px-1 ml-1">Withdraw Amount</label>
                    <div class="relative mt-1">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 font-bold"><?= $currency ?></span>
                        <input type="number" name="amount" class="w-full py-4 pl-10 pr-4 rounded-2xl text-sm font-bold" placeholder="Min <?= $min_withdraw ?>" required min="<?= $min_withdraw ?>">
                    </div>
                </div>
            </div>

            <div class="glass-card p-4 rounded-2xl bg-red-500/5 border-l-2 border-red-500">
                <p class="text-[11px] text-slate-400 leading-relaxed">
                    <i class="fas fa-info-circle text-red-500 mr-1"></i> 
                    Minimum withdrawal is <b><?= $currency . $min_withdraw ?></b>. Processing time: 1-24 hours.
                </p>
            </div>

            <button type="submit" name="submit_withdraw" class="w-full bg-gradient-to-r from-red-600 to-red-500 py-4 rounded-2xl font-black uppercase tracking-widest text-sm text-white shadow-xl shadow-red-600/20 active:scale-95 transition-all">
                Submit Withdraw Request
            </button>
        </form>
    </div>

</body>
</html>