<?php
/**
 * Clean database bootstrap for PickPack Ship.
 *
 * Example:
 * php backend/setup_clean_database.php --business-slug=pickpack --business-name="PickPack Ship" --setup-key="change-me" --allow-courier=packie --skip-create-db
 */

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "This script must be run from the command line.\n");
    exit(1);
}

function load_env_file(string $path): array {
    if (!file_exists($path)) return [];
    $parsed = parse_ini_file($path, false, INI_SCANNER_RAW);
    return is_array($parsed) ? $parsed : [];
}

function arg_value(array $opts, string $key, ?string $default = null): ?string {
    $value = $opts[$key] ?? $default;
    return is_string($value) ? trim($value) : $default;
}

function safe_slug(string $value): string {
    return preg_replace('/[^a-z0-9\-_]/', '', strtolower(trim($value)));
}

function safe_db_name(string $value): string {
    $safe = preg_replace('/[^a-z0-9_]/', '_', strtolower(trim($value)));
    return trim($safe, '_');
}

function safe_db_prefix(string $value): string {
    $safe = preg_replace('/[^a-z0-9_]/', '_', strtolower(trim($value)));
    return ltrim($safe, '_');
}

function parse_allowed_couriers($raw): string {
    if ($raw === false || $raw === null) return '';
    $values = is_array($raw) ? $raw : [$raw];
    $allowed = [];
    foreach ($values as $value) {
        foreach (preg_split('/[\s,;]+/', (string)$value) as $part) {
            $slug = safe_slug($part);
            if ($slug === '') continue;
            $allowed[$slug] = true;
        }
    }
    return implode(',', array_keys($allowed));
}

function arg_allowed_couriers(array $argv, array $opts) {
    $values = [];
    if (array_key_exists('allow-courier', $opts)) {
        $optValue = $opts['allow-courier'];
        foreach (is_array($optValue) ? $optValue : [$optValue] as $value) {
            if ($value !== false && $value !== null) $values[] = $value;
        }
    }

    $count = count($argv);
    for ($i = 1; $i < $count; $i++) {
        $arg = (string)$argv[$i];
        $matched = false;
        if ($arg === '--allow-courier') {
            $matched = true;
        } elseif (strpos($arg, '--allow-courier=') === 0) {
            $matched = true;
            $values[] = substr($arg, strlen('--allow-courier='));
        }
        if (!$matched) continue;

        for ($j = $i + 1; $j < $count; $j++) {
            $next = (string)$argv[$j];
            if (strpos($next, '--') === 0) break;
            $values[] = $next;
            $i = $j;
        }
    }

    return $values;
}


function apply_db_prefix(string $name, string $prefix): string {
    $safeName = safe_db_name($name);
    $safePrefix = safe_db_prefix($prefix);
    if ($safePrefix === '' || $safeName === '' || strpos($safeName, $safePrefix) === 0) {
        return $safeName;
    }
    return substr($safePrefix . $safeName, 0, 64);
}

function run_sql(mysqli $db, string $sql): void {
    if (!$db->query($sql)) {
        throw new RuntimeException($db->error . "\nSQL:\n" . $sql);
    }
}

