<?php

declare(strict_types=1);

$base = rtrim((string)getenv('POC_BASE_URL'), '/');
$route = (string)getenv('POC_ROUTE');
if ($base === '' || strpos($route, '/') !== 0) {
    throw new RuntimeException('Loopback base URL and route required');
}
$context = stream_context_create(['http' => [
    'method' => (string)(getenv('POC_METHOD') ?: 'POST'),
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
    'content' => (string)getenv('POC_CONTENT'),
    'ignore_errors' => true,
    'timeout' => 15,
]]);
$body = file_get_contents($base . $route, false, $context);
if (!is_string($body)) throw new RuntimeException('No HTTP response');
$status = null;
$contentType = null;
foreach ($http_response_header as $header) {
    if (preg_match('/^HTTP\/\S+\s+(\d{3})/', $header, $matches)) {
        $status = (int)$matches[1];
    } elseif (stripos($header, 'Content-Type:') === 0) {
        $contentType = trim(substr($header, strlen('Content-Type:')));
    }
}
echo json_encode(['http_status' => $status, 'content_type' => $contentType,
    'body' => $body], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
