<?php

/**
 * Advanced Settings REST API Controller
 *
 * Handles advanced settings for power users including debug, security, and WordPress features
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * Advanced Settings controller class
 */


class AdvancedSettingsController extends BaseController {
    
    /**
     * Rest base
     */
    protected $rest_base = 'advanced-settings';
    
    /**
     * Register routes
     */
    public function register_routes(): void {
        // Get/Save advanced settings
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_settings'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'save_settings'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );
        
        // Apply settings immediately
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/apply',
            [
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'apply_settings'],
                    'permission_callback' => [$this, 'check_permission'],
                ],
            ]
        );
    }
    
    /**
     * Get advanced settings
     */
    public function get_settings(WP_REST_Request $request): WP_REST_Response {
        $settings = wp_parse_args(
            get_option('prorank_seo_advanced_settings', []),
            $this->get_default_settings()
        );

        // Include code injection settings (separate option).
        $settings['code_injection'] = wp_parse_args(
            get_option('prorank_seo_code_injection', []),
            ['head_code' => '', 'body_code' => '', 'footer_code' => '']
        );

        // Include CDN rewrite settings (from cache settings option).
        $cache = get_option('prorank_cache_settings', []);
        if (!is_array($cache)) {
            $cache = [];
        }
        $settings['cdn_rewrite'] = [
            'url'         => (string) ($cache['cdn_rewrite_url'] ?? ''),
            'directories' => (string) ($cache['cdn_rewrite_directories'] ?? 'wp-content,wp-includes'),
            'exclusions'  => (string) ($cache['cdn_rewrite_exclusions'] ?? ''),
        ];

        // Include per-module performance overrides.
        $settings['performance_module_overrides'] = get_option('prorank_performance_module_overrides', []);

        $settings['third_party_governance'] = [
            'delay_google_services' => !empty($settings['delay_google_services']),
            'delay_review_widgets'  => !empty($settings['delay_review_widgets']),
            'defer_consent_scripts' => !empty($settings['defer_consent_scripts']),
            'delay_identity_widgets'=> !empty($settings['delay_identity_widgets']),
        ];
        
        return new WP_REST_Response([
            'success' => true,
            'data'    => $settings,
        ]);
    }
    
    /**
     * Save advanced settings
     */
    public function save_settings(WP_REST_Request $request): WP_REST_Response {
        $settings = $request->get_param('advanced');
        
        if (!$settings) {
            return new WP_REST_Response([
                'success' => false,
                'message' => __('No settings provided', 'prorank-seo'),
            ], 400);
        }
        
        // Validate and sanitize settings
        $sanitized = $this->sanitize_settings($settings);
        
        // Save to database and legacy mirror used by older runtime helpers.
        update_option('prorank_seo_advanced_settings', $sanitized);
        update_option('prorank_advanced_settings', $sanitized);

        // Save code injection (separate option).
        if (isset($settings['code_injection']) && is_array($settings['code_injection'])) {
            $ci = $settings['code_injection'];
            update_option('prorank_seo_code_injection', [
                'head_code'   => wp_unslash((string) ($ci['head_code'] ?? '')),
                'body_code'   => wp_unslash((string) ($ci['body_code'] ?? '')),
                'footer_code' => wp_unslash((string) ($ci['footer_code'] ?? '')),
            ]);
        }

        // Save CDN rewrite (merged into cache settings).
        if (isset($settings['cdn_rewrite']) && is_array($settings['cdn_rewrite'])) {
            $cdn = $settings['cdn_rewrite'];
            $cache = get_option('prorank_cache_settings', []);
            if (!is_array($cache)) {
                $cache = [];
            }
            $cache['cdn_rewrite_url']         = esc_url_raw((string) ($cdn['url'] ?? ''));
            $cache['cdn_rewrite_directories'] = sanitize_text_field((string) ($cdn['directories'] ?? 'wp-content,wp-includes'));
            $cache['cdn_rewrite_exclusions']  = sanitize_text_field((string) ($cdn['exclusions'] ?? ''));
            update_option('prorank_cache_settings', $cache);
        }

        // Save per-module performance overrides.
        if (isset($settings['performance_module_overrides']) && is_array($settings['performance_module_overrides'])) {
            $overrides = [];
            foreach ($settings['performance_module_overrides'] as $k => $v) {
                $overrides[sanitize_key((string) $k)] = !empty($v);
            }
            update_option('prorank_performance_module_overrides', $overrides);
        }
        
        // Apply settings immediately
        $this->apply_settings_internal($sanitized);
        
        return new WP_REST_Response([
            'success' => true,
            'message' => __('Advanced settings saved successfully', 'prorank-seo'),
            'data'    => $sanitized,
        ]);
    }
    
    /**
     * Apply settings immediately
     */
    public function apply_settings(WP_REST_Request $request): WP_REST_Response {
        $settings = get_option('prorank_seo_advanced_settings', $this->get_default_settings());
        $this->apply_settings_internal($settings);
        
        return new WP_REST_Response([
            'success' => true,
            'message' => __('Settings applied successfully', 'prorank-seo'),
        ]);
    }
    
    /**
     * Apply settings internally
     */
    private function apply_settings_internal(array $settings): void {
        // Debug & Development
        if ($settings['debug_mode'] && defined('WP_DEBUG') && WP_DEBUG) {
            // Set error reporting based on log level
            switch ($settings['log_level']) {
                case 'debug':
                    error_reporting(E_ALL);
                    break;
                case 'info':
                    error_reporting(E_ALL & ~E_NOTICE);
                    break;
                case 'warning':
                    error_reporting(E_ERROR | E_WARNING | E_PARSE);
                    break;
                case 'error':
                default:
                    error_reporting(E_ERROR | E_PARSE);
                    break;
            }
        }
        
        // Performance settings
        if (!empty($settings['api_timeout'])) {
            add_filter('http_request_timeout', function() use ($settings) {
                return intval($settings['api_timeout']);
            });
        }
        
        if (!empty($settings['cache_duration'])) {
            // Store cache duration for use by caching modules
            update_option('prorank_seo_cache_duration', intval($settings['cache_duration']));
        }
        
        // Security features
        if ($settings['disable_xmlrpc']) {
            add_filter('xmlrpc_enabled', '__return_false');
            add_filter('xmlrpc_methods', function($methods) {
                return [];
            });
        }
        
        if ($settings['disable_rest_api_public']) {
            add_filter('rest_authentication_errors', function($result) {
                if (!is_user_logged_in()) {
                    return new WP_Error(
                        'rest_forbidden',
                        __('REST API restricted to authenticated users.', 'prorank-seo'),
                        ['status' => 401]
                    );
                }
                return $result;
            });
        }
        
        if ($settings['remove_version_strings']) {
            // Remove version from scripts and styles
            add_filter('style_loader_src', [$this, 'remove_version_from_url'], 9999);
            add_filter('script_loader_src', [$this, 'remove_version_from_url'], 9999);
            
            // Remove WordPress version
            remove_action('wp_head', 'wp_generator');
            add_filter('the_generator', '__return_empty_string');
        }
        
        if ($settings['disable_file_editing']) {
            // Enforce file editor lock via WP filter instead of redefining constants at runtime.
            add_filter('file_mod_allowed', function($allowed, $context) {
                if ($context === 'file_edit') {
                    return false;
                }
                return $allowed;
            }, 10, 2);
        }
        
        // WordPress features
        if ($settings['disable_emojis']) {
            $this->disable_emojis();
        }
        
        if ($settings['disable_gutenberg']) {
            add_filter('use_block_editor_for_post', '__return_false', 10);
            add_filter('use_block_editor_for_post_type', '__return_false', 10);
            
            // Remove Gutenberg CSS
            add_action('wp_print_styles', function() {
                wp_dequeue_style('wp-block-library');
                wp_dequeue_style('wp-block-library-theme');
                wp_dequeue_style('wc-block-style');
                wp_dequeue_style('global-styles');
            }, 100);
        }

        if ($settings['disable_dashicons']) {
            $this->disable_dashicons();
        }

        if ($settings['remove_global_styles']) {
            $this->remove_global_styles();
        }

        if ($settings['disable_password_strength_meter']) {
            $this->disable_password_strength_meter();
        }

        if ($settings['disable_woocommerce_scripts']) {
            $this->disable_woocommerce_scripts();
        }

        if ($settings['disable_woocommerce_cart_fragments']) {
            $this->disable_woocommerce_cart_fragments();
        }

        if ($settings['disable_woocommerce_widgets']) {
            $this->disable_woocommerce_widgets();
        }

        if ($settings['disable_woocommerce_status_meta_box']) {
            $this->disable_woocommerce_status_meta_box();
        }
        
        // Store a flag that settings have been applied
        update_option('prorank_seo_advanced_settings_applied', true);
    }
    
    /**
     * Disable WordPress emojis
     */
    private function disable_emojis(): void {
        remove_action('wp_head', 'print_emoji_detection_script', 7);
        remove_action('admin_print_scripts', 'print_emoji_detection_script');
        remove_action('wp_print_styles', 'print_emoji_styles');
        remove_action('admin_print_styles', 'print_emoji_styles');
        remove_filter('the_content_feed', 'wp_staticize_emoji');
        remove_filter('comment_text_rss', 'wp_staticize_emoji');
        remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
        
        add_filter('tiny_mce_plugins', function($plugins) {
            if (is_array($plugins)) {
                return array_diff($plugins, ['wpemoji']);
            }
            return [];
        });
        
        add_filter('wp_resource_hints', function($urls, $relation_type) {
            if ('dns-prefetch' === $relation_type) {
                $emoji_svg_url = apply_filters('emoji_svg_url', 'https://s.w.org/images/core/emoji/');
                $urls = array_diff($urls, [$emoji_svg_url]);
            }
            return $urls;
        }, 10, 2);
    }

    /**
     * Disable front-end Dashicons for logged-out visitors.
     */
    private function disable_dashicons(): void {
        $remove_dashicons = function() {
            if (is_user_logged_in()) {
                return;
            }

            wp_dequeue_style('dashicons');
            wp_deregister_style('dashicons');
        };

        add_action('wp_enqueue_scripts', $remove_dashicons, 100);
        add_action('wp_print_styles', $remove_dashicons, 100);
    }

    /**
     * Remove front-end global styles output while keeping the block editor intact.
     */
    private function remove_global_styles(): void {
        $blocked_handles = ['global-styles', 'classic-theme-styles', 'wp-block-library-theme'];

        $prevent_core_global_styles = function() {
            if (!$this->can_buffer_frontend_html()) {
                return;
            }

            remove_action('wp_enqueue_scripts', 'wp_enqueue_global_styles', 1);
            remove_action('wp_enqueue_scripts', 'wp_enqueue_global_styles', 10);
            remove_action('wp_footer', 'wp_enqueue_global_styles', 1);
            remove_action('wp_enqueue_scripts', 'wp_enqueue_classic_theme_styles', 1);
            remove_action('wp_enqueue_scripts', 'wp_enqueue_classic_theme_styles', 10);
            remove_action('enqueue_block_assets', 'wp_enqueue_classic_theme_styles', 1);
            remove_action('enqueue_block_assets', 'wp_enqueue_classic_theme_styles', 10);
        };

        $remove_global_styles = function() use ($blocked_handles) {
            if (!$this->can_buffer_frontend_html()) {
                return;
            }

            global $wp_styles;

            foreach ($blocked_handles as $handle) {
                wp_dequeue_style($handle);
                wp_deregister_style($handle);
            }

            if ($wp_styles instanceof \WP_Styles) {
                foreach (['queue', 'to_do', 'done'] as $prop) {
                    if (isset($wp_styles->$prop) && is_array($wp_styles->$prop)) {
                        $wp_styles->$prop = array_values(array_diff($wp_styles->$prop, $blocked_handles));
                    }
                }

                foreach ($blocked_handles as $handle) {
                    if (isset($wp_styles->registered[$handle])) {
                        $wp_styles->registered[$handle]->extra['after'] = [];
                    }
                }
            }
        };

        add_action('after_setup_theme', $prevent_core_global_styles, 100);
        add_action('init', $prevent_core_global_styles, 0);
        add_action('wp_enqueue_scripts', $prevent_core_global_styles, 0);
        add_action('wp_enqueue_scripts', $remove_global_styles, 100);
        add_action('enqueue_block_assets', $prevent_core_global_styles, 0);
        add_action('enqueue_block_assets', $remove_global_styles, 100);
        add_action('wp_head', $remove_global_styles, 0);
        add_action('wp_print_styles', $remove_global_styles, 100);
        add_filter('print_styles_array', function($handles) use ($blocked_handles) {
            if (!$this->can_buffer_frontend_html() || !is_array($handles)) {
                return $handles;
            }

            return array_values(array_diff($handles, $blocked_handles));
        });
        add_filter('style_loader_tag', function($html, $handle) use ($blocked_handles) {
            if (!$this->can_buffer_frontend_html()) {
                return $html;
            }

            if (in_array($handle, $blocked_handles, true)) {
                return '';
            }

            return $html;
        }, 100, 2);

        if ($this->can_buffer_frontend_html()) {
            $prevent_core_global_styles();
            remove_action('wp_body_open', 'wp_global_styles_render_svg_filters');
        }

        if ($this->can_buffer_frontend_html()) {
            ob_start(function($html) use ($remove_global_styles) {
                if (!is_string($html) || $html === '') {
                    return $html;
                }

                $remove_global_styles();

                $patterns = [
                    '#<style[^>]+id=[\'"]classic-theme-styles-inline-css[\'"][^>]*>.*?</style>#is',
                    '#<style[^>]+id=[\'"]global-styles-inline-css[\'"][^>]*>.*?</style>#is',
                    '#<style[^>]+id=[\'"]wp-block-library-theme-inline-css[\'"][^>]*>.*?</style>#is',
                    '#<link[^>]+id=[\'"]global-styles-css[\'"][^>]*>#is',
                    '#<link[^>]+id=[\'"]classic-theme-styles-css[\'"][^>]*>#is',
                    '#<link[^>]+id=[\'"]wp-block-library-theme-css[\'"][^>]*>#is',
                ];

                return preg_replace($patterns, '', $html) ?? $html;
            });
        }
    }

    /**
     * Disable WooCommerce password strength meter scripts on the front end.
     */
    private function disable_password_strength_meter(): void {
        $remove_password_meter = function() {
            try {
                if (is_admin()) {
                    return;
                }

                foreach (['wc-password-strength-meter', 'zxcvbn-async', 'zxcvbn'] as $handle) {
                    wp_dequeue_script($handle);
                    wp_deregister_script($handle);
                }
            } catch (\Throwable $e) {
                if (function_exists('prorank_log')) {
                    prorank_log('[ProRank AdvancedSettingsController] password meter cleanup failed: ' . $e->getMessage());
                }
            }
        };

        add_action('wp_enqueue_scripts', $remove_password_meter, 100);
        add_action('wp_print_scripts', $remove_password_meter, 100);
        add_action('wp_print_footer_scripts', $remove_password_meter, 100);
    }

    /**
     * Disable WooCommerce front-end assets on non-store pages.
     */
    private function disable_woocommerce_scripts(): void {
        if (!class_exists('\WooCommerce')) {
            return;
        }

        $cleanup = function() {
            try {
                if (is_admin() || $this->should_keep_woocommerce_assets()) {
                    return;
                }

                $this->remove_woocommerce_frontend_assets();
            } catch (\Throwable $e) {
                if (function_exists('prorank_log')) {
                    prorank_log('[ProRank AdvancedSettingsController] WooCommerce asset cleanup failed: ' . $e->getMessage());
                }
            }
        };

        add_action('wp_enqueue_scripts', $cleanup, 1000);
        add_action('wp_print_styles', $cleanup, 0);
        add_action('wp_print_styles', $cleanup, 999999);
        add_action('wp_print_scripts', $cleanup, 0);
        add_action('wp_print_scripts', $cleanup, 999999);
        add_action('wp_print_footer_scripts', $cleanup, 0);
        add_action('wp_print_footer_scripts', $cleanup, 999999);
        add_filter('script_loader_tag', function($tag, $handle, $src) {
            $fallback = is_string($tag) ? $tag : '';

            try {
                if (is_admin() || $this->should_keep_woocommerce_assets()) {
                    return $fallback;
                }

                return $this->is_woocommerce_frontend_asset((string) $handle, (string) $src, 'script') ? '' : $fallback;
            } catch (\Throwable $e) {
                if (function_exists('prorank_log')) {
                    prorank_log('[ProRank AdvancedSettingsController] WooCommerce script tag filter failed: ' . $e->getMessage());
                }
                return $fallback;
            }
        }, 100, 3);
        add_filter('style_loader_tag', function($html, $handle, $href, $media) {
            $fallback = is_string($html) ? $html : '';

            try {
                if (is_admin() || $this->should_keep_woocommerce_assets()) {
                    return $fallback;
                }

                return $this->is_woocommerce_frontend_asset((string) $handle, (string) $href, 'style') ? '' : $fallback;
            } catch (\Throwable $e) {
                if (function_exists('prorank_log')) {
                    prorank_log('[ProRank AdvancedSettingsController] WooCommerce style tag filter failed: ' . $e->getMessage());
                }
                return $fallback;
            }
        }, 100, 4);
        if ($this->can_buffer_frontend_html()) {
            ob_start(function($html) {
                if (!is_string($html) || $html === '') {
                    return $html;
                }

                try {
                    if ($this->should_keep_woocommerce_tracking_assets()) {
                        return $html;
                    }

                    return $this->strip_woocommerce_tracking_assets_from_html($html);
                } catch (\Throwable $e) {
                    if (function_exists('prorank_log')) {
                        prorank_log('[ProRank AdvancedSettingsController] WooCommerce tracking buffer failed: ' . $e->getMessage());
                    }
                    return $html;
                }
            });
        }
    }

    /**
     * Disable WooCommerce cart fragments globally.
     */
    private function disable_woocommerce_cart_fragments(): void {
        if (!class_exists('\WooCommerce')) {
            return;
        }

        add_filter('woocommerce_cart_fragments_enabled', '__return_false', 100);
        add_filter('woocommerce_get_script_data', function($data, $handle) {
            if ($handle === 'wc-cart-fragments') {
                return null;
            }

            return $data;
        }, 100, 2);
        add_filter('woocommerce_add_to_cart_fragments', '__return_empty_array', 100);

        $remove_cart_fragments = function() {
            try {
                if (is_admin()) {
                    return;
                }

                wp_dequeue_script('wc-cart-fragments');
                wp_deregister_script('wc-cart-fragments');
            } catch (\Throwable $e) {
                if (function_exists('prorank_log')) {
                    prorank_log('[ProRank AdvancedSettingsController] cart fragments cleanup failed: ' . $e->getMessage());
                }
            }
        };

        add_action('wp_enqueue_scripts', $remove_cart_fragments, 1000);
        add_action('wp_print_scripts', $remove_cart_fragments, 0);
        add_action('wp_print_scripts', $remove_cart_fragments, 1000);
        add_action('wp_print_footer_scripts', $remove_cart_fragments, 0);
        add_action('wp_print_footer_scripts', $remove_cart_fragments, 1000);
        add_filter('script_loader_tag', function($tag, $handle) {
            try {
                return $handle === 'wc-cart-fragments' ? '' : $tag;
            } catch (\Throwable $e) {
                if (function_exists('prorank_log')) {
                    prorank_log('[ProRank AdvancedSettingsController] cart fragments script filter failed: ' . $e->getMessage());
                }
                return is_string($tag) ? $tag : '';
            }
        }, 100, 2);
        if ($this->can_buffer_frontend_html()) {
            ob_start(function($html) {
                if (!is_string($html) || $html === '') {
                    return $html;
                }

                try {
                    return $this->strip_woocommerce_cart_fragments_from_html($html);
                } catch (\Throwable $e) {
                    if (function_exists('prorank_log')) {
                        prorank_log('[ProRank AdvancedSettingsController] cart fragments buffer failed: ' . $e->getMessage());
                    }
                    return $html;
                }
            });
        }
    }

    /**
     * Disable classic WooCommerce widgets.
     */
    private function disable_woocommerce_widgets(): void {
        if (!class_exists('\WooCommerce')) {
            return;
        }

        add_action('widgets_init', function() {
            $widget_classes = [
                'WC_Widget_Cart',
                'WC_Widget_Layered_Nav',
                'WC_Widget_Layered_Nav_Filters',
                'WC_Widget_Price_Filter',
                'WC_Widget_Product_Categories',
                'WC_Widget_Product_Search',
                'WC_Widget_Product_Tag_Cloud',
                'WC_Widget_Products',
                'WC_Widget_Recently_Viewed',
                'WC_Widget_Top_Rated_Products',
                'WC_Widget_Recent_Reviews',
                'WC_Widget_Rating_Filter',
                'WC_Widget_Onsale',
                'WC_Widget_Featured_Products',
                'WC_Widget_Recent_Products',
            ];

            foreach ($widget_classes as $widget_class) {
                if (class_exists($widget_class)) {
                    unregister_widget($widget_class);
                }
            }
        }, 100);
    }

    /**
     * Disable the WooCommerce dashboard status widgets.
     */
    private function disable_woocommerce_status_meta_box(): void {
        if (!class_exists('\WooCommerce')) {
            return;
        }

        add_action('wp_dashboard_setup', function() {
            remove_meta_box('woocommerce_dashboard_status', 'dashboard', 'normal');
            remove_meta_box('woocommerce_dashboard_recent_reviews', 'dashboard', 'normal');
            remove_meta_box('woocommerce_network_orders', 'dashboard', 'normal');
        }, 100);
    }

    /**
     * Decide whether the current request needs WooCommerce assets.
     */
    private function should_keep_woocommerce_assets(): bool {
        foreach (['is_woocommerce', 'is_cart', 'is_checkout', 'is_account_page', 'is_product', 'is_shop', 'is_product_category', 'is_product_tag'] as $fn) {
            if (function_exists($fn) && $fn()) {
                return true;
            }
        }

        if (!is_singular()) {
            return false;
        }

        $post = get_post();
        if (!$post instanceof \WP_Post) {
            return false;
        }

        return $this->content_contains_any_woocommerce_hint(
            $this->get_singular_woocommerce_hint_sources($post),
            [
                '[woocommerce_',
                '[products',
                '[product_page',
                '[add_to_cart',
                '[featured_products',
                '[sale_products',
                '[best_selling_products',
                '[recent_products',
                '[product_category',
                '[product_categories',
                'woocommerce/',
                'woocommerce-',
                '"widgettype":"loop-grid"',
                '"widgettype":"products"',
                '"widgettype":"menu-cart"',
                '"widgettype":"woocommerce',
                '"_skin":"product"',
                'woocommerce_thumbnail',
                'size-woocommerce_',
            ]
        );
    }

    /**
     * Keep WooCommerce tracking/attribution scripts only on real transactional/store contexts.
     */
    private function should_keep_woocommerce_tracking_assets(): bool {
        foreach (['is_woocommerce', 'is_cart', 'is_checkout', 'is_account_page', 'is_product', 'is_shop', 'is_product_category', 'is_product_tag'] as $fn) {
            if (function_exists($fn) && $fn()) {
                return true;
            }
        }

        if (!is_singular()) {
            return false;
        }

        $post = get_post();
        if (!$post instanceof \WP_Post) {
            return false;
        }

        return $this->content_contains_any_woocommerce_hint(
            $this->get_singular_woocommerce_hint_sources($post),
            [
                '[woocommerce_cart',
                '[woocommerce_checkout',
                '[woocommerce_my_account',
                '[add_to_cart',
                'menu-cart',
                'woocommerce-menu-cart',
                '"widgettype":"woocommerce-cart"',
                '"widgettype":"woocommerce-checkout"',
                '"widgettype":"woocommerce-my-account"',
                '"widgettype":"woocommerce-product-add-to-cart"',
                '"widgettype":"woocommerce-product-data-tabs"',
                '"widgettype":"woocommerce-product-images"',
                '"widgettype":"woocommerce-product-meta"',
                '"widgettype":"woocommerce-product-price"',
                '"widgettype":"woocommerce-product-rating"',
                '"widgettype":"woocommerce-product-stock"',
                'cart_page_url',
                'checkout_page_url',
            ]
        );
    }

    /**
     * Collect singular-content sources that may declare WooCommerce dependencies.
     *
     * @param \WP_Post $post
     * @return array<int, string>
     */
    private function get_singular_woocommerce_hint_sources(\WP_Post $post): array {
        $sources = [];

        if ($post->post_content !== '') {
            $sources[] = (string) $post->post_content;
        }

        foreach (['_elementor_data', '_elementor_element_cache'] as $meta_key) {
            $meta = get_post_meta($post->ID, $meta_key, true);
            if (is_string($meta) && $meta !== '') {
                $sources[] = $meta;
            }
        }

        return $sources;
    }

    /**
     * Check whether any source contains WooCommerce-related hints.
     *
     * @param array<int, string> $sources
     * @param array<int, string> $needles
     * @return bool
     */
    private function content_contains_any_woocommerce_hint(array $sources, array $needles): bool {
        if (empty($sources) || empty($needles)) {
            return false;
        }

        $normalized_needles = array_map('strtolower', $needles);

        foreach ($sources as $source) {
            $haystack = strtolower((string) $source);
            if ($haystack === '') {
                continue;
            }

            foreach ($normalized_needles as $needle) {
                if ($needle !== '' && strpos($haystack, $needle) !== false) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Whether it is safe to start a frontend HTML output buffer on this request.
     */
    private function can_buffer_frontend_html(): bool {
        if (is_admin() || wp_doing_ajax()) {
            return false;
        }

        if ((defined('REST_REQUEST') && REST_REQUEST) || (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST)) {
            return false;
        }

        if ((defined('DOING_CRON') && DOING_CRON) || (defined('WP_CLI') && WP_CLI)) {
            return false;
        }

        return true;
    }

    /**
     * Remove queued WooCommerce front-end assets from the current request.
     */
    private function remove_woocommerce_frontend_assets(): void {
        global $wp_scripts, $wp_styles;

        if ($wp_scripts instanceof \WP_Scripts) {
            $handles_to_remove = [];
            foreach ((array) $wp_scripts->queue as $handle) {
                $src = isset($wp_scripts->registered[$handle]) ? (string) ($wp_scripts->registered[$handle]->src ?? '') : '';
                if ($this->is_woocommerce_frontend_asset((string) $handle, $src, 'script')) {
                    $handles_to_remove[] = (string) $handle;
                }
            }

            foreach ($handles_to_remove as $handle) {
                wp_dequeue_script($handle);
                wp_deregister_script($handle);
            }

            foreach (['queue', 'to_do', 'done'] as $prop) {
                if (isset($wp_scripts->$prop) && is_array($wp_scripts->$prop)) {
                    $wp_scripts->$prop = array_values(array_diff($wp_scripts->$prop, $handles_to_remove));
                }
            }
        }

        if ($wp_styles instanceof \WP_Styles) {
            $handles_to_remove = [];
            foreach ((array) $wp_styles->queue as $handle) {
                $src = isset($wp_styles->registered[$handle]) ? (string) ($wp_styles->registered[$handle]->src ?? '') : '';
                if ($this->is_woocommerce_frontend_asset((string) $handle, $src, 'style')) {
                    $handles_to_remove[] = (string) $handle;
                }
            }

            foreach ($handles_to_remove as $handle) {
                wp_dequeue_style($handle);
                wp_deregister_style($handle);
            }

            foreach (['queue', 'to_do', 'done'] as $prop) {
                if (isset($wp_styles->$prop) && is_array($wp_styles->$prop)) {
                    $wp_styles->$prop = array_values(array_diff($wp_styles->$prop, $handles_to_remove));
                }
            }
        }
    }

    /**
     * Match known WooCommerce front-end asset handles and sources.
     */
    private function is_woocommerce_frontend_asset(string $handle, string $src, string $asset_type): bool {
        $handle = strtolower($handle);
        $src = strtolower($src);

        $known_scripts = [
            'woocommerce',
            'wc-add-to-cart',
            'wc-cart-fragments',
            'wc-checkout',
            'wc-add-to-cart-variation',
            'wc-single-product',
            'wc-country-select',
            'wc-address-i18n',
            'wc-credit-card-form',
            'wc-cart',
            'wc-chosen',
            'wc-order-attribution',
            'js-cookie',
            'sourcebuster-js',
            'wc-facebook-pixel-events',
            'facebook-capi-param-builder',
            'wcpay_assets',
        ];

        $known_styles = [
            'woocommerce-layout',
            'woocommerce-smallscreen',
            'woocommerce-general',
            'wc-block-style',
            'wc-blocks-style',
            'wc-blocks-vendors-style',
            'wc-blocks-packages-style',
            'wc-blocks-style-mini-cart',
        ];

        $known_handles = $asset_type === 'script' ? $known_scripts : $known_styles;
        if (in_array($handle, $known_handles, true)) {
            return true;
        }

        if (str_starts_with($handle, 'woocommerce') || str_starts_with($handle, 'wc-')) {
            return true;
        }

        foreach ([
            '/plugins/woocommerce/',
            '/plugins/woocommerce-blocks/',
            '/plugins/woo-gutenberg-products-block/',
            '/plugins/facebook-for-woocommerce/',
            '/plugins/woocommerce-payments/',
        ] as $needle) {
            if ($src !== '' && strpos($src, $needle) !== false) {
                return true;
            }
        }

        if (str_starts_with($handle, 'wcpay') || str_starts_with($handle, 'wc-facebook')) {
            return true;
        }

        return false;
    }

    /**
     * Strip WooCommerce tracking / attribution scripts from final HTML.
     */
    private function strip_woocommerce_tracking_assets_from_html(string $html): string {
        $patterns = [
            '#<script\b[^>]*id=[\'"]sourcebuster-js-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]wc-order-attribution-js-extra[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]wc-order-attribution-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]wc-facebook-pixel-events-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]facebook-capi-param-builder-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]facebook-capi-param-builder-js-after[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]facebook-for-woocommerce-inline-js-after[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]googlesitekit-events-provider-woocommerce-js-before[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]googlesitekit-events-provider-woocommerce-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]wcpay-frontend-tracks-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*/plugins/woocommerce/assets/js/sourcebuster/[^\'"]*[\'"][^>]*>\s*</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*/plugins/woocommerce/assets/js/frontend/order-attribution[^\'"]*[\'"][^>]*>\s*</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*/cache/perfmatters/[^\'"]*pixel-events[^\'"]*[\'"][^>]*>\s*</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*clientParamBuilder\.bundle\.js[^\'"]*[\'"][^>]*>\s*</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*googlesitekit-events-provider-woocommerce[^\'"]*[\'"][^>]*>\s*</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*/plugins/woocommerce-payments/dist/frontend-tracks[^\'"]*[\'"][^>]*>\s*</script>#is',
        ];

        return preg_replace($patterns, '', $html) ?? $html;
    }

    /**
     * Strip cart-fragment loaders from final HTML.
     */
    private function strip_woocommerce_cart_fragments_from_html(string $html): string {
        $patterns = [
            '#<script\b[^>]*id=[\'"]wc-cart-fragments-js-extra[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*id=[\'"]wc-cart-fragments-js[\'"][^>]*>.*?</script>#is',
            '#<script\b[^>]*src=[\'"][^\'"]*cart-fragments\.min\.js[^\'"]*[\'"][^>]*>\s*</script>#is',
            '#<script\b[^>]*>\s*function\s+perfmatters_check_cart_fragments\s*\(.*?</script>#is',
        ];

        return preg_replace($patterns, '', $html) ?? $html;
    }
    
    /**
     * Remove version from URL
     */
    public function remove_version_from_url($src) {
        if (!is_string($src) || $src === '') {
            return $src;
        }

        try {
            if (function_exists('is_admin') && is_admin()) {
                return $src;
            }

            if ($this->is_prorank_build_asset_url($src)) {
                return $src;
            }
            if (strpos($src, '?ver=') !== false || strpos($src, '&ver=') !== false) {
                $src = remove_query_arg('ver', $src);
            }
        } catch (\Throwable $e) {
            if (function_exists('prorank_log')) {
                prorank_log('[ProRank AdvancedSettingsController] remove_version_from_url failed: ' . $e->getMessage());
            }
        }

        return $src;
    }

    /**
     * Keep version query strings for assets that are updated in-place.
     * This avoids stale caches on long-lived immutable cache policies.
     *
     * @param mixed $url
     * @return bool
     */
    private function is_prorank_build_asset_url($url): bool {
        if (!is_string($url) || $url === '') {
            return false;
        }

        $path = (string) wp_parse_url($url, PHP_URL_PATH);
        if ($path === '') {
            return false;
        }

        return strpos($path, '/wp-content/plugins/prorank-seo/build/') !== false
            || strpos($path, '/wp-content/plugins/prorank-seo-premium/build/') !== false
            || strpos($path, '/wp-admin/') !== false
            || strpos($path, '/wp-includes/js/') !== false
            || strpos($path, '/wp-includes/css/') !== false
            || strpos($path, '/wp-content/uploads/elementor/css/') !== false;
    }
    
    /**
     * Sanitize settings
     */
    private function sanitize_settings(array $settings): array {
        $sanitized = [];
        $third_party_settings = isset($settings['third_party_governance']) && is_array($settings['third_party_governance'])
            ? $settings['third_party_governance']
            : [];
        
        // Boolean settings
        $boolean_keys = [
            'debug_mode',
            'disable_emojis',
            'disable_gutenberg',
            'disable_dashicons',
            'remove_global_styles',
            'disable_password_strength_meter',
            'disable_woocommerce_scripts',
            'disable_woocommerce_cart_fragments',
            'disable_woocommerce_widgets',
            'disable_woocommerce_status_meta_box',
            'disable_google_maps',
            'disable_xmlrpc',
            'disable_rest_api_public',
            'remove_version_strings',
            'disable_file_editing',
            'structural_guard_enabled',
            'performance_compatibility_mode',
            'performance_auto_rollback',
            'delay_google_services',
            'delay_review_widgets',
            'defer_consent_scripts',
            'delay_identity_widgets',
        ];
        
        foreach ($boolean_keys as $key) {
            $value = $settings[$key] ?? null;
            if (array_key_exists($key, $third_party_settings)) {
                $value = $third_party_settings[$key];
            }
            $sanitized[$key] = !empty($value);
        }
        
        // String settings
        $sanitized['log_level'] = in_array($settings['log_level'] ?? 'error', ['error', 'warning', 'info', 'debug']) 
            ? $settings['log_level'] 
            : 'error';

        $sanitized['performance_profile'] = in_array($settings['performance_profile'] ?? 'safe', ['safe', 'balanced', 'aggressive'], true)
            ? (string) $settings['performance_profile']
            : 'safe';

        // Free-text settings
        $sanitized['disable_google_maps_exclusions'] = sanitize_text_field((string) ($settings['disable_google_maps_exclusions'] ?? ''));
        
        // Numeric settings
        $sanitized['api_timeout'] = min(120, max(5, absint($settings['api_timeout'] ?? 30)));
        $sanitized['cache_duration'] = min(86400, max(60, absint($settings['cache_duration'] ?? 3600)));
        
        return $sanitized;
    }
    
    /**
     * Get default settings
     */
    private function get_default_settings(): array {
        return [
            'debug_mode' => false,
            'disable_emojis' => false,
            'disable_gutenberg' => false,
            'disable_dashicons' => false,
            'remove_global_styles' => false,
            'disable_password_strength_meter' => false,
            'disable_woocommerce_scripts' => false,
            'disable_woocommerce_cart_fragments' => false,
            'disable_woocommerce_widgets' => false,
            'disable_woocommerce_status_meta_box' => false,
            'disable_google_maps' => false,
            'disable_google_maps_exclusions' => '',
            'disable_xmlrpc' => true,
            'disable_rest_api_public' => false,
            'remove_version_strings' => true,
            'disable_file_editing' => true,
            'structural_guard_enabled' => true,
            'performance_compatibility_mode' => true,
            'performance_auto_rollback' => true,
            'performance_profile' => 'safe',
            'delay_google_services' => false,
            'delay_review_widgets' => true,
            'defer_consent_scripts' => false,
            'delay_identity_widgets' => false,
            'api_timeout' => 30,
            'cache_duration' => 3600,
            'log_level' => 'error',
        ];
    }
}
