<?php

namespace AdminStarterPack;

if (!defined('WPINC')) { die; }

require_once ABSPATH . 'wp-includes/pluggable.php';

class AspPluginMisc {
    
    private $options = [];
    
    public function __construct() {
        
        $this->options = get_option('starterpack_options', []);
        
        if (!empty($this->options['starterpack_custom_html_lang'])) {
            add_filter('language_attributes', [$this, 'customLangAttr'], 99 ); // change html lang (front-end only)
        }
        
        if ( !is_admin() && !empty($this->options['starterpack_developer_branding'])) {
           // add_action('template_redirect', [$this, 'addDeveloperBranding'], 0 );
           //add_action('wp_loaded', [$this, 'addDeveloperBranding'] );
           $this->addDeveloperBranding();
        }
        
        if ($this->options['starterpack_minify_html'] || $this->options['starterpack_progresive_minify_html'] ) {
            $this->minifyHTML();
        }
        
        if ( $this->options['starterpack_openlinks_innewtab']) {
            add_filter('the_content', [$this, 'openLinksInNewTab'], PHP_INT_MAX);
        }
        
        if ( $this->options['starterpack_use_medialib_user_avatar']) {
            // Actions
    		add_action( 'personal_options', [$this, 'edit_user_profile'] );
    		add_action( 'personal_options_update', [$this, 'edit_user_profile_update'] );
    		add_action( 'edit_user_profile_update', [$this, 'edit_user_profile_update' ] );
    		// Filters
    		add_filter( 'get_avatar_data', [$this, 'get_avatar_data' ], 10, 2 );
    		add_filter( 'get_avatar', [$this, 'get_avatar' ], 10, 6 );
    		//add_filter( 'avatar_defaults', [$this, 'avatar_defaults'] );
        }
        
        if ( $this->options['use_free_img_cdn'] && $this->options['use_free_img_cdn_imagekit'] ) {
            $imagekit_file = STARTERPACK_CLASSES_DIR . 'parts/Imagekit.php';
            if ( file_exists( $imagekit_file ) ) {
                require_once( $imagekit_file );
                $this->ImagekitCDN = ImagekitCDN::getInstance();
            }
        }
        
        if ( $this->options['use_free_img_cdn'] && $this->options['use_free_img_cdn_photon'] ) {
            $photon_file = STARTERPACK_CLASSES_DIR . 'parts/Photon.php';
            if ( file_exists( $photon_file ) ) {
                require_once( $photon_file );
                $this->PhotonCDN = PhotonCDN::getInstance();
            }
        }
        
        if ( $this->options['starterpack_disable_img_scrset']) {
            // disable automatic wp compress
            add_filter('jpeg_quality', function($arg){return 100;});
            // disable scaled image size
            add_filter('big_image_size_threshold', '__return_false');
            // disable all images sizes
            add_filter('intermediate_image_sizes_advanced', [$this, 'disableImgSizes']);
            // disable scrset
            add_filter('wp_get_attachment_image_attributes', [$this, 'disableImgScrset']);
        }
        
        if ($this->options['starterpack_smtp_enable']) {
            add_action('phpmailer_init', [$this, 'useSmtpForEmail']);
            //add_action('admin_post_send_test_email', [$this, 'testSmtpForEmail']);
            //add_action('admin_post_nopriv_send_test_email', [$this, 'testSmtpForEmail']); // For non-authenticated users
           // $this->testSmtpForEmail();
        }
        
        // enable blocks in wc product editor
        if ($this->options['starterpack_enable_guten_woo']) {
            if (is_plugin_active('woocommerce/woocommerce.php')) {
                add_filter('use_block_editor_for_post_type', [$this, 'enable_gutenberg_for_product_editor'], 20, 2);
                add_action('add_meta_boxes', [$this, 'register_catalog_meta_boxes']);
                add_filter('woocommerce_register_post_type_product', [$this, 'reset_product_template']);
                
                //add_filter('woocommerce_taxonomy_args_product_cat', [$this, 'enable_taxonomy_rest']);
                //add_filter('woocommerce_taxonomy_args_product_tag', [$this, 'enable_taxonomy_rest']);
                // Remove already registered blocks to prevent conflicts
                //add_action('init', array($this, 'remove_already_registered_blocks'), 99);
            }
        }
        
        // stript product category
        if ($this->options['starterpack_strip_woo_product_category']) {
            if (is_plugin_active('woocommerce/woocommerce.php')) {
                add_filter('term_link', [$this, 'filter_term_links'], 10, 3);
        		add_filter('request', [$this, 'filter_query'], 999);
        		//add_filter('request', [$this, 'filter_query_s']);
        		
            }
        }
        
    }
    
