<?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';
foreach (['hostname', 'hostport', 'database', 'username', 'password'] as $key) {
    if (empty($config[$key])) throw new RuntimeException('Isolated business connection incomplete');
}
$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_';
$equipment = $prefix . ($dialect === 'dm' ? 'EQUIPMENT' : 'equipment');
$restaurants = $prefix . ($dialect === 'dm' ? 'RESTAURANTS' : 'restaurants');
$shops = $prefix . ($dialect === 'dm' ? 'RESTAURANT_SHOP' : 'restaurant_shop');
$areas = $prefix . ($dialect === 'dm' ? 'RESTAURANT_AREA' : 'restaurant_area');
$sql = "SELECT e.CODE,e.RESTAURANT_ID FROM $equipment e "
    . "JOIN $restaurants r ON r.ID=e.RESTAURANT_ID "
    . "JOIN $shops s ON s.ID=r.RESTAURANT_SHOP_ID "
    . "JOIN $areas a ON a.ID=s.AREA_ID "
    . 'WHERE e.DEL_FLAG=0 AND r.IS_DELETE=2 AND r.STATUS=1 '
    . 'AND s.IS_DELETE=0 AND s.STATUS=1 AND a.IS_DELETE=0 AND a.STATUS=1 '
    . 'ORDER BY e.ID LIMIT 1';
$fixture = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
if (!$fixture || empty($fixture['CODE'])) {
    echo json_encode(['dialect' => $dialect, 'status' => 'fixture_missing']) . PHP_EOL;
    exit(3);
}
$body = http_build_query(['equipment_code' => $fixture['CODE']], '', '&', 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(rtrim($url, '/') . '/api/orderMachine/restaurantList', false, $context);
$result = is_string($response) ? json_decode($response, true) : null;
if (!is_array($result) || ($result['code'] ?? null) !== 0
    || (int)($result['data']['equipment']['restaurant_id'] ?? 0) !== (int)$fixture['RESTAURANT_ID']) {
    throw new RuntimeException('Order-machine HTTP query and database relationship differ');
}
echo json_encode(['dialect' => $dialect, 'status' => 'passed', 'area_found' => true,
    'restaurant_matches_database' => true, 'shop_count' => count((array)($result['data']['list'] ?? []))]) . PHP_EOL;
