<?php

declare(strict_types=1);

$root = rtrim((string)getenv('POC_TARGET_ROOT'), '/');
$baseUrl = rtrim((string)getenv('POC_BASE_URL'), '/');
$route = (string)getenv('POC_ROUTE');
$form = json_decode((string)getenv('POC_FORM_JSON'), true);
if ($root === '' || $baseUrl === '' || strpos($route, '/') !== 0 || !is_array($form)) {
    throw new RuntimeException('POC target, route, and form JSON required');
}
$headers = "Content-Type: application/x-www-form-urlencoded\r\n";
if (getenv('POC_AUTH') === 'admin') {
    require_once $root . '/application/base/Security.php';
    $token = \app\base\Security::encrypt(implode("\t", [
        '1', 'CDX-ADMIN', 'CODEX', '0', '', '', 'CODEX',
    ]));
    $headers .= 'token: ' . $token . "\r\n";
}
$context = stream_context_create(['http' => [
    'method' => 'POST',
    'header' => $headers,
    'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
    'timeout' => 15,
    'ignore_errors' => true,
]]);
$raw = file_get_contents($baseUrl . $route, false, $context);
if (!is_string($raw)) {
    throw new RuntimeException('HTTP response unavailable');
}
$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:')));
    }
}
$body = json_decode($raw, true);
if (!is_array($body) || json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Expected JSON object response');
}
echo json_encode(['http_status' => $status, 'content_type' => $contentType,
    'body' => $body], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
