<?php
// Get the request URI
$request_uri = $_SERVER['REQUEST_URI'];

// Build the target URL
$target_url = 'http://127.0.0.1:3000' . $request_uri;

// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);  // Include headers in output
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Forward the original request method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);

// Forward POST data if it exists
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}

// Execute the request
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

curl_close($ch);

// Separate headers and body
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);

// Set the response code
http_response_code($http_code);

// Forward important headers
$header_lines = explode("\n", $headers);
foreach ($header_lines as $header) {
    $header = trim($header);
    if (preg_match('/^(Content-Type|Content-Length|Set-Cookie):/i', $header)) {
        header($header);
    }
}

// Ensure proper content type for HTML
if (strpos($body, '<html') !== false) {
    header('Content-Type: text/html; charset=utf-8');
}

// Output the response body
echo $body;
?>