<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_runner extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        
        // Only allow in development environment or with proper authentication
        if (ENVIRONMENT === 'production') {
            show_error('Migrations are not allowed in production environment');
        }
    }
    
    /**
     * Run all pending migrations
     */
    public function run() {
        $this->load->library('migration');
        
        if ($this->migration->current() === FALSE) {
            show_error($this->migration->error_string());
        } else {
            echo "Migrations completed successfully!<br>";
            echo "Current version: " . $this->migration->version() . "<br>";
            
            // Show what was migrated
            $this->show_migration_status();
        }
    }
    
    /**
     * Run specific migration
     */
    public function run_to($version) {
        $this->load->library('migration');
        
        if ($this->migration->version($version) === FALSE) {
            show_error($this->migration->error_string());
        } else {
            echo "Migration to version {$version} completed successfully!<br>";
            echo "Current version: " . $this->migration->version() . "<br>";
        }
    }
    
    /**
     * Show migration status
     */
    public function status() {
        $this->load->library('migration');
        
        echo "<h3>Migration Status</h3>";
        echo "Current version: " . $this->migration->version() . "<br>";
        echo "Latest version: " . $this->migration->latest() . "<br>";
        
        $this->show_migration_status();
    }
    
    /**
     * Show detailed migration status
     */
    private function show_migration_status() {
        $migration_path = APPPATH . 'migrations/';
        $files = glob($migration_path . '*.php');
        
        echo "<h4>Available Migrations:</h4>";
        echo "<ul>";
        
        foreach ($files as $file) {
            $filename = basename($file);
            echo "<li>{$filename}</li>";
        }
        
        echo "</ul>";
        
        // Check if system_settings table exists
        if ($this->db->table_exists('db_system_settings')) {
            echo "<p style='color: green;'>✅ db_system_settings table exists</p>";
        } else {
            echo "<p style='color: red;'>❌ db_system_settings table does not exist</p>";
        }
    }
    
    /**
     * Reset migrations (rollback to version 0)
     */
    public function reset() {
        $this->load->library('migration');
        
        if ($this->migration->version(0) === FALSE) {
            show_error($this->migration->error_string());
        } else {
            echo "Migrations reset to version 0 successfully!<br>";
        }
    }
}
