<?php
include 'config.php';
$conn->set_charset("utf8mb4");

/* =========================
   🔐 Withdraw Service Status & Global Limits
========================= */
// এখানে maximumwd কলামটিও সিলেক্ট করা হয়েছে
$psp = $conn->query("SELECT withdraw_open, daily_limit, maximumwd FROM appinfo WHERE id = 1 LIMIT 1");
if (!$psp || $psp->num_rows == 0) {
    echo "Payment System Error";
    exit;
}
$pspData = $psp->fetch_assoc();

if ((int)$pspData['withdraw_open'] === 1) {
    echo "Withdraw Service is Currently Closed";
    exit;
}

$global_count_limit = (int)$pspData['daily_limit']; 
$max_withdraw_amount = (int)$pspData['maximumwd']; // সর্বোচ্চ কত টাকা উইথড্র করা যাবে

/* =========================
   🧾 Input Data
========================= */
$username = $_POST['username'] ?? null;
$email    = $_POST['email'] ?? null;
$method   = $_POST['method'] ?? null;
$number   = $_POST['number'] ?? null;
$amount   = $_POST['amount'] ?? null;
$trxid    = $_POST['trxid'] ?? null;
$fcm      = $_POST['fcm'] ?? null;

$today_date = date("d-M-Y"); 
$time = date("h:i:s A");

/* =========================
   🧩 Validation
========================= */
if (!$username || !$email || !$method || !$number || !$amount || !$trxid) {
    echo "Missing Fields";
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid Email";
    exit;
}

if (!preg_match('/^[a-zA-Z0-9]{8,20}$/', $trxid)) {
    echo "Invalid Transaction ID";
    exit;
}

if (!ctype_digit($amount) || intval($amount) <= 0) {
    echo "Invalid Withdraw Amount";
    exit;
}

$amount = intval($amount);

// 🆕 নতুন লজিক: Maximum Withdraw Amount Check
if ($amount > $max_withdraw_amount) {
    echo "Maximum Withdraw Limit is $max_withdraw_amount";
    exit;
}

/* =========================
   🚫 USER CHECK & AUTO RESET LIMIT (Daily Count)
========================= */
$userCheck = $conn->prepare(
    "SELECT withdraw_block, withdraw_block_time, wd_limit, last_wd_date, winning FROM users WHERE username = ? LIMIT 1"
);
$userCheck->bind_param("s", $username);
$userCheck->execute();
$userDataResult = $userCheck->get_result();

if ($userDataResult->num_rows === 0) {
    echo "No User Found";
    $userCheck->close();
    exit;
}

$userData = $userDataResult->fetch_assoc();
$userCheck->close();

$current_wd_limit = (int)$userData['wd_limit'];
$db_last_date = $userData['last_wd_date'];

// তারিখ না মিললে লিমিট রিসেট
if ($db_last_date !== $today_date) {
    $current_wd_limit = 0; 
    $reset = $conn->prepare("UPDATE users SET wd_limit = 0, last_wd_date = ? WHERE username = ?");
    $reset->bind_param("ss", $today_date, $username);
    $reset->execute();
    $reset->close();
}

// ডেইলি কতবার রিকোয়েস্ট দিতে পারবে সেই চেক
if ($current_wd_limit >= $global_count_limit) {
    echo "Daily Withdraw Limit Reached";
    exit;
}

/* =========================
   🛡️ Auto Unblock Logic (Old Logic)
========================= */
if ((int)$userData['withdraw_block'] === 1 && !empty($userData['withdraw_block_time'])) {
    $blockTimeStr = str_replace(["Time:", "At"], "", $userData['withdraw_block_time']);
    $blockTimeStr = trim($blockTimeStr);
    $blockTime = DateTime::createFromFormat('d/m/Y h:i A', $blockTimeStr);
    $now = new DateTime();

    if ($blockTime && $now >= $blockTime) {
        $unblock = $conn->prepare("UPDATE users SET withdraw_block = 0, withdraw_block_time = NULL WHERE username = ?");
        $unblock->bind_param("s", $username);
        $unblock->execute();
        $userData['withdraw_block'] = 0;
        $unblock->close();
    }
}

if ((int)$userData['withdraw_block'] === 1) {
    echo "Withdrawal Request Blocked";
    exit;
}

/* =========================
   🟠 Pending Check
========================= */
$check_pending = $conn->prepare("SELECT id FROM withdraw WHERE username = ? AND status = 'Pending' LIMIT 1");
$check_pending->bind_param("s", $username);
$check_pending->execute();

if ($check_pending->get_result()->num_rows > 0) {
    echo "You already have a pending request";
    $check_pending->close();
    exit;
}
$check_pending->close();

/* =========================
   🟢 Balance Check
========================= */
if ($userData['winning'] < $amount) {
    echo "Insufficient Balance";
    exit;
}

/* =========================
   💾 Insert Withdraw
========================= */
$insert = $conn->prepare(
    "INSERT INTO withdraw (username, email, method, number, amount, trxid, date, time, fcm)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$insert->bind_param("ssssissss", $username, $email, $method, $number, $amount, $trxid, $today_date, $time, $fcm);

/* =========================
   💰 Update User Data (Balance + Limit + Date)
========================= */
$update = $conn->prepare(
    "UPDATE users SET winning = winning - ?, wd_limit = wd_limit + 1, last_wd_date = ? WHERE username = ?"
);
$update->bind_param("iss", $amount, $today_date, $username);

/* =========================
   ✅ Execute
========================= */
if ($insert->execute() && $update->execute()) {
    echo "Withdraw Request Successfully Submitted";
} else {
    echo "Error Processing Withdraw Request";
}

$insert->close();
$update->close();
$conn->close();
?>