<?php
/**
 * Auto Migration System
 * Automatically runs migrations when features are accessed
 */

require_once 'migrations/migration_runner.php';

class AutoMigrate {
    private static $migrated = [];
    
    /**
     * Auto-migrate a feature if needed
     */
    public static function feature($featureName) {
        // Skip if already migrated in this request
        if (in_array($featureName, self::$migrated)) {
            return true;
        }
        
        try {
            $runner = new MigrationRunner();
            $tables = $runner->checkFeatureTables($featureName);
            
            if ($tables['all_exist']) {
                self::$migrated[] = $featureName;
                return true;
            }
            
            // Run specific migration for this feature
            $success = $runner->runMigrationByName($featureName);
            
            if ($success) {
                self::$migrated[] = $featureName;
                return true;
            }
            
            return false;
            
        } catch (Exception $e) {
            error_log("Auto-migration failed for {$featureName}: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Check if feature is ready (tables exist)
     */
    public static function isFeatureReady($featureName) {
        try {
            $runner = new MigrationRunner();
            $tables = $runner->checkFeatureTables($featureName);
            return $tables['all_exist'];
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Get migration status for a feature
     */
    public static function getFeatureStatus($featureName) {
        try {
            $runner = new MigrationRunner();
            return $runner->checkFeatureTables($featureName);
        } catch (Exception $e) {
            return [
                'existing' => [],
                'missing' => ['error'],
                'all_exist' => false
            ];
        }
    }
}

/**
 * Helper function for easy use
 */
function auto_migrate_feature($featureName) {
    return AutoMigrate::feature($featureName);
}

/**
 * Helper function to check if feature is ready
 */
function is_feature_ready($featureName) {
    return AutoMigrate::isFeatureReady($featureName);
}
?>