    public function filter_term_links($termlink, $term, $taxonomy) {
	    if ($taxonomy === 'product_cat') {
	        $wc_options = get_option('woocommerce_permalinks');
	
	        if (is_array($wc_options) && isset($wc_options['category_base'])) {
	            $base = $wc_options['category_base'];
	            $termlink = str_replace("/{$base}/", "/", $termlink);
	        }
	    } 
	
	    return $termlink;
	    
	}
	
	
	public function filter_query($query_vars) {
		global $wpdb;

		if (!empty($query_vars['pagename'])
			|| !empty($query_vars['category_name'])
			|| !empty($query_vars['name'])
			|| !empty($query_vars['attachment'])) {

			$slug = !empty($query_vars['pagename']) ? $query_vars['pagename'] : (!empty($query_vars['name']) ? $query_vars['name'] : (!empty($query_vars['category_name']) ? $query_vars['category_name'] : $query_vars['attachment']));
            
			$term_exists = $wpdb->get_var($wpdb->prepare("SELECT t.term_id
				FROM $wpdb->terms t
				LEFT JOIN $wpdb->term_taxonomy tt
				ON tt.term_id = t.term_id
				WHERE tt.taxonomy = 'product_cat'
				AND t.slug = %s", [$slug]
			));

			if ($term_exists) {

				$old_vars = $query_vars;
				$query_vars = ['product_cat' => $slug];

				if (!empty($old_vars['paged']) || !empty($old_vars['page'])) {
					$query_vars['paged'] = !empty($old_vars['paged']) ? $old_vars['paged'] : $old_vars['page'];
				}

				if (!empty($old_vars['orderby'])) {
					$query_vars['orderby'] = $old_vars['orderby'];
				}

				if (!empty($old_vars['order'])) {
					$query_vars['order'] = $old_vars['order'];
				}
			}
		}

		return $query_vars;
	}
	
	public function filter_query_s($query_vars) {
    global $wpdb;

    if (!empty($query_vars['pagename'])
        || !empty($query_vars['category_name'])
        || !empty($query_vars['name'])
        || !empty($query_vars['attachment'])) {

        $slug = !empty($query_vars['pagename']) ? $query_vars['pagename'] : (!empty($query_vars['name']) ? $query_vars['name'] : (!empty($query_vars['category_name']) ? $query_vars['category_name'] : $query_vars['attachment']));

        $term_exists = $wpdb->get_var($wpdb->prepare("SELECT t.term_id
            FROM $wpdb->terms t
            LEFT JOIN $wpdb->term_taxonomy tt
            ON tt.term_id = t.term_id
            WHERE tt.taxonomy = 'product_cat'
            AND t.slug = %s", [$slug]
        ));

        if ($term_exists) {
            $old_vars = $query_vars;
            $query_vars = ['product_cat' => $slug];

            if (!empty($old_vars['paged']) || !empty($old_vars['page'])) {
                $query_vars['paged'] = !empty($old_vars['paged']) ? $old_vars['paged'] : $old_vars['page'];
            }

            if (!empty($old_vars['orderby'])) {
                $query_vars['orderby'] = $old_vars['orderby'];
            }

            if (!empty($old_vars['order'])) {
                $query_vars['order'] = $old_vars['order'];
            }

            // Remove the '/product/' base from the URL
            $query_vars['name'] = $slug;
            unset($query_vars['pagename']);
            unset($query_vars['category_name']);
            unset($query_vars['attachment']);
        }
    }

    return $query_vars;
}

    
    public function enable_taxonomy_rest( $args ) {
        $args['show_in_rest'] = true;
        return $args;
    }
    
