<?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 = '$email'";
        $result = $conn->query($query);

        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 ('$name', '$email', '$method', '$number', '$amount', '$trxid', '$date', '$time', '$fcm')";
                $update = "UPDATE users SET winning = winning - '$amount' WHERE email = '$email'";
                
                if ($conn->query($sql) === TRUE && $conn->query($update) === TRUE) {
                    echo "Request Successfully";
                } else {
                    echo "Error Requesting: " . $sql . "<br>" . $conn->error;
                }
            } else {
                echo "Withdraw Amount Is Insufficient";
            }
        } else {
            echo "No User Found";
        }
    }
    
    if ($type === 'pending') {
        $query = "SELECT * FROM withdraw WHERE status = 'Pending'";
        $result = mysqli_query($conn, $query);
        
        if ($result) {
            $data = [];
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }

            if (!empty($data)) {
                echo json_encode($data, JSON_UNESCAPED_UNICODE);
            } else {
                echo "No Unpaid Request Found";
            }
        } else {
            echo "Error Getting Unpaid Request: " . mysqli_error($conn);
        }
    }
    
    if ($type === 'failed') {
        $amount = $_POST['amount'];
        $email = $_POST['email'];
        $id = $_POST['id'];
        
        $sql = "UPDATE users SET winning = winning + $amount WHERE email = '$email'";
        $update = "UPDATE withdraw SET status = 'Failed' WHERE id = '$id'";
        
        if ($conn->query($sql) === TRUE && $conn->query($update) === TRUE) {
            echo "Withdraw Failed";
        } else {
            echo "Error Withdrawal: " . $conn->error;
        }
    }
    
    if ($type === 'success') {
        $id = $_POST['id'];
        
        $update = "UPDATE withdraw SET status = 'Success' WHERE id = '$id'";
        
        if ($conn->query($update) === TRUE) {
            echo "Withdraw Successfully";
        } else {
            echo "Error Withdrawal: " . $conn->error;
        }
    }
    $conn->close();
} else {
    echo "Invalid Request Method";
}
?>