<?php
require_once(__DIR__ . '/api/routes.php');

header("Content-Type: application/json; charset=UTF-8");

$allowedOrigins = [
    "http://localhost",
    "http://localhost:3000",
    "http://127.0.0.1",
    "http://localhost:64049",
    "http://localhost:53522"
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowedOrigins)) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    header("Access-Control-Allow-Origin: *"); // For testing only, restrict in production
}

// Allow methods
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

// Allow headers
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, shopboy_api_key");

// Allow credentials
header("Access-Control-Allow-Credentials: true");

// Handle OPTIONS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Enable error reporting
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

// Get URI and method
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$basePath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
// This strips /sb/api/ or /sb/ from the start
$request = ltrim(preg_replace('#^sb(/api)?/#', '', trim($uri, '/')), '/');
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';

error_log("Final routed request: " . $request);

// Route request
$response = route($request, $requestMethod);

// Output response
echo json_encode($response);
