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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!isset($_POST['type']) || trim($_POST['type']) !== 'requestxstrong') {
        echo "Invalid request";
        exit;
    }

    $username = trim($_POST['username'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $method   = trim($_POST['method'] ?? '');
    $number   = trim($_POST['number'] ?? '');
    $amount   = trim($_POST['amount'] ?? '');
    $trxid    = trim($_POST['trxid'] ?? '');
    $fcm      = trim($_POST['fcm'] ?? '');

    if (empty($username) || empty($email) || empty($method) || empty($number) || empty($amount) || empty($trxid) || empty($fcm)) {
        echo "All fields are required";
        exit;
    }

    // 🔒 Check AddMoney Service Status
    $psp = $conn->query("SELECT addmoney_open FROM appinfo WHERE id = 1 LIMIT 1");
    if (!$psp || $psp->num_rows == 0) {
        echo "Payment System Error";
        exit;
    }
    $pspData = $psp->fetch_assoc();
    $addmoneyOpen = intval($pspData['addmoney_open']); // 1 = OFF, 0 = ON

    if ($addmoneyOpen === 1) {
        echo "Add Money Service is Currently Closed";
        exit;
    }

    // 🟠 Pending request check
    $check_stmt = $conn->prepare("SELECT id FROM addmoney WHERE username = ? AND status = 'Pending' LIMIT 1");
    $check_stmt->bind_param("s", $username);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();

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

    // 🧾 Insert Pending AddMoney Request
    $date = date("d-M-Y");
    $time = date("h:i:s A");
    $status = "Pending";

    $insert = $conn->prepare("INSERT INTO addmoney (username, email, method, number, amount, trxid, date, time, fcm, status)
                              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $insert->bind_param("ssssssssss", $username, $email, $method, $number, $amount, $trxid, $date, $time, $fcm, $status);

    if ($insert->execute()) {
        echo "Request Successfully Submitted";
    } else {
        echo "Error Requesting: " . $insert->error;
    }

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

} else {
    echo "Invalid Request Method";
}
?>