<?php

// If this file is called directly, abort.
defined('ABSPATH') || die('No direct access!');

class Dragonizer_Woocommerce
{
    private static $options;

    private $blocked_urls = [
        'woocommerce.com/wp-json/wccom-extensions/1.0/featured' => '[]',
        'woocommerce.com/wp-json/wccom-extensions/2.0/featured' => '[]',
        'woocommerce.com/wp-json/wccom-extensions/3.0/featured' => '[]',
        'woocommerce.com/wp-json/wccom-extensions/1.0/search' => '{}',
        'woocommerce.com/wp-json/wccom-extensions/1.0/categories' => '[]',
        'woocommerce.com/wp-json/wccom-extensions/3.0/promotions' => '[]',
        'woocommerce.com/wp-json/helper/1.0/update-check-public' => '[]',
        'woocommerce.com/wp-json/wccom/obw-free-extensions/3.0/extensions.json' => '[]',
        'woocommerce.com/wp-json/wccom/payment-gateway-suggestions/1.0/payment-method/promotions.json' => '[]',
        'woocommerce.com/wp-json/wccom/payment-gateway-suggestions/1.0/suggestions.json' => '[]',
    ];

    private $tracking_options = [
        'woocommerce_allow_tracking' => 'no',
        'woocommerce_show_marketplace_suggestions' => 'no',
        'woocommerce_merchant_email_notifications' => 'no',
        'woocommerce_task_list_hidden' => 'yes',
        'woocommerce_task_list_complete' => 'yes',
    ];

    public function init($options)
    {
        if (empty($options) || !empty(self::$options)) {
            return;
        }

        $default = [
            'core_user_experience'                 => false,
            'sales_and_marketing'                  => false,
            'product_management'                   => false,
            'shipping_and_orders'                  => false,
            'onboarding_and_education'             => false,
            'notifications_and_feedback'           => false,
            'performance_and_security'             => false,
            'mobile_footer_text'                   => false,
            'block_external_requests'              => false,
            'interface_metabox'                    => false,
            'interface_setup'                      => false,
            'interface_suggestions'                => false,
            'interface_extensions'                 => false,
            'hide_payment_providers'               => false,
            'woocommerce_blocks'                   => false,
            'performance_scripts'                  => false,
            'performance_cart'                     => false,
            'performance_widgets'                  => false,
            'stripe_script'                        => false,
            'disable_tracking'                     => false,
            'optimize_meta_handling'               => false,
            'toplevelcatsonly'                     => false,
            'optimisewoodeleteoptions'             => false,
            'removecustommeta'                     => false,
            'cacheorderdeliverydate'               => false,
            'cacheshortcode_onsale'                => false,
            'cacheshortcode_bestselling'           => false,
            'ajaxattributeedit'                    => false,
            'fixwoo_onboarding'                    => false,
            'defertermcounting'                    => false,
            'cachepostcounts'                      => false,
            'action_scheduler'                     => false,
            'wpiperf_product_attributes_index_fix' => false,
            'removeajaxvariationscalc'             => false,
            'sortorder'                            => false,
            'calctotals'                           => false,
            'calctotals_admin'                     => false,
            'changetoexists'                       => false,
            'optimisewoogroup'                     => false,
            'optimiseprivatecheck'                 => false
        ];

        self::$options = dr_fix_settings($default, $options);

        // Initialize existing features
        $this->init_existing_features();

        // Initialize performance features
        $this->init_performance_features();
    }

    private function settings(): object
    {
        if (is_object(self::$options)) {
            return self::$options;
        } else {
            return (object)[];
        }
    }

