<?php

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

class Dragonizer_Optimizer
{
    private static $options;

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

        $default = [
            'welcome'                        => false,
            'widgets'                        => false,
            'rsd_link'                       => false,
            'wlwmanifest'                    => false,
            'feed_links'                     => false,
            'feed_generator'                 => false,
            'next_prev'                      => false,
            'shortlink'                      => false,
            'wp_generator'                   => false,
            'recentcomments'                 => false,
            'wp_resource_hints'              => false,
            'auto_linking'                   => false,
            'wc_generator'                   => false,
            'slider_generator'               => false,
            'vc_generator'                   => false,
            'yoast_comments'                 => false,
            'http_block'                     => false,
            'wp_updates'                     => false,
            'plugin_updates'                 => false,
            'theme_updates'                  => false,
            'automatic_updates'              => false,
            'page_updates'                   => false,
            'user_mail'                      => false,
            'mail_updates'                   => false,
            'disable_updates_notices'        => false,
            'disable_admin_notices'          => false,
            'disable_site_health'            => false,
            'disable_comments'               => false,
            'disable_gravatars'              => false,
            'disable_google_fonts'           => false,
            'disable_pingbacks'              => false,
            'disable_autosave'               => false,
            'emojicons'                      => false,
            'pdf_thumbnails'                 => false,
            'limit_revisions'                => false,
            'slow_heartbeat'                 => false,
            'comments_reply_feature'         => false,
            'empty_trash_soon'               => false,
            'capital_P_dangit'               => false,
            'disable_editor'                 => false,
            'medium_large_size'              => false,
            'comment_autolinks'              => false,
            'json_api'                       => false,
            'xmlrpc'                         => false,
            'performance_password'           => false,
            'jquery_migrate'                 => false,
            'oembed_scripts'                 => false,
            'wpcf7_refill'                   => false,
            'jpeg_quality'                   => false,
            'gutenberg_css'                  => false,
            'other_jetpack'                  => false,
            'other_skyVerge'                 => false,
            'other_elementor'                => false,
            'other_persian_woocommerce_feed' => false,
            'other_redux_dashboard_widget'   => false,
            'other_yith_dashboard_widget'    => false,
            'other_yoast_tweaks'             => false,
        ];

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

