<?php
/**
 * ExploreXR Addon Security Handler
 * 
 * Handles frontend security and meta filtering for addons
 */

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

class ExploreXR_Addon_Security_Handler {
    
    private $addon_manager;
    
    public function __construct($addon_manager) {
        $this->addon_manager = $addon_manager;
    }
    
    /**
     * Initialize frontend security filters
     */
    public function init() {
        add_action('wp', array($this, 'init_frontend_security'));
    }
    
    /**
     * Initialize frontend security filters
     * This sets up filters to prevent disabled addons from affecting the frontend
     */
    public function init_frontend_security() {
        // Filter frontend output for model-viewer attributes
        add_filter('explorexr_premium_model_viewer_attributes', array($this, 'filter_model_viewer_attributes'), 10, 2);
        
        // Filter frontend output for shortcode attributes
        add_filter('explorexr_premium_shortcode_attributes', array($this, 'filter_shortcode_attributes'), 10, 2);
        
        // Filter postmeta access for models
        add_filter('get_post_metadata', array($this, 'filter_post_metadata'), 10, 4);
        
        // Add frontend filter to prevent disabled addons from affecting the output
        add_filter('explorexr_premium_addon_is_active', array($this, 'filter_addon_active_status'), 10, 2);
    }
    
    /**
     * Filter model-viewer attributes to remove those from disabled addons
     * 
     * @param array $attributes The model-viewer attributes
     * @param int $post_id The post ID
     * @return array The filtered attributes
     */
    public function filter_model_viewer_attributes($attributes, $post_id) {
        // Define base model-viewer attributes that should NEVER be removed
        $base_attributes = array('camera-controls', 'camera-orbit', 'camera-target');
        
        foreach ($this->addon_manager->get_registered_addons() as $slug => $addon) {
            if ($this->is_addon_meta_disabled($slug)) {
                // Remove any attributes that start with this addon's prefix
                $prefixes = array(
                    "ar-",          // AR addon
                    "animation-",   // Animation addon
                    "camera-",      // Camera addon (but NOT base camera-controls, camera-orbit, camera-target)
                    "material-",    // Materials addon
                    "loading-",     // Loading addon
                    "annotation-"   // Annotations addon
                );
                
                foreach ($prefixes as $prefix) {
                    foreach ($attributes as $key => $value) {
                        // Skip base model-viewer attributes
                        if (in_array($key, $base_attributes)) {
                            continue;
                        }
                        if (strpos($key, $prefix) === 0) {
                            unset($attributes[$key]);
                        }
                    }
                }
            }
        }
        
        return $attributes;
    }
    
    /**
     * Filter shortcode attributes to remove those from disabled addons
     * 
     * @param array $attributes The shortcode attributes
     * @param int $post_id The post ID
     * @return array The filtered attributes
     */
    public function filter_shortcode_attributes($attributes, $post_id) {
        foreach ($this->addon_manager->get_registered_addons() as $slug => $addon) {
            if ($this->is_addon_meta_disabled($slug)) {
                // Filter out addon-specific attributes
                $addon_prefixes = array(
                    $slug . "_",
                    str_replace('-', '_', $slug) . "_"
                );
                
                foreach ($attributes as $key => $value) {
                    foreach ($addon_prefixes as $prefix) {
                        if (strpos($key, $prefix) === 0) {
                            unset($attributes[$key]);
                        }
                    }
                }
            }
        }
        
        return $attributes;
    }
    
    /**
     * Filter post metadata to prevent access to disabled addon meta
     * 
     * @param mixed $value The metadata value
     * @param int $object_id The object ID
     * @param string $meta_key The meta key
     * @param bool $single Whether to return a single value
     * @return mixed The filtered metadata value
     */
    public function filter_post_metadata($value, $object_id, $meta_key, $single) {
        // If already filtered, return as is
        if ($value !== null) {
            return $value;
        }
        
        // Only filter keys that have our prefixes
        if (!$meta_key || strpos($meta_key, '_explorexr_premium_') !== 0) {
            return $value;
        }
        
        foreach ($this->addon_manager->get_registered_addons() as $slug => $addon) {
            // Check addons with meta prefixes
            $addon_prefixes = array(
                "_explorexr_premium_{$slug}_",
                "_explorexr-premium-{$slug}_"
            );
            
            foreach ($addon_prefixes as $prefix) {
                if (strpos($meta_key, $prefix) === 0 && $this->is_addon_meta_disabled($slug)) {
                    // Return empty value based on $single parameter
                    return $single ? '' : array();
                }
            }
        }
        
        return $value;
    }
    
    /**
     * Filter addon active status to prevent disabled addons from affecting output
     * 
     * @param bool $is_active The current active status
     * @param string $slug The addon slug
     * @return bool The filtered active status
     */
    public function filter_addon_active_status($is_active, $slug) {
        if ($this->is_addon_meta_disabled($slug)) {
            return false;
        }
        return $is_active;
    }
    
    /**
     * 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
     */
    private function is_addon_meta_disabled($addon_slug) {
        $options_manager = $this->addon_manager->get_options_manager();
        if ($options_manager) {
            return $options_manager->is_addon_meta_disabled($addon_slug);
        }
        return (bool) get_option("explorexr_premium_{$addon_slug}_meta_disabled", false);
    }
}
