<?php
declare(strict_types=1);

/**
 * CLI Entry Point — Migrations, Seeds, and System Commands.
 *
 * Usage:
 *   php cli.php migrate            Run all pending migrations
 *   php cli.php migrate:rollback   Rollback last batch
 *   php cli.php migrate:status     Show migration status
 *   php cli.php seed               Run all pending seeds
 *   php cli.php seed:run <Name>    Run a specific seed
 *   php cli.php cron               Run background jobs
 */

// Prevent web access
if (PHP_SAPI !== 'cli') {
    die('CLI only.');
}

require_once __DIR__ . '/app/Core/Autoloader.php';
\App\Core\Autoloader::register();

// Load .env
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        if (str_contains($line, '=')) {
            [$key, $value] = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);
            if (!isset($_ENV[$key])) {
                $_ENV[$key] = $value;
                putenv("{$key}={$value}");
            }
        }
    }
}

// Minimal bootstrap — just database, no session/routing
$config = [];
$configDir = __DIR__ . '/config';
if (is_dir($configDir)) {
    foreach (glob($configDir . '/*.php') as $configFile) {
        $key = basename($configFile, '.php');
        $config[$key] = require $configFile;
    }
}

// Build database config
$dbConfig = [
    'host'      => $_ENV['DB_HOST'] ?? $config['database']['host'] ?? '127.0.0.1',
    'port'      => $_ENV['DB_PORT'] ?? $config['database']['port'] ?? '3306',
    'name'      => $_ENV['DB_NAME'] ?? $config['database']['name'] ?? 'the_club_erp',
    'user'      => $_ENV['DB_USER'] ?? $config['database']['user'] ?? 'root',
    'pass'      => $_ENV['DB_PASS'] ?? $config['database']['pass'] ?? '',
    'charset'   => $config['database']['charset'] ?? 'utf8mb4',
    'collation' => $config['database']['collation'] ?? 'utf8mb4_unicode_ci',
];

$db = new \App\Core\Database(
    (string) $dbConfig['host'],
    (int) $dbConfig['port'],
    (string) $dbConfig['name'],
    (string) $dbConfig['user'],
    (string) $dbConfig['pass'],
    (string) $dbConfig['charset']
);

$command = $argv[1] ?? 'help';
$arg2 = $argv[2] ?? null;

echo "\n";

switch ($command) {
    case 'migrate':
        $runner = new \App\Core\Migration\MigrationRunner($db);
        $results = $runner->migrate();
        if (empty($results)) {
            echo "✅ Nothing to migrate. All migrations are up to date.\n";
        } else {
            echo "✅ Ran " . count($results) . " migration(s):\n";
            foreach ($results as $name) {
                echo "   ✔ {$name}\n";
            }
        }
        break;

    case 'migrate:rollback':
        $runner = new \App\Core\Migration\MigrationRunner($db);
        $results = $runner->rollback();
        if (empty($results)) {
            echo "⚠️  Nothing to rollback.\n";
        } else {
            echo "✅ Rolled back " . count($results) . " migration(s):\n";
            foreach ($results as $name) {
                echo "   ↩ {$name}\n";
            }
        }
        break;

    case 'migrate:status':
        $runner = new \App\Core\Migration\MigrationRunner($db);
        $status = $runner->status();
        echo str_pad('Migration', 60) . "Status\n";
        echo str_repeat('─', 70) . "\n";
        foreach ($status as $s) {
            $icon = $s['status'] === 'Ran' ? '✔' : '○';
            echo "{$icon} " . str_pad($s['migration'], 58) . $s['status'] . "\n";
        }
        break;

    case 'seed':
        echo "🌱 Running seeds...\n";
        $runner = new \App\Core\Seeder\SeederRunner($db);
        $results = $runner->run();
        if (empty($results)) {
            echo "✅ Nothing to seed. All seeds already executed.\n";
        } else {
            echo "✅ Ran " . count($results) . " seed(s):\n";
            foreach ($results as $name) {
                echo "   🌱 {$name}\n";
            }
        }
        break;

    case 'seed:run':
        if (!$arg2) {
            echo "❌ Please specify seed name: php cli.php seed:run SeedName\n";
            exit(1);
        }
        $runner = new \App\Core\Seeder\SeederRunner($db);
        $runner->runSingle($arg2);
        echo "✅ Seed executed: {$arg2}\n";
        break;

    case 'cron':
        echo "⏰ Running cron jobs...\n";
        $cronRunner = __DIR__ . '/cron/runner.php';
        if (file_exists($cronRunner)) {
            require $cronRunner;
        } else {
            echo "⚠️  No cron runner found.\n";
        }
        break;

    case 'help':
    default:
        echo "THE CLUB ERP — CLI Commands\n";
        echo "───────────────────────────────────\n";
        echo "  php cli.php migrate            Run pending migrations\n";
        echo "  php cli.php migrate:rollback   Rollback last batch\n";
        echo "  php cli.php migrate:status     Show migration status\n";
        echo "  php cli.php seed               Run all pending seeds\n";
        echo "  php cli.php seed:run <Name>    Run specific seed\n";
        echo "  php cli.php cron               Run background jobs\n";
        echo "  php cli.php help               Show this help\n";
        break;
}

echo "\n";