<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/common/backup_service.php';

if (PHP_SAPI !== 'cli') {
    echo "Run this script from CLI.\n";
    exit(1);
}

$options = getopt('', ['master', 'all-tenants', 'tenant-db::', 'tenant-user::', 'tenant-pass::']);
$runMaster = isset($options['master']) || (!$options);
$runAllTenants = isset($options['all-tenants']);
$singleTenantDb = trim((string)($options['tenant-db'] ?? ''));
$singleTenantUser = trim((string)($options['tenant-user'] ?? ''));
$singleTenantPass = (string)($options['tenant-pass'] ?? '');

function golder_run_migration_dir(PDO $pdo, string $dir): array
{
    $applied = 0;
    $errors = [];

    $files = glob(rtrim($dir, '/\\') . DIRECTORY_SEPARATOR . '*.sql') ?: [];
    sort($files);

    foreach ($files as $file) {
        $sql = @file_get_contents($file);
        if (!is_string($sql) || trim($sql) === '') {
            continue;
        }

        try {
            $pdo->exec($sql);
            $applied++;
            echo '[OK] ' . basename($file) . PHP_EOL;
        } catch (Throwable $e) {
            $errors[] = basename($file) . ': ' . $e->getMessage();
            echo '[ERR] ' . basename($file) . ' => ' . $e->getMessage() . PHP_EOL;
        }
    }

    return ['applied' => $applied, 'errors' => $errors];
}

if ($runMaster) {
    echo "Running master migrations...\n";
    $master = golder_master_pdo();
    $result = golder_run_migration_dir($master, dirname(__DIR__) . '/migrations/master');
    echo sprintf("Master migration done. Applied=%d Errors=%d\n", $result['applied'], count($result['errors']));
}

$tenantMigrationDir = dirname(__DIR__) . '/migrations/tenant';
if ($runAllTenants) {
    echo "Running tenant migrations for all customers...\n";
    $master = golder_master_pdo();
    $rows = $master->query('SELECT id, mysql_db_name, mysql_db_user, mysql_db_pass FROM customers')->fetchAll() ?: [];
    foreach ($rows as $row) {
        $dbName = trim((string)($row['mysql_db_name'] ?? ''));
        $dbUser = trim((string)($row['mysql_db_user'] ?? ''));
        $dbPass = (string)($row['mysql_db_pass'] ?? '');
        if ($dbName === '' || $dbUser === '') {
            continue;
        }
        try {
            $cfg = golder_master_db_config();
            $tenant = new PDO(
                sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $cfg['host'], (int)$cfg['port'], $dbName),
                $dbUser,
                $dbPass,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]
            );
            echo "Tenant {$dbName}:\n";
            $result = golder_run_migration_dir($tenant, $tenantMigrationDir);
            echo sprintf("Tenant %s done. Applied=%d Errors=%d\n", $dbName, $result['applied'], count($result['errors']));
        } catch (Throwable $e) {
            echo "[ERR] Tenant {$dbName} => {$e->getMessage()}\n";
        }
    }
}

if ($singleTenantDb !== '') {
    if ($singleTenantUser === '') {
        echo "--tenant-user is required when --tenant-db is provided.\n";
        exit(1);
    }

    $cfg = golder_master_db_config();
    $pass = $singleTenantPass;
    try {
        $tenant = new PDO(
            sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $cfg['host'], (int)$cfg['port'], $singleTenantDb),
            $singleTenantUser,
            $pass,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]
        );
        echo "Tenant {$singleTenantDb}:\n";
        $result = golder_run_migration_dir($tenant, $tenantMigrationDir);
        echo sprintf("Tenant %s done. Applied=%d Errors=%d\n", $singleTenantDb, $result['applied'], count($result['errors']));
    } catch (Throwable $e) {
        echo "[ERR] Tenant {$singleTenantDb} => {$e->getMessage()}\n";
        exit(1);
    }
}

echo "Migration script finished.\n";


