<?php
// ============================================================
// Entry point — CORS + routing
// ============================================================
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

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

$uri    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// Remove the base path and /api prefix
$uri    = str_replace('/stile-lpg/backend/api/', '', $uri);
$uri    = str_replace('/stile-lpg/backend/', '', $uri);
$uri    = trim($uri, '/');
$method = $_SERVER['REQUEST_METHOD'];

// Route map
$routes = [
    // Auth
    'auth/login'    => 'auth/login.php',
    'auth/register' => 'auth/register.php',

    // Customer - matching actual file paths
    'customer/products/list'           => 'customer/products/list.php',
    'customer/orders/my-orders'        => 'customer/orders/my-orders.php',
    'customer/orders/place-order'      => 'customer/orders/place-order.php',
    'customer/profile'                 => 'customer/profile.php',

    // Admin
    'admin/products'     => 'admin/products/index.php',
    'admin/orders'       => 'admin/orders/index.php',
    'admin/users'        => 'admin/users/index.php',
    'admin/gallery'      => 'admin/gallery/index.php',
    'admin/messages'     => 'admin/messages/index.php',
    'admin/stats'        => 'admin/stats/index.php',

    // Public
    'public/gallery'     => 'public/gallery.php',
    'public/contact'     => 'public/contact.php',
];

if (isset($routes[$uri])) {
    require __DIR__ . '/api/' . $routes[$uri];
} else {
    http_response_code(404);
    echo json_encode(['error' => 'Not found', 'path' => $uri]);
}
