<?php

namespace SearchFilterSort\Filter;

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

use SearchFilterSort\Filter\Pro\Api\ApiRequests;
use SearchFilterSort\Filter\Shortcodes;
use SearchFilterSort\Filter\Pro\PluginPro;

class Plugin
{
    private $wpManager;

    public function __construct()
    {
        $this->wpManager = Container::instance()->getWpManager();
        $this->wpManager->init();
        $this->register_hooks();

        new Shortcodes();

        if( defined('SFS_FILTERS_PRO') && SFS_FILTERS_PRO ){
            new PluginPro();
        }

        if( is_admin() ){
            new Admin();
        }
    }

    public function register_hooks(){
        /**
         * string
         */
        $getData  = Container::instance()->getTheGet();

        if( ! is_admin() ){
            global $wp_version;

            // Different ParseRequest methods for WP version 6.0 or prior
            if( version_compare( $wp_version, '5.9.3', '>' ) ){
                add_filter( 'do_parse_request', array( $this->wpManager, 'customParseRequest' ), 10, 3 );
            }else{
                add_filter( 'do_parse_request', array( $this->wpManager, 'customParseRequestBefore60' ), 10, 3 );
            }

            add_action( 'parse_request', array( $this->wpManager, 'parseRequest' ) );
            add_action( 'pre_get_posts', array( $this->wpManager, 'addFilterQueryToWpQuery' ), 9999 );

            add_filter( 'posts_where', [ $this->wpManager, 'fixPostsWhereForSearch' ], 10, 2 );
            add_filter( 'post_limits_request', [ $this->wpManager, 'addSQlComment' ], 10, 2 );
            add_action( 'pre_get_posts', array( $this->wpManager, 'fixSearchPostType' ), 9999 );

            add_action( 'template_redirect', [ $this, 'prepareEntities' ] );

            add_action( 'sfswp_filtered_query_end', [ $this, 'addSearchArgsToWpQuery' ] );
            add_action( 'sfswp_all_set_wp_queried_posts', [ $this, 'addSearchArgsToWpQuery' ] );

            add_filter( 'posts_where', [ $this, 'postDateWhere' ], 10000, 2 );

            if ( sfs_is_woocommerce() ){
                add_action( 'woocommerce_product_query', 'sfs_remove_product_query_post_clauses', 10, 2 );
                add_filter( 'posts_search', [$this, 'addSkuSearchSql'], 10000, 2 );
            }

            $sorting = new Sorting();
            $sorting->registerHooks();
        }

        add_action( 'body_class', array( $this, 'bodyClass' ) );

        add_action( 'admin_print_styles', array( $this, 'includeAdminCss' ) );
        add_action( 'admin_print_scripts', array( $this, 'includeAdminJs' ) );

        // Do not include JS, if this page is admin or can't contain filters
        if( ! is_admin() && ! is_login() ){
            add_action( 'wp_head', [ $this, 'inlineFrontCss' ] );
            add_action( 'wp_print_styles', array( $this, 'includeFrontCss' ) );
            add_action( 'wp_print_scripts', array( $this, 'includeFrontJs' ) );
            add_action( 'wp_print_styles', array( $this, 'dynamicFrontCss' ) );
        }

        add_action( 'wp_footer', [$this, 'footerHtml'] );

        if( ! defined('SFS_FILTERS_PRO') ) {
            add_action( 'wp_head', array($this, 'noIndexFilterPages'), 1 );
            add_filter( 'sfswp_filter_set_default_fields', [ $this, 'addAvailableInProFields' ], 10, 2 );
            add_filter( 'sfswp_pre_save_set_fields', [ $this, 'unsetAvailableInProFields' ] );
        }

        add_filter( 'sfswp_filter_set_default_fields', [ $this, 'addSetTailFields' ], 20, 2 );

        // Disable single search result redirect
        add_filter( 'woocommerce_redirect_single_search_result', '__return_false' );

        add_action( 'save_post', [$this, 'resetTransitions'] );
        add_action( 'delete_post', [$this, 'resetTransitions'] );
        add_action( 'woocommerce_ajax_save_product_variations', [$this, 'resetTransitions'] );

        if( isset( $getData['reset_filters_cache'] ) && $getData['reset_filters_cache'] == true ){
            $this->resetTransitions();
        }

        add_action( 'sfswp_before_filter_set_settings_fields', [$this, 'removeApplyButtonOrderField'] );
        add_filter( 'sfswp_filter_set_prepared_values', [$this, 'handleSFSSetFieldsVisibility'] );

        add_action( 'sfswp_cycle_filter_fields', [$this, 'showCombinedFields'], 10, 2 );

        $woo_shortcodes = array(
            'products',
            'featured_products',
            'sale_products',
            'best_selling_products',
            'recent_products',
            'product_attribute',
            'top_rated_products'
        );

        // Set first install timestamp
        $first_install = get_option( 'sfswp_first_install' );
        if ( ! $first_install ){
            $first_install = [];
            $first_install['install_time']  = time();
            $first_install['rate_disabled'] = false;
            $first_install['rate_delayed']  = false;
            update_option( 'sfswp_first_install', $first_install );
        }

        // Fix caching problem for products queried by shortcode
        foreach ( $woo_shortcodes as $woo_shortcode ){
            add_filter( "shortcode_atts_{$woo_shortcode}", [$this, 'disableCacheProductsShortcode'] );
        }

        add_action('wp_ajax_install_and_activate_plugin', [ $this, 'sfs_install_and_activate_plugin'] );
    }

    public function resetTransitions()
    {
        $em = Container::instance()->getEntityManager();
        $all_filters = $em->getGlobalConfiguredSlugs();

        if( is_array( $all_filters ) ){
            foreach ( $all_filters as $entityEname => $slug ){
                // For terms it should be entity name
                $parts = explode( '#', $entityEname, 2 );
                $e_name = isset( $parts[1] ) ? $parts[1] : '';
                $type   = isset( $parts[0] ) ? $parts[0] : '';

                $terms_transient_key = '';

                if ( in_array( $type, [ 'post_meta_num', 'tax_numeric' ] ) ) {
                    global $wpdb;
                    $key = sfs_get_terms_transient_key(  $type . '_'. $e_name, false );

                    $result = $wpdb->get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%{$key}%'", ARRAY_A );

                    if ( isset( $result[0]['option_name'] ) ) {
                        $terms_transient_key = str_replace( '_transient_', '', str_replace( '_transient_timeout_', '', $result[0]['option_name'] ) );
                    }
                }

                if ( in_array( $type, [ 'post_date', 'post_meta_date' ] ) ) {
                    global $wpdb;
                    $key = 'sfswp_terms_post_date_';
                    $result = $wpdb->get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%{$key}%'", ARRAY_A );
                    if ( isset( $result[0]['option_name'] ) ) {
                        $terms_transient_key = str_replace( '_transient_', '', str_replace( '_transient_timeout_', '', $result[0]['option_name'] ) );
                    }
                }

                if ( $type === 'post_meta_exists' ) {
                    delete_transient( sfs_get_post_ids_transient_key( $e_name .'_yes' ) );
                    delete_transient( sfs_get_post_ids_transient_key( $e_name .'_no' ) );
                }

                if( ! $terms_transient_key ){
                    $terms_transient_key    = sfs_get_terms_transient_key( $type . '_'. $e_name );
                }

                $post_ids_transient_key = sfs_get_post_ids_transient_key( $slug );
                $var_meta_transient_key = sfs_get_variations_transient_key( 'attribute_'. $e_name );

                delete_transient( $terms_transient_key );
                delete_transient( $post_ids_transient_key );
                delete_transient( $var_meta_transient_key );
            }
        }

        $variations_key = 'sfswp_posts_variations';
        $filter_key     = 'sfswp_filters_query';

        delete_transient($variations_key);
        delete_transient($filter_key);

        unset( $terms_transient_key, $post_ids_transient_key, $var_meta_transient_key, $all_filters, $em );
    }

    public function prepareEntities()
    {
        $wpManager  = Container::instance()->getWpManager();
        $em         = Container::instance()->getEntityManager();
        $sets       = $wpManager->getQueryVar('sfswp_page_related_set_ids');

        if( $sets ){
            foreach( $sets as $set ){
                $em->prepareEntitiesToDisplay( array( $set ) );
            }
        }
    }


