<?php
/**
 * ExploreXR Addon Options Manager
 * 
 * Handles addon options and settings management
 */

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

class ExploreXR_Addon_Options_Manager {
    
    private $addon_manager;
    private $addon_default_options = array();
    
    public function __construct($addon_manager) {
        $this->addon_manager = $addon_manager;
    }
    
    /**
     * Initialize options management hooks
     */
    public function init() {
        // Options management is handled through direct method calls
    }
    
    /**
     * Set addon default options for storage
     * 
     * @param string $addon_slug
     * @param array $default_options
     */
    public function set_addon_default_options($addon_slug, $default_options) {
        if (!empty($default_options)) {
            $this->addon_default_options[$addon_slug] = $default_options;
        }
    }
    
    /**
     * Ensure addon options are active for a specific addon
     * 
     * @param string $addon_slug The addon slug
     * @return boolean True on success, false on failure
     */
    public function ensure_addon_options_active($addon_slug) {
        $registered_addons = $this->addon_manager->get_registered_addons();
        
        // Check if addon is registered
        if (!isset($registered_addons[$addon_slug])) {
            return false;
        }
        
        $addon_data = $registered_addons[$addon_slug];
        
        // Check if addon has default options defined
        if (isset($addon_data['default_options']) && is_array($addon_data['default_options'])) {
            foreach ($addon_data['default_options'] as $option_name => $default_value) {
                // Only add option if it doesn't exist
                if (get_option($option_name) === false) {
                    add_option($option_name, $default_value);
                }
            }
        } else {
            // Fallback: Try to set common default options based on addon slug
            $this->set_default_addon_options($addon_slug);
        }
        
        return true;
    }
    
    /**
     * Ensure addon options are set to inactive/disabled state
     * 
     * @param string $addon_slug The addon slug
     * @return boolean True on success, false on failure
     */
    public function ensure_addon_options_inactive($addon_slug) {
        $registered_addons = $this->addon_manager->get_registered_addons();
        
        // Check if addon is registered
        if (!isset($registered_addons[$addon_slug])) {
            return false;
        }
        
        $addon_data = $registered_addons[$addon_slug];
        
        // Check if addon has default options defined
        if (isset($addon_data['default_options']) && is_array($addon_data['default_options'])) {
            foreach ($addon_data['default_options'] as $option_name => $default_value) {
                // Set option to inactive/disabled state
                // For boolean options, set to false
                // For other options, consider removing or setting to 'disabled'
                if (is_bool($default_value)) {
                    update_option($option_name, false);
                } else {
                    // For non-boolean options, check if there's a disabled equivalent
                    $disabled_value = $this->get_disabled_option_value($option_name, $default_value);
                    update_option($option_name, $disabled_value);
                }
            }
        } else {
            // Fallback: Try to disable common options based on addon slug
            $this->disable_default_addon_options($addon_slug);
        }
        
        return true;
    }
    
    /**
     * Get the disabled equivalent of an option value
     */
    private function get_disabled_option_value($option_name, $original_value) {
        // For most string options, return empty string or 'disabled'
        if (is_string($original_value)) {
            return '';
        }
        // For arrays, return empty array
        if (is_array($original_value)) {
            return array();
        }
        // For numbers, return 0
        if (is_numeric($original_value)) {
            return 0;
        }
        // Default to false
        return false;
    }
    
    /**
     * Disable default options for common addons
     */
    private function disable_default_addon_options($addon_slug) {
        // Common option patterns for different addons
        $common_options = array(
            'explorexr_premium_' . $addon_slug . '_enabled' => false,
            'explorexr_premium_' . $addon_slug . '_active' => false,
            'explorexr_premium_' . $addon_slug . '_settings' => array(),
        );
        
        foreach ($common_options as $option_name => $disabled_value) {
            if (get_option($option_name) !== false) {
                update_option($option_name, $disabled_value);
            }
        }
    }
    
    /**
     * Set default options for common addons
     * 
     * @param string $addon_slug The addon slug
     */
    private function set_default_addon_options($addon_slug) {
        switch ($addon_slug) {
            case 'explorexr-premium-loading':
                $defaults = array(
                    'explorexr_premium_loading_bar_color' => '#1e88e5',
                    'explorexr_premium_loading_bar_size' => 'medium',
                    'explorexr_premium_loading_bar_position' => 'middle',
                    'explorexr_premium_percentage_font_size' => 24,
                    'explorexr_premium_percentage_font_family' => 'Arial, sans-serif',
                    'explorexr_premium_percentage_font_color' => '#333333',
                    'explorexr_premium_percentage_position' => 'center-center',
                    'explorexr_premium_overlay_bg_color' => '#FFFFFF',
                    'explorexr_premium_overlay_bg_opacity' => 70,
                    'explorexr_premium_loading_text' => 'Loading 3D Model...',
                    'explorexr_premium_loading_text_position' => 'top-center',
                    'explorexr_premium_loading_text_font_size' => 18,
                    'explorexr_premium_loading_text_font_family' => 'Arial, sans-serif',
                    'explorexr_premium_loading_text_font_color' => '#666666'
                );
                break;
                
            case 'explorexr-premium-ar':
                $defaults = array(
                    'explorexr_premium_ar_placement' => 'floor',
                    'explorexr_premium_ar_scale' => 'auto',
                    'explorexr_premium_ar_interaction' => 'enabled'
                );
                break;
                
            case 'explorexr-premium-annotations':
                $defaults = array(
                    'explorexr_premium_annotations_style' => 'default',
                    'explorexr_premium_annotations_position' => 'auto'
                );
                break;
                
            case 'explorexr-premium-camera':
                $defaults = array(
                    'explorexr_premium_camera_controls' => 'orbit',
                    'explorexr_premium_camera_zoom' => 'enabled'
                );
                break;
                
            case 'explorexr-premium-animation':
                $defaults = array(
                    'explorexr_premium_animation_autoplay' => 'false',
                    'explorexr_premium_animation_loop' => 'true'
                );
                break;
                
            default:
                $defaults = array();
                break;
        }
        
        // Add the default options
        foreach ($defaults as $option_name => $default_value) {
            if (get_option($option_name) === false) {
                add_option($option_name, $default_value);
            }
        }
    }
    