    public function enable_gutenberg_for_product_editor($use_block_editor, $post_type) {
        if ($post_type === 'product') {
            return true;
        }
        return $use_block_editor;
    }

    public function register_catalog_meta_boxes() {
        global $current_screen;

        if (method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor()) {
            if (!function_exists('register_block_type')) {
                return;
            }

            // Register the blocks if they are not already registered
            if (!isset($GLOBALS['registered_blocks']['core/paragraph'])) {
                register_block_type('core/paragraph');
            }

            if (!isset($GLOBALS['registered_blocks']['core/image'])) {
                register_block_type('core/image');
            }

            if (!isset($GLOBALS['registered_blocks']['core/heading'])) {
                register_block_type('core/heading');
            }

            if (!isset($GLOBALS['registered_blocks']['core/list'])) {
                register_block_type('core/list');
            }

            if (!isset($GLOBALS['registered_blocks']['core/list-item'])) {
                register_block_type('core/list-item');
            }

            if (!isset($GLOBALS['registered_blocks']['core/quote'])) {
                register_block_type('core/quote');
            }

            if (!isset($GLOBALS['registered_blocks']['core/video'])) {
                register_block_type('core/video');
            }

            add_meta_box(
                'catalog-visibility',
                __('Catalog visibility', 'blocks-product-editor-for-woocommerce'),
                array($this, 'product_data_visibility'),
                'product',
                'side'
            );
        }
    }

    public function product_data_visibility($post) {
        $thepostid = $post->ID;
        $product_object = ($thepostid ? wc_get_product($thepostid) : new WC_Product());
        $current_visibility = $product_object->get_catalog_visibility();
        $current_featured = wc_bool_to_string($product_object->get_featured());
        $visibility_options = wc_get_product_visibility_options();
        ?>

        <div class="misc-pub-section" id="catalog-visibility">
            <?php echo esc_html__('Catalog visibility:', 'woocommerce'); ?>

            <strong id="catalog-visibility-display">
                <?php
                echo (isset($visibility_options[$current_visibility]) ? esc_html($visibility_options[$current_visibility]) : esc_html($current_visibility));

                if ('yes' === $current_featured) {
                    echo ', ' . esc_html__('Featured', 'woocommerce');
                }
                ?>
            </strong>

            <a href="#catalog-visibility" class="edit-catalog-visibility hide-if-no-js">
                <?php esc_html_e('Edit', 'woocommerce'); ?>
            </a>

            <div id="catalog-visibility-select" class="hide-if-js">
                <input type="hidden" name="current_visibility" id="current_visibility" value="<?php echo esc_attr($current_visibility); ?>" />
                <input type="hidden" name="current_featured" id="current_featured" value="<?php echo esc_attr($current_featured); ?>" />

                <?php
                echo '<p>' . esc_html__('This setting determines which shop pages products will be listed on.', 'woocommerce') . '</p>';

                foreach ($visibility_options as $name => $label) {
                    echo '<input type="radio" name="_visibility" id="_visibility_' . esc_attr($name) . '" value="' . esc_attr($name) . '" ' . checked($current_visibility, $name, false) . ' data-label="' . esc_attr($label) . '" /> <label for="_visibility_' . esc_attr($name) . '" class="selectit">' . esc_html($label) . '</label><br />';
                }

                echo '<br /><input type="checkbox" name="_featured" id="_featured" ' . checked($current_featured, 'yes', false) . ' /> <label for="_featured">' . esc_html__('This is a featured product', 'woocommerce') . '</label><br />';
                ?>

                <p>
                    <a href="#catalog-visibility" class="save-post-visibility hide-if-no-js button">
                        <?php esc_html_e('OK', 'woocommerce'); ?>
                    </a>
                    <a href="#catalog-visibility" class="cancel-post-visibility hide-if-no-js">
                        <?php esc_html_e('Cancel', 'woocommerce'); ?>
                    </a>
                </p>
            </div>
        </div>

        <?php
    }

    public function reset_product_template($post_type_args) {
        if (array_key_exists('template', $post_type_args)) {
            unset($post_type_args['template']);
        }
        return $post_type_args;
    }
    
