<?php

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

use \SearchFilterSort\Filter\PostDateEntity;

// Make post type name lowercase in posts found message
add_filter( 'sfswp_label_singular_posts_found_msg', 'mb_strtolower' );
add_filter( 'sfswp_label_plural_posts_found_msg', 'mb_strtolower' );

add_action( 'init', 'sfs_initiate_overridden_functions' );
function sfs_initiate_overridden_functions()
{
// All hooks with function wrapper with function_exists()
    add_filter('sfswp_filter_post_meta_num_term_name', 'sfs_ucfirst_term_slug_name');
    add_filter('sfswp_filter_post_meta_term_name', 'sfs_ucfirst_term_slug_name');
    add_filter('sfswp_filter_tax_numeric_term_name', 'sfs_ucfirst_term_slug_name');
    add_filter('sfswp_filter_post_meta_exists_term_name', 'sfs_custom_field_exists_name');
    add_filter('sfswp_filter_post_meta_term_name', 'sfs_stock_status_term_name', 10, 2);
    add_filter('sfswp_filter_post_meta_exists_term_name', 'sfs_on_sale_term_name', 15, 2);
    add_filter('sfswp_filter_taxonomy_term_name', 'sfs_modify_taxonomy_term_name', 10, 2);
    add_filter('sfswp_filter_term_query_args', 'sfs_exclude_uncategorized_category', 10, 3);
    add_filter('sfswp_filter_get_taxonomy_terms', 'sfs_exclude_product_visibility_terms', 10, 2);
    add_filter('sfswp_filter_author_query_post_types', 'sfs_remove_author_query_post_types');
    add_filter('sfswp_filter_post_types', 'sfs_exclude_post_types');
    add_action('sfswp_after_filter_input', 'sfs_after_filter_input');
    add_filter('sfswp_filters_checkbox_term_html', 'sfswp_term_brand_logo', 5, 4);
    add_filter('sfswp_filters_radio_term_html', 'sfswp_term_brand_logo', 5, 4);
    add_filter('sfswp_filters_label_term_html', 'sfswp_term_brand_logo', 5, 4);
    add_filter('sfswp_taxonomy_location_terms', 'sfs_remove_default_category_location', 10, 2);
    add_filter( 'sfswp_set_num_shift', 'sfs_round_numeric_values', 10, 3 );

    if (!function_exists('sfs_ucfirst_term_slug_name')) {
        function sfs_ucfirst_term_slug_name($term_name)
        {
            $term_name = sfs_ucfirst($term_name);
            return $term_name;
        }
    }


    if (!function_exists('sfs_custom_field_exists_name')) {
        function sfs_custom_field_exists_name($term_name)
        {
            if ($term_name === 'yes') {
                return esc_html__('Yes', 'searchfiltersort');
            } else if ($term_name === 'no') {
                return esc_html__('No', 'searchfiltersort');
            }
            return $term_name;
        }
    }

    if (!function_exists('sfs_stock_status_term_name')) {
        function sfs_stock_status_term_name($term_name, $e_name)
        {
            if ($e_name === '_stock_status') {
                $term_name = strtolower($term_name);
                if ($term_name === "instock") {
                    $term_name = esc_html__('In stock', 'searchfiltersort');
                }

                if ($term_name === "onbackorder") {
                    $term_name = esc_html__('On backorder', 'searchfiltersort');
                }

                if ($term_name === "outofstock") {
                    $term_name = esc_html__('Out of stock', 'searchfiltersort');
                }
            }

            return $term_name;
        }
    }

    if (!function_exists('sfs_on_sale_term_name')) {
        function sfs_on_sale_term_name($term_name, $entity)
        {
            if ($entity === '_sale_price') {
                $check_name = mb_strtolower($term_name);

                if (in_array($check_name, ['yes', 'ja', 'ano', 'sí', 'так'])) {
                    $term_name = esc_html__('On Sale', 'searchfiltersort');
                }
                if (in_array($check_name, ['no', 'nein', 'ne', 'ні'])) {
                    $term_name = esc_html__('Regular price', 'searchfiltersort');
                }
            }
            return $term_name;
        }
    }


    if (!function_exists('sfs_modify_taxonomy_term_name')) {
        function sfs_modify_taxonomy_term_name($term_name, $e_name)
        {
            if (in_array($e_name, array('product_type', 'product_visibility'))) {
                $term_name = sfs_ucfirst($term_name);
            }
            return $term_name;
        }
    }


    if (!function_exists('sfs_exclude_uncategorized_category')) {
        function sfs_exclude_uncategorized_category($args, $entity, $e_name)
        {
            if ($e_name === 'category') {
                $args['exclude'] = array(1); // Uncategorized category
            }

            return $args;
        }
    }


    if (!function_exists('sfs_exclude_product_visibility_terms')) {
        function sfs_exclude_product_visibility_terms($terms, $e_name)
        {
            if ($e_name === 'product_visibility') {
                if (is_array($terms)) {
                    foreach ($terms as $index => $term) {

                        if (in_array($term->slug, array('exclude-from-search', 'exclude-from-catalog'))) {
                            unset($terms[$index]);
                        }
                    }
                }
            }

            if ($e_name === 'product_cat') {
                if (is_array($terms)) {
                    foreach ($terms as $index => $term) {
                        if (in_array($term->slug, array('uncategorized'))) {
                            unset($terms[$index]);
                        }
                    }
                }
            }

            return $terms;
        }
    }

    if (!function_exists('sfs_remove_author_query_post_types')) {
        function sfs_remove_author_query_post_types($post_types)
        {
            if (isset($post_types['attachment'])) {
                unset($post_types['attachment']);
            }
            return $post_types;
        }
    }

    if (!function_exists('sfs_exclude_post_types')) {
        function sfs_exclude_post_types($post_types)
        {

            $post_types = array(
                SFS_FILTERS_POST_TYPE,
                SFS_FILTERS_SET_POST_TYPE,
                'attachment',
                'elementor_library',
                'e-landing-page',
                'jet-smart-filters',
                'ct_template'
            );

            return $post_types;
        }
    }


    if (!function_exists('sfs_after_filter_input')) {
        function sfs_after_filter_input($attributes)
        {
            if (isset($attributes['class']) && $attributes['class'] === 'sfswp-field-slug' && $attributes['value'] === '') {
                echo '<p class="description">' . esc_html__('a-z, 0-9, "_" and "-" symbols supported only', 'searchfiltersort') . '</p>';
            }

            if (isset($attributes['class']) && $attributes['class'] === 'sfswp-field-ename' && $attributes['value'] === '') {
                echo '<p class="description">' . esc_html__('Note: for ACF meta fields, please use names without the "_" character at the beginning', 'searchfiltersort') . '</p>';
            }

        }
    }

    if (!function_exists('sfswp_term_brand_logo')) {
        function sfswp_term_brand_logo($html, $link_attributes, $term, $filter)
        {
            if (!in_array($filter['e_name'], sfs_brand_filter_entities())) {
                return $html;
            }
            if (!isset($term->slug)) {
                return $html;
            }
            $src = sfs_get_term_brand_image($term->term_id, $filter);

            $link_attributes .= ' title="' . $term->name . '"';

            if ($src) {
                $img = '<span class="sfswp-term-image-wrapper"><img src="' . $src . '" alt="' . $term->name . '" /></span>';
                $html = '<a ' . $link_attributes . '>' . $img . '<span class="sfswp-term-name">' . $term->name . '</span></a>';
            }

            return $html;
        }
    }

    if( !function_exists( 'sfs_remove_default_category_location' ) ) {
        function sfs_remove_default_category_location( $terms, $taxonomy ){
            $default_category = 0;

            if ( $taxonomy === 'product_cat' ) {
                $default_category = get_option( 'default_product_cat' );
            } elseif( $taxonomy === 'category' ) {
                $default_category = get_option('default_category');
            }

            // Remove default category from the list
            if ( $default_category > 0 ) {
                unset( $terms[ $default_category ] );
            }

            return $terms;
        }
    }

    /**
     * Fix for the LiveCanvas page builder
     */
    if( defined( 'LC_MU_PLUGIN_NAME' ) && LC_MU_PLUGIN_NAME === 'livecanvas-must-use-plugin.php' ) {
        add_filter('sfswp_pre_save_set_fields', 'sfs_safe_save_set_fields');
        function sfs_safe_save_set_fields($setFields)
        {

            if (isset($setFields['wp_filter_query_vars'])) {
                $query_vars = $setFields['wp_filter_query_vars'];
                $new_query_vars = [];
                $search_values = [
                    '…'
                ];
                $replace_values = [
                    '&hellip;'
                ];

                foreach ($query_vars as $hash => $vars_serialized_str) {
                    $new_query_vars[$hash] = str_replace($search_values, $replace_values, $vars_serialized_str);
                }

                $setFields['wp_filter_query_vars'] = $new_query_vars;
            }

            return $setFields;
        }
    }

    function sfs_round_numeric_values( $value, $entity_name, $limit )
    {
        if( $limit === 'min' ) {
            $value = floor( $value );
        } elseif ( $limit === 'max' ){
            $value = ceil( $value );
        }

        return $value;
    }

}

