<?php
/**
 * ExploreXR Addon Manager - Refactored Modular Version
 * 
 * Centralized system for managing ExploreXR addons with modular components
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Include component classes
require_once __DIR__ . '/components/license-validator.php';
require_once __DIR__ . '/components/compatibility-checker.php';
require_once __DIR__ . '/components/options-manager.php';
require_once __DIR__ . '/components/security-handler.php';
require_once __DIR__ . '/components/lifecycle-handler.php';
require_once __DIR__ . '/components/conflict-detector.php';

class ExploreXR_Addon_Manager {
    
    private static $instance = null;
    private $registered_addons = array();
    private $active_addons = array();
    
    /**
     * Slug aliases for backward compatibility
     * Maps old slugs to new canonical slugs
     * 
     * @var array
     */
    private $slug_aliases = array(
        'explorexr-premium-woocommerce' => 'woocommerce',
    );
    
    // Component instances
    private $license_validator;
    private $compatibility_checker;
    private $options_manager;
    private $security_handler;
    private $lifecycle_handler;
    private $conflict_detector;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Resolve addon slug (handle aliases)
     * 
     * @param string $slug Addon slug (may be alias)
     * @return string Canonical slug
     */
    public function resolve_slug($slug) {
        // Check if this is an aliased slug
        if (isset($this->slug_aliases[$slug])) {
            return $this->slug_aliases[$slug];
        }
        
        return $slug;
    }
    
    /**
     * Constructor - Initialize components
     */
    private function __construct() {
        $this->init_components();
    }
    
    /**
     * Initialize component instances
     */
    private function init_components() {
        $this->license_validator = new ExploreXR_Addon_License_Validator($this);
        $this->compatibility_checker = new ExploreXR_Addon_Compatibility_Checker($this);
        $this->options_manager = new ExploreXR_Addon_Options_Manager($this);
        $this->security_handler = new ExploreXR_Addon_Security_Handler($this);
        $this->lifecycle_handler = new ExploreXR_Addon_Lifecycle_Handler($this);
        $this->conflict_detector = new ExploreXR_Addon_Conflict_Detector($this);
    }
    
    /**
     * Whether init() has already been called
     *
     * @var bool
     */
    private $initialized = false;

    /**
     * Initialize the addon manager
     */
    public function init() {
        // Prevent double initialization
        if ($this->initialized) {
            return;
        }
        $this->initialized = true;

        // Initialize core hooks
        add_action('plugins_loaded', array($this, 'load_active_addons'), 15);
        
        // Initialize component hooks
        $this->license_validator->init();
        $this->compatibility_checker->init();
        $this->options_manager->init();
        $this->security_handler->init();
        $this->lifecycle_handler->init();
        $this->conflict_detector->init();
    }
    
    /**
     * Register an addon
     */
    public function register_addon($addon_slug, $addon_data) {
        // Resolve slug (in case alias is used)
        $addon_slug = $this->resolve_slug($addon_slug);
        
        $this->registered_addons[$addon_slug] = wp_parse_args($addon_data, array(
            'name' => '',
            'version' => '1.0.0',
            'min_core_version' => '0.2.0',
            'max_core_version' => null,
            'file' => '',
            'main_class' => '',
            'dependencies' => array(),
            'description' => '',
            'default_options' => array()
        ));
        
        // Store default options in the options manager
        if (!empty($addon_data['default_options'])) {
            $this->options_manager->set_addon_default_options($addon_slug, $addon_data['default_options']);
        }
    }
    
    /**
     * Load active addons
     */
    public function load_active_addons() {
        foreach ($this->registered_addons as $slug => $addon) {
            if ($this->is_addon_active($slug) && $this->compatibility_checker->is_addon_compatible($slug)) {
                $this->load_addon($slug);
            }
        }
    }
    
    /**
     * Check if addon is active
     */
    public function is_addon_active($addon_slug) {
        // Resolve slug before checking (support old references)
        $addon_slug = $this->resolve_slug($addon_slug);
        
        if (!isset($this->registered_addons[$addon_slug])) {
            return false;
        }
        
        // Ensure is_plugin_active() is available
        if (!function_exists('is_plugin_active')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        
        $addon = $this->registered_addons[$addon_slug];
        return is_plugin_active(plugin_basename($addon['file']));
    }
    
    /**
     * Load a specific addon
     */
    private function load_addon($addon_slug) {
        $addon = $this->registered_addons[$addon_slug];
        
        if (empty($addon['main_class'])) {
            return;
        }
        
        if (!class_exists($addon['main_class'])) {
            return;
        }
        
        // Check if class has a singleton pattern (get_instance method)
        if (method_exists($addon['main_class'], 'get_instance')) {
            try {
                $this->active_addons[$addon_slug] = call_user_func(array($addon['main_class'], 'get_instance'));
            } catch (Exception $e) {
                return;
            }
        } else {
            // Try to instantiate normally
            try {
                $this->active_addons[$addon_slug] = new $addon['main_class']();
            } catch (Error $e) {
                // If instantiation fails, skip this addon
                return;
            } catch (Exception $e) {
                return;
            }
        }
        
        // Call init method if it exists and hasn't been called yet
        if (method_exists($this->active_addons[$addon_slug], 'init')) {
            try {
                $this->active_addons[$addon_slug]->init();
            } catch (Exception $e) {
                // Silently handle initialization errors
            }
        }
        
        // Fire action for addon loaded
        do_action('exploreXR_addon_loaded', $addon_slug, $addon);
    }
    
    // ===================
    // COMPONENT ACCESSORS
    // ===================
    
    /**
     * Get license validator component
     * 
     * @return ExploreXR_Addon_License_Validator
     */
    public function get_license_validator() {
        return $this->license_validator;
    }
    
    /**
     * Get compatibility checker component
     * 
     * @return ExploreXR_Addon_Compatibility_Checker
     */
    public function get_compatibility_checker() {
        return $this->compatibility_checker;
    }
    
    /**
     * Get options manager component
     * 
     * @return ExploreXR_Addon_Options_Manager
     */
    public function get_options_manager() {
        return $this->options_manager;
    }
    
    /**
     * Get security handler component
     * 
     * @return ExploreXR_Addon_Security_Handler
     */
    public function get_security_handler() {
        return $this->security_handler;
    }
    
    /**
     * Get lifecycle handler component
     * 
     * @return ExploreXR_Addon_Lifecycle_Handler
     */
    public function get_lifecycle_handler() {
        return $this->lifecycle_handler;
    }
    
    // ================
    // PUBLIC ACCESSORS
    // ================
    
    /**
     * Get active addons
     */
    public function get_active_addons() {
        return $this->active_addons;
    }
    
    /**
     * Get registered addons
     */
    public function get_registered_addons() {
        // All slugs in this array are canonical (aliases already resolved)
        // WooCommerce add-on will ONLY appear as 'woocommerce', not 'explorexr-premium-woocommerce'
        return $this->registered_addons;
    }
    
    // ==========================================
    // PROXY METHODS TO MAINTAIN COMPATIBILITY
    // ==========================================
    
    /**
     * Proxy method for compatibility checker
     */
    public function is_addon_compatible($addon_slug) {
        return $this->compatibility_checker->is_addon_compatible($addon_slug);
    }
    
    /**
     * Get the conflict detector instance.
     *
     * @return ExploreXR_Addon_Conflict_Detector
     */
    public function get_conflict_detector() {
        return $this->conflict_detector;
    }

    /**
     * Proxy method for options manager
     */
    public function ensure_addon_options_active($addon_slug) {
        return $this->options_manager->ensure_addon_options_active($addon_slug);
    }
    
    /**
     * Proxy method for options manager
     */
    public function ensure_addon_options_inactive($addon_slug) {
        return $this->options_manager->ensure_addon_options_inactive($addon_slug);
    }
    
    /**
     * Proxy method for options manager
     */
    public function activate_all_addon_options() {
        return $this->options_manager->activate_all_addon_options();
    }
    
    /**
     * Proxy method for options manager
     */
    public function is_addon_meta_disabled($addon_slug) {
        return $this->options_manager->is_addon_meta_disabled($addon_slug);
    }
    
    /**
     * Update addon options
     * Proxy method for options manager to update addon-specific settings
     * 
     * @param string $addon_slug Addon identifier
     * @param array $settings Array of settings to update
     * @return bool Success status
     */
    public function update_addon_options($addon_slug, $settings) {
        if (!is_array($settings) || empty($settings)) {
            return false;
        }
        
        // Update each setting option
        foreach ($settings as $key => $value) {
            update_option($key, $value);
        }
        
        return true;
    }
}

// ===================
// GLOBAL FUNCTIONS
// ===================

/**
 * Initialize addon manager singleton
 */
function exploreXR_addon_manager() {
    return ExploreXR_Addon_Manager::get_instance();
}

/**
 * Helper function to activate all addon options manually
 */
function exploreXR_activate_all_addon_options() {
    $addon_manager = exploreXR_addon_manager();
    $addon_manager->activate_all_addon_options();
}

// Auto-initialize
add_action('init', function() {
    exploreXR_addon_manager()->init();
});