        if (is_admin()) {

            if ($this->settings()->welcome) {
                remove_action('welcome_panel', 'wp_welcome_panel');
            }

            if ($this->settings()->widgets) {
                add_action('wp_dashboard_setup', function () {
                    remove_meta_box('dashboard_browser_nag', 'dashboard', 'normal');
                    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
                    remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal');
                    remove_meta_box('dashboard_plugins', 'dashboard', 'normal');
                    remove_meta_box('dashboard_quick_press', 'dashboard', 'side');
                    remove_meta_box('dashboard_recent_drafts', 'dashboard', 'side');
                    remove_meta_box('dashboard_primary', 'dashboard', 'side');
                    remove_meta_box('dashboard_secondary', 'dashboard', 'normal');
                    remove_meta_box('wpseo-dashboard-overview', 'dashboard', 'normal');
                    remove_meta_box('dashboard_right_now', 'dashboard', 'normal');
                    remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
                    // remove_meta_box('dashboard_activity', 'dashboard', 'side');
                });
            }

            if (is_admin() && $this->settings()->http_block) {
                new DragonizerRequestBlocker();
            }

            if (is_admin() && $this->settings()->wp_updates) {
                remove_action('init', 'wp_version_check');
                add_filter('pre_option_update_core', '__return_null');
                add_filter('wp_auto_update_core', '__return_false');
                add_filter('auto_update_core', '__return_false');
                add_filter('allow_minor_auto_core_updates', '__return_false');
                add_filter('allow_major_auto_core_updates', '__return_false');
                add_filter('allow_dev_auto_core_updates', '__return_false');
                remove_action('wp_version_check', 'wp_version_check');
                wp_clear_scheduled_hook('wp_version_check');
            }

            if (is_admin() && $this->settings()->plugin_updates) {
                remove_all_filters('plugins_api');
                add_filter('site_transient_update_plugins', '__return_false');
                remove_action('load-update-core.php', 'wp_update_plugins');
                remove_action('load-plugins.php', 'wp_update_plugins');
                remove_action('load-update.php', 'wp_update_plugins');
                remove_action('admin_init', '_maybe_update_plugins');
                remove_action('wp_update_plugins', 'wp_update_plugins');
                wp_clear_scheduled_hook('wp_update_plugins');
            }

            if (is_admin() && $this->settings()->theme_updates) {
                add_filter('site_transient_update_themes', '__return_false');
                remove_action('load-update-core.php', 'wp_update_themes');
                remove_action('load-themes.php', 'wp_update_themes');
                remove_action('load-update.php', 'wp_update_themes');
                remove_action('wp_update_themes', 'wp_update_themes');
                remove_action('admin_init', '_maybe_update_themes');
                wp_clear_scheduled_hook('wp_update_themes');
            }

            if (is_admin() && $this->settings()->automatic_updates) {
                add_filter('automatic_updater_disabled', '__return_true');
                remove_action('admin_init', 'wp_maybe_auto_update');
                remove_action('admin_init', 'wp_auto_update_core');
                remove_action('wp_version_check', 'wp_version_check');
                remove_action('admin_init', '_maybe_update_core');
                remove_action('wp_maybe_auto_update', 'wp_maybe_auto_update');
                add_filter('auto_update_translation', '__return_false');
                add_filter('allow_minor_auto_core_updates', '__return_false');
                add_filter('allow_major_auto_core_updates', '__return_false');
                add_filter('allow_dev_auto_core_updates', '__return_false');
                add_filter('allow_minor_auto_core_updates', '__return_false');
                add_filter('allow_major_auto_core_updates', '__return_false');
                add_filter('allow_dev_auto_core_updates', '__return_false');
                add_filter('auto_update_core', '__return_false');
                add_filter('wp_auto_update_core', '__return_false');
                add_filter('auto_core_update_send_email', '__return_false');
                add_filter('send_core_update_notification_email', '__return_false');
                add_filter('automatic_updates_send_debug_email', '__return_false');
                add_filter('auto_update_plugin', '__return_false');
                add_filter('auto_update_theme', '__return_false');
                defined('WP_AUTO_UPDATE_CORE') || define('WP_AUTO_UPDATE_CORE', false);
            }

            if (is_admin() && $this->settings()->page_updates) {
                add_action('admin_menu', function () {
                    remove_submenu_page('index.php', 'update-core.php');
                });
            }

            if (is_admin() && $this->settings()->mail_updates) {
                add_filter('auto_core_update_send_email', '__return_false');
                add_filter('auto_core_update_send_email', '__return_false');
                add_filter('automatic_updates_send_debug_email ', '__return_false');
                add_filter('send_core_update_notification_email', '__return_false');
            }

            if (is_admin() && $this->settings()->disable_updates_notices) {
                remove_action('admin_notices', 'update_nag', 3);
                remove_action('network_admin_notices', 'update_nag', 3);
                remove_action('admin_notices', 'maintenance_nag');
                remove_action('network_admin_notices', 'maintenance_nag');
            }

            if (is_admin() && $this->settings()->disable_admin_notices) {
                add_action('admin_print_scripts', function () {
                    global $wp_filter;

                    // Get the current admin page
                    $screen = get_current_screen();

                    // Check if not on the Members plugin settings page
                    if ($screen && $screen->id !== 'edit-ywcmbs-membership') {
                        // Remove all universal admin notices
                        if (isset($wp_filter['all_admin_notices'])) {
                            unset($wp_filter['all_admin_notices']);
                        }
                    }

                    // Remove user-specific admin notices if in a user admin context
                    if (is_user_admin()) {
                        if (isset($wp_filter['user_admin_notices'])) {
                            unset($wp_filter['user_admin_notices']);
                        }
                    }
                    // Remove general admin notices if not in a user admin context
                    elseif (isset($wp_filter['admin_notices'])) {
                        unset($wp_filter['admin_notices']);
                    }
                });
            }

            if (is_admin() && $this->settings()->disable_pingbacks) {
                update_option('default_ping_status', 'close');
            } elseif (is_admin()) {
                update_option('default_ping_status', 'open');
            }

            if (is_admin() && $this->settings()->disable_autosave) {
                add_action('wp_print_scripts', function () {
                    wp_deregister_script('autosave');
                });
            }


            if ($this->settings()->pdf_thumbnails && is_admin()) {
                add_filter(
                    'fallback_intermediate_image_sizes',
                    function () {
                        return array();
                    }
                );
            }

            if ($this->settings()->limit_revisions && is_admin()) {
                if (defined('WP_POST_REVISIONS') && (WP_POST_REVISIONS !== false)) {
                    add_filter(
                        'wp_revisions_to_keep',
                        function ($num, $post) {
                            return 5;
                        },
                        10,
                        2
                    );
                }
            }

            if ($this->settings()->slow_heartbeat && is_admin()) {
                add_filter(
                    'heartbeat_settings',
                    function ($settings) {
                        $settings['interval'] = 60;
                        return $settings;
                    }
                );
            }

            if ($this->settings()->comments_reply_feature && is_admin()) {
                add_action(
                    'wp_print_scripts',
                    function () {
                        if (@is_singular() && (get_option('thread_comments') === 1) && comments_open() && have_comments()) {
                            wp_enqueue_script('comment-reply');
                        } else {
                            wp_dequeue_script('comment-reply');
                        }
                    },
                    100
                );
            }

            if ($this->settings()->other_jetpack) {
                add_filter('jetpack_just_in_time_msgs', '__return_false', 20);
                add_filter('jetpack_show_promotions', '__return_false', 20);
            }

            if ($this->settings()->other_skyVerge) {
                add_action('admin_menu', function () {
                    remove_menu_page('skyverge');
                }, 99);

                add_action('admin_enqueue_scripts', function () {
                    wp_dequeue_style('sv-wordpress-plugin-admin-menus');
                }, 20);
            }

            if ($this->settings()->other_elementor) {
                add_action('wp_dashboard_setup', function () {
                    remove_meta_box('e-dashboard-overview', 'dashboard', 'normal');
                }, 40);
            }

            if ($this->settings()->other_persian_woocommerce_feed) {
                add_action('wp_dashboard_setup', function () {
                    remove_meta_box('persian_woocommerce_feed', 'dashboard', 'normal');
                }, 40);
            }

            if ($this->settings()->other_redux_dashboard_widget) {
                add_action('wp_dashboard_setup', function () {
                    remove_meta_box('redux_dashboard_widget', 'dashboard', 'side');
                }, 40);
            }

            if ($this->settings()->other_yith_dashboard_widget) {
                add_action('wp_dashboard_setup', function () {
                    remove_meta_box('yith_dashboard_blog_news', 'dashboard', 'normal');
                    remove_meta_box('yith_dashboard_products_news', 'dashboard', 'normal');
                }, 40);
            }

            if ($this->settings()->other_yoast_tweaks) {

                if (defined('WPSEO_VERSION')) {

                    $wpseo_version = constant('WPSEO_VERSION');

                    // the wpseo_debug_markers() filter was added in WP SEO version 14.1
                    if (version_compare($wpseo_version, '14.1', '<')) {

                        add_action('get_header', function () {
                            ob_start(function ($o) {
                                return preg_replace('/\n?<.*?Yoast SEO plugin.*?>/mi', '', $o);
                            });
                        });
                        add_action('wp_head', function () {
                            ob_end_flush();
                        }, 999);
                    } else {

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

                    add_action('wp_dashboard_setup', function () {
                        remove_meta_box('wpseo-dashboard-overview', 'dashboard', 'side');
                    });

                    add_action('admin_bar_menu', function ($wp_admin_bar) {
                        $all_toolbar_nodes = $wp_admin_bar->get_nodes();
                        $nodes = array_keys($all_toolbar_nodes);
                        foreach ($nodes as $node) {
                            if (false !== strpos($node, 'wpseo')) {
                                $wp_admin_bar->remove_node($node);
                            }
                        }
                    }, 999);

                    add_action('admin_head', function () {
                        echo '<style type="text/css">
                            #sidebar-container.wpseo_content_cell {
                                display: none !important;
                            }
                    
                            #yoast-warnings #wpseo-upsell-notice,
                            #yoast-additional-keyphrase-collapsible-metabox,
                            .wpseo-keyword-synonyms,
                            .wpseo-multiple-keywords {
                                display: none !important;
                            }
                    
                            .yoast_premium_upsell,
                            .yoast_premium_upsell_admin_block,
                            #wpseo-local-seo-upsell,
                            div[class^="SocialUpsell__PremiumInfoText"],
                            .fBWRwy {
                                display: none;
                            }
                    
                            li#toplevel_page_wpseo_dashboard>ul>li:nth-child(6),
                            li#toplevel_page_wpseo_dashboard>ul>li:nth-child(7) {
                                display: none;
                            }
                    
                            body.edit-php .yoast-alert.notice.notice-warning,
                            body.edit-tags-php .yoast-alert.notice.notice-warning {
                                display: none;
                            }
                    
                            .wpseo-tab-video__panel.wpseo-tab-video__panel--text,
                            #tab-link-dashboard_dashboard__contact-support,
                            #tab-link-dashboard_general__contact-support,
                            #tab-link-dashboard_features__contact-support,
                            #tab-link-dashboard_knowledge-graph__contact-support,
                            #tab-link-dashboard_webmaster-tools__contact-support,
                            #tab-link-dashboard_security__contact-support,
                            #tab-link-metabox_metabox__contact-support,
                            .yoast-video-tutorial__description:first-child,
                            #yoast-helpscout-beacon {
                                display: none;
                            }
                    
                            .yoast-help-center__button {
                                display: none !important;
                            }
                    
                            body.edit-php .yoast-notification.notice.notice-warning.is-dismissible,
                            body[class*="taxonomy-"] .yoast-notification.notice.notice-warning.is-dismissible {
                                display: none;
                            }
                        </style>';
                    });
                }
            }
        }

        if (!is_admin()) {
            if ($this->settings()->rsd_link) {
                remove_action('wp_head', 'rsd_link');
            }

            if ($this->settings()->wlwmanifest) {
                remove_action('wp_head', 'wlwmanifest_link');
            }

            if ($this->settings()->feed_links) {
                remove_action('wp_head', 'feed_links', 2);
                remove_action('wp_head', 'feed_links_extra', 3);
            }

            if ($this->settings()->feed_generator) {
                remove_action('atom_head', 'the_generator');
                remove_action('comments_atom_head', 'the_generator');
                remove_action('rss_head', 'the_generator');
                remove_action('rss2_head', 'the_generator');
                remove_action('commentsrss2_head', 'the_generator');
                remove_action('rdf_header', 'the_generator');
                remove_action('opml_head', 'the_generator');
                remove_action('app_head', 'the_generator');
            }

            if ($this->settings()->next_prev) {
                remove_action('wp_head', 'adjacent_posts_rel_link', 10);
                remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10);
            }

            if ($this->settings()->shortlink) {
                remove_action('wp_head', 'wp_shortlink_wp_head', 10);
                remove_action('template_redirect', 'wp_shortlink_header', 11);
            }

            if ($this->settings()->wp_generator) {
                remove_action('wp_head', 'wp_generator');
                add_filter('the_generator', function () {
                    return '';
                });
            }

            if ($this->settings()->recentcomments) {
                add_filter('show_recent_comments_widget_style', '__return_false');
            }

            if ($this->settings()->wp_resource_hints) {
                add_action('init', function () {
                    remove_action('wp_head', 'wp_resource_hints', 2);
                });
            }

            if ($this->settings()->auto_linking) {
                remove_filter('comment_text', 'make_clickable', 9);
            }

            if ($this->settings()->wc_generator) {
                remove_action('wp_head', 'wc_generator_tag');
            }

            if ($this->settings()->slider_generator) {
                add_filter('revslider_meta_generator', '__return_empty_string');
            }

            if ($this->settings()->vc_generator) {
                add_action('wp_head', function () {
                    if (class_exists('Vc_Manager')) {
                        remove_action('wp_head', array(visual_composer(), 'addMetaData'));
                    }
                }, 1);
            }

            if ($this->settings()->yoast_comments) {
                add_filter('wpseo_debug_markers', '__return_false');
            }

            if ($this->settings()->comment_autolinks) {
                remove_filter('comment_text', 'make_clickable', 9);
            }

            if ($this->settings()->oembed_scripts) {
                // Since WordPress 4.4, oEmbed is installed and available by default. WordPress assumes you’ll want to easily embed media like tweets and YouTube videos so includes the scripts as standard. If you don’t need oEmbed, you can remove it.
                remove_action('rest_api_init', 'wp_oembed_register_route');
                add_filter('embed_oembed_discover', '__return_false');
                remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);
                remove_action('wp_head', 'wp_oembed_add_discovery_links');
                remove_action('wp_head', 'wp_oembed_add_host_js');
                add_filter('tiny_mce_plugins', function ($plugins) {
                    return array_diff($plugins, array('wpembed'));
                });
                add_filter('rewrite_rules_array', function ($rules) {
                    foreach ($rules as $rule => $rewrite) {
                        if (false !== strpos($rewrite, 'embed=true')) {
                            unset($rules[$rule]);
                        }
                    }
                    return $rules;
                });
            }

            if ($this->settings()->wpcf7_refill) {
                add_action(
                    'wp_enqueue_scripts',
                    function () {
                        wp_localize_script(
                            'contact-form-7',
                            'wpcf7',
                            array(
                                'apiSettings' => array(
                                    'root' => esc_url_raw(rest_url('contact-form-7/v1')),
                                    'namespace' => 'contact-form-7/v1',
                                ),
                                'jqueryUi' => 1,
                            )
                        );
                    },
                    10
                );
            }

            /* Disable Password Strength Meter */
            if ($this->settings()->performance_password) {
                add_action('wp_print_scripts', function () {
                    global $wp;

                    $wp_check = isset($wp->query_vars['lost-password']) || (isset($_GET['action']) && $_GET['action'] === 'lostpassword') || is_page('lost_password');

                    $wc_check = (class_exists('WooCommerce') && (is_account_page() || is_checkout()));

                    if (!$wp_check && !$wc_check) {
                        if (wp_script_is('zxcvbn-async', 'enqueued')) {
                            wp_dequeue_script('zxcvbn-async');
                        }

                        if (wp_script_is('password-strength-meter', 'enqueued')) {
                            wp_dequeue_script('password-strength-meter');
                        }

                        if (wp_script_is('wc-password-strength-meter', 'enqueued')) {
                            wp_dequeue_script('wc-password-strength-meter');
                        }
                    }
                }, 100);
            }

            if ($this->settings()->jquery_migrate) {
                add_filter('wp_default_scripts', function (&$scripts) {

                    $scripts->remove('jquery');
                    $scripts->add('jquery', false, array('jquery-core'), '1.12.4');
                });
            }

            if ($this->settings()->disable_google_fonts) {
                add_action('wp_enqueue_scripts', [$this, 'dragon_dequeueu_google_fonts'], 9999);
                add_action('wp_print_styles', [$this, 'dragon_dequeueu_google_fonts'], 9999);
                add_filter('elementor/frontend/print_google_fonts', '__return_false');
                add_filter('fl_builder_google_fonts_pre_enqueue', function ($fonts) {
                    return array();
                });
                add_filter('jupiterx_register_fonts', function ($fonts) {
                    return array();
                }, 99999);
                add_filter('hustle_load_google_fonts', '__return_false');
                add_filter('mailpoet_display_custom_fonts', '__return_false');
            }
        }

        if ($this->settings()->user_mail) {
            add_filter('wp_new_user_notification_email_admin', function ($wp_new_user_notification_email_admin, $user, $blogname) {
                add_filter('pre_wp_mail', '__return_false');
                return $wp_new_user_notification_email_admin;
            }, 10, 3);

            add_filter('wp_new_user_notification_email', function ($wp_new_user_notification_email, $user, $blogname) {
                if (has_filter('pre_wp_mail', '__return_false')) {
                    remove_filter('pre_wp_mail', '__return_false');
                }
                return $wp_new_user_notification_email;
            }, 10, 3);
        }

        if ($this->settings()->disable_site_health) {
            add_action('admin_menu', function () {
                remove_submenu_page('tools.php', 'site-health.php');
            });

            add_action('current_screen', function () {

                if (is_admin()) {

                    $screen = get_current_screen();
                    if ('site-health' == $screen->id) {
                        wp_redirect(admin_url());
                        exit;
                    }
                }
            });
        }

        if ($this->settings()->disable_comments) {

            add_action('admin_init', function () {
                $post_types = get_post_types();
                foreach ($post_types as $post_type) {
                    if (post_type_supports($post_type, 'comments')) {
                        remove_post_type_support($post_type, 'comments');
                        remove_post_type_support($post_type, 'trackbacks');
                    }
                }
            });

            add_action('admin_init', function () {
                remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
            });

            add_action('admin_init', function () {
                global $pagenow;
                if ($pagenow === 'edit-comments.php' || $pagenow === 'options-discussion.php') {
                    wp_safe_redirect(admin_url());
                    exit;
                }
            });

            add_action('admin_menu', function () {
                remove_menu_page('edit-comments.php');
            });

            add_action('admin_menu', function () {
                remove_submenu_page('options-general.php', 'options-discussion.php');
            });

            add_filter('comments_open', '__return_false', 20, 2);

            add_filter('pings_open', '__return_false', 20, 2);

            add_action('wp_before_admin_bar_render', function () {
                global $wp_admin_bar;
                $wp_admin_bar->remove_menu('comments');
            }, 0);

            add_filter('comment_form_default_fields', function ($fields) {
                if (isset($fields['url'])) {
                    unset($fields['url']);
                }
                return $fields;
            });

            add_action('admin_init', function () {
                if (is_admin_bar_showing()) {
                    remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
                }
            });
        }

        if ($this->settings()->disable_gravatars) {
            if (is_admin()) {
                update_option('show_avatars', false);
            }
            add_filter("get_avatar", function ($avatar, $id_or_email, $size, $default, $alt) {
                global $in_comment_loop;
                return $in_comment_loop ? '' : $avatar;
            }, 1, 5);
        } else {
            update_option('show_avatars', true);
        }

        if ($this->settings()->emojicons) {
            add_action('admin_init', function () {
                remove_action('admin_print_scripts', 'print_emoji_detection_script');
                remove_action('admin_print_styles', 'wp_enqueue_emoji_styles');
            });

            remove_action('wp_head', 'print_emoji_detection_script', 7);
            remove_action('embed_head', 'print_emoji_detection_script');
            remove_action('wp_print_styles', 'wp_enqueue_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) {
                return is_array($plugins) ? array_diff($plugins, ['wpemoji']) : [];
            });
            add_filter('emoji_svg_url', '__return_false');
            if (get_site_option('initial_db_version') >= 32453)
                remove_action('init', 'smilies_init', 5);
        }

        if ($this->settings()->empty_trash_soon) {
            if (!defined('EMPTY_TRASH_DAYS')) {
                define('EMPTY_TRASH_DAYS', 7);
            }
        }

        if ($this->settings()->capital_P_dangit) {
            foreach (array('the_content', 'the_title', 'wp_title', 'comment_text') as $dragonizer_filter) {
                $dragonizer_priority = has_filter($dragonizer_filter, 'capital_P_dangit');
                if (false !== $dragonizer_priority) {
                    remove_filter($dragonizer_filter, 'capital_P_dangit', $dragonizer_priority);
                }
            }
        }

        if ($this->settings()->disable_editor) {
            if (!defined('DISALLOW_FILE_EDIT')) {
                define('DISALLOW_FILE_EDIT', true);
            }
        }

        if ($this->settings()->medium_large_size) {
            add_image_size('medium_large', 0, 0);

            add_filter(
                'intermediate_image_sizes',
                function ($sizes) {
                    // If $sizes is an associative array, unset directly by key
                    if (isset($sizes['medium_large'])) {
                        unset($sizes['medium_large']);
                    }
                    return $sizes;
                },
                100
            );

            add_filter(
                'intermediate_image_sizes_advanced',
                function ($sizes) {
                    // If $sizes is an associative array, unset directly by key
                    if (isset($sizes['medium_large'])) {
                        unset($sizes['medium_large']);
                    }
                    return $sizes;
                },
                100
            );

            add_filter('pre_option_medium_large_size_w', '__return_zero');
            add_filter('pre_option_medium_large_size_h', '__return_zero');
        }

        if ($this->settings()->json_api) {

            add_action('init', function () {
                if (!is_admin()) {
                    remove_action('wp_head', 'rest_output_link_wp_head', 10);
                    remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);
                    remove_action('wp_head', 'wp_oembed_add_host_js');
                }
                if (!is_user_logged_in()) {
                    remove_action('rest_api_init', 'wp_oembed_register_route');
                    add_filter('embed_oembed_discover', '__return_false');
                    remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);
                    remove_action('template_redirect', 'rest_output_link_header', 11);
                    add_filter('json_enabled', '__return_false');
                    add_filter('json_jsonp_enabled', '__return_false');
                };

                // Require Authentication for All Requests.
                // https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests .
                add_filter(
                    'rest_authentication_errors',
                    function ($result) {
                        if (!empty($result)) {
                            return $result;
                        }
                        if (!is_user_logged_in()) {
                            return new \WP_Error(
                                'rest_disabled',
                                __('The REST API on this site has been disabled.', 'dragonizer') . ' dragonizer don\'t REST',
                                array(
                                    'status' => rest_authorization_required_code(),
                                )
                            );
                        }
                        return $result;
                    }
                );
            });
        }

        if ($this->settings()->xmlrpc) {

            add_filter('pings_open', '__return_false', 9999);

            // Remove REST API info from head and headers.
            add_filter('xmlrpc_enabled', '__return_false');

            // Hide xmlrpc.php in HTTP response headers.
            add_filter(
                'wp_headers',
                function ($headers) {
                    unset($headers['X-Pingback']);
                    return $headers;
                }
            );

            remove_action('xmlrpc_rsd_apis', 'rest_output_rsd');
            add_filter('xmlrpc_enabled', '__return_false');
            add_filter(
                'xmlrpc_methods',
                function ($methods) {
                    unset($methods['pingback.ping']);
                    return $methods;
                }
            );
        }

        if ($this->settings()->jpeg_quality) {
            add_filter(
                'jpeg_quality',
                function ($arg) {
                    return 72;
                }
            );
        }

        if ($this->settings()->gutenberg_css) {
            add_action(
                'wp_enqueue_scripts',
                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');
                    wp_dequeue_style('generate-fonts');
                    wp_dequeue_style('generate-widget-areas');
                    wp_dequeue_style('generateblocks');
                    wp_dequeue_style('generate-style');
                    wp_dequeue_style('generatepress-dynamic');
                },
                100
            );
        }
    }

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

    public function dragon_dequeueu_google_fonts()
    {
        // Remove fonts added by the Divi Extra theme
        remove_action('wp_footer', 'et_builder_print_font');

        // Dequeue Google Fonts loaded by Revolution Slider.
        remove_action('wp_footer', array('RevSliderFront', 'load_google_fonts'));

        // Dequeue the Jupiter theme font loader.
        wp_dequeue_script('mk-webfontloader');

        // Remove the aThemes resource hints.
        remove_action('wp_head', 'sydney_preconnect_google_fonts');
        remove_action('wp_head', 'botiga_preconnect_google_fonts');

        global $wp_styles;

        if (!($wp_styles instanceof WP_Styles)) {
            return;
        }

        $allowed = apply_filters('drgf_exceptions', ['olympus-google-fonts']);

        foreach ($wp_styles->registered as $style) {
            $handle = $style->handle;
            $src    = $style->src;

            if (strpos($src, 'fonts.googleapis') !== false) {
                if (!array_key_exists($handle, array_flip($allowed))) {
                    wp_dequeue_style($handle);
                }
            }
        }

        foreach ($wp_styles->registered as $style) {
            foreach ($style->deps as $dep) {
                if ((strpos($dep, 'google-fonts') !== false) || (strpos($dep, 'google_fonts') !== false) || (strpos($dep, 'googlefonts') !== false)) {
                    $wp_styles->remove($dep);
                    $wp_styles->add($dep, '');
                }
            }
        }
        remove_action('wp_head', 'hu_print_gfont_head_link', 2);
    }
}