    public function addAvailableInProFields( $fields, $filterSet )
    {
        foreach ( $fields as $key => $attributes ){
            // Always insert regular 'old' field
            $new_fields[$key] = $attributes;

            if( $key === 'post_name' ){

                $new_fields['instead_post_name'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('Where to filter?', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('instead_post_name'),
                    'id'            => $filterSet->generateFieldId('instead_post_name'),
                    'class'         => 'sfswp-field-instead-of-location',
                    'default'       => '',
                    'readonly'      => 'readonly',
                    'placeholder'   => esc_html__('Available in PRO', 'searchfiltersort'),
                    'instructions'  => esc_html__('Specify page(s) where the Posts list should be filtered is located', 'searchfiltersort'),
                    'settings'      => true
                );

                $new_fields['instead_wp_filter_query'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('And what to filter?', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('instead_wp_filter_query'),
                    'id'            => $filterSet->generateFieldId('instead_wp_filter_query'),
                    'class'         => 'sfswp-field-instead-wp-filter-query',
                    'default'       => '',
                    'readonly'      => 'readonly',
                    'placeholder'   => esc_html__('Available in PRO', 'searchfiltersort'),
                    'instructions'  => esc_html__('Determines what exactly the Posts list (WP_Query) on a page should be filtered', 'searchfiltersort'),
                    'tooltip'       => wp_kses ( __( 'Every Posts list, like "Popular products" or "Recent posts" on a page, is related to some WP_Query. This field allows you to set desired Posts list by choosing its WP_Query.<br /><br />If the filtering process does not change the Posts you need, it means you selected the wrong WP_Query. Please, try to experiment with different ones until it starts to filter.', 'searchfiltersort' )
                        ,
                        array(
                            'br' => array()
                        )
                    ),
                    'settings' => true
                );

            }

            if( $key === 'show_count' ){

                $new_fields['instead_custom_posts_container'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('HTML id or class of the Posts Container', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('instead_custom_posts_container'),
                    'id'            => $filterSet->generateFieldId('instead_custom_posts_container'),
                    'class'         => 'sfswp-field-instead-custom-posts-container',
                    'default'       => '',
                    'readonly'      => 'readonly',
                    'placeholder'   => esc_html__('Available in PRO', 'searchfiltersort'),
                    'instructions'  => esc_html__('Specify individual HTML selector of Posts Container for AJAX', 'searchfiltersort'),
                    'settings'      => true
                );

            }

        }

        return $new_fields;
    }

    public function addSetTailFields(  $fields, $filterSet )
    {
        $new_fields     = [];
        $insert_after   = defined('SFS_FILTERS_PRO') ? 'custom_posts_container' : 'show_count';

        foreach ( $fields as $key => $attributes ){
            // Always insert regular 'old' field
            $new_fields[$key] = $attributes;

            if( $key === $insert_after ){

                $new_fields['use_search_field'] =  array(
                    'type'          => 'Checkbox',
                    'label'         => esc_html__('Search Field', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('use_search_field'),
                    'id'            => $filterSet->generateFieldId('use_search_field'),
                    'class'         => 'sfswp-field-use-search-field',
                    'default'       => 'no',
                    'instructions'  => esc_html__('Allows you to search by text among filtered posts', 'searchfiltersort'),
                    'settings'      => false
                );

                $new_fields['search_field_menu_order'] = array(
                    'type'          => 'Hidden',
                    'label'         => '',
                    'class'         => 'sfswp-menu-order-field',
                    'id'            => $filterSet->generateFieldId('search_field_menu_order'),
                    'name'          => $filterSet->generateFieldName('search_field_menu_order'),
                    'default'       => -1,
                    'settings'      => false
                );

                $new_fields['search_field_label'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('Search Field Title', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('search_field_label'),
                    'id'            => $filterSet->generateFieldId('search_field_label'),
                    'class'         => 'sfswp-search-field-label',
                    'default'       => esc_html__('Search', 'searchfiltersort'),
                    'instructions'  => esc_html__('Specify if needed or leave empty', 'searchfiltersort'),
                    'settings'      => false
                );

                $new_fields['search_field_placeholder'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('Search Field Placeholder', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('search_field_placeholder'),
                    'id'            => $filterSet->generateFieldId('search_field_placeholder'),
                    'class'         => 'sfswp-search-field-placeholder',
                    'placeholder'   => esc_html__( 'Example: Search products, Search posts', 'searchfiltersort' ),
                    'default'       => '',
                    'settings'      => false
                );

                $new_fields['use_apply_button'] =  array(
                    'type'          => 'Checkbox',
                    'label'         => esc_html__('«Apply Button» mode', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('use_apply_button'),
                    'id'            => $filterSet->generateFieldId('use_apply_button'),
                    'class'         => 'sfswp-field-use-apply-button',
                    'default'       => 'no',
                    'instructions'  => esc_html__('Enables filtering by clicking the Apply button', 'searchfiltersort'),
                    'settings'      => false
                );

                $new_fields['apply_button_menu_order'] = array(
                    'type'          => 'Hidden',
                    'label'         => '',
                    'class'         => 'sfswp-menu-order-field',
                    'id'            => $filterSet->generateFieldId('apply_button_menu_order'),
                    'name'          => $filterSet->generateFieldName('apply_button_menu_order'),
                    'default'       => -1,
                    'settings'      => false
                );

                $new_fields['apply_button_text'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('Apply Button label', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('apply_button_text'),
                    'id'            => $filterSet->generateFieldId('apply_button_text'),
                    'class'         => 'sfswp-field-apply-button-text',
                    'default'       => esc_html__('Apply', 'searchfiltersort'),
                    'settings'      => false
                );

                $new_fields['reset_button_text'] = array(
                    'type'          => 'Text',
                    'label'         => esc_html__('Reset Button label', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('reset_button_text'),
                    'id'            => $filterSet->generateFieldId('reset_button_text'),
                    'class'         => 'sfswp-field-reset-button-text',
                    'default'       => esc_html__('Reset', 'searchfiltersort'),
                    'settings'      => false
                );
                $new_fields['use_sort_option'] =  array(
                    'type'          => 'Checkbox',
                    'label'         => esc_html__('Sorting', 'searchfiltersort'),
                    'name'          => $filterSet->generateFieldName('use_sort_option'),
                    'id'            => $filterSet->generateFieldId('use_sort_option'),
                    'class'         => 'sfswp-field-use-sort-option',
                    'default'       => 'no',
                    'instructions'  => esc_html__('Allows you to sort.', 'searchfiltersort'),
                    'sort'      => false
                );
            }
        }
        return $new_fields;
    }

    public function unsetAvailableInProFields( $setFields )
    {
        unset( $setFields['instead_post_name'], $setFields['instead_custom_posts_container'] );

        return $setFields;
    }

    public function noIndexFilterPages()
    {
        if( sfs_is_filter_request() ){
            $robots['index']    = 'noindex';
            $robots['follow']   = 'nofollow';
            $content = implode(', ', $robots );
            echo sprintf('<meta name="robots" content="%s">', $content)."\r\n";
        }
    }

    public function inlineFrontCss()
    {
        $inline = '<style type="text/css" id="search-filter-sort-inline-css">.sfswp-orderby-select{width:100%}.sfswp-filters-open-button-container{display:none}.sfswp-debug-message{padding:16px;font-size:14px;border:1px dashed #ccc;margin-bottom:20px}.sfswp-debug-title{visibility:hidden}.sfswp-button-inner,.sfswp-chip-content{display:flex;align-items:center}.sfswp-icon-html-wrapper{position:relative;margin-right:10px;top:2px}.sfswp-icon-html-wrapper span{display:block;height:1px;width:18px;border-radius:3px;background:#2c2d33;margin-bottom:4px;position:relative}span.sfswp-icon-line-1:after,span.sfswp-icon-line-2:after,span.sfswp-icon-line-3:after{content:"";display:block;width:3px;height:3px;border:1px solid #2c2d33;background-color:#fff;position:absolute;top:-2px;box-sizing:content-box}span.sfswp-icon-line-3:after{border-radius:50%;left:2px}span.sfswp-icon-line-1:after{border-radius:50%;left:5px}span.sfswp-icon-line-2:after{border-radius:50%;left:12px}body .sfswp-filters-open-button-container a.sfswp-filters-open-widget,body .sfswp-filters-open-button-container a.sfswp-open-close-filters-button{display:inline-block;text-align:left;border:1px solid #2c2d33;border-radius:2px;line-height:1.5;padding:7px 12px;background-color:transparent;color:#2c2d33;box-sizing:border-box;text-decoration:none!important;font-weight:400;transition:none;position:relative}@media screen and (max-width:768px){.sfswp_show_bottom_widget .sfswp-filters-open-button-container,.sfswp_show_open_close_button .sfswp-filters-open-button-container{display:block}.sfswp_show_bottom_widget .sfswp-filters-open-button-container{margin-top:1em;margin-bottom:1em}}</style>'."\r\n";
        echo $inline;
    }

    public function dynamicFrontCss()
    {
        // Do not include plugin CSS if there are no SFS Sets on the page
        $sets = $this->wpManager->getQueryVar( 'sfswp_page_related_set_ids', [] );
        if( empty( $sets ) ) {
            return false;
        }

        $maxHeight        = sfs_get_option( 'container_height' );
        $color            = sfs_get_option( 'primary_color', sfs_default_theme_color() );
        $move_to_top      = sfs_get_option( 'try_move_to_top_sidebar' );
        $sfswp_mobile_width = sfs_get_mobile_width();

        // Experimental Options
        $custom_css     = sfs_get_experimental_option('custom_css');
        $use_loader     = sfs_get_experimental_option('use_loader');
        $dark_overlay   = sfs_get_experimental_option('dark_overlay');
        $styled_inputs  = sfs_get_experimental_option('styled_inputs');
        $use_select2    = sfs_get_experimental_option('select2_dropdowns');
        $rounded_swatch = sfs_get_experimental_option('rounded_swatches');
        $contrastColor  = false;

        $swatches_measurements = [ 'width' => 24, 'height' => 24 ];
        if( $rounded_swatch ) {
            $swatches_measurements = [ 'width' => 31, 'height' => 31 ];
        }

        $swatches       = apply_filters( 'sfswp_swatches_width_height', $swatches_measurements );
        $brands         = apply_filters( 'sfswp_brands_width_height', [ 'width' => 70, 'height' => 40 ] );

        $css = '';
        $css .= '@media screen and (min-width:'.($sfswp_mobile_width+1).'px){.sfswp_show_bottom_widget .sfswp-filters-widget-content{height:auto!important}body.sfswp_show_open_close_button .sfswp-filters-widget-content.sfswp-closed,body.sfswp_show_open_close_button .sfswp-filters-widget-content.sfswp-opened,body.sfswp_show_open_close_button .sfswp-filters-widget-content:not(.sfswp-opened){display:block!important}}@media screen and (min-width:'.$sfswp_mobile_width.'px){.sfswp-custom-selected-terms{clear:both;width:100%}.sfswp-custom-selected-terms ul.sfswp-filter-chips-list{display:flex;overflow-x:auto;padding-left:0}.sfswp-filters-main-wrap .sfswp-custom-selected-terms ul.sfswp-filter-chips-list{display:block;overflow:visible}html.is-active .sfswp-filters-overlay{top:0;opacity:.3;background:#fff}.sfswp-filters-main-wrap input.sfswp-label-input+label:hover{border:1px solid rgba(0,0,0,.25);border-radius:5px}.sfswp-filters-main-wrap input.sfswp-label-input+label:hover span.sfswp-filter-label-wrapper{color:#333;background-color:rgba(0,0,0,.25)}.sfswp-filters-main-wrap .sfswp-filters-labels li.sfswp-term-item input+label:hover a{color:#333}.theme-storefront #primary .storefront-sorting .sfswp-custom-selected-terms{font-size:inherit}.theme-storefront #primary .sfswp-custom-selected-terms{font-size:.875em}}@media screen and (max-width:'.$sfswp_mobile_width.'px){.sfswp-filters-labels li.sfswp-term-item label:hover .sfswp-term-swatch-wrapper:after,.sfswp-filters-labels li.sfswp-term-item label:hover .sfswp-term-swatch-wrapper:before{display:none;}.sfswp_show_bottom_widget .sfswp-filters-widget-top-container,.sfswp_show_open_close_button .sfswp-filters-widget-top-container{text-align:center}.sfswp_show_bottom_widget .sfswp-filters-widget-top-container{position:sticky;top:0;z-index:99999;border-bottom:1px solid #f7f7f7}.sfswp-custom-selected-terms:not(.sfswp-show-on-mobile),.sfswp-edit-sfs-set,.sfswp_show_bottom_widget .widget_sfswp_selected_filters_widget,.sfswp_show_bottom_widget .sfswp-filters-widget-content .sfswp-sfs-set-widget-title,.sfswp_show_bottom_widget .sfswp-filters-main-wrap .widget-title,.sfswp_show_bottom_widget .sfswp-filters-widget-wrapper .sfswp-filter-layout-submit-button,.sfswp_show_bottom_widget .sfswp-posts-found,body.sfswp_show_bottom_widget .sfswp-open-close-filters-button,body.sfswp_show_open_close_button .sfswp-filters-widget-content:not(.sfswp-opened){display:none}.sfswp_show_bottom_widget .sfswp-filters-widget-top-container:not(.sfswp-show-on-desktop),.sfswp_show_bottom_widget .sfswp-spinner.is-active,.sfswp_show_bottom_widget .sfswp-widget-close-container,html.is-active body:not(.sfswp_show_bottom_widget) .sfswp-spinner{display:block}body .sfswp-filters-main-wrap li.sfswp-term-item{padding:2px 0}.sfswp-chip-empty{width:0;display:list-item;visibility:hidden;margin-right:0!important}.sfswp-overlay-visible #secondary{z-index:auto}html.is-active:not(.sfswp-overlay-visible) .sfswp-filters-overlay{top:0;opacity:.2;background:#fff}.sfswp-custom-selected-terms.sfswp-show-on-mobile ul.sfswp-filter-chips-list{display:flex;overflow-x:auto;padding-left:0}html.is-active body:not(.sfswp_show_bottom_widget) .sfswp-filters-overlay{top:0;opacity:.3;background:#fff}body.sfswp_show_bottom_widget .sfswp-filters-widget-content.sfswp-closed,body.sfswp_show_bottom_widget .sfswp-filters-widget-content.sfswp-opened,body.sfswp_show_bottom_widget .sfswp-filters-widget-content:not(.sfswp-opened){display:block!important}.sfswp-open-close-filters-button{display:block;margin-bottom:20px}.sfswp-overlay-visible body,html.sfswp-overlay-visible{overflow:hidden!important}.sfswp_show_bottom_widget .widget_sfswp_filters_widget,.sfswp_show_bottom_widget .sfswp-filters-main-wrap{padding:0!important;margin:0!important}.sfswp_show_bottom_widget .sfswp-filters-range-column{width:48%;max-width:none}.sfswp_show_bottom_widget .sfswp-filters-toolbar{display:flex;margin:1em 0}.sfswp_show_bottom_widget .sfswp-inner-widget-chips-wrapper{display:block;padding-left:20px;padding-right:20px}.sfswp_show_bottom_widget .sfswp-filters-main-wrap .widget-title.sfswp-filter-title{display:flex}.sfswp_show_bottom_widget .sfswp-inner-widget-chips-wrapper .sfswp-filter-chips-list,.sfswp_show_open_close_button .sfswp-inner-widget-chips-wrapper .sfswp-filter-chips-list{display:flex;-webkit-box-pack:start;place-content:center flex-start;overflow-x:auto;padding-top:5px;padding-bottom:5px;margin-left:0;padding-left:0}.sfswp-overlay-visible .sfswp_show_bottom_widget .sfswp-filters-overlay{top:0;opacity:.4}.sfswp_show_bottom_widget .sfswp-filters-main-wrap .sfswp-spinner.is-active+.sfswp-filters-widget-content .sfswp-filters-scroll-container .sfswp-filters-widget-wrapper{opacity:.6;pointer-events:none}.sfswp_show_bottom_widget .sfswp-filters-open-button-container{margin-top:1em;margin-bottom:1em}.sfswp_show_bottom_widget .sfswp-filters-widget-content{position:fixed;bottom:0;right:0;left:0;top:5%;z-index:999999;padding:0;background-color:#fff;margin:0;box-sizing:border-box;border-radius:7px 7px 0 0;transition:transform .25s;transform:translate3d(0,120%,0);-webkit-overflow-scrolling:touch;height:auto}.sfswp_show_bottom_widget .sfswp-filters-widget-containers-wrapper{padding:0;margin:0;overflow-y:scroll;box-sizing:border-box;position:fixed;top:56px;left:0;right:0;bottom:0}.sfswp_show_bottom_widget .sfswp-filters-widget-content.sfswp-filters-widget-opened{transform:translate3d(0,0,0)}.theme-twentyfourteen .sfswp_show_bottom_widget .sfswp-filters-widget-content,.theme-twentyfourteen.sfswp_show_bottom_widget .sfswp-filters-scroll-container{background-color:#000}.sfswp_show_bottom_widget .sfswp-filters-section:not(.sfswp-filter-post_meta_num):not(.sfswp-filter-tax_numeric) .sfswp-filter-content ul.sfswp-filters-ul-list,.sfswp_show_open_close_button .sfswp-filters-section:not(.sfswp-filter-post_meta_num):not(.sfswp-filter-tax_numeric) .sfswp-filter-content ul.sfswp-filters-ul-list{max-height:none}.sfswp_show_bottom_widget .sfswp-filters-scroll-container{background:#fff;min-height:100%}.sfswp_show_bottom_widget .sfswp-filters-widget-wrapper{padding:20px 20px 15px}.sfswp-search-filter-sort-dropdown .select2-search--dropdown .select2-search__field,.sfswp-sorting-form select,.sfswp_show_bottom_widget .sfswp-filters-main-wrap input[type=number],.sfswp_show_bottom_widget .sfswp-filters-main-wrap input[type=text],.sfswp_show_bottom_widget .sfswp-filters-main-wrap select,.sfswp_show_bottom_widget .sfswp-filters-main-wrap textarea,.sfswp_show_bottom_widget .sfswp-search-field,.sfswp_show_open_close_button .sfswp-search-field,.sfswp_show_open_close_button .sfswp-filter-search-field{font-size:16px}.sfswp-filter-layout-dropdown .select2-container .select2-selection--single,.sfswp-sorting-form .select2-container .select2-selection--single{height:auto;padding:6px}.sfswp_show_bottom_widget .sfswp-filters-section:not(.sfswp-filter-post_meta_num):not(.sfswp-filter-tax_numeric) .sfswp-filter-content ul.sfswp-filters-ul-list{overflow-y:visible}.theme-twentyeleven #primary,.theme-twentyeleven #secondary{margin-left:0;margin-right:0;clear:both;float:none}#main>.fusion-row{max-width:100%}.sfswp_show_bottom_widget .sfswp-filters-open-button-container,.sfswp_show_bottom_widget .sfswp-filters-widget-controls-container,.sfswp_show_bottom_widget .sfswp-filters-widget-top-container,.sfswp_show_open_close_button .sfswp-filters-open-button-container{display:block}}'."\r\n";
        $css .= '.sfswp-preload-img{display:none;}';
        // Number of items visible by default in More/Less filters
        $css .= '.sfswp-filter-more-less:not(.sfswp-search-active) .sfswp-filters-ul-list > li:nth-child(-n+'.sfs_more_less_count().'){display: list-item;}'."\r\n";

        $css .= 'li.sfswp-term-item label span.sfswp-term-swatch,.sfswp-term-swatch-wrapper{width:'.$swatches['width'].'px;min-width:'.$swatches['width'].'px;';

        if ( $rounded_swatch ) {
            $css .= 'border-radius:'.$swatches['height'].'px;';
        }

        $css .= 'height:'.$swatches['height'].'px;}'."\r\n";
        $css .= '.sfswp-term-swatch-wrapper:after{width:'.($swatches['width']/2.5).'px;height:'.($swatches['width']/5).'px;left:'.($swatches['width']/3.5).'px;top:'.($swatches['height']/3.5).'px;}';
        $css .= '.sfswp-term-image-wrapper{width:'.$brands['width'].'px;min-width:'.$brands['width'].'px;height:'.$brands['height'].'px;}';

        if( $maxHeight ){
            $css .= '.sfswp-filters-section:not(.sfswp-filter-more-less):not(.sfswp-filter-post_meta_num):not(.sfswp-filter-tax_numeric):not(.sfswp-filter-layout-dropdown):not(.sfswp-filter-terms-count-0) .sfswp-filter-content:not(.sfswp-filter-has-hierarchy) ul.sfswp-filters-ul-list{
                        max-height: '.$maxHeight.'px;
                        overflow-y: auto;
                }'."\r\n";
        }

        if( $color ){
            $contrastColor = sfs_get_contrast_color($color);
            $css .= '.sfswp-filters-range-inputs .ui-slider-horizontal .ui-slider-range{
                        background-color: '.$color.';
                    }
                '."\r\n";

            $css .= '.sfswp-spinner:after {
                        border-top-color: '.$color.';
                    }'."\r\n";

            $css .= '.theme-Avada .sfswp-filter-product_visibility .star-rating:before,
                .sfswp-filter-product_visibility .star-rating span:before{
                    color: '.$color.';
                }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap input.sfswp-label-input:checked+label span.sfswp-filter-label-wrapper{
                        background-color: '.$color.';
                }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap input.sfswp-label-input:checked+label{
                        border-color: '.$color.';
                }'."\r\n";

            // Disabled label
            $css .= 'body .sfswp-filters-main-wrap .sfswp-term-disabled input.sfswp-label-input:checked+label span.sfswp-filter-label-wrapper{
                        background-color: #d8d8d8;
                }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap .sfswp-term-disabled input.sfswp-label-input:checked+label{
                        border-color: #d8d8d8;
                }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap .sfswp-term-disabled input.sfswp-label-input+label:hover{
                        border-color: #d8d8d8;
                }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap .sfswp-term-disabled input.sfswp-label-input:checked+label span.sfswp-filter-label-wrapper,
                body .sfswp-filters-main-wrap .sfswp-filters-labels li.sfswp-term-item.sfswp-term-disabled input:checked+label a{
                        color: #333333;
                }'."\r\n";
            // End of disabled label

            $css .= 'body .sfswp-filters-main-wrap input.sfswp-label-input:checked+label span.sfswp-filter-label-wrapper,
                body .sfswp-filters-main-wrap .sfswp-filters-labels li.sfswp-term-item input:checked+label a{
                        color: '.$contrastColor.';
                }'."\r\n";

            $css .= 'body .sfswp-filter-chips-list li.sfswp-filter-chip:not(.sfswp-chip-reset-all) a{
                    border-color: '.$color.';
                }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap .sfswp-filters-widget-controls-container a.sfswp-filters-apply-button,
                body .sfswp-filters-main-wrap a.sfswp-filters-submit-button{
                    border-color: '.$color.';
                    background-color: '.$color.';
                    color: '.$contrastColor.';
                }'."\r\n";

            $css .= 'body .sfswp-filter-chips-list li.sfswp-filter-chip a:hover{
                    opacity: 0.9;
                }'."\r\n";

            $css .= 'body .sfswp-filter-chips-list li.sfswp-filter-chip a:active{
                    opacity: 0.75;
                }'."\r\n";

            $css .= '.star-rating span,
                .star-rating span:before{
                    color: '.$color.';
                }'."\r\n";

            $css .= 'body a.sfswp-filters-open-widget:active, a.sfswp-filters-open-widget:active, 
                .sfswp-filters-open-widget:active{
                    border-color: '.$color.';
                    background-color: '.$color.';
                    color: '.$contrastColor.';
                }'."\r\n";

            $css .= 'a.sfswp-filters-open-widget:active span.sfswp-icon-line-1:after,
                a.sfswp-filters-open-widget:active span.sfswp-icon-line-2:after,
                a.sfswp-filters-open-widget:active span.sfswp-icon-line-3:after{
                    background-color: '.$color.';
                    border-color: '.$contrastColor.';
                }'."\r\n";

            $css .= 'a.sfswp-filters-open-widget:active .sfswp-icon-html-wrapper span{
                    background-color: '.$contrastColor.';
                }'."\r\n";

            $css .= '@media screen and (min-width: '.$sfswp_mobile_width.'px) {'."\r\n";
            $css .= 'body .sfswp-filters-main-wrap input.sfswp-label-input+label:hover span.sfswp-filter-label-wrapper{
                        color: '.$contrastColor.';
                        background-color: '.$color.';
                    }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap .sfswp-filters-labels li.sfswp-term-item input+label:hover a{
                        color: '.$contrastColor.';
                    }'."\r\n";
            $css .= 'body .sfswp-filters-main-wrap input.sfswp-label-input+label:hover{
                        border-color: '.$color.';
                    }'."\r\n";


            $css .= '#ui-datepicker-div.sfswp-filter-datepicker .ui-state-active, 
            #ui-datepicker-div.ui-widget-content.sfswp-filter-datepicker .ui-state-active, 
            #ui-datepicker-div.sfswp-filter-datepicker .ui-widget-header .ui-state-active{
                    border-color: '.$color.';
                    background: '.$color.';
                    opacity: 0.95;
            }'."\r\n";

