<?php

declare(strict_types=1);

$base = rtrim((string)getenv('POC_BASE_URL'), '/');
$dialect = (string)getenv('POC_DIALECT');
if ($base === '' || !in_array($dialect, ['mysql', 'dm'], true)) {
    throw new RuntimeException('Private cooking HTTP base required');
}
$send = static function (string $route, array $form) use ($base): array {
    $context = stream_context_create(['http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
        'timeout' => 15, 'ignore_errors' => true,
    ]]);
    $body = file_get_contents($base . $route, false, $context);
    $headers = $http_response_header ?? [];
    preg_match('/HTTP\/\S+\s+(\d+)/', (string)($headers[0] ?? ''), $match);
    $json = is_string($body) ? json_decode($body, true) : null;
    return ['http_status' => isset($match[1]) ? (int)$match[1] : 0,
        'json' => is_array($json) ? $json : null];
};
$day = '2001-01-02';
$primary = $send('/p/restaurant/cook_method', [
    'restaurant_id' => 1, 'menu_date' => $day, 'meal_times' => 1,
]);
$primaryMap = (array)($primary['json']['data']['map'] ?? []);
$primaryPass = $primary['http_status'] === 200
    && (int)($primary['json']['code'] ?? -1) === 0
    && count($primaryMap) === 20
    && array_sum(array_map('intval', $primaryMap)) === 0;
$stage = $send('/p/restaurant/stage_cook_method', [
    'restaurant_id' => 1, 'start_time' => $day, 'end_time' => $day,
    'meal_times' => 1, 'cook' => 1,
]);
$stageMap = (array)($stage['json']['data']['map'] ?? []);
$stagePass = $stage['http_status'] === 200
    && (int)($stage['json']['code'] ?? -1) === 0
    && count($stageMap) === 14;
echo json_encode(['dialect' => $dialect, 'fixed_empty_day' => $day,
    'primary' => ['status' => $primaryPass ? 'tested-pass' : 'tested-fail',
        'http_status' => $primary['http_status'],
        'business_code' => $primary['json']['code'] ?? null,
        'cook_categories' => count($primaryMap)],
    'stage' => ['status' => $stagePass ? 'tested-pass' : 'tested-fail',
        'http_status' => $stage['http_status'],
        'business_code' => $stage['json']['code'] ?? null,
        'cook_categories' => count($stageMap)]], JSON_UNESCAPED_UNICODE) . PHP_EOL;
if (!$primaryPass || !$stagePass) exit(1);
