<?php

declare(strict_types=1);

// Read-only code-local MySQL numeric definitions; no business rows or secrets.
try {
    $path=realpath(__DIR__
        . '/../../../../../zhctproject/store/application/config/local/database.php');
    if (!$path || strpos($path,
        '/zhctproject/store/application/config/local/')===false) {
        throw new RuntimeException('Approved local config absent');
    }
    $load=static function(string $file): array { return require $file; };
    $config=$load($path);
    $db=new PDO('mysql:host='.$config['hostname'].';port='
        .(int)($config['hostport']??3306).';dbname='
        .$config['database'].';charset=utf8mb4',
        (string)$config['username'],(string)$config['password'],[
            PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES=>false,
            PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT=>8,
        ]);
    $version=(string)$db->query('SELECT VERSION()')->fetchColumn();
    if (strpos($version,'5.6.')===false) {
        throw new RuntimeException('Unexpected engine');
    }
    $wanted=[
        'weight','price','energy','carbohydrate','protein','fat',
        'dietary_fiber','sfa','mufa','pufa','cholesterol','va',
        'renieratene','retinol','vb1','vb2','vpp','vc','ve','folic_acid',
        'biotin','pantothenic_acid','choline','potassium','sodium',
        'calcium','magnesium','iron','zinc','selenium','gi','gl',
        'purine','moisture','ash','iodine','phosphorus','cuprum',
        'manganese','spicy_level','ssb','saccharides',
    ];
    $in=implode(',',array_fill(0,count($wanted),'?'));
    $sql='SELECT TABLE_NAME,COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,'
        .'NUMERIC_PRECISION,NUMERIC_SCALE,IS_NULLABLE'
        .' FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=?'
        .' AND TABLE_NAME IN (?,?) AND COLUMN_NAME IN ('.$in.')'
        .' ORDER BY TABLE_NAME,COLUMN_NAME';
    $stmt=$db->prepare($sql);
    $stmt->execute(array_merge([$config['database'],'ydy_dishes',
        'ydy_foods_composition'],$wanted));
    $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['engine'=>$version,'row_count'=>count($rows),
        'columns'=>$rows],JSON_UNESCAPED_SLASHES).PHP_EOL;
} catch (Throwable $error) {
    echo json_encode(['status'=>'error','class'=>get_class($error),
        'code'=>$error->getCode()]).PHP_EOL;
    exit(1);
}