function sfs_chips( $showReset = false, $setIds = [] ) {
    $templateManager    = \SearchFilterSort\Filter\Container::instance()->getTemplateManager();
    $wpManager          = \SearchFilterSort\Filter\Container::instance()->getWpManager();

    if( empty( $setIds ) || ! $setIds || ! is_array( $setIds ) ){
        foreach ( $wpManager->getQueryVar('sfswp_page_related_set_ids') as $set ){
            $setIds[] = $set['ID'];
        }
    }

    $chipsObj = new \SearchFilterSort\Filter\Chips( $showReset, $setIds );
    $chips = $chipsObj->getChips();

    $templateManager->includeFrontView( 'chips', array( 'chips' => $chips, 'setid' => reset($setIds) ) );

}

function sfs_show_selected_terms( $showReset = true, $setIds = [], $class = [] )
{
    $default_class  = array('sfswp-custom-selected-terms');

    if(! empty( $class ) && is_array($class) ){
        $default_class = array_merge( $default_class, $class );
    }

    echo '<div class="'.implode(' ', $default_class).'">'."\r\n";
        sfs_chips( $showReset, $setIds );
    echo '</div>'."\r\n";
}

add_filter( 'sfswp_dropdown_option_attr', 'sfs_parse_dropdown_value' );
function sfs_parse_dropdown_value( $attr ){
    if( ! is_array( $attr ) ){
        $new_attr = array();
        $new_attr['label'] = $attr;
        return $new_attr;
    }

    return $attr;
}

