<?php

declare(strict_types=1);

$root = getenv('POC_TARGET_ROOT');
$url = getenv('POC_BASE_URL');
$dialect = getenv('POC_DIALECT');
if (!$root || !$url || !in_array($dialect, ['mysql', 'dm'], true)) exit(2);
$config = require $root . '/application/database.php';
$dsn = $dialect === 'dm'
    ? 'dm:host=' . $config['hostname'] . ';port=' . $config['hostport'] . ';schema=' . $config['database']
    : 'mysql:host=' . $config['hostname'] . ';port=' . $config['hostport'] . ';dbname=' . $config['database'] . ';charset=utf8mb4';
$pdo = new PDO($dsn, $config['username'], $config['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$prefix = $dialect === 'dm' ? 'YDY_' : 'ydy_';
$restaurants = $prefix . ($dialect === 'dm' ? 'RESTAURANTS' : 'restaurants');
$recipes = $prefix . ($dialect === 'dm' ? 'RECIPES' : 'recipes');
$dishes = $prefix . ($dialect === 'dm' ? 'DISHES' : 'dishes');
$sql = "SELECT r.ID AS RESTAURANT_ID, x.MENU_DATE, x.MEAL_TIMES, x.DISHES_UUID FROM $restaurants r "
    . "JOIN $recipes x ON x.RESTAURANT_ID=r.ID "
    . "JOIN $dishes d ON d.UUID=x.DISHES_UUID "
    . 'WHERE r.STALL_TYPE=2 AND r.STATUS=1 AND r.IS_DELETE=2 '
    . 'AND x.MENU_DATE>=? AND d.STATUS=1 AND d.IS_DEL=1 '
    . 'ORDER BY x.MENU_DATE DESC,x.MEAL_TIMES DESC,x.ID '
    . ($dialect === 'dm' ? 'FETCH FIRST 20 ROWS ONLY' : 'LIMIT 20');
$stmt = $pdo->prepare($sql);
$stmt->execute([date('Y-m-d')]);
$candidates = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$candidates) {
    echo json_encode(['dialect' => $dialect, 'status' => 'fixture_missing', 'candidate_recipes' => 0]) . PHP_EOL;
    exit(3);
}
$endpoint = rtrim($url, '/') . '/api/orderMachine/confirm';
$rejections = [];
foreach ($candidates as $candidate) {
    $payload = [
        'restaurant_id' => (int)$candidate['RESTAURANT_ID'],
        'meal_date' => substr((string)$candidate['MENU_DATE'], 0, 10),
        'meal_times' => (int)$candidate['MEAL_TIMES'],
        'dishes' => [['uuid' => (string)$candidate['DISHES_UUID'], 'number' => 1]],
    ];
    $body = http_build_query($payload, '', '&', PHP_QUERY_RFC3986);
    $context = stream_context_create(['http' => [
        'method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => $body, 'timeout' => 12, 'ignore_errors' => true,
    ]]);
    $response = file_get_contents($endpoint, false, $context);
    $data = is_string($response) ? json_decode($response, true) : null;
    if (!is_array($data)) throw new RuntimeException('Order-machine confirm returned non-JSON');
    if (($data['code'] ?? null) === 0) {
        if ((int)($data['data']['restaurant_id'] ?? 0) !== $payload['restaurant_id']
            || count((array)($data['data']['dishes'] ?? [])) < 1) {
            throw new RuntimeException('Confirmed order fixture did not match database');
        }
        echo json_encode(['dialect' => $dialect, 'status' => 'passed', 'candidate_recipes' => count($candidates),
            'restaurant_matches_database' => true, 'confirmed_dishes' => count($data['data']['dishes'])]) . PHP_EOL;
        exit(0);
    }
    $key = substr((string)($data['message'] ?? 'unknown'), 0, 70);
    $rejections[$key] = ($rejections[$key] ?? 0) + 1;
}
echo json_encode(['dialect' => $dialect, 'status' => 'no_valid_candidate',
    'candidate_recipes' => count($candidates), 'rejections' => $rejections], JSON_UNESCAPED_UNICODE) . PHP_EOL;
exit(1);