    // Helper method to check if a block is registered
    private function is_block_registered($block_name) {
        global $wp_version;

        if (version_compare($wp_version, '5.5', '<')) {
            return function_exists('get_block_types') && array_key_exists($block_name, get_block_types());
        } else {
            return function_exists('wp_registered_block_type') && wp_registered_block_type($block_name);
        }
    }

    public function useSmtpForEmail($phpmailer) {
        // Retrieve SMTP settings from options
        $host = $this->options['starterpack_smtp_host'];
        $port = $this->options['starterpack_smtp_port'];
        $security = $this->options['starterpack_smtp_security'];
        $username = $this->options['starterpack_smtp_username'];
        $password = $this->options['starterpack_smtp_password'];
        $from_email = $this->options['starterpack_smtp_from_email'];
        $from_name = $this->options['starterpack_smtp_from_name'];

        // Check if SMTP settings are defined
        if ($host && $port && $username && $password && $from_email && $from_name) {
            // Set the mailer to use SMTP
            $phpmailer->isSMTP();

            // Set the SMTP host, port, and security
            $phpmailer->Host = $host;
            $phpmailer->Port = $port;
            $phpmailer->SMTPSecure = $security;

            // Enable SMTP authentication
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = $username;
            $phpmailer->Password = $password;

            // Set the 'From' email and name
            $phpmailer->From = $from_email;
            $phpmailer->FromName = $from_name;
        }
    }

    public function testSmtpForEmail() {
        if (isset($_POST['send_test_email'])) {
            $test_email = sanitize_email($this->options['starterpack_smtp_test_email']);

            if (!empty($test_email)) {
                $headers = array('Content-Type: text/html; charset=UTF-8');
                $test_email = sanitize_email($this->options['starterpack_smtp_test_email']);
    
                if (!empty($test_email)) {
                    $subject = 'Test SMTP Email';
                    $body = 'This is a test email sent from your website.';
    
                    $sent = wp_mail($test_email, $subject, $body, $headers);
    
                    if ($sent) {
                        starterpack_Queue('Email sent.');
                        wp_redirect(starterpack_instance()->admin_url());
                        exit;
                    } else {
                        starterpack_Queue('Something\'s wrong. We can not send email.');
                        wp_redirect(starterpack_instance()->admin_url());
                        exit;
                    }
                }
            }
        }
    }
    
    public function disableImgScrset($attr) {
        unset($attr['srcset']);
        return $attr;
    }
    
    public function disableImgSizes($sizes) {
        /*
        unset($sizes['thumbnail']);    // disable thumbnail size
    	unset($sizes['medium']);       // disable medium size
    	unset($sizes['large']);        // disable large size
    	unset($sizes['medium_large']); // disable medium-large size
    	unset($sizes['1536x1536']);    // disable 2x medium-large size
    	unset($sizes['2048x2048']);    // disable 2x large size
    	 
    	// Add the full-size image size
        $sizes['full'] = __('Full Size');
        */
        
        if (!$sizes) {
            return $sizes;
        }
    
        $allowed_sizes = array('full'); // Initialize with 'full' size
    
        // Check if WooCommerce is active
        if (is_plugin_active('woocommerce/woocommerce.php')) {
            // Add WooCommerce registered image sizes
            $woocommerce_sizes = array_keys(apply_filters('woocommerce_get_image_sizes', array()));
            $allowed_sizes = array_merge($allowed_sizes, $woocommerce_sizes);
    
            // Define unwanted image sizes from WooCommerce
            $unwanted_sizes = array('450x450', '600x400');
    
            // Remove unwanted sizes from the allowed sizes
            foreach ($unwanted_sizes as $unwanted_size) {
                if (($key = array_search($unwanted_size, $allowed_sizes)) !== false) {
                    unset($allowed_sizes[$key]);
                }
            }
        }
    
        // Unset all other image sizes
        foreach ($sizes as $size => $value) {
            if (!in_array($size, $allowed_sizes)) {
                unset($sizes[$size]);
            }
        }
    
        return $sizes;
        
    }
    
    
    // exclude
    private function is_exclude_file() {
        $request_uri = $_SERVER['REQUEST_URI'];
        $file_extension = pathinfo($request_uri, PATHINFO_EXTENSION);
    
        return in_array($file_extension, array('txt', 'xml'));
    }
    
