<?php
// Router for PHP built-in server
$request_uri = $_SERVER['REQUEST_URI'];
$request_method = $_SERVER['REQUEST_METHOD'];

// Remove query string from request URI
$path = parse_url($request_uri, PHP_URL_PATH);

// Set CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// Handle OPTIONS requests
if ($request_method == 'OPTIONS') {
    exit(0);
}

// Route API requests
if (strpos($path, '/api/') === 0) {
    // Extract the API file path
    $api_file = substr($path, 5); // Remove '/api/' prefix
    
    // Add .php extension if not present
    if (!strpos($api_file, '.php')) {
        $api_file .= '.php';
    }
    
    // Construct full file path
    $file_path = __DIR__ . '/api/' . $api_file;
    
    // Check if file exists
    if (file_exists($file_path)) {
        include $file_path;
    } else {
        // Return 404 for non-existent API endpoints
        http_response_code(404);
        echo json_encode(array("message" => "API endpoint not found"));
    }
} else {
    // Serve static files or return 404
    $file_path = __DIR__ . $path;
    
    if ($path === '/' || $path === '/index.html') {
        // Serve a simple index page
        http_response_code(200);
        echo "<h1>Inventory API Server</h1>";
        echo "<p>API is running on port 8080</p>";
        echo "<p>Available endpoints:</p>";
        echo "<ul>";
        echo "<li><a href='/api/auth.php'>/api/auth.php</a></li>";
        echo "<li><a href='/api/items.php'>/api/items.php</a></li>";
        echo "<li><a href='/api/clients.php'>/api/clients.php</a></li>";
        echo "<li><a href='/api/invoices.php'>/api/invoices.php</a></li>";
        echo "</ul>";
    } elseif (file_exists($file_path) && is_file($file_path)) {
        // Serve static files
        $mime_types = array(
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'html' => 'text/html',
            'txt' => 'text/plain'
        );
        
        $extension = pathinfo($file_path, PATHINFO_EXTENSION);
        if (isset($mime_types[$extension])) {
            header("Content-Type: " . $mime_types[$extension]);
        }
        
        readfile($file_path);
    } else {
        // Return 404 for other requests
        http_response_code(404);
        echo json_encode(array("message" => "Not found"));
    }
}
?>
