#!/usr/bin/env php
<?php
/**
 * Database Migration CLI
 * Usage:
 *   php bin/migrate up       - Run all pending migrations
 *   php bin/migrate down     - Rollback last migration
 *   php bin/migrate status   - Show migration status
 */

// Get base path
$basePath = dirname(__DIR__);
define('BASE_PATH', $basePath . '/');

require $basePath . '/core/helpers/Env.php';
Env::load($basePath . '/.env');

// Load Migrator
require $basePath . '/database/Migrator.php';

// Get command
$command = $argv[1] ?? 'status';

// Try to load configuration (may not exist in all environments)
$app_host = $app_db = $app_user = $app_pass = null;

if (file_exists($basePath . '/app/config/Config.php')) {
    require $basePath . '/app/config/Config.php';
}

if (file_exists($basePath . '/app/config/ConfigEnv.php')) {
    require $basePath . '/app/config/ConfigEnv.php';
}

// Database configuration - try multiple sources
$dbConfig = null;

// Try from ConfigEnv class first (if loaded)
if (class_exists('ConfigEnv') && property_exists('ConfigEnv', 'DB_CONNECTIONS')) {
    $connections = ConfigEnv::$DB_CONNECTIONS;
    if (isset($connections['klee'])) {
        $dbConfig = $connections['klee'];
    }
}

// Fallback to environment variables
if (!$dbConfig) {
    $dbConfig = [
        'name' => 'klee',
        'driver' => getenv('DB_DRIVER') ?: 'mysql',
        'host' => getenv('DB_HOST') ?: 'localhost',
        'dbname' => getenv('DB_NAME') ?: 'klee_core',
        'user' => getenv('DB_USER') ?: 'root',
        'password' => getenv('DB_PASS') ?: '',
    ];
}

// Validate configuration
if (empty($dbConfig['host']) || empty($dbConfig['dbname']) || empty($dbConfig['user'])) {
    echo "Error: Database configuration not found.\n";
    echo "Set DB_HOST, DB_NAME, and DB_USER environment variables, or check app/config/ConfigEnv.php\n";
    exit(1);
}

// Create PDO connection
try {
    if ($dbConfig['driver'] === 'mysql') {
        $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset=utf8mb4";
        $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['password']);
    } else {
        echo "Error: Unsupported database driver: {$dbConfig['driver']}\n";
        exit(1);
    }

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Database connection error: " . $e->getMessage() . "\n";
    exit(1);
}

// Create migrator instance
$migrator = new Migrator($pdo, $basePath . '/database/migrations');

// Execute command
echo "\n";
switch ($command) {
    case 'up':
        $migrator->migrate();
        break;
    case 'down':
        $migrator->rollback();
        break;
    case 'status':
        $migrator->status();
        break;
    default:
        echo "Unknown command: $command\n";
        echo "Available commands: up, down, status\n";
        exit(1);
}

echo "\n";
exit(0);
