<?php
/**
 * Database Migration Runner for API Module
 * Run this script to upgrade the API module database schema
 */

// Define necessary constants
define('BASEPATH', true);
define('APPPATH', '../application/');
define('ENVIRONMENT', 'production');

echo "API Module Database Migration Runner\n";
echo "=====================================\n\n";

try {
    // Load Perfex CRM framework
    require_once '../../index.php';

    $CI =& get_instance();

    // Check if API module is active
    if (!$CI->app_modules->is_active('api')) {
        echo "❌ ERROR: API module is not active. Please activate it first.\n";
        echo "   Go to Admin → Setup → Modules and activate the API module.\n\n";
        exit(1);
    }

    echo "✅ API module is active\n";

    // Check database connection
    if (!isset($CI->db) || !$CI->db->conn_id) {
        echo "❌ ERROR: Database connection failed\n";
        exit(1);
    }

    echo "✅ Database connection established\n";

    // Get current migration version from database
    $current_version = 0;
    $migration_table = db_prefix() . 'migrations';

    if ($CI->db->table_exists('migrations')) {
        $result = $CI->db->select('version')->from('migrations')->where('module', 'api')->get();
        if ($result->num_rows() > 0) {
            $current_version = $result->row()->version;
        }
    }

    echo "📊 Current migration version: $current_version\n\n";

    // Define available migrations (based on the files we saw)
    $migrations = [
        101 => 'Version_101',
        102 => 'Version_102',
        103 => 'Version_103',
        200 => 'Version_200',
        201 => 'Version_201',
        202 => 'Version_202',
        203 => 'Version_203',
        204 => 'Version_204',
        205 => 'Version_205',
        206 => 'Version_206',
        207 => 'Version_207',
        208 => 'Version_208',
        209 => 'Version_209',
        210 => 'Version_210',
        211 => 'Version_211'
    ];

    // Find migrations that need to be run
    $migrations_to_run = [];
    foreach ($migrations as $version => $class_name) {
        if ($version > $current_version) {
            $migrations_to_run[$version] = $class_name;
        }
    }

    if (empty($migrations_to_run)) {
        echo "✅ All migrations are up to date!\n\n";
        exit(0);
    }

    echo "📋 Migrations to run:\n";
    foreach ($migrations_to_run as $version => $class_name) {
        echo "   - Version $version: $class_name\n";
    }
    echo "\n";

    // Ask for confirmation
    if (php_sapi_name() === 'cli') {
        echo "Do you want to run these migrations? (y/N): ";
        $handle = fopen("php://stdin", "r");
        $response = trim(fgets($handle));
        fclose($handle);

        if (strtolower($response) !== 'y' && strtolower($response) !== 'yes') {
            echo "Migration cancelled.\n";
            exit(0);
        }
    }

    // Run migrations
    $success_count = 0;
    $error_count = 0;

    foreach ($migrations_to_run as $version => $class_name) {
        echo "🔄 Running migration Version_$version...\n";

        try {
            // Load the migration file
            $migration_file = "migrations/{$version}_version_{$version}.php";

            if (!file_exists($migration_file)) {
                echo "   ❌ Migration file not found: $migration_file\n";
                $error_count++;
                continue;
            }

            require_once $migration_file;

            // Instantiate the migration class
            $migration_class = "Migration_$class_name";
            $migration = new $migration_class();

            // Run the up() method
            if (method_exists($migration, 'up')) {
                $migration->up();
                echo "   ✅ Migration completed successfully\n";

                // Update migration version in database
                $CI->db->replace('migrations', [
                    'module' => 'api',
                    'version' => $version
                ]);

                $success_count++;
            } else {
                echo "   ⚠️  Migration class has no up() method\n";
            }

        } catch (Exception $e) {
            echo "   ❌ Migration failed: " . $e->getMessage() . "\n";
            $error_count++;
        }

        echo "\n";
    }

    // Summary
    echo "📊 Migration Summary:\n";
    echo "   ✅ Successful: $success_count\n";
    echo "   ❌ Failed: $error_count\n\n";

    if ($error_count > 0) {
        echo "⚠️  Some migrations failed. Please check the errors above.\n";
        exit(1);
    } else {
        echo "🎉 All migrations completed successfully!\n";
        echo "   API module database is now up to date.\n";
    }

} catch (Exception $e) {
    echo "❌ CRITICAL ERROR: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
?>