#!/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
 *   php bin/migrate validate - Review file conventions without connecting to the database
 */

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

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

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

if ($command === 'validate') {
    require $basePath . '/database/DatabaseStructureAuditor.php';
    $auditor = new DatabaseStructureAuditor();
    $report = $auditor->audit(
        $basePath . '/database/migrations',
        $basePath . '/database/seeders'
    );
    exit($auditor->printReport($report));
}

// Variables de entorno: se cargan ANTES que Config para que
// Config::syncConfigFromEnv() vea el fichero .env de la raiz. El CLI no pasa
// por core/AutoLoad.php, asi que hay que cargarlas aqui explicitamente.
require_once $basePath . '/core/Env.php';
Env::load($basePath . '/.env');

// 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';
}

// Load environment-specific configuration
if (file_exists($basePath . '/app/config/ConfigEnv.local.php') && 
    (strpos($_SERVER['HTTP_HOST'] ?? '', 'localhost') !== false || 
     strpos($_SERVER['HTTP_HOST'] ?? '', '127.0.0.1') !== false ||
     php_sapi_name() === 'cli')) {
    // Local environment - use ConfigEnv.local if available, else ConfigEnv
    if (file_exists($basePath . '/app/config/ConfigEnv.local.php')) {
        require $basePath . '/app/config/ConfigEnv.local.php';
    } else {
        require $basePath . '/app/config/ConfigEnv.php';
    }
} else if (file_exists($basePath . '/app/config/ConfigEnv.php')) {
    require $basePath . '/app/config/ConfigEnv.php';
}

// Inyecta el .env en las propiedades estaticas de Config (DB_CONNECTIONS
// incluido). Despues de ConfigEnv, para que el entorno tenga la ultima palabra.
if (class_exists('Config') && method_exists('Config', 'syncConfigFromEnv')) {
    Config::syncConfigFromEnv();
}

// 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' => Env::get('DB_DRIVER', 'mysql'),
        'host' => Env::get('DB_HOST', 'localhost'),
        'dbname' => Env::get('DB_NAME', ''),
        'user' => Env::get('DB_USER', ''),
        'password' => Env::get('DB_PASSWORD', Env::get('DB_PASS', '')),
    ];
}

// Validate configuration
if (empty($dbConfig['host']) || empty($dbConfig['dbname']) || empty($dbConfig['user'])) {
    echo "Error: Database configuration not found.\n";
    echo "Defina DB_HOST, DB_NAME y DB_USER en el fichero .env de la raiz (o como variables de entorno).\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, validate\n";
        exit(1);
}

echo "\n";
exit(0);
