<?php

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');

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'],
        ]);
    }
});

include "../pages/dbFunctions.php";
include "../auth/config.php";
include_once __DIR__ . '/../includes/order_status_lib.php';

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

$required_params = ["user_token", "order_id"];
foreach ($required_params as $param) {
    if (!isset($_POST[$param]) || empty($_POST[$param])) {
        http_response_code(400);
        echo json_encode(["status" => false, "message" => "Missing required parameter"]);
        exit();
    }
}

$user_token = filter_var($_POST["user_token"], FILTER_SANITIZE_STRING);
$order_id = filter_var($_POST["order_id"], FILTER_SANITIZE_STRING);

// This endpoint being reachable at all on the current domain is exactly
// what in-process callers (e.g. auth/lib/wallet_callback.php) now avoid
// depending on - see includes/order_status_lib.php's
// check_neopay_order_status(), called directly rather than over HTTP by
// anything that lives on this same server.
$result = check_neopay_order_status($conn, $user_token, $order_id, $site_settings ?? null);

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