<?php
declare(strict_types=1);

// A/B/C SELECT-only clock, meal-window and recipe-count probe. No IDs/names output.
$lane = (string)getenv('CDX_EM_DUAL_LANE');
if (!in_array($lane, ['A', 'B', 'C'], true)
    || count($argv) !== 2 || ($argv[1] ?? '') !== '--preflight'
    || (string)getenv('CDX_EM_DUAL_WINDOW') !== 'OWNED_DUAL_WINDOW_SELECT_ONLY_V1'
    || !hash_equals((string)hash_file('sha256', __FILE__),
        (string)getenv('CDX_EM_DUAL_WINDOW_SHA'))) {
    echo json_encode(['status' => 'default-deny', 'db_connected' => false,
        'business_http_sent' => false, 'dml_sent' => false]), PHP_EOL;
    exit(78);
}
$stage = 'runtime';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted_stop', 'stage' => $stage,
        'error_class' => get_class($error), 'code' => (string)$error->getCode(),
        'business_http_sent' => false, 'dml_sent' => false]), PHP_EOL;
    exit(2);
});
$targets = [
    'A' => ['/tmp/zhct-http-store-a.l5omH8', 18097, 21023, 'mysql',
        '525caaeb63bc83a4f401de077b0784de49b98572b3b7732577b143138d9e7e28'],
    'B' => ['/tmp/zhct-http-store-mysql.dQTTBP', 18081, 10001, 'mysql',
        '179869c96cfdaf5e9de1003ace06949dc654bc4876efe89ec53455a7721e47cd'],
    'C' => ['/tmp/zhct-dm-poc-20260928.fcpiiN/store', 18080, 112175, 'dm',
        '179869c96cfdaf5e9de1003ace06949dc654bc4876efe89ec53455a7721e47cd'],
];
[$root, $port, $pid, $dialect, $serviceSha] = $targets[$lane];
if (PHP_VERSION_ID < 70300 || PHP_VERSION_ID >= 70400
    || is_link($root) || hash_file('sha256',
        $root . '/application/common/service/ElectronicMenu.php') !== $serviceSha
    || hash_file('sha256', $root . '/application/common/Common.php')
        !== '49e2eab5fdc17e514f9420418b4cc281b92edb560b99f7cc62935011138dfeb4') {
    throw new RuntimeException('Approved meal-time source changed');
}
$cmd = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
$children = trim((string)@file_get_contents('/proc/' . $pid
    . '/task/' . $pid . '/children'));