    /**
     * Disable all settings and options for a specific addon
     * 
     * This is a security measure to prevent inactive addon settings from affecting
     * the frontend or backend of the site.
     * 
     * @param string $addon_slug The slug of the addon
     */
    public function disable_addon_settings($addon_slug) {
        global $wpdb;
        
        // Common option prefixes for ExploreXR addons
        $prefixes = array(
            "explorexr_premium_{$addon_slug}_",       // e.g., explorexr_premium_ar_
            "explorexr_premium_{$addon_slug}s_",      // e.g., explorexr_premium_annotations_
            "explorexr-premium-{$addon_slug}_",       // e.g., explorexr-premium-ar_
            "explorexr-premium-{$addon_slug}s_",      // e.g., explorexr-premium-annotations_
            "{$addon_slug}_explorexr_premium_"        // e.g., ar_explorexr_premium_
        );
        
        // Store disabled options for later reactivation
        $disabled_options = array();
        
        // Get all options that match our prefixes
        foreach ($prefixes as $prefix) {
            $like_prefix = $wpdb->esc_like($prefix) . '%';
            
            // Try to get from cache first
            $cache_key = 'explorexr_addon_options_' . md5($like_prefix);
            $options = wp_cache_get($cache_key, 'explorexr_addon_options');
            
            if (false === $options) {
                // Direct query is necessary here as WordPress doesn't provide a way to search options by pattern
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- No WordPress API exists for pattern matching option names
                $options = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s",
                        $like_prefix
                    )
                );
                
                // Cache the results for 5 minutes
                wp_cache_set($cache_key, $options, 'explorexr_addon_options', 300);
            }
            
            if (!empty($options)) {
                foreach ($options as $option) {
                    // Store the current value for potential restoration
                    $disabled_options[$option->option_name] = $option->option_value;
                    
                    // For boolean options, set to false
                    if ($option->option_value === '1' || $option->option_value === 'yes' || $option->option_value === 'true') {
                        update_option($option->option_name, false);
                    }
                    // For array options, empty the array but preserve the key
                    else if (is_serialized($option->option_value)) {
                        $value = maybe_unserialize($option->option_value);
                        if (is_array($value)) {
                            update_option($option->option_name, array());
                        }
                    }
                }
            }
        }
        
        // Save the disabled options for potential restoration later
        if (!empty($disabled_options)) {
            update_option("explorexr_premium_{$addon_slug}_disabled_options", $disabled_options);
        }
        
        // Also handle addon-specific post meta
        $meta_prefixes = array(
            "_explorexr_premium_{$addon_slug}_",       // e.g., _explorexr_premium_ar_
            "_explorexr-premium-{$addon_slug}_"        // e.g., _explorexr-premium-ar_
        );
        
        // Disable post meta functionality by setting a flag
        update_option("explorexr_premium_{$addon_slug}_meta_disabled", true);
    }
    
    /**
     * Restore previously disabled addon settings
     * 
     * This method is called when an addon is activated to restore any previously
     * disabled settings and options.
     * 
     * @param string $addon_slug The slug of the addon
     */
    public function restore_addon_settings($addon_slug) {
        // Check if we have any disabled options stored
        $disabled_options = get_option("explorexr_premium_{$addon_slug}_disabled_options", array());
        
        if (!empty($disabled_options)) {
            foreach ($disabled_options as $option_name => $option_value) {
                update_option($option_name, $option_value);
            }
            
            // Remove the stored disabled options
            delete_option("explorexr_premium_{$addon_slug}_disabled_options");
        }
        
        // Re-enable addon-specific post meta functionality
        delete_option("explorexr_premium_{$addon_slug}_meta_disabled");
    }
    
    /**
     * Activate all options for all registered addons
     */
    public function activate_all_addon_options() {
        foreach ($this->addon_manager->get_registered_addons() as $slug => $addon) {
            if ($this->addon_manager->is_addon_active($slug)) {
                $this->ensure_addon_options_active($slug);
            }
        }
    }
    
    /**
     * Check if an addon's meta data should be disabled
     * This is a frontend security measure to prevent disabled addon settings from affecting the site
     * 
     * @param string $addon_slug The slug of the addon
     * @return bool True if meta should be disabled, false otherwise
     */
    public function is_addon_meta_disabled($addon_slug) {
        $option_key = "explorexr_premium_{$addon_slug}_meta_disabled";
        
        // If the addon is active, ensure meta is not disabled.
        if ($this->addon_manager && $this->addon_manager->is_addon_active($addon_slug)) {
            if (get_option($option_key, false)) {
                delete_option($option_key);
            }
            return false;
        }
        
        return (bool) get_option($option_key, false);
    }
}
