<?php
/**
 * AYSA Content Filter Remover - Simplified Version
 * 
 * This class removes default WordPress and WooCommerce content sanitization filters
 * to preserve HTML content in posts, products, and meta fields.
 * 
 * @package AYSA_SEO_Generator
 * @since 1.0.0
 */

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

class Aysa_Content_Filter_Remover {
    
    /**
     * Single instance of the class
     */
    private static $instance = null;
    
    /**
     * Get single instance of the class
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Initialize the content filter remover
     * 
     * @return Aysa_Content_Filter_Remover
     */
    public static function init() {
        try {
            $instance = self::get_instance();
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA: Content filter remover init() called successfully');
            }
            return $instance;
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA: Content filter remover init() failed: ' . $e->getMessage());
            }
            return null;
        }
      }
      
      /**
       * Filter content using a comprehensive HTML tag whitelist
       * 
       * @param string $content The content to filter
       * @return string The filtered content
       */
      private function filter_content_with_whitelist($content) {
          $allowed_tags = $this->get_allowed_html_tags();
          
          if (defined('WP_DEBUG') && WP_DEBUG) {
              aysa_debug_log('AYSA: Filtering content with whitelist - ' . count($allowed_tags) . ' tag types allowed');
          }
          
          return wp_kses($content, $allowed_tags);
      }
      
      /**
       * Get comprehensive list of allowed HTML tags and attributes
       * 
       * @return array Allowed HTML tags with their attributes
       */
      private function get_allowed_html_tags() {
          // Base allowed tags - comprehensive list for content creation
          $allowed_tags = array(
              // Text formatting
              'p' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'br' => array(),
              'hr' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              
              // Headings
              'h1' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'h2' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'h3' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'h4' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'h5' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'h6' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              
              // Text styling
              'strong' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'b' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'em' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'i' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'u' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              's' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'del' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'datetime' => array(),
              ),
              'ins' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'datetime' => array(),
              ),
              'mark' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'small' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'sub' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'sup' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              
              // Links
              'a' => array(
                  'href' => array(),
                  'title' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'target' => array(),
                  'rel' => array(),
                  'data-*' => array(),
                  'download' => array(),
              ),
              
              // Lists
              'ul' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'ol' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'start' => array(),
                  'type' => array(),
                  'data-*' => array(),
              ),
              'li' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'value' => array(),
                  'data-*' => array(),
              ),
              'dl' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'dt' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'dd' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              
              // Layout and containers
              'div' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'span' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'section' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'article' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'header' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'footer' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'main' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'aside' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'nav' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              
              // Media
              'img' => array(
                  'src' => array(),
                  'alt' => array(),
                  'title' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'width' => array(),
                  'height' => array(),
                  'loading' => array(),
                  'srcset' => array(),
                  'sizes' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'figure' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'figcaption' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'picture' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'source' => array(
                  'src' => array(),
                  'srcset' => array(),
                  'sizes' => array(),
                  'media' => array(),
                  'type' => array(),
                  'data-*' => array(),
              ),
              
              // Tables
              'table' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'border' => array(),
                  'cellpadding' => array(),
                  'cellspacing' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'thead' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'tbody' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'tfoot' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'tr' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'th' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'colspan' => array(),
                  'rowspan' => array(),
                  'scope' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'td' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'colspan' => array(),
                  'rowspan' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'caption' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              
              // Code and preformatted text
              'code' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'pre' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'kbd' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'samp' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'var' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              
              // Quotes and citations
              'blockquote' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'cite' => array(),
                  'data-*' => array(),
              ),
              'q' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'cite' => array(),
              ),
              'cite' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
              ),
              'abbr' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'title' => array(),
              ),
              'acronym' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'title' => array(),
              ),
              'dfn' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'title' => array(),
              ),
              
              // Forms (basic elements)
              'form' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'action' => array(),
                  'method' => array(),
                  'enctype' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'input' => array(
                  'type' => array(),
                  'name' => array(),
                  'value' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'placeholder' => array(),
                  'required' => array(),
                  'disabled' => array(),
                  'readonly' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'textarea' => array(
                  'name' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'rows' => array(),
                  'cols' => array(),
                  'placeholder' => array(),
                  'required' => array(),
                  'disabled' => array(),
                  'readonly' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'select' => array(
                  'name' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'multiple' => array(),
                  'size' => array(),
                  'required' => array(),
                  'disabled' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'option' => array(
                  'value' => array(),
                  'selected' => array(),
                  'disabled' => array(),
                  'class' => array(),
                  'id' => array(),
                  'data-*' => array(),
              ),
              'optgroup' => array(
                  'label' => array(),
                  'disabled' => array(),
                  'class' => array(),
                  'id' => array(),
              ),
              'button' => array(
                  'type' => array(),
                  'name' => array(),
                  'value' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'disabled' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'label' => array(
                  'for' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'fieldset' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'disabled' => array(),
                  'data-*' => array(),
              ),
              'legend' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              
              // Multimedia
              'video' => array(
                  'src' => array(),
                  'poster' => array(),
                  'width' => array(),
                  'height' => array(),
                  'controls' => array(),
                  'autoplay' => array(),
                  'loop' => array(),
                  'muted' => array(),
                  'preload' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'audio' => array(
                  'src' => array(),
                  'controls' => array(),
                  'autoplay' => array(),
                  'loop' => array(),
                  'muted' => array(),
                  'preload' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'track' => array(
                  'src' => array(),
                  'kind' => array(),
                  'srclang' => array(),
                  'label' => array(),
                  'default' => array(),
                  'data-*' => array(),
              ),
              
              // Embedded content
              'iframe' => array(
                  'src' => array(),
                  'width' => array(),
                  'height' => array(),
                  'frameborder' => array(),
                  'allowfullscreen' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'title' => array(),
                  'loading' => array(),
                  'data-*' => array(),
                  'role' => array(),
                  'aria-*' => array(),
              ),
              'embed' => array(
                  'src' => array(),
                  'type' => array(),
                  'width' => array(),
                  'height' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'object' => array(
                  'data' => array(),
                  'type' => array(),
                  'width' => array(),
                  'height' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'param' => array(
                  'name' => array(),
                  'value' => array(),
                  'data-*' => array(),
              ),
              
              // Details and summary
              'details' => array(
                  'open' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'summary' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              
              // Progress and meter
              'progress' => array(
                  'value' => array(),
                  'max' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              'meter' => array(
                  'value' => array(),
                  'min' => array(),
                  'max' => array(),
                  'low' => array(),
                  'high' => array(),
                  'optimum' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              
              // Time
              'time' => array(
                  'datetime' => array(),
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
              
              // Address
              'address' => array(
                  'class' => array(),
                  'id' => array(),
                  'style' => array(),
                  'data-*' => array(),
              ),
          );
          
          // Allow filtering of the allowed tags
          $allowed_tags = apply_filters('aysa_allowed_html_tags', $allowed_tags);
          
          return $allowed_tags;
      }
      
      /**
       * Get a simplified list of allowed HTML tags for basic content
       * 
       * @return array Basic allowed HTML tags
       */
      public function get_basic_allowed_tags() {
          $basic_tags = array(
              'p' => array('class' => array(), 'id' => array(), 'style' => array()),
              'br' => array(),
              'strong' => array('class' => array(), 'id' => array()),
              'b' => array('class' => array(), 'id' => array()),
              'em' => array('class' => array(), 'id' => array()),
              'i' => array('class' => array(), 'id' => array()),
              'u' => array('class' => array(), 'id' => array()),
              'a' => array('href' => array(), 'title' => array(), 'class' => array(), 'target' => array()),
              'ul' => array('class' => array(), 'id' => array()),
              'ol' => array('class' => array(), 'id' => array()),
              'li' => array('class' => array(), 'id' => array()),
              'h1' => array('class' => array(), 'id' => array()),
              'h2' => array('class' => array(), 'id' => array()),
              'h3' => array('class' => array(), 'id' => array()),
              'h4' => array('class' => array(), 'id' => array()),
              'h5' => array('class' => array(), 'id' => array()),
              'h6' => array('class' => array(), 'id' => array()),
              'img' => array('src' => array(), 'alt' => array(), 'title' => array(), 'class' => array(), 'width' => array(), 'height' => array()),
              'div' => array('class' => array(), 'id' => array(), 'style' => array()),
              'span' => array('class' => array(), 'id' => array(), 'style' => array()),
          );
          
          return apply_filters('aysa_basic_allowed_tags', $basic_tags);
      }
      
      /**
       * Get allowed tags for SEO content (more restrictive)
       * 
       * @return array SEO-focused allowed HTML tags
       */
      public function get_seo_allowed_tags() {
          $seo_tags = array(
              'p' => array('class' => array()),
              'br' => array(),
              'strong' => array(),
              'b' => array(),
              'em' => array(),
              'i' => array(),
              'a' => array('href' => array(), 'title' => array(), 'rel' => array()),
              'ul' => array(),
              'ol' => array(),
              'li' => array(),
              'h1' => array(),
              'h2' => array(),
              'h3' => array(),
              'h4' => array(),
              'h5' => array(),
              'h6' => array(),
              'img' => array('src' => array(), 'alt' => array(), 'title' => array()),
              'span' => array(),
          );
          
          return apply_filters('aysa_seo_allowed_tags', $seo_tags);
      }
    
    /**
     * Constructor - Set up the filter removal
     */
    private function __construct() {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Content filter remover constructor called');
        }
        
        // Hook into WordPress initialization
        add_action('init', array($this, 'remove_content_filters'), 1);
        add_action('wp_loaded', array($this, 'add_bypass_filters'), 1);
        add_filter('wp_kses_allowed_html', array($this, 'allow_schema_microdata_attributes'), 10, 2);
        add_filter('tiny_mce_before_init', array($this, 'preserve_custom_schema_attributes_in_tinymce'), 10, 1);
        
        // Handle WooCommerce-specific filters if WooCommerce is active
        if (class_exists('WooCommerce')) {
            add_action('woocommerce_init', array($this, 'handle_woocommerce_filters'), 1);
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Content filter remover hooks registered');
        }
    }

    /**
     * Allow schema.org microdata attributes in post content sanitization.
     *
     * @param array  $allowedposttags Existing allowed tags/attributes.
     * @param string $context          KSES context.
     * @return array
     */
    public function allow_schema_microdata_attributes($allowedposttags, $context) {
        if (!is_array($allowedposttags)) {
            return $allowedposttags;
        }

        // Apply to post content contexts used by WordPress sanitization.
        if (!in_array($context, array('post', 'data', 'strip'), true)) {
            return $allowedposttags;
        }

        $schema_attrs = array(
            'itemscope' => true,
            'itemtype'  => true,
            'itemprop'  => true,
        );

        $schema_tags = array('section', 'div', 'h2', 'h3', 'h4', 'p', 'span');
        foreach ($schema_tags as $tag) {
            if (!isset($allowedposttags[$tag]) || !is_array($allowedposttags[$tag])) {
                $allowedposttags[$tag] = array();
            }
            $allowedposttags[$tag] = array_merge($allowedposttags[$tag], $schema_attrs);
        }

        return $allowedposttags;
    }

    /**
     * Prevent TinyMCE from stripping custom schema attributes.
     *
     * @param array $init TinyMCE init config.
     * @return array
     */
    public function preserve_custom_schema_attributes_in_tinymce($init) {
        if (!is_array($init)) {
            return $init;
        }

        // Allow all attributes; needed for microdata itemprop/itemscope/itemtype round-trip.
        $init['extended_valid_elements'] = '*[*]';
        $init['valid_elements'] = '*[*]';
        $init['verify_html'] = false;

        return $init;
    }
    
    /**
     * Remove WordPress content sanitization filters
     */
    public function remove_content_filters() {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Removing content filters');
        }
        
        // Remove WordPress core content sanitization on display
        remove_filter('the_content', 'wp_filter_post_kses');
        remove_filter('the_excerpt', 'wp_filter_post_kses');
        remove_filter('the_title', 'wp_filter_kses');
        
        // Remove WordPress core content sanitization on save (CRITICAL)
        remove_filter('content_save_pre', 'wp_filter_post_kses');
        remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
        remove_filter('title_save_pre', 'wp_filter_kses');
        
        // Remove taxonomy description sanitization
        remove_filter('pre_term_description', 'wp_filter_kses');
        
        // Remove additional content filters
        remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Core WordPress sanitization filters removed');
        }
    }
    
    /**
     * Add bypass filters to prevent content sanitization
     */
    public function add_bypass_filters() {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Adding bypass filters');
        }
        
        // Add debugging filters to monitor sanitization
        $this->add_sanitization_debugging();
        
        // Add bypass filters for content
        add_filter('content_save_pre', array($this, 'bypass_content_sanitization'), 1);
        add_filter('excerpt_save_pre', array($this, 'bypass_excerpt_sanitization'), 1);
        add_filter('title_save_pre', array($this, 'bypass_title_sanitization'), 1);
        add_filter('pre_term_description', array($this, 'bypass_term_description_sanitization'), 1);
        add_filter('content_filtered_save_pre', array($this, 'bypass_content_sanitization'), 1);
        
        // Add meta sanitization bypass
        add_filter('sanitize_meta', array($this, 'bypass_meta_sanitization'), 1, 4);
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Bypass filters added');
        }
    }
    
    /**
     * Add debugging filters to monitor what's being sanitized
     */
    private function add_sanitization_debugging() {
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return;
        }
        
        // Debug content sanitization
        add_filter('content_save_pre', function($content) {
            aysa_debug_log('AYSA DEBUG: Original content length: ' . strlen($content));
            aysa_debug_log('AYSA DEBUG: Original content preview: ' . substr($content, 0, 200) . '...');
            return $content;
        }, 1);
        
        add_filter('content_save_pre', function($content) {
            aysa_debug_log('AYSA DEBUG: Final content length: ' . strlen($content));
            aysa_debug_log('AYSA DEBUG: Final content preview: ' . substr($content, 0, 200) . '...');
            return $content;
        }, 999);
        
        // Debug excerpt sanitization
        add_filter('excerpt_save_pre', function($excerpt) {
            aysa_debug_log('AYSA DEBUG: Original excerpt: ' . $excerpt);
            return $excerpt;
        }, 1);
        
        add_filter('excerpt_save_pre', function($excerpt) {
            aysa_debug_log('AYSA DEBUG: Final excerpt: ' . $excerpt);
            return $excerpt;
        }, 999);
        
        // Debug title sanitization
        add_filter('title_save_pre', function($title) {
            aysa_debug_log('AYSA DEBUG: Original title: ' . $title);
            return $title;
        }, 1);
        
        add_filter('title_save_pre', function($title) {
            aysa_debug_log('AYSA DEBUG: Final title: ' . $title);
            return $title;
        }, 999);
    }
    
    /**
     * Bypass content sanitization - return content as-is or with whitelist filtering
     * 
     * @param string $content The content to sanitize
     * @return string The processed content
     */
    public function bypass_content_sanitization($content) {
        // Allow filtering to enable sanitization for specific cases
        $bypass_sanitization = apply_filters('aysa_bypass_content_sanitization', true, $content);
        
        if ($bypass_sanitization) {
            // Check if whitelist filtering is enabled
            $use_whitelist = apply_filters('aysa_use_content_whitelist', false, $content);
            
            if ($use_whitelist) {
                return $this->filter_content_with_whitelist($content);
            }
            
            // Return content without any sanitization
            return $content;
        }
        
        // If bypass is disabled, apply minimal safe sanitization
        return wp_kses_post($content);
    }
    
    /**
     * Bypass excerpt sanitization - return content as-is
     * 
     * @param string $excerpt The excerpt to sanitize
     * @return string The unsanitized excerpt
     */
    public function bypass_excerpt_sanitization($excerpt) {
        // Allow filtering to enable sanitization for specific cases
        $bypass_sanitization = apply_filters('aysa_bypass_excerpt_sanitization', true, $excerpt);
        
        if ($bypass_sanitization) {
            // Return excerpt without any sanitization
            return $excerpt;
        }
        
        // If bypass is disabled, apply minimal safe sanitization
        return wp_kses_post($excerpt);
    }
    
    /**
     * Bypass title sanitization - return title as-is
     * 
     * @param string $title The title content
     * @return string Unmodified title
     */
    public function bypass_title_sanitization($title) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Bypassing title sanitization for: ' . substr($title, 0, 100));
        }
        return $title;
    }
    
    /**
     * Bypass term description sanitization - return description as-is
     * 
     * @param string $description The term description
     * @return string Unmodified description
     */
    public function bypass_term_description_sanitization($description) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log('AYSA: Bypassing term description sanitization for: ' . substr($description, 0, 100));
        }
        return $description;
    }
    
    /**
     * Bypass meta sanitization for specific meta keys
     * 
     * @param mixed $meta_value The meta value
     * @param string $meta_key The meta key
     * @param string $object_type The object type (post, term, user, etc.)
     * @param string $object_subtype The object subtype
     * @return mixed The unsanitized meta value
     */
    public function bypass_meta_sanitization($meta_value, $meta_key, $object_type, $object_subtype = '') {
        // Define meta keys that should bypass sanitization
        $bypass_keys = apply_filters('aysa_bypass_meta_keys', array(
            '_aysa_generated_content',
            '_aysa_seo_content',
            '_aysa_meta_description',
            '_aysa_meta_keywords',
            '_aysa_structured_data',
            'description', // For taxonomy descriptions
        ));
        
        if (in_array($meta_key, $bypass_keys)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA: Bypassing meta sanitization for key: ' . $meta_key);
            }
            return $meta_value;
        }
        
        // For other meta keys, apply default sanitization
         return $meta_value;
     }
     
     /**
      * Handle WooCommerce-specific filters
      */
     public function handle_woocommerce_filters() {
         if (defined('WP_DEBUG') && WP_DEBUG) {
             aysa_debug_log('AYSA: Handling WooCommerce-specific filters');
         }
         
         // Remove WooCommerce product description sanitization
         remove_filter('woocommerce_short_description', 'wp_filter_post_kses');
         remove_filter('woocommerce_product_get_description', 'wp_filter_post_kses');
         remove_filter('woocommerce_product_get_short_description', 'wp_filter_post_kses');
         
         // Remove WooCommerce category description sanitization
         remove_filter('woocommerce_taxonomy_archive_description', 'wp_filter_post_kses');
         
         if (defined('WP_DEBUG') && WP_DEBUG) {
             aysa_debug_log('AYSA: WooCommerce-specific filters handled');
         }
     }
     
     /**
      * Utility method to temporarily execute code without sanitization
      * 
      * @param callable $callback The callback to execute
      * @return mixed The result of the callback
      */
     public static function execute_without_sanitization($callback) {
         if (!is_callable($callback)) {
             return false;
         }
         
         // Temporarily remove all sanitization filters
         $removed_filters = array();
         
         // Store and remove content filters
         $content_filters = array(
             'content_save_pre' => 'wp_filter_post_kses',
             'excerpt_save_pre' => 'wp_filter_post_kses',
             'title_save_pre' => 'wp_filter_kses',
             'pre_term_description' => 'wp_filter_kses',
         );
         
         foreach ($content_filters as $hook => $function) {
             if (has_filter($hook, $function)) {
                 remove_filter($hook, $function);
                 $removed_filters[$hook] = $function;
             }
         }
         
         // Execute the callback
         $result = call_user_func($callback);
         
         // Restore the filters
         foreach ($removed_filters as $hook => $function) {
             add_filter($hook, $function);
         }
         
         return $result;
     }
     
     /**
      * Check if sanitization is currently bypassed for a specific context
      * 
      * @param string $context The context to check (content, excerpt, title, meta)
      * @return bool Whether sanitization is bypassed
      */
     public function is_sanitization_bypassed($context = 'content') {
         switch ($context) {
             case 'content':
                 return apply_filters('aysa_bypass_content_sanitization', true);
             case 'excerpt':
                 return apply_filters('aysa_bypass_excerpt_sanitization', true);
             case 'title':
                 return apply_filters('aysa_bypass_title_sanitization', true);
             case 'meta':
                 return apply_filters('aysa_bypass_meta_sanitization', true);
             default:
                 return false;
         }
     }
 }
 
 // Global utility function for easy access
 if (!function_exists('aysa_execute_without_sanitization')) {
     /**
      * Global utility function to execute code without sanitization
      * 
      * @param callable $callback The callback to execute
      * @return mixed The result of the callback
      */
     function aysa_execute_without_sanitization($callback) {
         return Aysa_Content_Filter_Remover::execute_without_sanitization($callback);
     }
 }
