<?php
/**
 * eKonsultar registration proxy (no Node or terminal needed).
 * Receives JSON from the React app, forwards to on-prem regapi as form-urlencoded.
 *
 * 1. Edit ONPREM_REGAPI_URL below if your API URL is different.
 * 2. Upload this file with the rest of deploy/ekonsultar-app (same folder as index.html).
 * 3. Build the client with VITE_API_PROXY_URL set to this script (e.g. /ekonsultar-app/proxy.php).
 */

// --- Edit this if your on-prem API URL is different ---
$ONPREM_REGAPI_URL = 'http://103.5.63.90:6060/ekonsultar/registration/regapi';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

$params = [];
foreach ($data as $key => $value) {
    $params[$key] = ($value !== null && $value !== '') ? (string) $value : ' ';
}
$body = http_build_query($params);

$ch = curl_init($ONPREM_REGAPI_URL);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 30,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);

if ($err) {
    http_response_code(502);
    echo json_encode(['error' => 'Proxy request failed', 'details' => $err]);
    exit;
}

http_response_code($httpCode);
echo $response;