add_filter( 'sfswp_unnecessary_get_parameters', 'sfs_unnecessary_get_parameters' );
function sfs_unnecessary_get_parameters( $params ){
    $unnecessary_params = array(
        'product-page' => true,
        '_pjax' => true,
        'cst'   => true,
    );

    $get = \SearchFilterSort\Filter\Container::instance()->getTheGet();

    if( ! empty( $get ) && is_array( $get ) ) {
        foreach ( $get as $param_name => $param_value ) {
            if( preg_match( '%query\-[0-9]+\-page%', $param_name ) ) {
                $unnecessary_params[$param_name] = true;
            }

            if( preg_match( '%e\-page\-[a-zA-Z0-9]+%im', $param_name ) ) {
                $unnecessary_params[$param_name] = true;
            }
        }
    }

    return array_merge( $params, $unnecessary_params );
}

add_filter('sfswp_posts_containers', 'sfs_convert_posts_container_to_array');
function sfs_convert_posts_container_to_array( $container ){

    if( ! is_array( $container ) ){
        return [ 'default' => trim($container) ];
    }

    return $container;
}

add_filter( 'sfswp_seo_title', 'do_shortcode' );
add_filter( 'sfswp_seo_description', 'do_shortcode' );
add_filter( 'sfswp_seo_h1', 'do_shortcode' );

/**
 * @return int
 * @since 1.7.1
 */
function sfs_more_less_count() {
    return apply_filters( 'sfswp_more_less_count', 5 );
}
/**
 * @return mixed|void
 * @since 1.7.1
 */
function sfs_more_less_opened() {
    return apply_filters( 'sfswp_more_less_opened', [] );
}
/**
 * @return mixed|void
 * @since 1.7.1
 */
function sfs_folding_opened() {
    return apply_filters( 'sfswp_folding_opened', [] );
}
/**
 * @return mixed|void
 * @since 1.7.1
 */
function sfs_hierarchy_opened() {
    return apply_filters( 'sfswp_hierarchy_opened', [] );
}
/**
 * @param $filter
 * @return mixed|void
 * @since 1.7.1
 */
