<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

$root = dirname(__DIR__);
$configFile = $root . '/app/config.php';
if (!is_file($configFile)) {
    fwrite(STDERR, "app/config.php پیدا نشد. ابتدا ربات مادر را نصب کنید.\n");
    exit(1);
}

$config = require $configFile;
if (!is_array($config) || !is_array($config['db'] ?? null)) {
    fwrite(STDERR, "ساختار app/config.php یا بخش db معتبر نیست.\n");
    exit(1);
}

$backup = $configFile . '.before-zero-input-' . date('Ymd-His') . '.bak';
if (!copy($configFile, $backup)) {
    fwrite(STDERR, "ساخت بکاپ config.php ناموفق بود.\n");
    exit(1);
}
@chmod($backup, 0600);

$db = $config['db'];
$config['child_db'] = [
    'driver' => 'table_namespace',
    'host' => (string)($db['host'] ?? 'localhost'),
    'port' => (int)($db['port'] ?? 3306),
    'charset' => (string)($db['charset'] ?? 'utf8mb4'),
    'storage_root' => 'storage/child_databases',
];

$php = "<?php\n/** Updated by tools/upgrade_zero_input.php */\nreturn " . var_export($config, true) . ";\n";
$temp = $configFile . '.tmp-' . bin2hex(random_bytes(6));
if (file_put_contents($temp, $php, LOCK_EX) === false || !rename($temp, $configFile)) {
    @unlink($temp);
    fwrite(STDERR, "به‌روزرسانی اتمیک app/config.php ناموفق بود.\n");
    exit(1);
}
@chmod($configFile, 0600);

fwrite(STDOUT, "OK: zero-input child isolation enabled. No cPanel/API/database-admin settings are required.\n");
fwrite(STDOUT, "Backup: {$backup}\n");
fwrite(STDOUT, "Next: php tools/check_isolation.php\n");
