<?php
// Configuration
$target_url = 'https://elcenia.k55.io';
$proxy_path = '/board';

// Function to forward the request
function forwardRequest($target_url, $proxy_path) {
    // Remove the proxy path from the request URI to get the actual path
    $request_uri = $_SERVER['REQUEST_URI'];
    if (strpos($request_uri, $proxy_path) === 0) {
        $request_uri = substr($request_uri, strlen($proxy_path));
    }
    
    // Build the target URL
    $url = rtrim($target_url, '/') . '/' . ltrim($request_uri, '/');
    
    // Initialize cURL
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);
    
    // Forward the request method
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
    
    // Forward POST data if present
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
    }
    
    // Forward headers
    $headers = [];
    foreach (getallheaders() as $name => $value) {
        if (!in_array(strtolower($name), ['host', 'connection', 'content-length', 'content-type'])) {
            $headers[] = "$name: $value";
        }
    }
    $headers[] = 'X-Forwarded-For: ' . $_SERVER['REMOTE_ADDR'];
    $headers[] = 'X-Forwarded-Proto: ' . 
        (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    // Execute the request
    $response = curl_exec($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    
    if ($error) {
        http_response_code(502);
        die('Proxy Error: ' . htmlspecialchars($error));
    }
    
    // Split headers and body
    $header_size = $info['header_size'];
    $header_text = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    
    // Forward response headers
    $headers = explode("\n", $header_text);
    foreach ($headers as $header) {
        $header = trim($header);
        if (!empty($header) && 
            !preg_match('/^(Transfer-Encoding|Content-Length|Connection):/i', $header)) {
            header($header);
        }
    }
    
    // Set response code
    http_response_code($info['http_code']);
    
    // Output the response body
    echo $body;
    
    curl_close($ch);
}

// Execute the proxy
forwardRequest($target_url, $proxy_path);
?>