function sfs_dropdown_default_option( $filter ) {
    $label = sprintf( __( '- Select %s -', 'searchfiltersort' ),  $filter['label'] );
    if( isset( $filter['dropdown_label'] ) && $filter['dropdown_label'] ){
        $label = $filter['dropdown_label'];
    }
    return apply_filters( 'sfswp_dropdown_default_option', $label, $filter );
}

function sfs_brand_filter_entities(){
    return apply_filters( 'sfswp_brand_filter_entities', ['product_brand', 'pa_brand', 'pwb-brand', 'yith_product_brand'] );
}

add_filter( 'sfswp_filter_classes', 'sfswp_frontend_filter_classes', 10, 2 );
function sfswp_frontend_filter_classes( $classes, $filter ){
    if( in_array( $filter['e_name'], sfs_brand_filter_entities() ) ) {
        $classes[] = 'sfswp-filter-has-brands';
    }

    return $classes;
}

add_filter( 'sfswp_filter_classes', 'sfs_frontend_filter_classes', 10, 2 );
function sfs_frontend_filter_classes( $classes, $filter ){
    if ( $filter['show_term_names'] === 'yes' ) {
        $classes[] = 'sfswp-filter-visible-term-names';
    } else {
        $classes[] = 'sfswp-filter-hidden-term-names';
    }

    return $classes;
}

//add_filter( 'sfswp_filter_classes', 'sfs_same_swatches_width', 20, 4 );
//function sfs_same_swatches_width( $classes, $filter, $default_classes, $terms, $args ){
//    if( in_array( 'sfswp-filter-has-swatches', $classes ) ){
//        if( ! empty( $terms ) ) {
//            $counters = [];
//            foreach ( $terms as $single_term ) {
//                $counters[] = $single_term->cross_count;
//            }
//
//            $max = max( $counters );
//            $classes[] = 'sfswp-counter-width-'. strlen( (string)$max );
//        }
//    }
//    return $classes;
//}


// Bricks Builder fix for Any Category SFS Set
add_action( 'sfswp_all_set_wp_queried_posts', 'sfs_bricks_builder_category_compat', 10, 2 );
function sfs_bricks_builder_category_compat( $set_wp_query, $setId ){

    //to check if there is Bricks Builder
    if ( defined( 'BRICKS_VERSION' ) && BRICKS_VERSION ) {
        $filterSet  = \SearchFilterSort\Filter\Container::instance()->getSFSSetService();
        $the_set    = $filterSet->getSet( $setId );

        if ( isset( $the_set['wp_page_type']['value'] ) && isset( $the_set['post_name']['value'] ) ){
            if ( strpos( $the_set['wp_page_type']['value'], 'taxonomy_' ) !== false ) {
                if ( strpos( $the_set['post_name']['value'], '-1' ) !== false ) {
                    $queried_object = get_queried_object();
                    if ( property_exists( $queried_object, 'taxonomy' ) ){
                        $set_wp_query->set( $queried_object->taxonomy, $queried_object->slug );
                    }
                }
            }
        }
    }

    return $set_wp_query;
}

add_filter( 'sfswp_chips_term_name', 'sfs_chips_labels', 10, 3 );
function sfs_chips_labels( $term_name, $term, $filter ) {
    if ( in_array( $filter['entity'], ['post_meta_num', 'tax_numeric', 'post_date'] ) ) {
        // 'min_num_label'
        // 'max_num_label'

        if( $filter['min_num_label'] !== '' ){
            if( ! is_null( $term ) && property_exists( $term, 'slug' ) && in_array( $term->slug, ['min', 'from'] ) ){
                if( strpos( $filter['min_num_label'], '{value}' ) !== false ){
                    $term_name = str_replace( '{value}', $filter['values'][$term->slug], $filter['min_num_label'] );
                }else {
                    $term_name = $filter['min_num_label'] .' '.$filter['values'][$term->slug];
                }

            }
        }

        if( $filter['max_num_label'] !== '' ){
            if( ! is_null( $term ) && property_exists( $term, 'slug' ) && in_array( $term->slug, ['max', 'to'] ) ){
                if( strpos( $filter['max_num_label'], '{value}' ) !== false ){
                    $term_name = str_replace( '{value}', $filter['values'][$term->slug], $filter['max_num_label'] );
                }else {
                    $term_name = $filter['max_num_label'] .' '.$filter['values'][$term->slug];
                }
            }
        }

    }

    return $term_name;
}

add_filter( 'query_loop_block_query_vars', 'sfs_query_loop_block_query_vars', 10, 2 );

