<?php

// Cargar Composer autoload
require_once __DIR__ . '/vendor/autoload.php';

// Cargar variables de entorno desde .env
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

if (!isset($_ENV['BACKEND_BASE_URL'])) {
    http_response_code(500);
    die("Error: BACKEND_BASE_URL no está configurado en .env");
}

// Configuración del backend desde variable de entorno
$backend_base_url = $_ENV['BACKEND_BASE_URL'];

// Construir la URL destino (evitar doble barra)
$path = $_SERVER['REQUEST_URI'];
$target_url = rtrim($backend_base_url, '/') . $path;

// Inicializar cURL
$ch = curl_init($target_url);

// Configurar método HTTP
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);

// Pasar cuerpo si existe
$input = file_get_contents('php://input');
if ($input !== false && !empty($input)) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
}

// Copiar headers, excluyendo algunos sensibles
$headers = [];
foreach (getallheaders() as $key => $value) {
    if (in_array(strtolower($key), ['host', 'connection'])) continue;
    $headers[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Configuraciones adicionales
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

// Ejecutar request
$response = curl_exec($ch);

// Manejo de errores
if ($response === false) {
    http_response_code(502);
    echo "Error al conectar con el backend: " . curl_error($ch);
    curl_close($ch);
    exit;
}

// Separar headers y body
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$raw_headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);

// Enviar headers de respuesta
foreach (explode("\r\n", $raw_headers) as $header_line) {
    if (stripos($header_line, 'Transfer-Encoding:') === 0) continue;
    if (stripos($header_line, 'Content-Length:') === 0) continue;
    if ($header_line) header($header_line, false);
}

// Enviar código de estado original
http_response_code(curl_getinfo($ch, CURLINFO_HTTP_CODE));

// Enviar cuerpo
echo $body;

curl_close($ch);
?>