<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', '/home/clients/24b5885304321852546155d14ac549e4/logs/php_errors.log');

error_log("=== Starting new request ===");
error_log("Request URI: " . $_SERVER['REQUEST_URI']);
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

try {
	// Check if Node.js server is running
	$ch = curl_init("http://127.0.0.1:3001/health");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
	$health_response = curl_exec($ch);
	$health_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

	if ($health_status !== 200) {
		error_log("Node.js server not responding. Health check failed with status: " . $health_status);
		throw new Exception("Backend service unavailable");
	}

	// Proceed with the main request
	$url = 'http://127.0.0.1:3001' . $_SERVER['REQUEST_URI'];
	error_log("Proxying to: " . $url);

	$ch = curl_init($url);
	if ($ch === false) {
		throw new Exception('Failed to initialize CURL');
	}

	// Forward request method
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_FAILONERROR, false);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

	// Forward headers
	$headers = getallheaders();
	$curlHeaders = [];
	foreach ($headers as $key => $value) {
		if ($key !== 'Host') {
			$curlHeaders[] = "$key: $value";
		}
		error_log("Header: $key: $value");
	}
	curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);

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

	$response = curl_exec($ch);
	$curl_info = curl_getinfo($ch);
	error_log("CURL Info: " . print_r($curl_info, true));

	if ($response === false) {
		throw new Exception("CURL Error: " . curl_error($ch));
	}

	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	error_log("Response code: " . $httpCode);
	error_log("Response body: " . substr($response, 0, 1000));

	http_response_code($httpCode);
	curl_close($ch);

	// Set JSON content type
	header('Content-Type: application/json');
	echo $response;

} catch (Exception $e) {
	error_log("Error in proxy: " . $e->getMessage());
	error_log("Stack trace: " . $e->getTraceAsString());
	
	http_response_code(500);
	header('Content-Type: application/json');
	echo json_encode([
		'error' => 'Internal server error',
		'message' => $e->getMessage()
	]);
} 