function sfs_query_loop_block_query_vars( $query, $block ){
    global $xd;
    $xd++;

    if( ! is_null( $block ) && property_exists( $block, 'parsed_block' ) ){
        if( isset( $block->parsed_block['blockName'] ) ) {
            if( in_array( $block->parsed_block['blockName'],
                [
                    'core/query-pagination-previous',
                    'core/query-pagination-next',
                    'core/query-pagination-numbers',
                ]
                ) ){
                $query['sfs_pagination'] = true;
            }
        }
    }

    return $query;
}

add_filter( 'sfswp_settings_field_checkbox', 'sfs_collapse_widget_checkbox_handler', 10, 2 );
function sfs_collapse_widget_checkbox_handler( $checkbox, $args )
{
    $checkbox  = '<div class="sfs-checkbox-switch-wrapper">';
    $checkbox .= '<label class="sfs-checkbox-switch"><input type="checkbox" name="%s[%s]" %s id="%s">';
    $checkbox .= '<span class="sfs-checkbox-slider"></span>';
    $checkbox .= '</label>';
    $checkbox .= '<span class="sfswp-checkbox-placeholder">%s</span>';
    $checkbox .= '</div>';
    return $checkbox;
}

add_filter( 'sfswp_input_type_checkbox', 'sfs_input_checkbox_switcher', 10, 2 );
function sfs_input_checkbox_switcher( $html, $attributes )
{

    $html_wrap = '<div class="sfs-checkbox-switch-wrapper">';
    $html_wrap .= '<label class="sfs-checkbox-switch">';
    $html_wrap .=  $html;
    $html_wrap .= '<span class="sfs-checkbox-slider"></span>';
    $html_wrap .= '</label>';
    $html_wrap .= '</div>';

    return $html_wrap;
}



if(!defined('SFS_FILTERS_PRO')) {

    add_action('sfswp_after_filter_input', 'sfs_location_preview');
    function sfs_location_preview($attr)
    {
        if ($attr['id'] == 'sfswp_set_fields-instead_post_name') {
            $link_html = '<div class="sfswp-location-preview-hidden"><a class="sfswp-location-preview-not-pro display-none"';
            $link_html .= ' target="_blank" title="'.esc_attr( esc_html__('Preview the selected location in a new tab', 'searchfiltersort') ).'" ';
            $link_html .= '>';
            $link_html .= '<span class="dashicons dashicons-visibility"></span>';
            $link_html .= '</a></div>';
            echo $link_html;
        }
    }

    add_filter('sfs_before_render_admin_select_option', 'sfs_add_data_to_option_before_render', 10, 2);
    function sfs_add_data_to_option_before_render($option_value, $attr)
    {
        if ($attr['id'] == 'sfswp_set_fields-post_type') {
            if($option_value == 'page'){
                $option_value = 'post';
            }

            $link = '';

            $archive_link = get_post_type_archive_link($option_value);
            if($archive_link){
                $link = $archive_link;
            }

            if(!$archive_link){
                $taxonomies = get_object_taxonomies($option_value);

                if (!empty($taxonomies)) {
                    $first_taxonomy = $taxonomies[0];
                    $taxonomy = get_taxonomy($first_taxonomy);
                    if (!empty($taxonomy) && !is_wp_error($taxonomy)) {
                        $terms = get_terms([
                            'taxonomy' => $taxonomy->name,
                            'number'   => 1,
                            'hide_empty' => false,
                        ]);
                        if (!empty($terms) && !is_wp_error($terms)) {
                            $term_link = get_term_link($terms[0]);
                            $link = esc_url($term_link);
                        }
                    }
                }
            }
            return ' data-link="' . $link . '"';
        }
    }
}

add_filter('sfswp_set_min_max', function($min_and_max, $filter_name) {
    global $wp_query;

    if (empty($wp_query->posts)) {
        $min_and_max = ['min' => 0, 'max' => 0];
        return $min_and_max;
    }

    return $min_and_max;
}, 10, 2);

//add_filter( 'stackable/posts/post_query', 'sfs_stackable_block_query_vars', 10, 3 );
//function sfs_stackable_block_query_vars( $post_query, $context, $query_string ){
//    if( is_user_logged_in() ) {
//        var_dump( $context );
//        var_dump( $query_string );
//    }
//
//    return $post_query;
//}