<?php
declare(strict_types=1);

$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) exit(78);
$root = $lane === 'B' ? '/tmp/zhct-http-store-mysql.dQTTBP'
    : '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
$cfg = require $root . '/application/database.php';
if ($lane === 'B') {
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    foreach (['hostname', 'database', 'username', 'password'] as $key) {
        if (($cfg[$key] ?? null) !== ($local[$key] ?? null)) exit(78);
    }
    $dsn = 'mysql:host=' . $cfg['hostname'] . ';port=' . ($cfg['hostport'] ?? 3306)
        . ';dbname=' . $cfg['database'] . ';charset=utf8mb4';
    $table = ['ydy_recipes', 'ydy_dishes', 'ydy_staff'];
    $limit = 'LIMIT 8';
} else {
    if ((string)($cfg['hostname'] ?? '') !== '127.0.0.1'
        || (int)($cfg['hostport'] ?? 0) !== 5237
        || strtoupper((string)($cfg['database'] ?? '')) !== 'ZHCT_APP') exit(78);
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
    $table = ['YDY_RECIPES', 'YDY_DISHES', 'YDY_STAFF'];
    $limit = 'FETCH FIRST 8 ROWS ONLY';
}
$db = new PDO($dsn, (string)$cfg['username'], (string)$cfg['password'], [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CASE => PDO::CASE_LOWER,
]);
$sql = 'SELECT a.MENU_DATE,a.MEAL_TIMES,a.RESTAURANT_ID,b.CATEGORY,COUNT(*) N FROM '
    . $table[0] . ' a JOIN ' . $table[1] . ' b ON a.DISHES_UUID=b.UUID'
    . ' WHERE b.STATUS=1 AND b.IS_DEL=1 GROUP BY a.MENU_DATE,a.MEAL_TIMES,a.RESTAURANT_ID,b.CATEGORY'
    . ' ORDER BY N DESC ' . $limit;
$result = [];
foreach ($db->query($sql, PDO::FETCH_ASSOC) as $row) {
    $row = array_change_key_case($row, CASE_LOWER);
    $result[] = ['date' => (string)$row['menu_date'], 'meal' => (int)$row['meal_times'],
        'restaurant' => (int)$row['restaurant_id'], 'category' => (int)$row['category'],
        'joined_count' => (int)$row['n']];
}
$staff = $db->prepare('SELECT COUNT(*) FROM ' . $table[2] . ' WHERE UUID=?');
$staff->execute(['1']);
echo json_encode(['lane' => $lane, 'groups' => $result,
    'default_restaurant_id_as_staff_uuid_count' => (int)$staff->fetchColumn()],
    JSON_UNESCAPED_UNICODE), PHP_EOL;