    /* 
     * Front-end
     */
    
    public function customLangAttr($lang) {
        
        $newLang = $this->options['starterpack_custom_html_lang'];
		
		if( !empty($newLang) ){
			return 'lang="'.$newLang.'" ';
		} else {
		    return $lang;
		}
        
    }
    
    public function addDeveloperBranding() {
        
        if (is_admin() || is_user_logged_in() || $this->is_exclude_file()) {
            return;
        }
        
        ob_start([$this, 'developerBranding']);
    }
    
    public function developerBranding($buffer) {
        $before_doctype = '<!-- ' . esc_html($this->options['starterpack_developer_branding']) . ' -->';
        //$after_html_tag = '<!-- ' . esc_html($this->options['starterpack_developer_branding']) . ' -->';

        //return $before_doctype . $buffer . $after_html_tag;
        return $before_doctype . $buffer ;
    }
    
    public function minifyHTML() {
        
        if (is_admin() || is_user_logged_in() || $this->is_exclude_file()) {
            return;
        }
        
        ob_start([$this, 'minify_html']);
    }
    
    private function minify_html($html) {
        
        $newMinifyHtml = preg_replace_callback('#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function($matches) {
            return '<' . $matches[1] . preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>';
        }, str_replace("\r", "", $html));

        // Targeting inline styles: execute with the minify_css function
        if(strpos($newMinifyHtml, ' style=') !== false) {
            $newMinifyHtml = preg_replace_callback('#<([^<]+?)\s+style=([\'"])(.*?)\2(?=[\/\s>])#s', function($matches) {
                return '<' . $matches[1] . ' style=' . $matches[2] . $this->minify_css($matches[3]) . $matches[2];
            }, $newMinifyHtml);
        }
        
        if(strpos($newMinifyHtml, '</style>') !== false) {
            $newMinifyHtml = preg_replace_callback('#<style(.*?)>(.*?)</style>#is', function($matches) {
                return '<style' . $matches[1] . '>' . $this->minify_css($matches[2]) . '</style>';
            }, $newMinifyHtml);
        }
        
        // Targeting inline script: execute with the minify_js function
        if(strpos($newMinifyHtml, '</script>') !== false) {
            $newMinifyHtml = preg_replace_callback('#<script(.*?)>(.*?)</script>#is', function($matches) {
                return '<script' . $matches[1] . '>' . $this->minify_js($matches[2]) . '</script>';
            }, $newMinifyHtml);
        }
        
        
        if ($this->options['starterpack_minify_html'] && !$this->options['starterpack_progresive_minify_html']) {
            $newMinifyHtml = preg_replace(
                ['/\s\s+/u'],
                [''],
                $newMinifyHtml);
        } elseif ($this->options['starterpack_progresive_minify_html']) {
            $newMinifyHtml = preg_replace(
                ['/\>[^\S ]+/s',
            	'/[^\S ]+\</s',
            	'/\t/'],
    		    ['>', '<', ' ',''], $newMinifyHtml);
        }

