<?php
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'];
    
    if ($type === 'requestxstrong') {
        $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");

        $sql = "INSERT INTO addmoney (name, email, method, number, amount, trxid, date, time, fcm) VALUES ('$name', '$email', '$method', '$number', '$amount', '$trxid', '$date', '$time', '$fcm')";
        
        if ($conn->query($sql) === TRUE) {
            echo "Request Successfully";
        } else {
            echo "Error Requesting: " . $sql . "<br>" . $conn->error;
        }
    }
    
    if ($type === 'pending') {
        $query = "SELECT * FROM addmoney 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 === 'success') {
        $amount = $_POST['amount'];
        $email = $_POST['email'];
        $id = $_POST['id'];
        
        $sql = "UPDATE users SET balance = balance + $amount WHERE email = '$email'";
        $update = "UPDATE addmoney SET status = 'Success' WHERE id = '$id'";
        
        if ($conn->query($sql) === TRUE && $conn->query($update) === TRUE) {
            echo "Add Money Successfully";
        } else {
            echo "Error Add Money: " . $conn->error;
        }
    }
    
    if ($type === 'failed') {
        $id = $_POST['Id'];
        
        $update = "UPDATE addmoney SET status = 'Failed' WHERE id = '$id'";
        
        if ($conn->query($update) === TRUE) {
            echo "Add Money Failed Success";
        } else {
            echo "Error Add Money: " . $conn->error;
        }
    }
    
    $conn->close();
} else {
    echo "Invalid Request Method";
}
?>