            $css .= '#ui-datepicker-div.sfswp-filter-datepicker .ui-state-hover, 
            #ui-datepicker-div.ui-widget-content.sfswp-filter-datepicker .ui-state-hover, 
            #ui-datepicker-div.sfswp-filter-datepicker .ui-widget-header .ui-state-hover, 
            #ui-datepicker-div.sfswp-filter-datepicker .ui-state-focus, 
            #ui-datepicker-div.ui-widget-content.sfswp-filter-datepicker .ui-state-focus, 
            #ui-datepicker-div.sfswp-filter-datepicker .ui-widget-header .ui-state-focus{
                border-color: '.$color.';
                background: '.$color.';
                opacity: 0.6;
            }';

            $css .= '#ui-datepicker-div.sfswp-filter-datepicker .ui-datepicker-close.ui-state-default{
                background: '.$color.';
                color: '.$contrastColor.';
            }'."\r\n";

            $css .= '}'."\r\n";
            $css .= '.sfs-star-label svg{
                    stroke: '.$color.';
            }'."\r\n";

            $css .= '.sfs-star-label-hover svg, .sfswp-chip-stars svg{
                    fill: '.$color.';
            }'."\r\n";

            $css .= '.sfswp-filter-label-stars-wrapper{
                   padding: 4px 5px !important;
            }'."\r\n";

            $css .= '.sfswp-filter-label-stars-wrapper .sfs-star-label svg{
                    height: 17px;
                    width: 17px;
            }'."\r\n";

            $css .= 'body .sfswp-filters-main-wrap input.sfswp-label-input:checked+label span.sfswp-filter-label-stars-wrapper .sfs-star-label svg, 
            span.sfswp-filter-label-stars-wrapper:hover .sfs-star-label svg{
                        fill: ' . sfs_get_contrast_color($color) . ';
                }'."\r\n";
        }
        if( $styled_inputs ){
            $styled_color   = $color ? $color : '#0570e2';
            $contrastColor  = $contrastColor ? $contrastColor : sfs_get_contrast_color($styled_color);
            $hoverColor     = sfs_add_color_opacity($color);
            $no_hex_color   = substr( $color, 1, 6 );
            $css .= '.sfswp-filters-main-wrap input[type=checkbox],
                        .sfswp-filters-main-wrap input[type=radio]{
                            -webkit-appearance: none;
                            -moz-appearance: none;
                            position: relative;
                            width: 20px;
                            height: 20px;
                            border: 1px solid #c9d1e0;
                            background: #ffffff;
                            border-radius: 5px;
                            min-width: 20px;
                        }
                        i.sfswp-toggle-children-list:after,
                        i.sfswp-toggle-children-list:before{
                            background-color: #b8bcc8;
                        }
                        i.sfswp-toggle-children-list:hover:after,
                        i.sfswp-toggle-children-list:hover:before{
                            background-color: '.$color.';
                        }
                        .sfswp-filters-widget-content input[type=email], 
                        .sfswp-filters-widget-content input[type=number], 
                        .sfswp-filters-widget-content input[type=password], 
                        .sfswp-filters-widget-content input[type=search], 
                        .sfswp-filters-widget-content input[type=tel], 
                        .sfswp-filters-widget-content input[type=text], 
                        .sfswp-filters-widget-content input[type=url]{
                            height: 44px;
                        }
                        .sfswp-filters-widget-content .sfswp-filters-section input[type="number"],
                        .sfswp-filters-widget-content .sfswp-filters-section input[type="text"]{
                            border: 1px solid #ccd0dc;
                            border-radius: 6px;
                            background: transparent;
                            box-shadow: none; 
                            padding: 8px 16px;
                        }
                        .sfswp-filters-main-wrap input[type=checkbox]:after {
                            content: "";
                            opacity: 0;
                            display: block;
                            left: 6px;
                            top: 3px;
                            position: absolute;
                            width: 4px;
                            height: 8px;
                            border: 2px solid '.$styled_color.';
                            border-top: 0;
                            border-left: 0;
                            transform: rotate(45deg);
                            box-sizing: content-box;
                        }
                        .sfswp-filters-main-wrap input[type=radio]:after {
                            content: "";
                            opacity: 0;
                            display: block;
                            left: 5px;
                            top: 5px;
                            position: absolute;
                            width: 8px;
                            height: 8px;
                            border-radius: 50%;
                            background: '.$styled_color.';
                            box-sizing: content-box;
                        }
                        .sfswp-filters-main-wrap input[type=radio]:checked,
                        .sfswp-filters-main-wrap input[type=checkbox]:checked {
                            border-color: '.$styled_color.';
                        }
                        .sfswp-filters-main-wrap .sfswp-radio-item.sfswp-term-disabled input[type=radio],
                        .sfswp-filters-main-wrap .sfswp-checkbox-item.sfswp-term-disabled > div > input[type=checkbox],
                        .sfswp-filters-main-wrap .sfswp-checkbox-item.sfswp-term-disabled > div > input[type=checkbox]:after,
                        .sfswp-filters-main-wrap .sfswp-term-count-0:not(.sfswp-has-not-empty-children) input[type=checkbox]:after,
                        .sfswp-filters-main-wrap .sfswp-term-count-0:not(.sfswp-has-not-empty-children) input[type=checkbox],
                        .sfswp-filters-main-wrap .sfswp-term-count-0:not(.sfswp-has-not-empty-children) input[type=radio]{
                            border-color: #d8d8d8;
                        }
                        .sfswp-filters-main-wrap .sfswp-radio-item.sfswp-term-disabled input[type=radio]:after,
                        .sfswp-filters-main-wrap .sfswp-term-count-0:not(.sfswp-has-not-empty-children) input[type=radio]:after{
                            background-color: #d8d8d8;
                        }
                        .sfswp-filters-main-wrap input[type=radio]:checked:after,
                        .sfswp-filters-main-wrap input[type=checkbox]:checked:after {
                            opacity: 1;
                        }
                        .sfswp-filters-main-wrap input[type=radio] {
                            border-radius: 50%;
                        }
                        .sfswp-filters-widget-content .sfswp-filters-date-range-wrapper input[type="text"]{
                            padding-right: 48px;
                            background-image: url("data:image/svg+xml,%3Csvg width=\'16\' height=\'16\' viewBox=\'0 0 16 16\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Crect x=\'2\' y=\'4\' width=\'12\' height=\'10\' rx=\'1.33333\' stroke=\'%23b8bcc8\' stroke-width=\'1.33333\'/%3E%3Cpath d=\'M2.66699 7.3335H13.3337\' stroke=\'%23b8bcc8\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3Cpath d=\'M6 10.6667H10\' stroke=\'%23b8bcc8\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3Cpath d=\'M5.33301 2L5.33301 4.66667\' stroke=\'%23b8bcc8\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3Cpath d=\'M10.667 2L10.667 4.66667\' stroke=\'%23b8bcc8\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3C/svg%3E%0A");
                            background-repeat: no-repeat;
                            background-position: right 16px bottom 50%;
                        }    
                        .sfswp-filters-widget-content .sfswp-filters-date-range-wrapper input[type="text"]:focus,
                        .sfswp-filters-widget-content .sfswp-filters-date-range-wrapper input[type="text"]:hover{
                            background-image: url("data:image/svg+xml,%3Csvg width=\'16\' height=\'16\' viewBox=\'0 0 16 16\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Crect x=\'2\' y=\'4\' width=\'12\' height=\'10\' rx=\'1.33333\' stroke=\'%23'.$no_hex_color.'\' stroke-width=\'1.33333\'/%3E%3Cpath d=\'M2.66699 7.3335H13.3337\' stroke=\'%23'.$no_hex_color.'\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3Cpath d=\'M6 10.6667H10\' stroke=\'%23b8bcc8\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3Cpath d=\'M5.33301 2L5.33301 4.66667\' stroke=\'%23'.$no_hex_color.'\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3Cpath d=\'M10.667 2L10.667 4.66667\' stroke=\'%23'.$no_hex_color.'\' stroke-width=\'1.33333\' stroke-linecap=\'round\'/%3E%3C/svg%3E%0A");
                        }
                        .sfswp-help-tip::after{
                            color: #b8bcc8;
                            border: 1px solid #b8bcc8; 
                        }
                        .sfswp-filter-layout-dropdown .select2-container--default .select2-selection--single .select2-selection__arrow b, 
                        .sfswp-sorting-form .select2-container--default .select2-selection--single .select2-selection__arrow b{
                            border-left: 1px solid #b8bcc8;
                            border-top: 1px solid #b8bcc8;
                        }
                        .sfswp-filter-layout-dropdown .select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b, 
                        .sfswp-sorting-form .select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{
                            border-left: 1px solid #b8bcc8;
                            border-top: 1px solid #b8bcc8;
                        }
                        .sfswp-filter-collapsible .sfswp-filter-title .sfswp-open-icon, 
                        .sfswp-filter-collapsible-reverse.sfswp-filter-collapsible.sfswp-closed .sfswp-filter-title .sfswp-open-icon, 
                        .sfswp-filter-collapsible.sfswp-closed .sfswp-filter-title .sfswp-open-icon, 
                        .sfswp-filter-has-selected.sfswp-closed .sfswp-filter-title .sfswp-open-icon{
                            border-left: 1px solid #b8bcc8;
                            border-top: 1px solid #b8bcc8;
                        }
                        .sfswp-sorting-form .select2-container--default .select2-selection--single:hover,
                        .sfswp-filters-widget-content input[type=email]:hover, 
                        .sfswp-filters-widget-content input[type=number]:hover, 
                        .sfswp-filters-widget-content input[type=password]:hover, 
                        .sfswp-filters-widget-content input[type=search]:hover, 
                        .sfswp-filters-widget-content input[type=tel]:hover, 
                        .sfswp-filters-widget-content input[type=text]:hover, 
                        .sfswp-filters-widget-content input[type=url]:hover{
                            border-color: '. $hoverColor.';
                        }
                        .sfswp-help-tip:hover::after,
                        .sfswp-filter-layout-dropdown .select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b, 
                        .sfswp-sorting-form .select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b,
                        .widget_sfswp_sorting_widget .select2-container--default .select2-selection--single:hover .select2-selection__arrow b,
                        .sfswp-filter-layout-dropdown .select2-container--default .select2-selection--single:hover .select2-selection__arrow b,
                        .sfswp-filter-layout-dropdown .select2-container--default .select2-selection--single:hover, 
                        .select2-container--default.select2-container--open .sfswp-search-filter-sort-dropdown.select2-dropdown,
                        .sfswp-sorting-form .select2-container--open .select2-selection--single:hover,
                        .widget_sfswp_sorting_widget .select2-container--open .select2-selection--single,
                        .sfswp-filter-layout-dropdown .select2-container--open .select2-selection--single, 
                        .sfswp-filters-widget-content input[type=email]:focus, 
                        .sfswp-filters-widget-content input[type=number]:focus, 
                        .sfswp-filters-widget-content input[type=password]:focus, 
                        .sfswp-filters-widget-content input[type=search]:focus, 
                        .sfswp-filters-widget-content input[type=tel]:focus, 
                        .sfswp-filters-widget-content input[type=text]:focus, 
                        .sfswp-filters-widget-content input[type=url]:focus,
                        .sfswp-filters-widget-content input[type=email]:active, 
                        .sfswp-filters-widget-content input[type=number]:active, 
                        .sfswp-filters-widget-content input[type=password]:active, 
                        .sfswp-filters-widget-content input[type=search]:active, 
                        .sfswp-filters-widget-content input[type=tel]:active, 
                        .sfswp-filters-widget-content input[type=text]:active, 
                        .sfswp-filters-widget-content input[type=url]:active,
                        .sfswp-filter-collapsible .sfswp-filter-title button:hover .sfswp-open-icon, 
                        .sfswp-filter-collapsible-reverse.sfswp-filter-collapsible.sfswp-closed .sfswp-filter-title button:hover .sfswp-open-icon, 
                        .sfswp-filter-collapsible.sfswp-closed .sfswp-filter-title button:hover .sfswp-open-icon, 
                        .sfswp-filter-has-selected.sfswp-closed .sfswp-filter-title button:hover .sfswp-open-icon{
                            border-color: '.$color.';
                        }
                       
                        .sfswp-filters-main-wrap a.sfswp-toggle-a:hover,
                        .sfswp-help-tip:hover::after{
                            color: '.$color.';
                        }
                        .sfswp-sorting-form .select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple, 
                        .sfswp-filter-layout-dropdown .select2-container--default.select2-container--open.select2-container--above .select2-selection--single,
                        .sfswp-sorting-form .select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple, 
                        .sfswp-filter-layout-dropdown .select2-container--default.select2-container--open.select2-container--above .select2-selection--single{
                            border-top: 1px solid transparent;
                        }
                        .sfswp-search-field-wrapper .sfswp-search-clear-icon-wrapper, 
                        .sfswp-filter-search-wrapper button.sfswp-search-clear{
                            color: #b8bcc8;
                        }
                        .sfswp-filters-main-wrap .sfswp-filters-labels li.sfswp-term-item label {
                            border-color: #ccd0dc;
                        }
                        .sfswp-filters-main-wrap .sfswp-filters-labels li.sfswp-term-item label span.sfswp-filter-label-wrapper{
                            padding: 8px 7px;
                        }
                        .sfswp-filters-labels li.sfswp-term-has-image label:hover .sfswp-term-image-wrapper, 
                        .sfswp-filters-labels li.sfswp-term-has-image input[type=checkbox]:checked + label .sfswp-term-image-wrapper{
                            border-color: '.$color.';
                        }
                        @media screen and (min-width: '.$sfswp_mobile_width.'px) {
                            .sfswp-filters-main-wrap input[type=radio]:hover,
                            .sfswp-filters-main-wrap input[type=checkbox]:hover{
                                border-color: '.$styled_color.';
                            }
                            .sfswp-filters-main-wrap .sfswp-term-count-0:not(.sfswp-has-not-empty-children) input[type=radio]:hover,
                            .sfswp-filters-main-wrap .sfswp-term-count-0:not(.sfswp-has-not-empty-children) input[type=checkbox]:hover{
                                border-color: #c3c3c3;
                            }
                        }';
        }

        if( $use_select2 ){
            $styled_color   = $color ? $color : '#0570e2';
            $contrastColor  = $contrastColor ? $contrastColor : sfs_get_contrast_color($styled_color);

            $css .= '.sfswp-sorting-form select,
                        .sfswp-filter-content select{
                            padding: 2px 8px 2px 10px;
                            border-color: #c9d1e0;
                            border-radius: 3px;
                            color: inherit;
                            -webkit-appearance: none;
                        }
                        .select2-container--default .sfswp-search-filter-sort-dropdown .select2-results__option--highlighted[aria-selected],
                        .select2-container--default .sfswp-search-filter-sort-dropdown .select2-results__option--highlighted[data-selected]{
                            background-color: rgba(0,0,0,0.05); 
                            color: inherit;
                        }
                        ';
            $css .= '@media screen and (max-width: '.$sfswp_mobile_width.'px) {'."\r\n";
            $css .=  '.sfswp-sorting-form select,
                        .sfswp-filter-content select{
                            padding: 6px 12px 6px 14px;
                        }';

            $css .= '}'."\r\n";
        }

        if( $move_to_top ){
            $css .= '@media screen and (max-width: '.$sfswp_mobile_width.'px) {'."\r\n";

            $css .= 'body #main,
                        body #content .col-full,
                        .woocommerce-page .content-has-sidebar,
                        .woocommerce-page .has-one-sidebar,
                        .woocommerce-page #main-sidebar-container,
                        .woocommerce-page .theme-page-wrapper,
                        .woocommerce-page #content-area,
                        .theme-jevelin.woocommerce-page .woocomerce-styling,
                        .woocommerce-page .content_wrapper,
                        .woocommerce-page #col-mask,
                        body #main-content .content-area {
                            -js-display: flex;
                            display: -webkit-box;
                            display: -webkit-flex;
                            display: -moz-box;
                            display: -ms-flexbox;
                            display: flex;
                            -webkit-box-orient: vertical;
                            -moz-box-orient: vertical;
                            -webkit-flex-direction: column;
                            -ms-flex-direction: column;
                            flex-direction: column;
                        }
                        body #primary,
                        .woocommerce-page .has-one-sidebar > section,
                        .woocommerce-page .theme-content,
                        .woocommerce-page #left-area,
                        .woocommerce-page #content,
                        .woocommerce-page .sections_group,
                        .woocommerce-page .content-box,
                        body #main-sidebar-container #main {
                            -webkit-box-ordinal-group: 2;
                            -moz-box-ordinal-group: 2;
                            -ms-flex-order: 2;
                            -webkit-order: 2;
                            order: 2;
                        }
                        body #secondary,
                        .woocommerce-page .has-one-sidebar > aside,
                        body aside#mk-sidebar,
                        .woocommerce-page #sidebar,
                        .woocommerce-page .sidebar,
                        body #main-sidebar-container #sidebar {
                            -webkit-box-ordinal-group: 1;
                            -moz-box-ordinal-group: 1;
                            -ms-flex-order: 1;
                            -webkit-order: 1;
                            order: 1;
                        }
                    
                        /*second method first method solve issue theme specific*/
                        .woocommerce-page:not(.single,.page) .btWithSidebar.btSidebarLeft .btContentHolder,
                        body .theme-generatepress.woocommerce #content {
                            display: table;
                        }
                        body .btContent,
                        body .theme-generatepress.woocommerce #primary {
                            display: table-footer-group;
                        }
                        body .btSidebar,
                        body .theme-generatepress.woocommerce #left-sidebar {
                            display: table-header-group;
                        }'."\r\n";
                        $css .= '#ui-datepicker-div.sfswp-filter-datepicker .ui-datepicker-close.ui-state-default{
                            background: '.$color.';
                            color: '.$contrastColor.';
                        }'."\r\n";
                        $css .= '.sfswp-filters-date-range-column{
                            justify-content: left;
                        }'."\r\n";
            $css .= '}'."\r\n";
        }

        if( $use_loader ){
            $css .= '@media screen and (min-width: '.$sfswp_mobile_width.'px) {'."\r\n";
            $css .= 'html.is-active .sfswp-spinner{
                                display: block;
                            }';
            $css .= '}'."\r\n";
        }

        if( $dark_overlay ){
            $css .= '@media screen and (min-width: '.$sfswp_mobile_width.'px) {'."\r\n";
            $css .= 'html.is-active .sfswp-filters-overlay{
                            opacity: .15;
                            background: #000000;
                        }';
            $css .= '}'."\r\n";
        }

        if( $custom_css ){
            $css .= $custom_css."\r\n";
        }

        $wp_upload_dir = wp_upload_dir();
        $upload_dir_baseurl = $wp_upload_dir['baseurl'];
        $upload_dir_basepath = $wp_upload_dir['basedir'];

        $cache_dir = $upload_dir_basepath . '/cache/search-filter-sort/';

        if ( ! file_exists( $cache_dir ) ) {
            mkdir($cache_dir, 0777, true);
            chmod($cache_dir, 0777);
        }

        $filename = md5( $css ) . '.css';

        $fileurl  = $upload_dir_baseurl .'/cache/search-filter-sort/' . $filename;
        $filepath = $cache_dir . $filename;

        if ( $css !== '' ) {
            if ( ! file_exists( $filepath ) ) {
                file_put_contents( $filepath, $css );
            }

            if( file_exists( $filepath ) ){
                wp_enqueue_style('sfswp-search-filter-sort-custom', $fileurl );
            }
        }

    }

    public function bodyClass( $classes )
    {
        if( sfs_get_option('mobile_filter_settings') === 'show_open_close_button' ){
            $classes[] = 'sfswp_show_open_close_button';
        }

        if( sfs_is_filter_request() ){
            $classes[] = 'sfswp_is_filter_request';
        }

        return $classes;
    }

    public static function activate()
    {
        if ( ! get_option('sfswp_filter_settings') ) {
            $default_show_terms_in_content  = [];
            $theme_dependencies             = sfs_get_theme_dependencies();

            if( sfs_is_woocommerce() ){
                $default_show_terms_in_content = ['woocommerce_no_products_found', 'woocommerce_archive_description'];
            }

            if ( isset( $theme_dependencies['chips_hook'] ) && is_array( $theme_dependencies['chips_hook'] ) ) {
                foreach ( $theme_dependencies['chips_hook'] as $compat_chips_hook ) {
                    $default_show_terms_in_content[] = $compat_chips_hook;
                }
            }

            $defaultOptions = array(
                'primary_color'              => '#0570e2',
                'container_height'           => '550',
                'mobile_filter_settings'     => 'nothing',
                'show_terms_in_content'      => $default_show_terms_in_content,
                'widget_debug_messages'      => 'on'
            );

            add_option('sfswp_filter_settings', $defaultOptions );
        }

        if( ! get_option( 'sfswp_filter_experimental' ) ){

            $defaultExperimentalOptions = array(
                'use_loader'        => 'on',
                'use_wait_cursor'   => 'on',
                'dark_overlay'      => 'on',
                'auto_scroll'       => '',
                'styled_inputs'     => '',
                'select2_dropdowns' => '',
            );

            add_option('sfswp_filter_experimental', $defaultExperimentalOptions );
        }
    }

    /**
     * Clears all plugin data: options and posts
     */
    public static function uninstall( $force = false )
    {
        $allow_to_delete = true;

        if( is_multisite() ){
            $active_plugins = get_site_option('active_sitewide_plugins');
            if( is_array( $active_plugins ) ){
                $active_plugins = array_keys( $active_plugins );
            }
        }else{
            $active_plugins = apply_filters('active_plugins', get_option('active_plugins'));
        }

        $fe_active    = [];
        $to_compare   = [
            'search-filter-sort-pro/search-filter-sort.php',
            'search-filter-sort/search-filter-sort.php'
        ];

        if( ! empty( $active_plugins ) ){
            foreach ( $active_plugins as $plugin_path ){
                if( in_array( $plugin_path, $to_compare ) ){
                    $fe_active[] = $plugin_path;
                }
            }
        }

        if( count( $fe_active ) > 0 ){
            $allow_to_delete = false;
        }

        if ( $force == true ) {
            $allow_to_delete = true;
        }

        if( $allow_to_delete ){

            $options = [
                'sfswp_filter_settings',
                'sfswp_indexing_deep_settings',
                'sfswp_filter_permalinks',
                'sfswp_seo_rules_settings',
                'sfswp_filter_experimental',
                'widget_sfswp_filters_widget',
                'widget_sfswp_sorting_widget',
                'widget_sfswp_chips_widget',
            ];

            foreach ( $options as $option_name ){
                delete_option( $option_name );
            }

            // Deactivate and erase license if exists
            if ( defined( 'SFS_FILTERS_PRO' ) && SFS_FILTERS_PRO ) {
                $to_send             = false;
                $saved_value         = get_option( SFS_LICENSE_KEY );

                if( isset( $saved_value['license_key'] ) ) {
                    $saved_value_arr = maybe_unserialize( base64_decode( $saved_value['license_key'] ) );
                    $to_send         = $saved_value_arr;
                }

                if ( is_array( $to_send ) ){
                    $to_send['home_url'] = home_url();

                    // Make data suitable to send as GET variables
                    $to_send = array_map( 'urlencode', $to_send );

                    if ( isset( $saved_value_arr['id'] ) && $saved_value_arr['id'] ) {
                        $apiRequest = new ApiRequests();
                        $result     = $apiRequest->sendRequest('DELETE', 'license', $to_send );

                        // If license was deactivated, we have to refresh updates info
                        delete_transient(SFS_VERSION_TRANSIENT );
                        delete_option( SFS_LICENSE_KEY );
                    }
                }

            }

            $postTypes = array(
                SFS_FILTERS_SET_POST_TYPE,
                SFS_FILTERS_POST_TYPE
            );

            if( defined( 'SFS_SEO_RULES_POST_TYPE' ) ){
                $postTypes[] = SFS_SEO_RULES_POST_TYPE;
            }

            $filterPosts = new \WP_Query(
                array(
                    'posts_per_page' => -1,
                    'post_status' => array('any'),
                    'post_type' => $postTypes,
                    'fields' => 'ids',
                    'suppress_filters' => true
                )
            );

            $filterPostsIds = $filterPosts->get_posts();

            if( ! empty( $filterPostsIds ) ){
                foreach ($filterPostsIds as $post_id) {
                    wp_delete_post( $post_id, true );
                }
            }

        }
    }

    public static function switchTheme() {
        sfs_remove_option('posts_container');
        sfs_remove_option('primary_color');
    }

    public function includeAdminCss()
    {
        $screen = get_current_screen();
        if ( ! is_null( $screen ) && property_exists( $screen, 'base' ) ) {
            $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
            $ver    = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? rand(0, 1000) : SFS_PLUGIN_VER;

            if ( in_array( $screen->base, [ 'edit', 'post', 'edit-tags', 'term' ] ) || ( strpos( $screen->base, 'sfs-settings' ) !== false ) ) {
                wp_enqueue_style( 'sfswp-search-filter-sort-admin', SFS_PLUGIN_DIR_URL . 'assets/css/search-filter-sort-admin'.$suffix.'.css', ['wp-color-picker'], $ver );

                wp_enqueue_style('sfswp-widgets-sorting', SFS_PLUGIN_DIR_URL . 'assets/css/sfswp-widgets' . $suffix . '.css', [], $ver );
            }

            if ( $screen && ( strpos( $screen->base, 'searchfiltersort_page_sfs-' ) !== false || $screen->post_type === 'sfs-set' ) ) {
                wp_enqueue_style( 'sfswp-search-filter-sort-admin-header-settings', SFS_PLUGIN_DIR_URL . 'assets/css/search-filter-sort-admin-header-settings'.$suffix.'.css', ['wp-color-picker'], $ver );
            }

            if ( $screen->base === 'widgets' ) {
                wp_enqueue_style('sfswp-widgets', SFS_PLUGIN_DIR_URL . 'assets/css/sfswp-widgets' . $suffix . '.css', [], $ver );
            }

            wp_add_inline_style(
                'wp-admin',
                '#toplevel_page_edit-post_type-sfs-set .wp-menu-image img {
                    width: 20px;
                    height: auto;
                    filter: brightness(100);
                }
                #toplevel_page_edit-post_type-sfs-set:hover .wp-menu-image img {
                    filter: unset;
                }
                #toplevel_page_edit-post_type-sfs-set.wp-has-current-submenu .wp-menu-image img {
                    filter: brightness(100) !important;
                }'
            );

        }
    }

    public function includeAdminJs()
    {
        $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
        $ver    = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? rand(0, 1000) : SFS_PLUGIN_VER;
        $select2ver = '4.1.0';

        wp_register_script( 'jquery-tiptip', SFS_PLUGIN_DIR_URL . 'assets/js/jquery-tiptip/jquery.tipTip' . $suffix . '.js', array( 'jquery' ), $ver, true );
        wp_enqueue_script('jquery-tiptip');

        wp_enqueue_script('sfswp-filters-admin', SFS_PLUGIN_DIR_URL . 'assets/js/sfswp-filters-common-admin' . $suffix . '.js', array( 'jquery', 'jquery-ui-sortable', 'wp-color-picker', 'select2' ), $ver, true );

        $l10n = array(
            'prefixesOrderAvailableInPro' => esc_html__( 'Editing the order of URL prefixes is available in the PRO version', 'searchfiltersort' ),
            'chipsPlaceholder'            => esc_html__( 'Select or enter hooks', 'searchfiltersort' ),
            'colorSwatchesPlaceholder'    => esc_html__( 'Click to select taxonomies', 'searchfiltersort' ),
        );
        wp_localize_script( 'sfswp-filters-admin', 'sfswpFiltersAdminCommon', $l10n );

        wp_enqueue_script( 'select2', SFS_PLUGIN_DIR_URL . "assets/js/select2/select2".$suffix.".js", array('jquery'), $select2ver );
        wp_enqueue_style('select2', SFS_PLUGIN_DIR_URL . "assets/css/select2/select2".$suffix.".css", '', $select2ver );

        $screen = get_current_screen();

        if( ! is_null( $screen ) && property_exists( $screen, 'base' ) && $screen->base === 'widgets' ){
            wp_enqueue_script('sfswp-widgets', SFS_PLUGIN_DIR_URL . 'assets/js/sfswp-widgets' . $suffix . '.js', array('jquery'), $ver );
            $l10n = array(
                'sfswpItemNum'  => esc_html__( 'Item #', 'searchfiltersort')
            );
            wp_localize_script( 'sfswp-widgets', 'sfswpWidgets', $l10n );
        }
        
        if ( $screen && ( strpos( $screen->base, 'searchfiltersort_page_sfs-' ) !== false || $screen->post_type === 'sfs-set' ) ) {
            wp_enqueue_script(
                'sfswp-search-filter-sort-admin-header-settings',
                esc_url( SFS_PLUGIN_DIR_URL . 'assets/js/sfswp-search-filter-sort-admin-header-settings' . $suffix . '.js' ),
                array( 'jquery' ),
                $ver
            );

            wp_localize_script(
                'sfswp-search-filter-sort-admin-header-settings',
                'admin_ajax_object',
                array(
                    'ajaxurl' => esc_url( admin_url( 'admin-ajax.php' ) ),
                )
            );
        }
    }

    public function includeFrontCss()
    {
        $suffix = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min';
        $ver = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? rand(0, 1000) : SFS_PLUGIN_VER;
        /**
         * string
         */
        $getData  = Container::instance()->getTheGet();
        if( isset( $getData[SFS_BEAVER_BUILDER_VAR] ) ){
            wp_enqueue_style('sfswp-widgets', SFS_PLUGIN_DIR_URL . 'assets/css/sfswp-widgets' . $suffix . '.css', [], $ver );
        }

        // Do not include plugin CSS if there are no SFS Sets on the page
        $sets = $this->wpManager->getQueryVar('sfswp_page_related_set_ids', []);
        if( empty( $sets ) ) {
            return false;
        }

        wp_enqueue_style('sfswp-search-filter-sort', SFS_PLUGIN_DIR_URL . 'assets/css/search-filter-sort' . $suffix . '.css', [], $ver);
    }

    public function footerHtml()
    {
        echo '<div class="sfswp-filters-overlay"></div>'."\r\n";
    }

    public function includeFrontJs()
    {
        $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
        $ver    = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? rand(0, 1000) : SFS_PLUGIN_VER;
        /**
         * string
         */
        $getData  = Container::instance()->getTheGet();
        $em       = Container::instance()->getEntityManager();

        $sfswpFrontJsVariables = [];

        if( isset( $getData[SFS_BEAVER_BUILDER_VAR] ) ){
            wp_enqueue_script('sfswp-widgets', SFS_PLUGIN_DIR_URL . 'assets/js/sfswp-widgets' . $suffix . '.js', array('jquery'), $ver );
            $l10n = array(
                'sfswpItemNum'  => esc_html__( 'Item #', 'searchfiltersort' )
            );
            wp_localize_script( 'sfswp-widgets', 'sfswpWidgets', $l10n );
        }

        // Do not include plugin JS if there are no SFS Sets on the page
        $sets               = $this->wpManager->getQueryVar( 'sfswp_page_related_set_ids', [] );
        $related_filters = $em->getSetsRelatedFilters( $sets );
        $date_filters       = [];
        $include_timepicker = false;

        if ( ! empty( $related_filters ) ) {
            foreach ( $related_filters as $filter ) {
                if ( in_array( $filter['entity'], [ 'post_date', 'post_meta_date' ] ) ) {

                    $date_time = sfs_split_date_time( $filter['date_format'] );

                    global $wp_locale;
                    $date_filters[ $filter['ID'] ] = [
                        'date_type'     => $filter['date_type'],
                        'date_format'   => sfs_convert_date_to_js( $date_time['date'] ),
                        'time_format'   => sfs_convert_time_to_js( $date_time['time'] ),
                    ];

                    if ( in_array( $filter['date_type'], [ 'time', 'datetime' ] ) ) {
                        $include_timepicker = true;
                    }

                }
            }
        }

        /**
         * Do not continue and do not include any assets
         * if this page does not contain SFS Sets
         */
        if ( empty( $sets ) ) {
            return false;
        }

        $showBottomWidget   = 'no';
        $ajaxEnabled        = false;
        $autoScroll         = false;
        $waitCursor         = false;
        $sfswpUseSelect2      = false;
        $sfswpPopupCompatMode = false;
        $autoScrollOffset   = apply_filters( 'sfswp_auto_scroll_offset', 150 );
        $sfswp_mobile_width   = sfs_get_mobile_width();
        $per_page           = [];
        $applyButtonSets    = [];
        $queryOnThePageSets = [];
        $filterSetService   = Container::instance()->getSFSSetService();

        if ( sfs_get_option('mobile_filter_settings') === 'show_bottom_widget' ) {
            $showBottomWidget = 'yes';
        }

        if ( sfs_get_option('enable_ajax') === 'on' ) {
            $ajaxEnabled = true;
        }

        if ( sfs_get_experimental_option('auto_scroll') === 'on' ) {
            $autoScroll = true;
        }

        if ( sfs_get_experimental_option( 'use_wait_cursor' ) === 'on' ) {
            $waitCursor = true;
        }

        if ( sfs_get_option('bottom_widget_compatibility') ) {
            $sfswpPopupCompatMode = true;
        }

        //@todo This appears on login page and produce not an array error
        foreach( $sets as $set ){
            if( $set['filtered_post_type'] === 'product' && function_exists('wc_get_default_products_per_row') ){
                $numberposts = apply_filters( 'loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page() );
            }else{
                $numberposts = get_option( 'posts_per_page' );
            }

            $per_page[ $set['ID'] ] = intval($numberposts);
            $theSet = $filterSetService->getSet( $set['ID'] );

            if( isset( $set['query_on_the_page'] ) && $set['query_on_the_page'] ){
                if( (int) $set['ID'] > 0 ) {
                    $queryOnThePageSets[] = (int) $set['ID'];
                }
            }

            if( isset( $theSet['use_apply_button']['value'] ) && $theSet['use_apply_button']['value'] === 'yes' ){
                if( (int) $set['ID'] > 0 ){
                    $applyButtonSets[] = (int) $set['ID'];
                }
            }
        }

        $per_page = apply_filters( 'sfswp_filter_sets_posts_per_page', $per_page );

        $sfswpPostContainers = apply_filters( 'sfswp_posts_containers', sfs_get_option( 'posts_container', sfs_default_posts_container() ) );

        wp_register_script( 'wc-jquery-ui-touchpunch', SFS_PLUGIN_DIR_URL . 'assets/js/jquery-ui-touch-punch/jquery-ui-touch-punch'.$suffix.'.js', [], $ver, true );

        $sfswpFrontJsVariables = array(
            'ajaxUrl'                    => admin_url('admin-ajax.php'),
            'sfswpAjaxEnabled'             => $ajaxEnabled,
            'sfswpStatusCookieName'        => SFS_FOLDING_COOKIE_NAME,
            'sfswpMoreLessCookieName'      => SFS_MORELESS_COOKIE_NAME,
            'sfswpHierarchyListCookieName' => SFS_HIERARCHY_LIST_COOKIE_NAME,
            'sfswpWidgetStatusCookieName'  => SFS_OPEN_CLOSE_BUTTON_COOKIE_NAME,
            'sfswpMobileWidth'             => $sfswp_mobile_width,
            'showBottomWidget'           => $showBottomWidget,
            '_nonce'                     => wp_create_nonce('sfswpNonceFront'),
            'sfswpPostContainers'          => $sfswpPostContainers,
            'sfswpAutoScroll'              => $autoScroll,
            'sfswpAutoScrollOffset'        => $autoScrollOffset,
            'sfswpWaitCursor'              => $waitCursor,
            'sfswpPostsPerPage'            => $per_page,
            'sfswpUseSelect2'              => $sfswpUseSelect2,
            'sfswpDateFilters'          => false,
            'sfswpPopupCompatMode'         => $sfswpPopupCompatMode,
            'sfswpApplyButtonSets'         => $applyButtonSets,
            'sfswpQueryOnThePageSets'      => $queryOnThePageSets,
            'sfswpNoPostsContainerMsg'     => esc_html__('It appears that this page does not contain a container with the specified «HTML id or class of the Posts Container». Try to specify the correct one in the SFS Set settings or the common plugin Settings.', 'searchfiltersort'),
        );

        /**
         * We includes Flatpickr.js only on pages, where date filter is used.
         */
        if ( ! empty( $date_filters ) ) {

            wp_enqueue_script( 'jquery-ui-datepicker' );
            wp_enqueue_style( 'sfswp-datepicker', SFS_PLUGIN_DIR_URL . 'assets/css/datepicker/jquery-ui'.$suffix.'.css', array(), '1.11.4' );

            if ( $include_timepicker ) {
                wp_enqueue_script( 'sfswp-timepicker', SFS_PLUGIN_DIR_URL . "assets/js/timepicker/jquery-ui-timepicker-addon".$suffix.".js", array( 'jquery-ui-datepicker' ), '1.6.3' );
                wp_enqueue_style( 'sfswp-timepicker', SFS_PLUGIN_DIR_URL . "assets/css/timepicker/jquery-ui-timepicker-addon".$suffix.".css", array(), '1.6.3' );
            }

            $sfswpFrontJsVariables['sfswpDateFilters'] = $date_filters;
            $sfswpFrontJsVariables['sfswpDateFiltersLocale'] = determine_locale();
            $sfswpFrontJsVariables['sfswpDateFiltersL10n'] = array(
                'closeText'       => _x( 'Filter', 'Date Picker closeText', 'searchfiltersort' ),
                'currentText'     => _x( 'Today', 'Date Picker currentText', 'searchfiltersort' ),
                'nextText'        => _x( 'Next', 'Date Picker nextText', 'searchfiltersort' ),
                'prevText'        => _x( 'Prev', 'Date Picker prevText', 'searchfiltersort' ),
                'weekHeader'      => _x( 'Wk', 'Date Picker weekHeader', 'searchfiltersort' ),
                'timeOnlyTitle'   => _x( 'Choose Time', 'Date Time Picker timeOnlyTitle', 'searchfiltersort' ),
                'timeText'        => _x( 'Time', 'Date Time Picker timeText', 'searchfiltersort' ),
                'hourText'        => _x( 'Hour', 'Date Time Picker hourText', 'searchfiltersort' ),
                'minuteText'      => _x( 'Minute', 'Date Time Picker minuteText', 'searchfiltersort' ),
                'secondText'      => _x( 'Second', 'Date Time Picker secondText', 'searchfiltersort' ),
                'timezoneText'    => _x( 'Time Zone', 'Date Time Picker timezoneText', 'searchfiltersort' ),
                'selectText'      => _x( 'Select', 'Date Time Picker selectText', 'searchfiltersort' ),
                'amNames'         => array(
                    _x( 'AM', 'Date Time Picker amText', 'searchfiltersort' ),
                    _x( 'A', 'Date Time Picker amTextShort', 'searchfiltersort' ),
                ),
                'pmNames'       => array(
                    _x( 'PM', 'Date Time Picker pmText', 'searchfiltersort' ),
                    _x( 'P', 'Date Time Picker pmTextShort', 'searchfiltersort' ),
                ),

                'monthNames'      => array_values( $wp_locale->month ),
                'monthNamesShort' => array_values( $wp_locale->month_abbrev ),
                'dayNames'        => array_values( $wp_locale->weekday ),
                'dayNamesMin'     => array_values( $wp_locale->weekday_initial ),
                'dayNamesShort'   => array_values( $wp_locale->weekday_abbrev ),
                'firstDay'        => get_option( 'start_of_week' ),
            );
        }

        /**
         * Include Main Front filters javascript
         */
        wp_enqueue_script('sfswp-search-filter-sort', SFS_PLUGIN_DIR_URL . 'assets/js/search-filter-sort'.$suffix.'.js', array('jquery', 'jquery-ui-slider', 'wc-jquery-ui-touchpunch'), $ver, true );

        if( sfs_get_experimental_option('select2_dropdowns') === 'on' ){
            $select2ver = '4.1.0';
            $sfswpUseSelect2 = 'yes';
            wp_enqueue_script( 'select2', SFS_PLUGIN_DIR_URL . "assets/js/select2/select2".$suffix.".js", array('jquery'), $select2ver );
            wp_enqueue_style('select2', SFS_PLUGIN_DIR_URL . "assets/css/select2/select2".$suffix.".css", '', $select2ver );
        }

        $sfswpFrontJsVariables['sfswpUseSelect2'] = $sfswpUseSelect2;

        wp_localize_script( 'sfswp-search-filter-sort', 'sfswpFilterFront', $sfswpFrontJsVariables );

        unset( $filterSetService, $sfswpFrontJsVariables );
    }

    public function removeApplyButtonOrderField( &$set_settings_fields )
    {
        unset( $set_settings_fields['apply_button_menu_order'], $set_settings_fields['search_field_menu_order'] );
    }

    public function handleSFSSetFieldsVisibility( $filterSetFields )
    {
        if( isset( $filterSetFields['use_apply_button']['value'] ) && $filterSetFields['use_apply_button']['value'] === 'yes' ) {
            $filterSetFields['apply_button_text']['additional_class'] = 'sfswp-opened';
            $filterSetFields['reset_button_text']['additional_class'] = 'sfswp-opened';
        }

        if ( isset( $filterSetFields['use_search_field']['value'] ) && $filterSetFields['use_search_field']['value'] === 'yes' ) {
            $filterSetFields['search_field_placeholder']['additional_class'] = 'sfswp-opened';
            $filterSetFields['search_field_label']['additional_class']       = 'sfswp-opened';
        }

        if ( isset( $filterSetFields['use_sort_option']['value'] ) && $filterSetFields['use_sort_option']['value'] === 'yes' ) {
            $filterSetFields['search_field_placeholder']['additional_class'] = 'sfswp-opened';
            $filterSetFields['search_field_label']['additional_class']       = 'sfswp-opened';
        }

        return $filterSetFields;
    }

    public function disableCacheProductsShortcode( $out )
    {
        $wpManager          = Container::instance()->getWpManager();
        $is_filter_request  = $wpManager->getQueryVar('sfswp_is_filter_request');
        $thePost            = Container::instance()->getThePost();
        $action             = isset( $thePost['action'] ) ? $thePost['action'] : false;

        // sfswp_get_wp_queries - action to get WP_Queries on a page
        if( isset( $out['cache'] ) && ( $is_filter_request || $action === 'sfswp_get_wp_queries' ) ){
            $out['cache'] = false;
        }

        return $out;
    }

    public function showCombinedFields( &$filter, $field_key )
    {
        $includeExclude = sfs_extract_vars( $filter, array('exclude', 'include') );
        if( $includeExclude ):

            ?><tr class="<?php echo esc_attr( sfs_filter_row_class( $includeExclude['exclude'] ) ); ?>"<?php sfs_maybe_hide_row( $includeExclude['exclude'] ); ?>><?php

            sfs_include_admin_view('sfs-field-label', array(
                    'field_key'  => 'exclude',
                    'attributes' => $includeExclude['exclude']
                )
            );
            ?>
            <td class="sfswp-sfs-field-td sfswp-sfs-field-include-exclude-td">
                <div class="sfswp-sfs-field-include-exclude-wrap">
                    <div class="sfswp-field-wrap sfswp-field-exclude-wrap <?php if( isset( $includeExclude['exclude']['id'] ) ){ echo esc_attr( $includeExclude['exclude']['id'] ); } ?>-wrap">
                        <?php echo sfs_render_input( $includeExclude['exclude'] ); // Already escaped in function ?>
                        <?php do_action('sfswp_after_filter_input', $includeExclude['exclude'] ); ?>
                    </div>
                    <div class="sfswp-field-wrap sfswp-field-include-wrap <?php if( isset( $includeExclude['include']['id'] ) ){ echo esc_attr( $includeExclude['include']['id'] ); } ?>-wrap">
                        <?php echo sfs_render_input( $includeExclude['include'] ); // Already escaped in function ?>
                        <?php do_action('sfswp_after_filter_input', $includeExclude['include'] ); ?>
                    </div>
                </div>
            </td>
            </tr><?php

        endif;

        if ( $field_key === 'min_num_label' ) {
            $min_max_num_labels = sfs_extract_vars( $filter, array( 'min_num_label', 'max_num_label' ) );

            if( $min_max_num_labels ) :
                $min_field_id = $max_field_id = '';

                if (isset($min_max_num_labels['min_num_label']['id'])) {
                    $min_field_id = esc_attr($min_max_num_labels['min_num_label']['id']);
                }
                if( isset( $min_max_num_labels['max_num_label']['id'] ) ){
                    $max_field_id =  esc_attr( $min_max_num_labels['max_num_label']['id'] );
                }

                if( isset($min_max_num_labels['min_num_label']['value']) ){
                    $min_max_num_labels['min_num_label']['data-caret'] = mb_strlen( $min_max_num_labels['min_num_label']['value'] ) + 1;
                }

                if( isset($min_max_num_labels['max_num_label']['value']) ){
                    $min_max_num_labels['max_num_label']['data-caret'] = mb_strlen( $min_max_num_labels['max_num_label']['value'] ) + 1;
                }

                ?><tr class="<?php echo esc_attr( sfs_filter_row_class( $min_max_num_labels['min_num_label'] ) ); ?>"<?php sfs_maybe_hide_row( $min_max_num_labels['min_num_label'] ); ?>><?php

                sfs_include_admin_view('sfs-field-label', array(
                        'field_key'  => 'min_num_label',
                        'attributes' => $min_max_num_labels['min_num_label']
                    )
                );
                ?>
                <td class="sfswp-sfs-field-td sfswp-sfs-field-min-max-labels-td">
                    <div class="sfswp-sfs-field-min-max-labels-wrap">
                        <div class="sfswp-field-wrap sfswp-field-min_num_label-wrap <?php echo $min_field_id; ?>-wrap">
                            <?php echo sfs_render_input( $min_max_num_labels['min_num_label'] ); // Already escaped in function ?>
                            <?php do_action('sfswp_after_filter_input', $min_max_num_labels['min_num_label'] ); ?>
                        </div>
                        <div class="sfswp-field-wrap sfswp-field-max_num_label-wrap <?php echo $max_field_id; ?>-wrap">
                            <?php echo sfs_render_input( $min_max_num_labels['max_num_label'] ); // Already escaped in function ?>
                            <?php do_action('sfswp_after_filter_input', $min_max_num_labels['max_num_label'] ); ?>
                        </div>
                        <p class="description"><?php echo wp_kses(
                                sprintf( __('For example, "Price from <span class="sfswp-variable-inserter" data-field="%s" title="Click to insert the variable">{value}</span> $" will be displayed as "Price from 150 $"', 'searchfiltersort'), $min_field_id ),
                                array( 'span' => array(
                                        'class' => true,
                                        'data-field' => true,
                                        'title' => true,
                                ) )
                            ) ?></p>
                    </div>
                </td>
                </tr><?php

            endif;
        }
    }

    public function addSearchArgsToWpQuery( $wp_query )
    {
        if ( isset( $_GET['srch'] ) && $_GET['srch']  ) {
            $keyword = filter_input( INPUT_GET, 'srch', FILTER_DEFAULT );
            $wp_query->set( 's', $keyword );
        }

        return $wp_query;
    }

    public function addSkuSearchSql( $search, $wp_query )
    {
        if( $wp_query->get('sfs_query_hash') || $wp_query->get('sfs_query_clone') ){

            if ( $wp_query->get('wc_query') === 'product_query' || $wp_query->get('post_type') === 'product' /* || $wp_query->get('post_type') === 'product_variation' */ ) {
                global $wpdb;

                $product_id = wc_get_product_id_by_sku( $wp_query->get('s') );
                if ( ! $product_id ) {
                    return $search;
                }

                $product = wc_get_product( $product_id );
                if ( $product->is_type( 'variation' ) ) {
                    $product_id = $product->get_parent_id();
                }

                $search = str_replace( 'AND (((', "AND (({$wpdb->posts}.ID IN (" . $product_id . ")) OR ((", $search );
                return $search;
            }

        }
        return $search;
    }

    public function postDateWhere( $where, $wp_query )
    {   global $wpdb;
        $sql = [];
        $operator = '';
        $sfswp_date_query = $wp_query->get( 'sfswp_date_query' );

        if( ! empty( $sfswp_date_query ) && is_array( $sfswp_date_query ) ) {
                foreach ( $sfswp_date_query as $edge => $value ) {
                    if( $edge === 'from' ) {
                        $operator = '>=';
                    } elseif ( $edge === 'to' ) {
                        $operator = '<=';
                    }

                    $sql[] = $wpdb->prepare( "AND {$wpdb->posts}.post_date {$operator} %s ", $value );

                }

                $where = implode( ' ', $sql ) . $where;
        }

        return $where;
    }
    /**
     * Handles AJAX request to install and activate a WordPress.org plugin.
    */
    public static function sfs_install_and_activate_plugin() {

        if (!current_user_can('install_plugins')) {
            wp_send_json_error('Permission denied.');
        }

        $plugin_slug = isset($_POST['plugin_slug']) ? sanitize_text_field($_POST['plugin_slug']) : '';

        if ( empty($plugin_slug) ) {
            wp_send_json_error('Plugin slug missing.');
        }

        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        include_once ABSPATH . 'wp-admin/includes/plugin.php';
        include_once ABSPATH . 'wp-admin/includes/file.php';
        include_once ABSPATH . 'wp-admin/includes/misc.php';
        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';

        if(!isset($_POST['plugin_active']) || $_POST['plugin_active'] != true)
        {
            $upgrader = new \Plugin_Upgrader(new \Plugin_Installer_Skin());
            $result = $upgrader->install("https://downloads.wordpress.org/plugin/{$plugin_slug}.latest-stable.zip");
        
            if (is_wp_error($result)) {
                wp_send_json_error('Plugin installation failed: ' . $result->get_error_message());
            }
        }
        // You might need to dynamically get the correct plugin file.
        $plugins = get_plugins("/{$plugin_slug}");
        if (empty($plugins)) {
            wp_send_json_error('Could not find installed plugin.');
        }

        // Get the first plugin file found
        $plugin_file = key($plugins);

        $activation = activate_plugin("{$plugin_slug}/{$plugin_file}");

        if (is_wp_error($activation)) {
            wp_send_json_error('Activation failed: ' . $activation->get_error_message());
        }

        wp_send_json_success('Plugin installed and activated successfully!');
    }
}