    private function init_existing_features()
    {
        $disabled_features = [];

        if ($this->settings()->core_user_experience) {
            $disabled_features = array_merge($disabled_features, [
                'activity-panels',
                'homescreen',
                'mobile-app-banner',
                'navigation',
                'woo-mobile-welcome',
            ]);

            add_filter('woocommerce_admin_disabled', '__return_true');

            // fix for WooCommerce Status Meta Box not showing
            if (!empty(get_option('woocommerce_task_list_hidden', 'yes'))) {
                update_option('woocommerce_task_list_hidden', 'yes');
            }
            if (!empty(get_option('woocommerce_task_list_complete', 'yes'))) {
                update_option('woocommerce_task_list_complete', 'yes');
            }
            // end fix

            add_action('admin_head', function () {
                echo '<script type="text/javascript">
                    jQuery(document).ready(function($) {
                        if (window.location.search.includes("wc-reports")) {
                            $("strong:contains(\'WooCommerce 4.0\')")
                                .parents("#message").remove();
                        }
                    });
                </script>';
            });

            add_action('admin_enqueue_scripts', function () {
                wp_dequeue_style('wc-admin-app');
                wp_deregister_style('wc-admin-app');
                echo '<style>
                    .woocommerce-layout__header {
                        display: none;
                    }
                </style>';
            }, 19);

            add_action('admin_head', function () {
                echo '<style>
                    .woocommerce-layout__header {
                        display: none;
                    }
                </style>';
            });
        }

        if ($this->settings()->sales_and_marketing) {
            $disabled_features = array_merge($disabled_features, [
                'coupons',
                'marketing',
                'multichannel-marketing',
                'wc-pay-promotion',
                'wc-pay-welcome-page',
            ]);

            add_filter('woocommerce_marketing_menu_items', '__return_empty_array');

            add_filter('woocommerce_admin_features', function ($features) {
                $marketing = array_search('marketing', $features);
                unset($features[$marketing]);
                return $features;
            });
        }
        if ($this->settings()->product_management) {
            $disabled_features = array_merge($disabled_features, [
                'import-products-task',
                'experimental-fashion-sample-products',
                'product-variation-management',
            ]);
        }
        if ($this->settings()->shipping_and_orders) {
            $disabled_features = array_merge($disabled_features, [
                'shipping-smart-defaults',
                'shipping-setting-tour',
                'settings', // Assuming it relates to settings that impact shipping and orders.
                'shipping-label-banner',
            ]);
        }
        if ($this->settings()->onboarding_and_education) {
            $disabled_features = array_merge($disabled_features, [
                'onboarding',
                'onboarding-tasks',
                'new-product-management-experience',
                'minified-js',
                'subscriptions', // This assumes subscriptions can affect performance or security through repeated checks or data management.
            ]);
        }
        if ($this->settings()->notifications_and_feedback) {
            $disabled_features = array_merge($disabled_features, [
                'customer-effort-score-tracks',
                'remote-inbox-notifications',
                'remote-free-extensions',
                'payment-gateway-suggestions',
                'store-alerts',
                'transient-notices',
            ]);
        }

        if (!empty($disabled_features)) {

            add_filter('woocommerce_admin_get_feature_config', function ($features) use ($disabled_features) {

                $disabled_features_keys = array_flip($disabled_features);

                foreach ($features as $key => $value) {
                    if (isset($disabled_features_keys[$key])) {
                        $features[$key] = false;
                    }
                }

                return $features;
            });
        }

        if ($this->settings()->mobile_footer_text) {
            add_action('woocommerce_email', function ($mailer) {
                remove_action('woocommerce_email_footer', array($mailer->emails['WC_Email_New_Order'], 'mobile_messaging'), 9);
            });
        }


        /* Disable WooCommerce Status Meta Box */
        if ($this->settings()->interface_metabox) {
            add_action('wp_dashboard_setup', function () {
                remove_meta_box('woocommerce_dashboard_status', 'dashboard', 'normal');
            });
        }

        /* Disable WooCommerce Dashboard Setup Widget */
        if ($this->settings()->interface_setup) {
            add_action('wp_dashboard_setup', function () {
                remove_meta_box('wc_admin_dashboard_setup', 'dashboard', 'normal');
            }, 40);
        }

        /* Disable WooCommerce Marketplace Suggestions */
        if ($this->settings()->interface_suggestions) {
            add_filter('woocommerce_allow_marketplace_suggestions', '__return_false', 999);
        }

        /* Disable Extensions submenu */
        if ($this->settings()->interface_extensions) {
            add_action('admin_menu', function () {
                remove_submenu_page('woocommerce', 'wc-addons');
                remove_submenu_page('woocommerce', 'wc-addons&section=helper');
            }, 999);
        }

        /* Hide Discover other payment providers link on the WooCommerce Settings Payments screen */
        if ($this->settings()->hide_payment_providers) {
            add_action('admin_head', function () {
                echo '<script type="text/javascript">
                    jQuery(document).ready(function($) {
                        if (window.location.search.includes(\'wc-settings&tab=checkout\')) {
                            const wcBloatDiscoverPaymentsBloat = document.querySelector(\'#settings-other-payment-methods\').parentElement.parentElement;
                            wcBloatDiscoverPaymentsBloat.style.display = \'none\';
                        }
                    });
                </script>';
            });
        }

        /* Disable WooCommerce Blocks */
        if ($this->settings()->woocommerce_blocks) {
            add_action('wp_enqueue_scripts', function () {
                wp_deregister_style('wc-block-editor');
            });

            add_action('wp_enqueue_scripts', function () {
                wp_dequeue_style('wc-blocks-style');
            }, 999);
        }

        if ($this->settings()->performance_scripts) {
            add_action('wp_enqueue_scripts', function () {
                // Check if WooCommerce is active
                if (!function_exists('is_woocommerce')) {
                    return;
                }

                // Additional homepage checks for various scenarios
                $is_home_related = (
                    is_front_page() ||     // Static front page
                    is_home() ||           // Blog page
                    is_page_template('template-homepage.php') ||  // WooCommerce homepage template
                    (function_exists('wc_get_page_id') && is_page(wc_get_page_id('shop'))) || // Shop page set as homepage
                    has_shortcode(get_post()->post_content ?? '', 'products') ||  // Has products shortcode
                    has_shortcode(get_post()->post_content ?? '', 'featured_products') ||
                    has_shortcode(get_post()->post_content ?? '', 'recent_products') ||
                    has_shortcode(get_post()->post_content ?? '', 'product_categories')
                );

                // Don't dequeue on these pages
                if (
                    is_woocommerce() ||
                    is_cart() ||
                    is_checkout() ||
                    is_account_page() ||
                    is_product() ||
                    is_product_category() ||
                    is_shop() ||
                    $is_home_related ||
                    is_search() // Keep scripts on search pages as they might show products
                ) {
                    return;
                }

                // WooCommerce Styles that are safe to dequeue
                $styles = [
                    'woocommerce-general',
                    'woocommerce-layout',
                    'woocommerce-smallscreen',
                    'woocommerce_frontend_styles',
                    'woocommerce_fancybox_styles',
                    'woocommerce_chosen_styles',
                    'woocommerce_prettyPhoto_css'
                ];

                // WooCommerce Scripts that are safe to dequeue
                $scripts = [
                    'wc_price_slider',
                    'wc-single-product',
                    'wc-add-to-cart',
                    'wc-checkout',
                    'wc-add-to-cart-variation',
                    'wc-cart',
                    'wc-chosen',
                    'woocommerce',
                    'prettyPhoto',
                    'prettyPhoto-init',
                    'jquery-blockui',
                    'jquery-placeholder',
                    'fancybox'
                ];

                // Check for WooCommerce widgets in sidebar
                $has_wc_widgets = false;
                $sidebars_widgets = wp_get_sidebars_widgets();
                $wc_widgets = ['woocommerce_products', 'woocommerce_product_categories', 'woocommerce_price_filter'];

                foreach ($sidebars_widgets as $sidebar => $widgets) {
                    if (!is_array($widgets)) continue;
                    foreach ($widgets as $widget) {
                        if (strpos($widget, 'woocommerce') !== false) {
                            $has_wc_widgets = true;
                            break 2;
                        }
                    }
                }

                // If WooCommerce widgets are present, keep the scripts
                if ($has_wc_widgets) {
                    return;
                }

                // Dequeue styles
                foreach ($styles as $style) {
                    // Check if style is enqueued before dequeuing
                    if (wp_style_is($style, 'enqueued')) {
                        wp_dequeue_style($style);
                    }
                }

                // Dequeue scripts
                foreach ($scripts as $script) {
                    // Check if script is enqueued before dequeuing
                    if (wp_script_is($script, 'enqueued')) {
                        wp_dequeue_script($script);
                    }
                }
            }, 99);
        }

        /* Disable WooCommerce Cart Fragments */
        if ($this->settings()->performance_cart) {
            add_action('wp_enqueue_scripts',  function () {
                if (function_exists('is_woocommerce')) {
                    wp_dequeue_script('wc-cart-fragments');
                }
            }, 99);
        }

        /* Disable WooCommerce Widgets */
        if ($this->settings()->performance_widgets) {
            add_action('widgets_init', function () {
                unregister_widget('WC_Widget_Products');
                unregister_widget('WC_Widget_Product_Categories');
                unregister_widget('WC_Widget_Product_Tag_Cloud');
                unregister_widget('WC_Widget_Cart');
                unregister_widget('WC_Widget_Layered_Nav');
                unregister_widget('WC_Widget_Layered_Nav_Filters');
                unregister_widget('WC_Widget_Price_Filter');
                unregister_widget('WC_Widget_Product_Search');
                unregister_widget('WC_Widget_Recently_Viewed');
                unregister_widget('WC_Widget_Recent_Reviews');
                unregister_widget('WC_Widget_Top_Rated_Products');
                unregister_widget('WC_Widget_Rating_Filter');
            }, 99);
        }

        /*  Stripe scripts */
        if ($this->settings()->stripe_script) {
            add_filter('wc_stripe_hide_payment_request_on_product_page', '__return_true');
        }
    }

    private function init_performance_features()
    {
        if ($this->settings()->block_external_requests) {
            $this->init_external_request_blocking();
        }

        if ($this->settings()->disable_tracking) {
            $this->init_tracking_disable();
        }

        if ($this->settings()->optimize_meta_handling) {
            $this->init_meta_optimization();
        }

        // Add hooks for new advanced features
        add_action('init', [$this, 'init_advanced_features']);
    }

    public function block_external_requests($preempt, $parsed_args, $url)
    {
        if (empty($url)) {
            return $preempt;
        }

        $url_parts = parse_url($url);

        if (!isset($url_parts['host']) || !isset($url_parts['path'])) {
            return $preempt;
        }

        $check_url = trim($url_parts['host'] . $url_parts['path'], '/');

        if (isset($this->blocked_urls[$check_url])) {
            return [
                'headers' => [],
                'body' => $this->blocked_urls[$check_url],
                'response' => [
                    'code' => 200,
                    'message' => 'OK'
                ],
                'cookies' => [],
                'http_response' => null
            ];
        }

        return $preempt;
    }

    private function init_meta_optimization()
    {
        if (is_admin()) {
            // Remove unnecessary meta boxes
            add_action('admin_menu', function () {
                foreach (get_post_types('', 'names') as $post_type) {
                    remove_meta_box('postcustom', $post_type, 'normal');
                }
            }, 100);

            // Optimize meta queries
            add_filter('update_post_metadata', function ($check, $object_id, $meta_key, $meta_value, $prev_value) {
                // Skip processing if meta key starts with underscore (internal use)
                if (strpos($meta_key, '_') === 0) {
                    return $check;
                }

                // Cache the meta value to reduce database calls
                wp_cache_set('post_meta_' . $object_id . '_' . $meta_key, $meta_value, 'post_meta');

                return $check;
            }, 10, 5);

            // Optimize get_post_meta calls
            add_filter('get_post_metadata', function ($check, $object_id, $meta_key, $single) {
                // Try to get from cache first
                $cached = wp_cache_get('post_meta_' . $object_id . '_' . $meta_key, 'post_meta');
                if ($cached !== false) {
                    return $single ? $cached : array($cached);
                }

                return $check;
            }, 10, 4);
        }
    }

    private function init_tracking_disable()
    {
        // Disable tracking options
        foreach ($this->tracking_options as $option => $value) {
            if (get_option($option) !== $value) {
                update_option($option, $value);
            }
        }

        // Additional tracking-related filters
        // Only add if interface_suggestions is not enabled to avoid duplicate filters
        if (!$this->settings()->interface_suggestions) {
            add_filter('woocommerce_allow_marketplace_suggestions', '__return_false');
        }

        // Only add if core_user_experience is not enabled to avoid duplicate filters
        if (!$this->settings()->core_user_experience) {
            add_filter('woocommerce_admin_disabled', '__return_true');
        }

        add_filter('woocommerce_show_marketplace_suggestions', '__return_false');
    }

    private function init_external_request_blocking()
    {
        add_filter('pre_http_request', [$this, 'block_external_requests'], 100, 3);
        add_filter('woocommerce_helper_suppress_admin_notices', '__return_true');
        add_filter('woocommerce_marketplace_suggestions', '__return_empty_array');
    }

    public function init_advanced_features()
    {
        if ($this->settings()->calctotals) {
            add_filter('posts_request', [$this, 'remove_sql_calc_found_rows'], 10, 2);
            add_filter('found_posts', [$this, 'fake_found_posts'], 10, 2);
            add_filter('post_limits_request', [$this, 'maybe_fake_total_found_posts'], PHP_INT_MAX - 10, 2);
        }

        if ($this->settings()->optimisewoogroup) {
            add_filter('posts_clauses', [$this, 'optimize_group_by'], PHP_INT_MAX - 5, 2);
        }

        // Category dropdown optimization
        if ($this->settings()->toplevelcatsonly) {
            add_filter('get_terms_args', [$this, 'modify_category_dropdown'], 10, 2);
            add_filter('woocommerce_products_admin_list_table_filters', [$this, 'remove_product_category_filter'], 1);
        }

        // WooCommerce cleanup optimization
        if ($this->settings()->optimisewoodeleteoptions) {
            add_filter('query', [$this, 'optimize_woo_delete_options']);
        }

        // Remove custom meta dropdown
        if ($this->settings()->removecustommeta) {
            add_filter('postmeta_form_keys', '__return_empty_array');
        }

        // Cache order delivery date
        if ($this->settings()->cacheorderdeliverydate) {
            add_filter('query', [$this, 'cache_order_delivery_date']);
        }

        // Cache shortcodes
        if ($this->settings()->cacheshortcode_onsale) {
            $this->init_sale_products_cache();
        }

        if ($this->settings()->cacheshortcode_bestselling) {
            $this->init_bestselling_products_cache();
        }

        // AJAX attribute editing
        if ($this->settings()->ajaxattributeedit) {
            add_action('admin_enqueue_scripts', [$this, 'enqueue_attribute_scripts']);
            add_action('wp_ajax_search_product_attributes', [$this, 'ajax_search_attributes']);
        }

        // Fix WooCommerce onboarding
        if ($this->settings()->fixwoo_onboarding) {
            add_filter('query', [$this, 'fix_woo_onboarding_queries']);
        }

        // Term counting optimization
        if ($this->settings()->defertermcounting) {
            $this->init_term_counting_optimization();
        }

        // Post counts caching
        if ($this->settings()->cachepostcounts) {
            add_filter('wp_count_posts', [$this, 'cache_post_counts'], 10, 3);
        }

        // Action scheduler cleanup
        if ($this->settings()->action_scheduler) {
            add_filter('action_scheduler_retention_period', [$this, 'modify_action_scheduler_retention']);
            add_action('init', [$this, 'schedule_action_scheduler_cleanup']);
        }

        // Product attributes optimization
        if ($this->settings()->wpiperf_product_attributes_index_fix) {
            add_filter('woocommerce_product_get_attributes', [$this, 'optimize_product_attributes']);
        }

        // Remove AJAX variations calculation
        if ($this->settings()->removeajaxvariationscalc) {
            add_filter('woocommerce_ajax_variation_threshold', [$this, 'modify_variation_threshold'], 10, 2);
        }

        // Sort order optimization
        if ($this->settings()->sortorder) {
            add_filter('posts_orderby', [$this, 'optimize_sort_order'], 10, 2);
        }

        // SQL_CALC_FOUND_ROWS optimization
        if ($this->settings()->calctotals) {
            add_filter('posts_clauses', [$this, 'remove_sql_calc_found_rows'], 10, 2);
        }

        // Admin queries optimization
        if ($this->settings()->calctotals_admin && is_admin()) {
            add_filter('posts_clauses', [$this, 'remove_sql_calc_found_rows_admin'], 10, 2);
        }

        // EXISTS query optimization
        if ($this->settings()->changetoexists) {
            add_filter('posts_where', [$this, 'convert_joins_to_exists'], 10, 2);
        }

        // Group by optimization
        if ($this->settings()->optimisewoogroup) {
            add_filter('posts_clauses', [$this, 'optimize_group_by'], 10, 2);
        }

        // Private post check optimization
        if ($this->settings()->optimiseprivatecheck) {
            add_filter('posts_where', [$this, 'optimize_private_post_check'], 10, 2);
        }
    }

    public function remove_sql_calc_found_rows_admin($clauses, $query)
    {
        if (is_admin() && $query->is_main_query()) {
            $clauses['found_rows'] = '';
        }
        return $clauses;
    }

    public function optimize_sort_order($orderby, $query)
    {
        if (!is_admin() && $query->is_main_query() && is_woocommerce()) {
            // Cache the orderby results
            $cache_key = 'sort_order_' . md5($orderby);
            $cached = wp_cache_get($cache_key);

            if ($cached === false) {
                wp_cache_set($cache_key, $orderby, '', HOUR_IN_SECONDS);
                return $orderby;
            }

            return $cached;
        }

        return $orderby;
    }

    public function enqueue_attribute_scripts()
    {
        if (!is_admin()) return;

        // Enqueue jQuery and include inline script after
        wp_enqueue_script('jquery');
        wp_add_inline_script('jquery', $this->inline_attribute_script());
    }

    public function inline_attribute_script()
    {
        return <<<JS
            jQuery(document).ready(function() {
                jQuery(document).on('keypress', 'input.select2-search__field', function(e) {
                    const updateAttributeList = function() {
                        const row = jQuery(this).closest('tr');
                        const taxonomy = row.find('.attribute_name input').first().val();
                        if (!taxonomy) return;
    
                        jQuery.ajax({
                            url: ajaxurl,
                            type: "POST",
                            data: {
                                action: 'search_product_attributes',
                                security: ajax_object.ajax_nonce,
                                term: jQuery(this).val(),
                            },
                            context: row,
                            success: function(response) {
                                const selectBox = row.find('select.attribute_values');
                                selectBox.find('option:not(:selected)').remove();
    
                                response.forEach(function(item) {
                                    selectBox.append(new Option(item.label, item.id));
                                });
    
                                selectBox.trigger('change');
                            }
                        });
                    }.bind(this);
    
                    setTimeout(updateAttributeList, 10);
                });
            });
        JS;
    }

    public function ajax_search_attributes()
    {
        check_ajax_referer('search-attributes', 'security');

        $term = sanitize_text_field($_GET['term']);
        $attributes = wc_get_attribute_taxonomies();
        $results = array();

        foreach ($attributes as $attribute) {
            if (stripos($attribute->attribute_label, $term) !== false) {
                $results[] = array(
                    'id' => $attribute->attribute_id,
                    'label' => $attribute->attribute_label
                );
            }
        }

        wp_send_json($results);
    }

    public function cache_post_counts($counts, $type, $perm)
    {
        $cache_key = 'post_counts_' . md5($type . $perm);
        $cached = wp_cache_get($cache_key);

        if ($cached === false) {
            wp_cache_set($cache_key, $counts, '', HOUR_IN_SECONDS);
            return $counts;
        }

        return $cached;
    }

    public function optimize_product_attributes($attributes)
    {
        global $wpdb;

        foreach ($attributes as $key => $attribute) {
            $cache_key = 'product_attr_' . md5(serialize($attribute));
            $cached = wp_cache_get($cache_key);

            if ($cached === false) {
                wp_cache_set($cache_key, $attribute, '', HOUR_IN_SECONDS);
            } else {
                $attributes[$key] = $cached;
            }
        }

        return $attributes;
    }

    public function cache_order_delivery_date($query)
    {
        if (strpos($query, '_delivery_date') !== false) {
            global $wpdb;
            $cache_key = 'delivery_date_' . md5($query);
            $cached_result = wp_cache_get($cache_key);

            if ($cached_result === false) {
                $result = $wpdb->get_results($query);
                wp_cache_set($cache_key, $result, '', HOUR_IN_SECONDS);
                return $result;
            }

            return $cached_result;
        }
        return $query;
    }

    public function modify_variation_threshold($qty, $product)
    {
        if ($this->settings()->removeajaxvariationscalc) {
            return 1;
        }
        return $qty;
    }

    public function convert_joins_to_exists($where, $query)
    {
        if (!empty($query->get('wpintense_taxexists'))) {
            $where .= $query->get('wpintense_taxexists');
        }
        return $where;
    }

    private function change_tax_to_exists($tax)
    {
        global $wpdb;
        if (!in_array('relation', $tax)) {
            return $tax;
        }
        $sql = '';
        $originalrelation = $tax['relation'];
        $relation = '';

        foreach ($tax as $key => $taxarray) {
            if ($key === 'relation') continue;

            if (array_key_exists('relation', $taxarray)) {
                $subtax = $this->change_tax_to_exists($taxarray);
                $sql .= $relation . "(" . $subtax['sql'] . ")";
                $tax[$key] = $subtax['tax'];
                $relation = $originalrelation;
            } else if ($taxarray['field'] == 'term_taxonomy_id') {
                $op = $taxarray['operator'] === "NOT IN" ? " NOT EXISTS " : " EXISTS ";
                $sql .= $relation . $op . "(select * from " . $wpdb->term_relationships . " tr 
                        inner join " . $wpdb->term_taxonomy . " tt 
                        on tr.term_taxonomy_id = tt.term_taxonomy_id 
                        where tt.taxonomy = '" . $taxarray['taxonomy'] . "' 
                        and " . $wpdb->posts . ".ID = tr.object_id 
                        AND tr.term_taxonomy_id IN (" . implode(',', $taxarray['terms']) . "))";
                $relation = $originalrelation;
                unset($tax[$key]);
            }
        }

        if (!empty($sql)) {
            $sql = ' AND (' . $sql . ") ";
        }
        if (count($tax) == 1) $tax = array();
        return array('tax' => $tax, 'sql' => $sql);
    }

    public function fake_found_posts($found_posts, $query)
    {
        if ($query->get('spro_fake_total_found_posts')) {
            if (isset($query->query_vars['posts_per_page']) && isset($query->query_vars['paged'])) {
                $page = $query->query_vars['paged'] == 0 ? 1 : $query->query_vars['paged'];
                $expect_to_find = $query->query_vars['posts_per_page'] * $page;
                if ($expect_to_find === $found_posts) {
                    return 1000;
                }
            }
        }
        return $found_posts;
    }

    public function remove_sql_calc_found_rows($request, $query)
    {
        if (
            $query->get('spro_remove_sql_calc_found_rows') &&
            strncmp($request, 'SELECT SQL_CALC_FOUND_ROWS', 26) === 0
        ) {
            return 'SELECT ' . substr($request, 26);
        }
        return $request;
    }

    public function maybe_fake_total_found_posts($limits, $query)
    {
        if (!empty($limits) && $query->get('spro_remove_sql_calc_found_rows')) {
            $query->set('spro_fake_total_found_posts', true);
        }
        return $limits;
    }

    public function optimize_group_by($clauses, $query)
    {
        if (!$this->settings()->optimisewoogroup) {
            return $clauses;
        }

        global $wpdb;

        $only_posts_fields = ($clauses['fields'] == "{$wpdb->posts}.*" || $clauses['fields'] == "{$wpdb->posts}.ID");
        $has_joins = ($clauses['join'] != '');

        if ($only_posts_fields) {
            if (!$has_joins) {
                $clauses['distinct'] = '';
                $clauses['groupby'] = '';
            } else if ($clauses['groupby'] != '') {
                $clauses['distinct'] = 'DISTINCT';
                $clauses['groupby'] = '';
            }
        }

        return $clauses;
    }

    public function optimize_private_post_check($where)
    {
        global $wpdb;
        if (!is_admin() && $this->settings()->optimiseprivatecheck) {
            $where = str_replace(
                "AND {$wpdb->posts}.post_status = 'publish' OR {$wpdb->posts}.post_status = 'private'",
                "AND {$wpdb->posts}.post_status = 'publish'",
                $where
            );
        }
        return $where;
    }

    public function modify_action_scheduler_retention($default)
    {
        if ($this->settings()->action_scheduler) {
            return DAY_IN_SECONDS; // 1 day retention instead of default 30
        }
        return $default;
    }

    private function schedule_action_scheduler_cleanup()
    {
        if (!wp_next_scheduled('dragonizer_cleanup_actions')) {
            wp_schedule_event(strtotime('02:00'), 'daily', 'dragonizer_cleanup_actions');
        }

        add_action('dragonizer_cleanup_actions', function () {
            global $wpdb;
            $wpdb->query("DELETE FROM {$wpdb->prefix}actionscheduler_actions 
                          WHERE status IN ('complete', 'failed', 'canceled')");
            $wpdb->query("DELETE FROM {$wpdb->prefix}actionscheduler_logs");
        });
    }

    public function fix_woo_onboarding_queries($sql)
    {
        global $wpdb;
        if (substr($sql, 0, 25) == "SELECT post_status, COUNT") {
            $e = new \Exception;
            $trace = $e->getTraceAsString();
            if (
                strpos($trace, "is_new_install()") !== false
                || strpos($trace, "get_homepage_template()") !== false
                || strpos($trace, "has_products()") !== false
            ) {
                return "SELECT 'publish' as post_status, 1 as num_posts 
                    union SELECT 'future' as post_status, 1 as num_posts
                    union SELECT 'draft' as post_status, 1 as num_posts
                    union SELECT 'pending' as post_status, 1 as num_posts
                    union SELECT 'private' as post_status, 1 as num_posts
                    union SELECT 'trash' as post_status, 1 as num_posts";
            }
        }
        return $sql;
    }

    private function init_term_counting_optimization()
    {
        // Defer term counting on post insert/update
        add_filter('wp_insert_post_data', function ($data, $postarr) {
            wp_defer_term_counting(true);
            wp_defer_comment_counting(true);
            return $data;
        }, 99, 2);

        // Override term recount functions
        add_action('init', function () {
            global $wp_taxonomies;

            foreach ($wp_taxonomies as $taxonomy => &$tax_object) {
                // Skip certain taxonomies that should always be counted
                if (in_array($taxonomy, ['product_cat', 'product_tag'])) {
                    continue;
                }

                // Store original callback for later use if needed
                $tax_object->original_update_count_callback = $tax_object->update_count_callback;

                // Replace with stub function
                $tax_object->update_count_callback = [$this, 'recount_terms_stub'];
            }
        });

        // Avoid WooCommerce term recounts
        add_filter('woocommerce_product_recount_terms', '__return_false');

        // Schedule daily term recount
        if (!wp_next_scheduled('dr_daily_term_recount')) {
            wp_schedule_event(strtotime('02:00'), 'daily', 'dr_daily_term_recount');
        }

        // Add recount action hook
        add_action('dr_daily_term_recount', [$this, 'recount_all_terms']);

        // WP All Import compatibility
        add_action('pmxi_before_xml_import', function () {
            add_filter('woocommerce_product_recount_terms', '__return_false');
        });
    }

    public function recount_terms_stub($terms, $taxonomy)
    {
        return; // Do nothing - counting is deferred
    }

    public function recount_all_terms()
    {
        global $wp_taxonomies;

        foreach ($wp_taxonomies as $taxonomy => &$tax_object) {
            // Skip if no original callback exists
            if (!isset($tax_object->original_update_count_callback)) {
                continue;
            }

            // Get all terms for this taxonomy
            $terms = get_terms([
                'taxonomy' => $taxonomy,
                'hide_empty' => false,
                'fields' => 'ids',
            ]);

            if (is_wp_error($terms) || empty($terms)) {
                continue;
            }

            // Remove our filter temporarily
            remove_filter('woocommerce_product_recount_terms', '__return_false');

            // Use original callback to update counts
            wp_update_term_count_now($terms, $taxonomy);

            // Re-add our filter
            add_filter('woocommerce_product_recount_terms', '__return_false');

            // Clean up memory
            unset($terms);
            wp_cache_flush();
        }

        // Force garbage collection
        if (function_exists('gc_collect_cycles')) {
            gc_collect_cycles();
        }
    }

    private function init_sale_products_cache()
    {
        add_shortcode('sale_products_cached', function ($atts) {
            $cache_key = 'dr_sale_products_' . md5(serialize($atts));
            $cached = get_transient($cache_key);

            if ($cached === false) {
                $content = WC_Shortcodes::sale_products($atts);
                set_transient($cache_key, $content, 12 * HOUR_IN_SECONDS);
                return $content;
            }

            return $cached;
        });
    }

    private function init_bestselling_products_cache()
    {
        add_shortcode('bestselling_products_cached', function ($atts) {
            $cache_key = 'dr_bestselling_' . md5(serialize($atts));
            $cached = get_transient($cache_key);

            if ($cached === false) {
                $content = WC_Shortcodes::best_selling_products($atts);
                set_transient($cache_key, $content, 12 * HOUR_IN_SECONDS);
                return $content;
            }

            return $cached;
        });
    }

    public function modify_category_dropdown($args, $taxonomies)
    {
        if (!is_admin()) {
            return $args;
        }

        if (isset($args['taxonomy']) && $args['taxonomy'] == array('product_cat')) {
            if (empty($args['slug']) && $args['object_ids'] === null && empty($args['include'])) {
                $args['parent'] = 0;
            }
        }

        return $args;
    }

    public function remove_product_category_filter($filters)
    {
        if (isset($filters['product_category'])) {
            unset($filters['product_category']);
        }
        return $filters;
    }

    public function optimize_woo_delete_options($sql)
    {
        global $wpdb;
        if (strpos($sql, "DELETE FROM {$wpdb->options} WHERE option_name LIKE ") !== false) {
            if (strpos($sql, " OR ") !== false) {
                return $sql;
            }

            $like_statement = $this->extract_like_statement($sql);
            if (!empty($like_statement)) {
                $prefixes = ['product', 'orders', 'shipping'];
                $new_conditions = array();

                foreach ($prefixes as $prefix) {
                    $new_conditions[] = str_replace(
                        'option_name LIKE',
                        "option_name LIKE '{$prefix}",
                        $like_statement
                    );
                }

                return str_replace(
                    $like_statement,
                    implode(' OR ', $new_conditions),
                    $sql
                );
            }
        }
        return $sql;
    }

    private function extract_like_statement($query)
    {
        preg_match('/option_name LIKE [\'"].*?[\'"]/', $query, $matches);
        return isset($matches[0]) ? $matches[0] : '';
    }
}
