<?php
// CORS - this API is meant to be called from any website (that's the whole
// point of the JS SDK), not just neopay.mgamer.online itself.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

header("Content-Type: application/json");

// This is a public API hit by external servers (WHMCS modules, the JS
// SDK, merchant backends) that can only parse JSON - if anything below
// fatal-errors, PHP's default behaviour (especially with error display
// off) can leave the response blank or full of raw HTML, which callers
// then can't parse, showing a generic "Unable to create payment order"
// with no real reason. Catch that here and always emit valid JSON with
// the actual error, instead.
register_shutdown_function(function () {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        if (!headers_sent()) {
            http_response_code(500);
            header("Content-Type: application/json");
        }
        echo json_encode([
            "status" => false,
            "message" => "Server error: " . $error['message'] . " in " . basename($error['file']) . " on line " . $error['line'],
        ]);
    }
});

define('PROJECT_ROOT', realpath(dirname(__FILE__)) . '/../');

include PROJECT_ROOT . 'pages/dbFunctions.php';
include PROJECT_ROOT . 'pages/dbInfo.php';
include PROJECT_ROOT . 'auth/config.php';
include PROJECT_ROOT . 'includes/subscription_lib.php';
include PROJECT_ROOT . 'includes/merchant_lib.php';
include PROJECT_ROOT . 'includes/white_label_lib.php';
include PROJECT_ROOT . 'includes/order_lib.php';

if ($_SERVER["REQUEST_METHOD"] != "POST") {
    http_response_code(400);
    echo json_encode(["status" => false, "message" => "Unauthorized Access"]);
    exit();
}

// This endpoint being reachable at all on the current domain (rewrite
// rules working etc.) is exactly what in-process callers like Payment
// Link / Wallet top-up now avoid depending on - see
// includes/order_lib.php's create_neopay_order(), called directly rather
// than over HTTP by anything that lives on this same server.
$result = create_neopay_order($conn, $_POST);

http_response_code($result['http_code']);
echo json_encode($result['body']);
exit();
