<?php

declare(strict_types=1);

// Offline SQL generation only. Dummy connection settings are never used to connect.
$root = realpath((string) getenv('POC_APP_ROOT'));
if (!$root || strpos($root, '/tmp/zhct-') !== 0) {
    throw new RuntimeException('Isolated framework tree required');
}
require $root . '/vendor/autoload.php';
$config = [
    'type' => \app\common\database\Dm::class,
    'hostname' => '127.0.0.1',
    'hostport' => 5236,
    'database' => 'SYNTHETIC',
    'username' => 'SYNTHETIC',
    'password' => 'SYNTHETIC',
    'prefix' => '',
    'debug' => false,
];
$manager = new \think\DbManager();
$manager->setConfig(['default' => 'probe', 'connections' => ['probe' => $config]]);
$db = $manager->connect('probe');
$raw = "SELECT 7 AS I,CAST('9007199254740993.01' AS DECIMAL(30,2)) AS D,"
    . "CAST('0.00' AS DECIMAL(5,2)) AS Z FROM DUAL";
$table = '(' . $raw . ') EXACT_Q';
$results = ['raw_query' => ['sql' => $raw, 'bind' => []]];
foreach (['find', 'select'] as $step) {
    $query = $db->table($table);
    if ($step === 'find') {
        $query->where('i', 7);
    }
    $query->parseOptions();
    $sql = $db->getBuilder()->select($query, $step === 'find');
    $bind = [];
    foreach ($query->getBind(false) as $name => $entry) {
        $value = is_array($entry) ? $entry[0] : $entry;
        $type = is_array($entry) ? $entry[1] : null;
        $bind[] = ['name' => (string) $name, 'value' => $value,
            'php_type' => gettype($value), 'pdo_type' => $type];
    }
    $results[$step] = ['sql' => $sql, 'bind' => $bind];
}
echo json_encode(['php' => PHP_VERSION, 'no_connection_attempted' => true,
    'steps' => $results], JSON_PRETTY_PRINT) . PHP_EOL;
