<?php

declare(strict_types=1);

$root = getenv('POC_TARGET_ROOT');
if (!$root) exit(2);
define('APP_PATH', $root . '/application/');
require $root . '/thinkphp/base.php';
\think\Config::set(require $root . '/application/database.php', 'database');
\think\Db::clear();
$query = \think\Db::name('meal_order')->alias('mo')
    ->join('meal_order_pickup pickup', 'pickup.meal_order_id = mo.id')
    ->join('restaurants restaurant', 'restaurant.id = mo.restaurant_id', 'LEFT')
    ->join('user user', 'user.id = mo.user_id', 'LEFT')
    ->where('mo.is_delete', 0)
    ->where('mo.pay_status', 20)
    ->where('mo.create_time', '>=', date('Y-m-d 00:00:00', strtotime('-2 day')))
    ->where('mo.order_no', 'CODEXDM8_NO_SUCH_ORDER_20260929')
    ->field([
        'mo.id', 'mo.order_no', 'mo.user_mobile', 'mo.user_name',
        'user.mobile as user_mobile_real', 'user.name as user_name_real',
        'mo.pay_price', 'mo.pay_time', 'mo.meal_date',
        'restaurant.name as restaurant_name', 'pickup.pickup_no',
        'pickup.prepare_status',
    ])
    ->order(['mo.id' => 'desc']);
$sql = $query->fetchSql(true)->select();
$config = require $root . '/application/database.php';
$dialect = getenv('POC_DIALECT');
$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]);
foreach ([$sql, str_replace(['user.mobile', 'user.name'], ['`user`.`mobile`', '`user`.`name`'], $sql)] as $index => $candidate) {
    try {
        $pdo->query($candidate);
        echo ($index === 0 ? 'current' : 'quoted_user') . ':passed' . PHP_EOL;
    } catch (Throwable $error) {
        echo ($index === 0 ? 'current' : 'quoted_user') . ':failed:' . $error->getCode() . PHP_EOL;
    }
}