if (strpos($cmd, '127.0.0.1:' . $port) === false
    || strpos($cmd, $root . '/public') === false || $children !== '') {
    throw new RuntimeException('Isolated HTTP root changed');
}
$runtime = require $root . '/application/database.php';
if (!is_array($runtime)) throw new RuntimeException('Runtime config invalid');
if ($dialect === 'mysql') {
    $config = $runtime;
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    foreach (['hostname', 'hostport', 'database', 'username', 'password', 'type'] as $field) {
        if (($runtime[$field] ?? null) !== ($local[$field] ?? null)) {
            throw new RuntimeException('Not code-local development MySQL');
        }
    }
    $dsn = 'mysql:host=' . $runtime['hostname'] . ';port=' . (int)$runtime['hostport']
        . ';dbname=' . $runtime['database'] . ';charset=' . ($runtime['charset'] ?? 'utf8');
    $dbUser = (string)$runtime['username'];
    $dbPassword = (string)$runtime['password'];
} else {
    foreach (['hostname' => 'POC_HOST', 'hostport' => 'POC_PORT',
        'database' => 'POC_SCHEMA', 'username' => 'POC_USER',
        'password' => 'POC_PASSWORD'] as $field => $envKey) {
        if ((string)($runtime[$field] ?? '') !== (string)getenv($envKey)) {
            throw new RuntimeException('C runtime not approved DM');
        }
    }
    if ((string)getenv('POC_HOST') !== '127.0.0.1'
        || (string)getenv('POC_PORT') !== '5237'
        || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP') {
        throw new RuntimeException('C DM target drift');
    }
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
    $dbUser = (string)getenv('POC_USER');
    $dbPassword = (string)getenv('POC_PASSWORD');
}
$stage = 'database_identity_and_counts';
$db = new PDO($dsn, $dbUser, $dbPassword,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
if ($dialect === 'mysql') {
    $identity = (string)$db->query(
        "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
        ->fetchColumn();
    if (hash('sha256', $identity)
        !== '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401') {
        throw new RuntimeException('Developer MySQL identity mismatch');
    }
} else {
    $schema = strtoupper((string)$db->query(
        "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn());
    if ($schema !== 'ZHCT_APP') throw new RuntimeException('C DM schema mismatch');
}
$table = static function (string $name) use ($dialect): string {
    if (!in_array($name, ['electronic_menu', 'restaurants', 'recipes', 'dishes'], true)) {
        throw new RuntimeException('Unapproved source table');
    }
    return $dialect === 'dm' ? strtoupper('ydy_' . $name) : 'ydy_' . $name;
};
$candidate = $db->query('SELECT m.LEFT_RESTAURANT_ID,m.RIGHT_RESTAURANT_ID'
    . ' FROM ' . $table('electronic_menu') . ' m JOIN ' . $table('restaurants')
    . ' l ON l.ID=m.LEFT_RESTAURANT_ID JOIN ' . $table('restaurants')
    . ' r ON r.ID=m.RIGHT_RESTAURANT_ID'
    . ' WHERE m.STORE_ID=10001 AND m.STATUS=1 AND m.IS_DELETE=0'
    . ' AND m.DISPLAY_MODE=2 AND m.RIGHT_RESTAURANT_ID>0'
    . ' AND l.STATUS=1 AND l.IS_DELETE=2 AND r.STATUS=1 AND r.IS_DELETE=2'
    . ' ORDER BY m.ID')->fetch(PDO::FETCH_ASSOC);
$left = (int)($candidate['left_restaurant_id'] ?? 0);
$right = (int)($candidate['right_restaurant_id'] ?? 0);
if ($left <= 0 || $right <= 0 || $left === $right) {
    throw new RuntimeException('No matching two-stall candidate');
}
$restaurant = $db->prepare('SELECT MORNING_START,MORNING_END,NOON_START,NOON_END,'
    . ' NIGHT_START,NIGHT_END FROM ' . $table('restaurants') . ' WHERE ID=?');
$recipe = $db->prepare('SELECT COUNT(*) FROM ' . $table('recipes')
    . ' r JOIN ' . $table('dishes') . ' d ON d.UUID=r.DISHES_UUID'
    . ' WHERE r.RESTAURANT_ID=? AND r.MENU_DATE=? AND r.MEAL_TIMES=?'
    . ' AND d.STATUS=1 AND d.IS_DEL=1');
date_default_timezone_set('PRC');
$day = date('Y-m-d');
$clock = date('H:i:s');
$sides = [];
foreach (['left' => $left, 'right' => $right] as $label => $restaurantId) {
    $restaurant->execute([$restaurantId]);
    $row = $restaurant->fetch(PDO::FETCH_ASSOC);
    if (!is_array($row)) throw new RuntimeException('Active restaurant disappeared');
    $ranges = [];
    foreach (['morning', 'noon', 'night'] as $period) {
        $start = substr((string)($row[$period . '_start'] ?? ''), 0, 5);
        $end = substr((string)($row[$period . '_end'] ?? ''), 0, 5);
        if (!preg_match('/^\d\d:\d\d$/D', $start)
            || !preg_match('/^\d\d:\d\d$/D', $end)) {
            throw new RuntimeException('Meal-window metadata invalid');
        }
        $ranges[$period] = [$start . ':00', $end . ':59'];
    }
    $counts = [];
    for ($meal = 1; $meal <= 4; $meal++) {
        $recipe->execute([$restaurantId, $day, $meal]);
        $counts[$meal] = (int)$recipe->fetchColumn();
    }
    $sides[$label] = ['window' => $ranges, 'valid_recipe_count_by_meal' => $counts];
}
$active = 4;
foreach (['morning' => 1, 'noon' => 2, 'night' => 3] as $period => $meal) {
    if ($clock >= $sides['left']['window'][$period][0]
        && $clock <= $sides['left']['window'][$period][1]) {
        $active = $meal;
        break;
    }
}
echo json_encode(['status' => 'select_only_pass', 'lane' => $lane,
    'business_date' => $day, 'clock' => $clock,
    'timezone' => 'PRC', 'current_left_meal_times' => $active,
    'left' => $sides['left'], 'right' => $sides['right'],
    'business_http_sent' => false, 'dml_sent' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
