<?php
/**
 * EdumacFlo SaaS Multi-Tenant CLI Migration Runner
 * 
 * Usage:
 *   php saas/migrate_tenants.php --status
 *   php saas/migrate_tenants.php [--dry-run]
 *   php saas/migrate_tenants.php --tenant=crownintl
 *   php saas/migrate_tenants.php --help
 */

if (php_sapi_name() !== 'cli') {
    die("This script must be run from the command line.\n");
}

require_once __DIR__ . '/admin/inc/master_db.php';
require_once __DIR__ . '/lib/MigrationRunner.php';

// Parse CLI options
$options = getopt('h', ['status', 'dry-run', 'tenant:', 'force', 'help']);

if (isset($options['h']) || isset($options['help'])) {
    echo <<<HELP
============================================================
  EdumacFlo Multi-Tenant Migration Runner (CLI)
============================================================
Usage:
  php saas/migrate_tenants.php [options]

Options:
  --status            Display migration status matrix for all tenants
  --dry-run           Preview pending migrations without applying changes
  --tenant=<slug>     Target a specific tenant by slug
  --help, -h          Show this help message

Examples:
  php saas/migrate_tenants.php --status
  php saas/migrate_tenants.php --dry-run
  php saas/migrate_tenants.php --tenant=crownintl
  php saas/migrate_tenants.php
============================================================

HELP;
    exit(0);
}

$masterConn = get_master_connection();
$runner     = new MigrationRunner($masterConn);
$isStatus   = isset($options['status']);
$isDryRun   = isset($options['dry-run']);
$targetSlug = $options['tenant'] ?? null;

echo "\n============================================================\n";
echo "  EdumacFlo Multi-Tenant Migration Runner\n";
echo "  Date: " . date('Y-m-d H:i:s') . "\n";
echo "  Migrations Dir: " . $runner->getMigrationsDir() . "\n";
echo "============================================================\n\n";

$available = $runner->getAvailableMigrations();
echo "Available migration files (" . count($available) . " total):\n";
if (empty($available)) {
    echo "  (No migration files found in database/migrations/)\n\n";
} else {
    foreach ($available as $idx => $m) {
        $num = str_pad($idx + 1, 2, ' ', STR_PAD_LEFT);
        $type = strtoupper($m['type']);
        echo "  [{$num}] [{$type}] {$m['name']} (" . round($m['size'] / 1024, 1) . " KB)\n";
    }
    echo "\n";
}

// ------------------------------------------------------------
// 1. STATUS MODE (--status)
// ------------------------------------------------------------
if ($isStatus) {
    echo "--- Tenant Migration Status Matrix ---\n";

    $statuses = $runner->getAllTenantsStatus();
    if ($targetSlug) {
        $statuses = array_filter($statuses, fn($s) => ($s['tenant']['slug'] ?? '') === $targetSlug);
    }

    if (empty($statuses)) {
        echo "No matching tenants found.\n\n";
        exit(0);
    }

    foreach ($statuses as $st) {
        $t = $st['tenant'];
        $slug = str_pad($t['slug'], 16);
        $name = str_pad(substr($t['school_name'], 0, 24), 24);
        $db   = str_pad($t['db_name'], 28);

        if ($st['status'] === 'connection_failed') {
            echo "  [CONNECTION FAILED] {$slug} | DB: {$t['db_name']} | Error: {$st['error']}\n";
            continue;
        }

        $appliedCount = count($st['applied']);
        $pendingCount = count($st['pending']);

        if ($pendingCount === 0) {
            $badge = "[UP TO DATE] ";
        } else {
            $badge = "[PENDING: {$pendingCount}] ";
        }

        echo "  {$badge} {$slug} ({$name}) | DB: {$db} | Applied: {$appliedCount} | Pending: {$pendingCount}\n";

        if ($pendingCount > 0) {
            foreach ($st['pending'] as $p) {
                echo "       └─ Pending: {$p['name']}\n";
            }
        }
    }

    echo "\nStatus check complete.\n";
    exit(0);
}

// ------------------------------------------------------------
// 2. RUN MIGRATIONS MODE
// ------------------------------------------------------------
$modeText = $isDryRun ? "DRY-RUN (Simulating without applying changes)" : "LIVE EXECUTION";
echo "Starting migrations in {$modeText} mode...\n";
if ($targetSlug) {
    echo "Target tenant: {$targetSlug}\n";
}
echo "------------------------------------------------------------\n\n";

$results = $runner->runAll($isDryRun, $targetSlug);

$totalTenants = count($results);
$successCount = 0;
$totalApplied = 0;

foreach ($results as $slug => $res) {
    $tName = $res['tenant']['school_name'] ?? $slug;
    $dbName = $res['tenant']['db_name'] ?? '';

    if ($res['success']) {
        $successCount++;
        $count = count($res['applied']);
        $totalApplied += $count;

        if ($count > 0) {
            echo "✅ [SUCCESS] {$slug} ({$tName}) -> DB: {$dbName}\n";
            echo "   Executed {$count} migration(s) in {$res['time_ms']} ms:\n";
            foreach ($res['applied'] as $app) {
                if (is_array($app)) {
                    echo "     ✓ {$app['migration']} (batch {$app['batch']}, {$app['time_ms']} ms)\n";
                } else {
                    echo "     ✓ {$app}\n";
                }
            }
        } else {
            echo "ℹ️  [NO-OP]   {$slug} ({$tName}) -> DB: {$dbName} — Schema up-to-date.\n";
        }
    } else {
        echo "❌ [FAILED]  {$slug} ({$tName}) -> DB: {$dbName}\n";
        foreach ($res['errors'] as $err) {
            echo "     ! {$err}\n";
        }
    }
    echo "\n";
}

echo "============================================================\n";
echo "  Migration Summary: {$successCount}/{$totalTenants} tenant(s) succeeded.\n";
echo "  Total migrations applied: {$totalApplied}\n";
echo "============================================================\n\n";

exit($successCount === $totalTenants ? 0 : 1);
