<?php
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'];
    
    if ($type === 'request') {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $method = $_POST['method'];
        $number = $_POST['number'];
        $amount = $_POST['amount'];
        $trxid = $_POST['trxid'];
        $fcm = $_POST['fcm'];
        $date = date("d-M-Y");
        $time = date("h:i:s A");

        $query = "SELECT * FROM users WHERE email = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $winning = $row["winning"];

            if ($amount > 0 && $winning > ($amount - 1)) {
                $sql = "INSERT INTO withdraw (name, email, method, number, amount, trxid, date, time, fcm) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("sssssssss", $name, $email, $method, $number, $amount, $trxid, $date, $time, $fcm);

                $update = "UPDATE users SET winning = winning - ? WHERE email = ?";
                $stmt2 = $conn->prepare($update);
                $stmt2->bind_param("is", $amount, $email);

                if ($stmt->execute() && $stmt2->execute()) {
                    echo "Request Successfully";
                } else {
                    echo "Error Requesting: " . $stmt->error;
                }
            } else {
                echo "Withdraw Amount Is Insufficient";
            }
        } else {
            echo "No User Found";
        }

        $stmt->close();
        $conn->close();
    }
} else {
    echo "Invalid Request Method";
}
?>