<?php
/**
 * Extra Config Bootstrap
 * Loads and initializes the new Extra Config architecture
 *
 * @package AIAutoTool
 * @subpackage ExtraConfig
 * @since 2.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

// Prevent multiple loading
if (defined('AIAUTOTOOL_EXTRA_CONFIG_LOADED')) {
    return;
}

define('AIAUTOTOOL_EXTRA_CONFIG_LOADED', true);

/**
 * Check compatibility
 */
function aiautotool_extra_config_check_compatibility() {
    // Check PHP version
    if (version_compare(PHP_VERSION, '5.6.0', '<')) {
        add_action('admin_notices', function() {
            // Use plain text to avoid triggering translation loading before 'init'
            echo '<div class="notice notice-error"><p>';
            echo esc_html('AI Auto Tool Extra Config requires PHP 5.6 or higher.');
            echo '</p></div>';
        }, 20); // Run after 'init' hook
        return false;
    }
    
    // Check WordPress version
    global $wp_version;
    if (version_compare($wp_version, '4.7.0', '<')) {
        add_action('admin_notices', function() {
            // Use plain text to avoid triggering translation loading before 'init'
            echo '<div class="notice notice-error"><p>';
            echo esc_html('AI Auto Tool Extra Config requires WordPress 4.7 or higher.');
            echo '</p></div>';
        }, 20); // Run after 'init' hook
        return false;
    }
    
    return true;
}

// Check compatibility before loading
if (!aiautotool_extra_config_check_compatibility()) {
    return;
}

/**
 * Load core classes
 */
function aiautotool_extra_config_load_classes() {
    $base_path = plugin_dir_path(__FILE__);
    
    // Load rendersetting class first (required by class-manager.php)
    // Calculate path to plugin root: go up 2 directories from inc/extra-config/bootstrap.php
    $plugin_root = defined('AIAUTOTOOL_DIR') ? AIAUTOTOOL_DIR : dirname(dirname(dirname(__FILE__))) . '/';
    $setting_file = $plugin_root . 'lib/setting.php';
    if (file_exists($setting_file) && !class_exists('rendersetting')) {
        require_once $setting_file;
    }
    
    // Core classes in order of dependency
    $classes = array(
        'class-security.php',
        'class-settings-registry.php',
        'class-ajax-handler.php',
        'class-features-manager.php',
        'class-html-compression.php',
        'class-admin-renderer.php',
        'class-manager.php',
    );
    
    foreach ($classes as $class_file) {
        $file_path = $base_path . $class_file;
        
        if (file_exists($file_path)) {
            require_once $file_path;
        } else {
            // Log error if in debug mode
            // Missing class file
        }
    }
}

// Load classes
aiautotool_extra_config_load_classes();

/**
 * Initialize Extra Config Manager
 * This will be called on plugins_loaded hook from the manager itself
 */
function aiautotool_extra_config_init() {
    // Check if class exists
    if (!class_exists('Aiautotool_Extra_Config_Manager')) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        return false;
    }
    
    // Initialize manager
    try {
        $manager = Aiautotool_Extra_Config_Manager::instance();
        
        // Make manager available globally if needed
        $GLOBALS['aiautotool_extra_config'] = $manager;
        
        return $manager;
    } catch (Exception $e) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        return false;
    }
}

// Initialize on init hook (late priority to ensure dependencies are loaded)
add_action('init', 'aiautotool_extra_config_init', 20);

/**
 * Migration from old version
 * Runs once to migrate settings from old structure
 */
function aiautotool_extra_config_migrate_from_old() {
    // Check if migration already done
    if (get_option('aiautotool_extra_config_migrated_v2', false)) {
        return;
    }
    
    // Check if old settings exist
    $old_settings = get_option('aiautotool_config_settings', array());
    
    if (empty($old_settings)) {
        // No old settings to migrate, mark as done
        update_option('aiautotool_extra_config_migrated_v2', true, false);
        return;
    }
    
    // Wait until classes are loaded
    if (!class_exists('Aiautotool_Extra_Config_Settings_Registry') || 
        !class_exists('Aiautotool_Extra_Config_Security')) {
        return;
    }
    
    try {
        // Get instances
        $registry = Aiautotool_Extra_Config_Settings_Registry::instance();
        $security = new Aiautotool_Extra_Config_Security();
        
        // Sanitize old settings
        $sanitized = $security->sanitize_settings($old_settings);
        
        // Update with new registry
        $registry->update($sanitized, false);
        
        // Mark migration as complete
        update_option('aiautotool_extra_config_migrated_v2', true, false);
        
        // Log success
        // Successfully migrated settings to new structure
        
        // Show admin notice (run after 'init' to ensure translations are loaded)
        add_action('admin_notices', function() {
            // Use translation functions only after 'init' hook has fired
            $title = did_action('init') ? esc_html__('AI Auto Tool:', 'ai-auto-tool') : 'AI Auto Tool:';
            $message = did_action('init') ? esc_html__('Extra Config settings have been migrated to the new secure architecture.', 'ai-auto-tool') : 'Extra Config settings have been migrated to the new secure architecture.';
            echo '<div class="notice notice-success is-dismissible">';
            echo '<p><strong>' . $title . '</strong> ';
            echo $message;
            echo '</p></div>';
        }, 20); // Run after 'init' to ensure translations are loaded
        
    } catch (Exception $e) {
        // Log error
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
}

// Run migration on admin_init
add_action('admin_init', 'aiautotool_extra_config_migrate_from_old', 5);

/**
 * Helper function to get manager instance
 *
 * @return Aiautotool_Extra_Config_Manager|false
 */
function aiautotool_extra_config() {
    if (isset($GLOBALS['aiautotool_extra_config'])) {
        return $GLOBALS['aiautotool_extra_config'];
    }
    
    if (class_exists('Aiautotool_Extra_Config_Manager')) {
        return Aiautotool_Extra_Config_Manager::instance();
    }
    
    return false;
}

/**
 * Helper function to check if a feature is enabled
 *
 * @param string $feature_key Feature key
 * @return bool
 */
function aiautotool_is_feature_enabled($feature_key) {
    $manager = aiautotool_extra_config();
    
    if ($manager) {
        return $manager->is_feature_enabled($feature_key);
    }
    
    return false;
}

/**
 * Helper function to get a setting value
 *
 * @param string $key     Setting key
 * @param mixed  $default Default value
 * @return mixed
 */
function aiautotool_get_config($key, $default = null) {
    $manager = aiautotool_extra_config();
    
    if ($manager) {
        $settings = $manager->get_settings();
        return $settings->get($key, $default);
    }
    
    return $default;
}

/**
 * Deactivation cleanup
 */
function aiautotool_extra_config_deactivate() {
    // Clear all caches
    if (class_exists('Aiautotool_Extra_Config_Settings_Registry')) {
        $settings = Aiautotool_Extra_Config_Settings_Registry::instance();
        $settings->clear_cache();
    }
    
    // Clear WordPress object cache
    wp_cache_flush();
}

// Register deactivation hook
register_deactivation_hook(AIAUTOTOOL_BASENAME, 'aiautotool_extra_config_deactivate');

// Log successful bootstrap
if (defined('WP_DEBUG') && WP_DEBUG) {
}