function create_client_schema(mysqli $db): void {
    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_order_locks` (
            `order_id` varchar(50) NOT NULL,
            `staff_name` varchar(100) DEFAULT NULL,
            `last_seen` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`order_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_packie_cache` (
            `shopify_order_number` varchar(50) NOT NULL,
            `packie_id` int NOT NULL DEFAULT 0,
            `label_consignment_id` int NOT NULL DEFAULT 0,
            `label_pdf_url` varchar(500) DEFAULT NULL,
            `packie_status` varchar(20) DEFAULT 'PENDING',
            `last_checked` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            `original_shopify_address` text,
            `corrected_address` text,
            PRIMARY KEY (`shopify_order_number`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_packie_stocks` (
            `id` int NOT NULL AUTO_INCREMENT,
            `name` varchar(100) DEFAULT NULL,
            `serviceType` int DEFAULT NULL,
            `height` decimal(10,2) DEFAULT NULL,
            `width` decimal(10,2) DEFAULT NULL,
            `length` decimal(10,2) DEFAULT NULL,
            `weight` decimal(10,2) DEFAULT NULL,
            `cubicWeight` decimal(10,2) DEFAULT NULL,
            `quick_pick_enabled` tinyint(1) NOT NULL DEFAULT 0,
            `quick_pick_carrier` varchar(100) DEFAULT NULL,
            `quick_pick_display_name` varchar(100) DEFAULT NULL,
            `quick_pick_is_default` tinyint(1) NOT NULL DEFAULT 0,
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_package_presets` (
            `code` varchar(20) NOT NULL,
            `display_name` varchar(100) NOT NULL,
            `length` decimal(10,2) NOT NULL DEFAULT 0,
            `width` decimal(10,2) NOT NULL DEFAULT 0,
            `height` decimal(10,2) NOT NULL DEFAULT 0,
            `weight` decimal(10,2) NOT NULL DEFAULT 0,
            `sort_order` int NOT NULL DEFAULT 99,
            `is_enabled` tinyint(1) NOT NULL DEFAULT 1,
            `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`code`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_provider_package_map` (
            `id` int NOT NULL AUTO_INCREMENT,
            `provider_slug` varchar(50) NOT NULL,
            `package_code` varchar(20) NOT NULL,
            `provider_stock_id` varchar(100) DEFAULT NULL,
            `provider_service_type` varchar(50) DEFAULT NULL,
            `provider_label` varchar(100) DEFAULT NULL,
            `length` decimal(10,2) DEFAULT NULL,
            `width` decimal(10,2) DEFAULT NULL,
            `height` decimal(10,2) DEFAULT NULL,
            `weight` decimal(10,2) DEFAULT NULL,
            `is_enabled` tinyint(1) NOT NULL DEFAULT 1,
            `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uniq_provider_package` (`provider_slug`, `package_code`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_picked_items` (
            `id` int NOT NULL AUTO_INCREMENT,
            `order_id` varchar(50) NOT NULL,
            `sku` varchar(100) NOT NULL,
            `picked_qty` int NOT NULL DEFAULT 0,
            `last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            `picked_by` varchar(50) DEFAULT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_pick` (`order_id`, `sku`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_order_notes` (
            `order_id` varchar(50) NOT NULL,
            `note_text` text NOT NULL,
            `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`order_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_staff_members` (
            `id` int NOT NULL AUTO_INCREMENT,
            `company_id` int NOT NULL DEFAULT 1,
            `username` varchar(100) NULL,
            `password_hash` varchar(255) NULL,
            `name` varchar(255) NOT NULL,
            `role` enum('master','secondary') NOT NULL DEFAULT 'secondary',
            `can_pick` tinyint(1) NOT NULL DEFAULT 1,
            `can_pack` tinyint(1) NOT NULL DEFAULT 1,
            `can_print` tinyint(1) NOT NULL DEFAULT 0,
            `pin_code` varchar(4) DEFAULT NULL,
            `is_active` tinyint(1) NOT NULL DEFAULT 1,
            `last_login` timestamp NULL DEFAULT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_name` (`name`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_settings` (
            `id` int NOT NULL AUTO_INCREMENT,
            `company_id` int NOT NULL DEFAULT 1,
            `category` enum('shipping','ecommerce','general') NOT NULL,
            `provider_slug` varchar(50) NOT NULL,
            `key` varchar(100) NOT NULL,
            `value` text NOT NULL,
            `is_encrypted` tinyint(1) NOT NULL DEFAULT 0,
            `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uq_company_cat_provider_key` (`company_id`, `category`, `provider_slug`, `key`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_companies` (
            `id` int NOT NULL AUTO_INCREMENT,
            `slug` varchar(50) NOT NULL,
            `display_name` varchar(100) NOT NULL,
            `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uq_slug` (`slug`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_auth_sessions` (
            `token` char(64) NOT NULL,
            `staff_id` int NOT NULL,
            `company_id` int NOT NULL,
            `device_name` varchar(100) DEFAULT NULL,
            `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `expires_at` timestamp NOT NULL,
            PRIMARY KEY (`token`),
            KEY `idx_staff` (`staff_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    $presets = [
        ['DL', 'Satchel DL', 23.00, 11.00, 2.00, 0.50, 1],
        ['A5', 'Satchel A5', 25.00, 20.00, 2.00, 1.00, 2],
        ['A4', 'Satchel A4', 33.00, 25.00, 2.00, 5.00, 3],
        ['A3', 'Satchel A3', 42.00, 30.00, 2.00, 5.00, 4],
        ['A2', 'Satchel A2', 59.00, 42.00, 2.00, 5.00, 5],
    ];
    $stmt = $db->prepare("
        INSERT INTO pp_package_presets (code, display_name, length, width, height, weight, sort_order, is_enabled)
        VALUES (?, ?, ?, ?, ?, ?, ?, 1)
        ON DUPLICATE KEY UPDATE
            display_name = VALUES(display_name),
            length = VALUES(length),
            width = VALUES(width),
            height = VALUES(height),
            weight = VALUES(weight),
            sort_order = VALUES(sort_order),
            is_enabled = 1
    ");
    foreach ($presets as $preset) {
        [$code, $name, $length, $width, $height, $weight, $sort] = $preset;
        $stmt->bind_param('ssddddi', $code, $name, $length, $width, $height, $weight, $sort);
        $stmt->execute();
    }
}

function create_master_schema(mysqli $db): void {
    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_clients` (
            `id` int NOT NULL AUTO_INCREMENT,
            `slug` varchar(50) NOT NULL,
            `business_name` varchar(150) NOT NULL,
            `client_key_hash` varchar(255) NOT NULL,
            `client_db_name` varchar(64) NOT NULL,
            `master_password_hash` varchar(255) DEFAULT NULL,
            `secondary_password_hash` varchar(255) DEFAULT NULL,
            `security_mode` enum('master_only','shared_honor','individual_pin') NOT NULL DEFAULT 'individual_pin',
            `allowed_couriers` text DEFAULT NULL,
            `is_active` tinyint(1) NOT NULL DEFAULT 1,
            `setup_completed_at` timestamp NULL DEFAULT NULL,
            `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uq_slug` (`slug`),
            UNIQUE KEY `uq_client_db_name` (`client_db_name`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_login_attempts` (
            `id` bigint NOT NULL AUTO_INCREMENT,
            `ip_address` varchar(45) NOT NULL,
            `company_slug` varchar(50) NOT NULL DEFAULT '',
            `attempted_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `idx_ip_time` (`ip_address`, `attempted_at`),
            KEY `idx_cleanup` (`attempted_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_shipping_providers` (
            `id` int NOT NULL AUTO_INCREMENT,
            `slug` varchar(50) NOT NULL,
            `display_name` varchar(100) NOT NULL,
            `auth_type` varchar(50) NOT NULL DEFAULT 'api_key',
            `required_fields` json NOT NULL,
            `notes` text,
            `is_active` tinyint(1) NOT NULL DEFAULT 1,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uq_slug` (`slug`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    run_sql($db, "
        CREATE TABLE IF NOT EXISTS `pp_cms_providers` (
            `id` int NOT NULL AUTO_INCREMENT,
            `slug` varchar(50) NOT NULL,
            `display_name` varchar(100) NOT NULL,
            `api_base_pattern` varchar(255) DEFAULT NULL,
            `required_fields` json NOT NULL,
            `notes` text,
            `is_active` tinyint(1) NOT NULL DEFAULT 1,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uq_slug` (`slug`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    $clientCols = [];
    $cols = $db->query("SHOW COLUMNS FROM pp_clients");
    if ($cols) while ($col = $cols->fetch_assoc()) $clientCols[] = $col['Field'];
    if (!in_array('security_mode', $clientCols, true)) {
        run_sql($db, "ALTER TABLE pp_clients ADD COLUMN `security_mode` enum('master_only','shared_honor','individual_pin') NOT NULL DEFAULT 'individual_pin' AFTER `secondary_password_hash`");
    }
    if (!in_array('allowed_couriers', $clientCols, true)) {
        run_sql($db, "ALTER TABLE pp_clients ADD COLUMN `allowed_couriers` text DEFAULT NULL AFTER `security_mode`");
    }
}

function seed_providers(mysqli $db): void {
    $shipping = [
        [
            'packie',
            'Packie',
            'api_key',
            [
                ['key' => 'base_url', 'label' => 'Packie API Base URL', 'type' => 'text', 'example' => 'https://www.packie.co.nz/api'],
                ['key' => 'username', 'label' => 'Packie Username', 'type' => 'text', 'example' => ''],
                ['key' => 'api_key', 'label' => 'Packie API Key', 'type' => 'password', 'example' => ''],
            ],
            'Uses Packie API credentials for stocks, quotes, labels, and address checks.',
        ],
        [
            'zappy',
            'Zappy',
            'form_cookie',
            [
                ['key' => 'base_url', 'label' => 'Zappy Base URL', 'type' => 'text', 'example' => 'https://ship.zappy.nz'],
                ['key' => 'username', 'label' => 'Zappy Username', 'type' => 'text', 'example' => ''],
                ['key' => 'api_key', 'label' => 'Zappy Password', 'type' => 'password', 'example' => ''],
                ['key' => 'client_id', 'label' => 'Zappy Client ID', 'type' => 'text', 'example' => '2879'],
                ['key' => 'sender_address_id', 'label' => 'Pickup Address ID', 'type' => 'text', 'example' => '133857'],
                ['key' => 'sender_suburb', 'label' => 'Pickup Suburb', 'type' => 'text', 'example' => 'Palmerston North'],
                ['key' => 'sender_email', 'label' => 'Pickup Email', 'type' => 'text', 'example' => 'sales@example.com'],
                ['key' => 'sender_phone', 'label' => 'Pickup Phone', 'type' => 'text', 'example' => ''],
            ],
            'Uses Zappy web session login for live quote lookup.',
        ],
    ];
    $stmt = $db->prepare("
        INSERT INTO pp_shipping_providers (slug, display_name, auth_type, required_fields, notes, is_active)
        VALUES (?, ?, ?, ?, ?, 1)
        ON DUPLICATE KEY UPDATE
            display_name = VALUES(display_name),
            auth_type = VALUES(auth_type),
            required_fields = VALUES(required_fields),
            notes = VALUES(notes),
            is_active = 1
    ");
    foreach ($shipping as [$slug, $name, $auth, $fields, $notes]) {
        $json = json_encode($fields, JSON_UNESCAPED_SLASHES);
        $stmt->bind_param('sssss', $slug, $name, $auth, $json, $notes);
        $stmt->execute();
    }

    $cms = [
        [
            'shopify',
            'Shopify',
            'https://{store}/admin/api/{version}',
            [
                ['key' => 'store_url', 'label' => 'Shopify Store URL', 'type' => 'text', 'example' => 'yourstore.myshopify.com'],
                ['key' => 'api_key', 'label' => 'Admin API Access Token', 'type' => 'password', 'example' => 'shpat_...'],
                ['key' => 'api_version', 'label' => 'API Version', 'type' => 'text', 'example' => '2024-01'],
            ],
            'Uses a Shopify Admin API access token.',
        ],
    ];
    $stmt = $db->prepare("
        INSERT INTO pp_cms_providers (slug, display_name, api_base_pattern, required_fields, notes, is_active)
        VALUES (?, ?, ?, ?, ?, 1)
        ON DUPLICATE KEY UPDATE
            display_name = VALUES(display_name),
            api_base_pattern = VALUES(api_base_pattern),
            required_fields = VALUES(required_fields),
            notes = VALUES(notes),
            is_active = 1
    ");
    foreach ($cms as [$slug, $name, $pattern, $fields, $notes]) {
        $json = json_encode($fields, JSON_UNESCAPED_SLASHES);
        $stmt->bind_param('sssss', $slug, $name, $pattern, $json, $notes);
        $stmt->execute();
    }
}

$opts = getopt('', [
    'business-slug:',
    'business-name:',
    'setup-key:',
    'db-prefix::',
    'master-db::',
    'client-db::',
    'allow-courier::',
    'skip-create-db',
]);

$env = load_env_file(__DIR__ . '/.env');
$dbHost = $env['DB_HOST'] ?? 'localhost';
$dbUser = $env['DB_USER'] ?? '';
$dbPass = $env['DB_PASS'] ?? '';

$businessSlug = safe_slug(arg_value($opts, 'business-slug', 'pickpack') ?? 'pickpack');
$businessName = arg_value($opts, 'business-name', 'PickPack Ship') ?? 'PickPack Ship';
$setupKey = arg_value($opts, 'setup-key', '');
$dbPrefix = safe_db_prefix(arg_value($opts, 'db-prefix', $env['DB_NAME_PREFIX'] ?? '') ?? '');
$masterDbName = apply_db_prefix(arg_value($opts, 'master-db', $env['MASTER_DB_NAME'] ?? 'pickpack_ship_master') ?? 'pickpack_ship_master', $dbPrefix);
$clientDbName = apply_db_prefix(arg_value($opts, 'client-db', 'pickpack_ship_' . str_replace('-', '_', $businessSlug)) ?? '', $dbPrefix);
$allowedCouriers = parse_allowed_couriers(arg_allowed_couriers($argv, $opts));
$skipCreateDb = array_key_exists('skip-create-db', $opts);

if ($dbUser === '' || $setupKey === '') {
    fwrite(STDERR, "Missing DB_USER in backend/.env or missing --setup-key.\n");
    exit(1);
}
if ($masterDbName === '' || $clientDbName === '' || $businessSlug === '') {
    fwrite(STDERR, "Invalid database name or business slug.\n");
    exit(1);
}

$admin = new mysqli($dbHost, $dbUser, $dbPass);
if ($admin->connect_error) {
    fwrite(STDERR, "Database connection failed: " . $admin->connect_error . "\n");
    exit(1);
}

try {
    if (!$skipCreateDb) {
        run_sql($admin, "CREATE DATABASE IF NOT EXISTS `{$masterDbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        run_sql($admin, "CREATE DATABASE IF NOT EXISTS `{$clientDbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    }

    $master = new mysqli($dbHost, $dbUser, $dbPass, $masterDbName);
    if ($master->connect_error) throw new RuntimeException($master->connect_error);
    $client = new mysqli($dbHost, $dbUser, $dbPass, $clientDbName);
    if ($client->connect_error) throw new RuntimeException($client->connect_error);

    create_master_schema($master);
    seed_providers($master);
    create_client_schema($client);

    $keyHash = password_hash($setupKey, PASSWORD_BCRYPT, ['cost' => 12]);
    $stmt = $master->prepare("
        INSERT INTO pp_clients (slug, business_name, client_key_hash, client_db_name, allowed_couriers, is_active)
        VALUES (?, ?, ?, ?, ?, 1)
        ON DUPLICATE KEY UPDATE
            business_name = VALUES(business_name),
            client_key_hash = VALUES(client_key_hash),
            client_db_name = VALUES(client_db_name),
            allowed_couriers = VALUES(allowed_couriers),
            is_active = 1,
            master_password_hash = NULL,
            secondary_password_hash = NULL,
            setup_completed_at = NULL
    ");
    $allowedCouriersDb = $allowedCouriers !== '' ? $allowedCouriers : null;
    $stmt->bind_param('sssss', $businessSlug, $businessName, $keyHash, $clientDbName, $allowedCouriersDb);
    $stmt->execute();

    echo "Clean PickPack Ship databases are ready.\n";
    echo "Master DB: {$masterDbName}\n";
    echo "Client DB: {$clientDbName}\n";
    echo "Business slug: {$businessSlug}\n";
    echo "Setup key: {$setupKey}\n";
    echo "Allowed couriers: " . ($allowedCouriers !== '' ? $allowedCouriers : 'all') . "\n";
    if ($dbPrefix !== '') echo "DB prefix: {$dbPrefix}\n";
    echo "Next: set DB_NAME_PREFIX={$dbPrefix} and MASTER_DB_NAME=pickpack_ship_master in backend/.env, then run first-time setup in the app.\n";
} catch (Throwable $e) {
    fwrite(STDERR, "Setup failed: " . $e->getMessage() . "\n");
    exit(1);
}
