<?php
ob_clean(); // clears any accidental whitespace/output

// === Set CORS Headers ===
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, Cache-Control, Pragma, Expires');


// === Handle CORS Preflight ===
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204); // No Content
    exit();
}

// === Forwarding Config ===
$forwardBase = 'https://score.gamespro.mobi/V1/gameplay';

// === Detect Endpoint ===
$headers = getallheaders();
$method = $_SERVER['REQUEST_METHOD'];
$endpoint = '';

if (!empty($_SERVER['PATH_INFO'])) {
    $endpoint = trim($_SERVER['PATH_INFO'], '/');
} elseif (preg_match('#/api\.php/([^?/]+)#', $_SERVER['REQUEST_URI'], $matches)) {
    $endpoint = $matches[1];
} else {
    http_response_code(400);
    echo json_encode(['error' => 'No endpoint detected']);
    exit;
}

$targetUrl = $forwardBase . '/' . $endpoint;

// === Stream Context Options ===
$options = [
    "http" => [
        "method" => $method,
        "header" => "",
        "ignore_errors" => true
    ]
];

// === Forward Authorization header if available ===
if (isset($headers['Authorization'])) {
    $options["http"]["header"] .= "Authorization: " . $headers['Authorization'] . "\r\n";
}

// === Append query string for GET requests ===
if ($method === 'GET' && !empty($_SERVER['QUERY_STRING'])) {
    $targetUrl .= '?' . $_SERVER['QUERY_STRING'];
}

// === Forward JSON body for POST ===
if ($method === 'POST') {
    $body = file_get_contents("php://input");
    $options["http"]["content"] = $body;
    $options["http"]["header"] .= "Content-Type: application/json\r\n";
    $options["http"]["header"] .= "Content-Length: " . strlen($body) . "\r\n";
}

// === Send the request ===
$context = stream_context_create($options);
$response = file_get_contents($targetUrl, false, $context);

// === Get status code from response header ===
$http_response_code = 200;
if (isset($http_response_header[0])) {
    preg_match('/HTTP\/[\d\.]+\s+(\d+)/', $http_response_header[0], $statusMatch);
    $http_response_code = isset($statusMatch[1]) ? (int)$statusMatch[1] : 200;
}
http_response_code($http_response_code);

// === Output the proxied response ===
echo $response;
exit;