        return $newMinifyHtml;
    }
    
    private function minify_css($newMinifyHtml) {
        
        return preg_replace([
            // Remove comment(s)
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
            // Remove unused white-space(s)
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
            // Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
            '#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
            // Replace `:0 0 0 0` with `:0`
            '#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
            // Replace `background-position:0` with `background-position:0 0`
            '#(background-position):0(?=[;\}])#si',
            // Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
            '#(?<=[\s:,\-])0+\.(\d+)#s',
            // Minify string value
            '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
            '#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
            // Minify HEX color code
            '#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
            // Replace `(border|outline):none` with `(border|outline):0`
            '#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
            // Remove empty selector(s)
            '#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s'
        ],
        [
            '$1',
            '$1$2$3$4$5$6$7',
            '$1',
            ':0',
            '$1:0 0',
            '.$1',
            '$1$3',
            '$1$2$4$5',
            '$1$2$3',
            '$1:0',
            '$1$2'
        ],
    	$newMinifyHtml);

    }
    
    private function minify_js($newMinifyHtml) {
        return preg_replace([
            // Remove comment(s)
            // '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', // remove comments alt
            '#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
            // Remove white-space(s) outside the string and regex
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
            // Remove the last semicolon
            '#;+\}#',
            // Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
            '#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
            // --ibid. From `foo['bar']` to `foo.bar`
            '#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i'
        ],
        [
            '$1',
            '$1$2',
            '}',
            '$1$3',
            '$1.$3'
        ],
    	$newMinifyHtml);
    }
    
    public function disableEmojis() {
        
        call_user_func(
    		'remove_action',
    		'wp_head',
    		'print_emoji_detection_script',
    		7
    	);
    
    	call_user_func(
    		'remove_action',
    		'wp_print_styles',
    		'print_emoji_styles'
    	);
    
    	call_user_func(
    		'remove_action',
    		'admin_print_scripts',
    		'print_emoji_detection_script'
    	);
    
    	call_user_func(
    		'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, array('wpemoji'));
    		} else {
    			return array();
    		}
    	});
    
    	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/2/svg/');
    			$urls = array_diff($urls, array($emoji_svg_url));
    		}
    
    		return $urls;
    	}, 10, 2);
    	
    }
    
    public function openLinksInNewTab($content) {
        $pattern = '/<a(.*?)href=["\'](https?:\/\/(?!' . $_SERVER['HTTP_HOST'] . ')[^\s"\'<>]+)["\'](.*?)>/i';
        $replacement = '<a$1href=$2$3';
        $content = preg_replace_callback($pattern, function($matches) {
            $link = $matches[0];
            if (strpos($link, 'target="_blank"') === false) {
                $link = str_replace('<a', '<a rel="noopener noreferrer" target="_blank"', $link);
            }
            return $link;
        }, $content);
        return $content;
    }
    
    /*
     * avatar 
     */
     
    /**
	 * Discussion settings option
	 */
	public function avatar_settings_field( $args ) {
	    $options = get_option( 'starterpack_user_avatars_caps' );
	    ?>
	    <label for="starterpack_user_avatars_caps">
	        <input type="checkbox" name="starterpack_user_avatars_caps" id="starterpack_user_avatars_caps" value="1" <?php checked( $options['starterpack_user_avatars_caps'], 1 ); ?>/>
	        <?php esc_html_e( 'Only allow users with file upload capabilities to upload local avatars (Authors and above)', 'starterpack' ); ?>
	    </label>
	    <?php
	}
	
	public function sanitize_options( $input ) {
	    $new_input = array();
	    $new_input['starterpack_user_avatars_caps'] = isset( $input['starterpack_user_avatars_caps'] ) ? 1 : 0;
	    // Add code to handle the avatar image option if available
	    $new_input['starterpack_user_avatar'] = isset( $input['starterpack-user-avatar'] ) ? esc_url_raw( $input['starterpack-user-avatar'] ) : '';
	    return $new_input;
	}
	
	public function get_avatar_data( $args, $id_or_email ) {
    	if ( ! empty( $args['force_default'] ) ) {
    		return $args;
    	}
    
    	global $wpdb;
    
    	$return_args = $args;
    
    	if ( is_numeric( $id_or_email ) && 0 < $id_or_email ) {
    		$user_id = (int) $id_or_email;
    	} elseif ( is_object( $id_or_email ) && isset( $id_or_email->user_id ) && 0 < $id_or_email->user_id ) {
    		$user_id = $id_or_email->user_id;
    	} elseif ( is_object( $id_or_email ) && isset( $id_or_email->ID ) && isset( $id_or_email->user_login ) && 0 < $id_or_email->ID ) {
    		$user_id = $id_or_email->ID;
    	} elseif ( is_string( $id_or_email ) && false !== strpos( $id_or_email, '@' ) ) {
    		$_user = get_user_by( 'email', $id_or_email );
    
    		if ( ! empty( $_user ) ) {
    			$user_id = $_user->ID;
    		}
    	}
    
    	if ( empty( $user_id ) ) {
    		return $args;
    	}
    
    	$user_avatar_url = null;
    	$local_avatars = get_user_meta( $user_id, 'starterpack_user_avatar', true );
    
    	if ( empty( $local_avatars ) || empty( $local_avatars['full'] ) ) {
    		return $args;
    	}
    
    	$size = (int) $args['size'];
    
    	if ( empty( $local_avatars[ $size ] ) ) {
    		$local_avatars[ $size ] = $local_avatars['full'];
    		update_user_meta( $user_id, 'starterpack_user_avatar', $local_avatars );
    	} elseif ( substr( $local_avatars[ $size ], 0, 4 ) != 'http' ) {
    		$local_avatars[ $size ] = home_url( $local_avatars[ $size ] );
    	}
    
    	if ( is_ssl() ) {
    		$local_avatars[ $size ] = str_replace( 'http:', 'https:', $local_avatars[ $size ] );
    	}
    
    	$user_avatar_url = $local_avatars[ $size ];
    
    	if ( $user_avatar_url ) {
    		$return_args['url'] = $user_avatar_url;
    		$return_args['found_avatar'] = true;
    	}
    
    	return $return_args;
    }
	
	public function get_avatar( $avatar, $id_or_email, $size = 96, $default = '', $alt = false, $args = array() ) {
	    return apply_filters( 'starterpack_user_avatar', $avatar, $id_or_email );
	}
	
	public function edit_user_profile( $profileuser ) {
	    ?>
	    <style>
	        #your-profile .form-table:first-of-type,
	        .user-profile-picture,
	        .super-hide {
	            display: none;
	        }
	        .user-avatar-preview {
	            min-width: 96px;
	        }
	        .user-avatar-preview img {
	            width: 96px;
                height: 96px;
                object-fit: cover;
	        }
	        .avatar-buttons {
	            display:flex;
	            column-gap: 5.5px;
	        }
	        .avatar-buttons input.button-primary,
	        .avatar-buttons a.button {
	            border: 0;
	            padding: 3px 11px;
                font-size: 12px;
                border-radius: 4px;
                overflow: hidden;
                box-shadow: 0px 0.5px 2px rgb(0 0 0 / 15%)!important;
	        }
	        #wpcontent .avatar-buttons input.button-primary:not(:hover) {
	            background: linear-gradient(183deg, #f7f7f7, transparent);
                color: #626262;
	        }
	        .form-table td.avatar-buttons-container {
	            display: flex;
                max-width: 90%;
                min-height: 96px;
                align-items: flex-end;
                flex-wrap: wrap;
	        }
	        .form-table.avatar {
	            margin-top: 30px;
	            margin-bottom: 20px;
	            font-family: verdana;
	        }
	        .form-table.avatar tr {
	            display: flex;
	        }
	        .form-table th.avatar-label,
	        .form-table.avatar tr td {
	            margin-bottom: 0;
                padding: 0 10px;
	        }
	        .form-table th.avatar-label {
	            padding-left: 0;
	            font-size: 13px;
	        }
	        .form-table.avatar tr td {
	            height: 100%;
	        }
	    </style>
	    <h2 class="super-hide"><?php _e( 'Avatar', 'starterpack' ); ?></h2>
	    <table class="form-table avatar">
            <tr>
                <th class="avatar-label"><label for="starterpack-user-avatar"><?php esc_html_e( 'User Avatar', 'starterpack' ); ?></label></th>
                <td class="change-avatar-container">
                    <?php
                    echo '<div class="user-avatar-preview">';
                    echo get_avatar( $profileuser->ID );
                    echo '</div>';
                    ?>
                </td>
                <td class="avatar-buttons-container">
                    <?php
                    $options = get_option( 'starterpack_user_avatars_caps' );
                    if ( empty( $options['starterpack_user_avatars_caps'] ) || current_user_can( 'upload_files' ) ) {
                        wp_nonce_field( 'starterpack_user_avatar_nonce', '_starterpack_user_avatar_nonce', false );
                        echo '<input type="hidden" name="starterpack-user-avatar" id="starterpack-local-avatar" />';
                        echo '<div class="avatar-buttons">';
                        echo '<a href="#" class="button button-primary" id="choose-avatar">' . esc_html__( 'Change Avatar', 'starterpack' ) . '</a>';
                        
                        // add extra update button
                        submit_button( __( 'Quick Update!', 'starterpack' ), 'primary', 'submit', false, array( 'id' => 'submit-top' ) );
                        
                        // Check if the user has a custom avatar
                        $avatar_data = get_user_meta( $profileuser->ID, 'starterpack_user_avatar', true );
                        if ( ! empty( $avatar_data ) && ! empty( $avatar_data['full'] ) ) {
                            echo '<a href="#" class="button" id="remove-avatar">' . esc_html__( 'Remove Avatar', 'starterpack' ) . '</a>';
                        }
                        
                        echo '</div>';
                        /*
                        if ( empty( $profileuser->starterpack_user_avatar ) ) {
                            echo '<p class="description">' . esc_html__( 'No local avatar is set.', 'starterpack' ) . '</p>';
                        }
                        */
                        
                    } else {
                        if ( empty( $profileuser->starterpack_user_avatar ) ) {
                            echo '<p class="description">' . esc_html__( 'No local avatar is set. Set up your avatar at Gravatar.com.', 'starterpack' ) . '</p>';
                        } else {
                            echo '<p class="description">' . esc_html__( 'You do not have media management permissions. To change your local avatar, contact the site administrator.', 'starterpack' ) . '</p>';
                        }
                    }
                    ?>
                </td>
            </tr>
        </table>
        <script>
            jQuery(document).ready(function($){
                var frame;
    
                function updateAvatarPreview(attachment) {
                    $('.user-avatar-preview').html('');
                    $('#starterpack-local-avatar').val('');
    
                    if (attachment && attachment.url) {
                        $('.user-avatar-preview').html('<img src="' + attachment.url + '" alt="Avatar Preview" class="avatar" />');
                        $('#starterpack-local-avatar').val(attachment.url);
                    }
                }
    
                $('#choose-avatar').on('click', function(event) {
                    event.preventDefault();
    
                    if (frame) {
                        frame.open();
                        return;
                    }
    
                    frame = wp.media({
                        title: 'Choose Avatar',
                        button: {
                            text: 'Select'
                        },
                        multiple: false
                    });
    
                    frame.on('select', function() {
                        var attachment = frame.state().get('selection').first().toJSON();
                        updateAvatarPreview(attachment);
                    });
    
                    frame.open();
                });
    
                $('#remove-avatar').on('click', function(event) {
                    event.preventDefault();
                    updateAvatarPreview(null);
                    $('#your-profile').find('input[type="submit"]').trigger('click');
                });
            });
        </script>
	    <?php
	}
	
	public function edit_user_profile_update( $user_id ) {
	    if ( ! isset( $_POST['_starterpack_user_avatar_nonce'] ) || ! wp_verify_nonce( $_POST['_starterpack_user_avatar_nonce'], 'starterpack_user_avatar_nonce' ) ) {
	        return;
	    }
	
	    if ( isset( $_POST['starterpack-user-avatar'] ) ) {
	        $avatar_url = esc_url_raw( $_POST['starterpack-user-avatar'] );
	        $this->set_user_avatar_meta( $user_id, $avatar_url );
	    }
	
	    if ( isset( $_POST['starterpack-user-avatar-erase'] ) && $_POST['starterpack-user-avatar-erase'] == '1' ) {
	        $this->avatar_delete( $user_id );
	    }
	}
	
	public function delete_user_avatar_meta( $user_id ) {
	    $this->avatar_delete_meta( $user_id );
	}
	
	public function avatar_delete_meta( $user_id ) {
	    $avatar_data = get_user_meta( $user_id, 'starterpack_user_avatar', true );
	
	    delete_user_meta( $user_id, 'starterpack_user_avatar' );
	}
	
	private function set_user_avatar_meta( $user_id, $filename ) {
	    $avatar_data = get_user_meta( $user_id, 'starterpack_user_avatar', true );
	
	    if ( empty( $avatar_data ) ) {
	        $avatar_data = array();
	    }
	
	    foreach ( $avatar_data as $size => $avatar ) {
	        unset( $avatar_data[$size] );
	    }
	
	    $avatar_data['full'] = $filename;
	
	    update_user_meta( $user_id, 'starterpack_user_avatar', $avatar_data );
	}


}