<?php
// proxy.php — place next to your HTML file under /html
// Usage from JS: fetch('/proxy.php?path=webhook/test-run-async', { method:'POST', body: ... })

set_time_limit(60); // 60s is enough — async calls return fast

$TARGET = 'http://192.168.1.150:5678';

// ── CORS preflight ──────────────────────────────────────────────
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

// ── Build target URL ────────────────────────────────────────────
$path = isset($_GET['path']) ? ltrim($_GET['path'], '/') : '';
if (empty($path)) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Missing path parameter']);
    exit;
}
$url = $TARGET . '/' . $path;

// ── Forward request body ────────────────────────────────────────
$body   = file_get_contents('php://input');
$method = $_SERVER['REQUEST_METHOD'];

// ── cURL request ────────────────────────────────────────────────
$ch = curl_init($url);

curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => $method,
    CURLOPT_POSTFIELDS     => $body,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 55,          // under PHP set_time_limit
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($body),
    ],
    // Pass response code through
    CURLOPT_HEADER         => false,
]);

$result   = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr  = curl_error($ch);
curl_close($ch);

// ── Return response ─────────────────────────────────────────────
header('Content-Type: application/json');
http_response_code($httpCode ?: 502);

if ($result === false) {
    echo json_encode(['error' => 'Proxy cURL error: ' . $curlErr]);
    exit;
}

echo $result;