class DragonizerRequestBlocker
{
    private $blocked_urls = [
        // Exact URL matches with expected responses
        'api.wordpress.org/core/browse-happy/1.1' => '[]',
        'api.wordpress.org/core/serve-happy/1.0' => '[]',
    ];

    private $blocked_domains = [
        'automatorplugin.com',
        'yithemes.com',
        'update.yithemes.com',
        'wp.com',
        'aceplugins.com',
        'rankmath.com',
        'googleapis.com',
        'fonts.googleapis.com',
        'reduxframework.com',
        'github.com',
        'yoast.com',
        'w.org',
        'yoa.st',
        'unyson.io',
        'siteorigin.com',
        'my.elementor.com',
        'elementor.com',
        'elementorfa.ir',
        'cdnjs.cloudflare.com',
        'cloudflare.com',
        'woocommerce.com',
        'packages.translationspress.com',
        'wpplugins-midlayer.tmm-technology.com',
        'stats.wp.com',
        'wpintense.com',
        'crocoblock.com',
        'translate.wordpress.com',
        'demo.phlox.pro',
        'plugin-planet.com',
        'dineshkarki.com.np',
        'api.appsero.com',
        // 'api.wordpress.org',
    ];

    public function __construct()
    {
        add_filter('pre_http_request', [$this, 'block_requests'], 1000, 3);
    }

    public function block_requests($preempt, $parsed_args, $url)
    {
        // 1. Check exact URL matches first (most efficient)
        $path = trim(parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH), '/');
        if (isset($this->blocked_urls[$path])) {
            return [
                'headers' => [],
                'body' => $this->blocked_urls[$path],
                'response' => ['code' => 200, 'message' => false],
                'cookies' => [],
                'http_response' => null
            ];
        }

        // 2. Check domain patterns
        $host = parse_url($url, PHP_URL_HOST);
        foreach ($this->blocked_domains as $domain) {
            if ($host && strpos($host, $domain) !== false) {
                return [
                    'headers' => [],
                    'body' => '',
                    'response' => ['code' => 200, 'message' => false],
                    'cookies' => [],
                    'http_response' => null
                ];
            }
        }

        return $preempt;
    }
}
