<?php
if (!defined('ABSPATH')) {exit;}

// Enqueue jQuery UI styles
wp_enqueue_style('jquery-ui', KRFSAPP_PLUGIN_DIR . '/assets/libs/jquery-ui.css', array(), '1.11.2', 'all');

// Enqueue jQuery UI
wp_enqueue_script('jquery-ui-slider');


global $krfsapp_max_pages; 
//Fetching Metal values 
$category_name = $props['category'];
global $krfsapp_current_category; 
// $krfsapp_current_category = KRFSAPP_ALL_CATEGORIES_MAP[$category_name]; 
$krfsapp_current_category = $category_name;
$ShapesTerm = json_decode(krfsapp_getMeta('shape_attr_advance_filters'), true);
$MetalTermItems = json_decode(krfsapp_getMeta('metal_attr_advance_filters'), true);
$sidestoneTerm = json_decode(krfsapp_getMeta('side_stone_attr_advance_filters'), true);
$sectionSettings = json_decode(krfsapp_getMeta('_setting_section_controls'), true) ?? [];
$order = ['Natural', 'Lab', 'Ruby', 'Emerald', 'Blue Sapphire', 'Pink Sapphire', 'Amethyst', 'Morganite', 'Black Diamond', 'Yellow Sapphire', 'Citrine'];

// Convert the predefined order array to lowercase for case-insensitive comparison
$orderLowercase = array_map('strtolower', $order);

usort($sidestoneTerm, function ($a, $b) use ( $orderLowercase) {
    $aIndex = array_search(strtolower($a['name']), $orderLowercase);
    $bIndex = array_search(strtolower($b['name']), $orderLowercase);

    // Handle cases where array_search() returns false
    $aIndex = ($aIndex === false) ? PHP_INT_MAX : $aIndex;
    $bIndex = ($bIndex === false) ? PHP_INT_MAX : $bIndex;

    return $aIndex - $bIndex;
});
if ($krfsapp_current_category == "engagement-rings") { 
    $RingStyleItems = json_decode(krfsapp_getMeta('style_attr_advance_filters'), true);
    $isRingStyleEnabled = $sectionSettings['eng_ring_styles'];
    $ringStoneString = esc_html("Enhance your ring with sparkling side stones for added brilliance and a personalized touch that reflects your unique style.");
    $ringShapeString = esc_html("Shape refers to a stone's geometric outline and physical form. It affects appearance and is defined by specific cut attributes.");
    $ringStyleString = esc_html("Ring styles include a wide variety of designs and settings, each with unique characteristics.");
    $order = array('Solitaire','Halo','Three-Stone','Pave','Vintage','Bypass', 'Fancy', 'Multi-Row','Trellis', 'Single-Row','Side Stone');
    $subtitle = stripslashes(krfsapp_get_string('engagement-ring-listing','subtitle_engagement_ring_listing'));
    usort($RingStyleItems, function ($a, $b) use ( $order) {
        $aIndex = array_search($a['name'], $order);
        $bIndex = array_search($b['name'], $order);

        // Handle cases where array_search() returns false
        $aIndex = ($aIndex === false) ? PHP_INT_MAX : $aIndex;
        $bIndex = ($bIndex === false) ? PHP_INT_MAX : $bIndex;

        return $aIndex - $bIndex;
    });
} elseif ($krfsapp_current_category == "wedding-men-rings") { 
    $RingStyleItems = json_decode(krfsapp_getMeta('wed_men_attr_advance_filters'), true);
    $isRingStyleEnabled = $sectionSettings['wed_men_ring_styles'];
    $ringStoneString = esc_html("Enhance your ring with sparkling side stones for added brilliance and a personalized touch that reflects your unique style.");
    $ringShapeString = esc_html("Shape refers to a stone's geometric outline and physical form. It affects appearance and is defined by specific cut attributes.");
    $ringStyleString = esc_html("Ring styles include a wide variety of designs and settings, each with unique characteristics.");
    $subtitle = stripslashes(krfsapp_get_string('wedding-ring-listing','subtitle_wedding_ring_listing'));
} else {
    $RingStyleItems = json_decode(krfsapp_getMeta('wed_women_attr_advance_filters'), true);
    $isRingStyleEnabled = $sectionSettings['wed_women_ring_styles'];
    $ringStoneString = esc_html("Enhance your ring with sparkling side stones for added brilliance and a personalized touch that reflects your unique style.");
    $ringShapeString = esc_html("Shape refers to a stone's geometric outline and physical form. It affects appearance and is defined by specific cut attributes.");
    $ringStyleString = esc_html("Ring styles include a wide variety of designs and settings, each with unique characteristics.");
    $subtitle = stripslashes(krfsapp_get_string('wedding-ring-listing','subtitle_wedding_ring_listing'));
}

$isMetalTermItemsEnabled = $sectionSettings['metal'];
$isSidestoneTermEnabled = $sectionSettings['eng_ring_stones'];
$isShapeTermEnabled = $sectionSettings['diamond_shapes'];
$isBridalSetsEnabled = $sectionSettings['bridal_sets'];
$isHomePreviewSettingEnabled = $sectionSettings['home_preview'];
$classCol = 'col-lg-4';
if(!$isMetalTermItemsEnabled || !$isRingStyleEnabled) {
 $classCol = 'col-lg-6';
}
if(!$isMetalTermItemsEnabled && !$isRingStyleEnabled) {
    $classCol = 'col-lg-12';
   }
$classColMoreFilters = 'col-lg-4';
$classColMoreFiltersShape = 'col-lg-8';
if(!$isShapeTermEnabled || !$isSidestoneTermEnabled) {
    $classColMoreFilters = 'col-lg-12';
    $classColMoreFiltersShape = 'col-lg-12';
}


$priceLimits = krfsapp_get_min_max_price_by_category($krfsapp_current_category); 

global $krfsapp_minprice, $krfsapp_maxprice;

$krfsapp_minprice = $priceLimits['min_price'];
$krfsapp_maxprice = $priceLimits['max_price'];


$language_group = "";
if($krfsapp_current_category == 'engagement-rings') { 
    $language_group = "engagement-ring-listing";
}else  {
    $language_group = "wedding-ring-listing";
} 

wp_enqueue_script('diamond-listing-page-script', KRFSAPP_PLUGIN_DIR . '/src/'. KRFSAPP_THEME. "/scripts/ring-listing-krfs.js", array('jquery'), KRFSAPP_VERSION_CONTROL['ring_listing_krfs_js'], true);

wp_localize_script( 'diamond-listing-page-script', 'KRFListing', [
    'ajax_url' => admin_url('admin-ajax.php'),
    'krfs_nonce' => wp_create_nonce('krfs_nonce'),
    'current_category' => $krfsapp_current_category, 
    'krfs_minprice' => $krfsapp_minprice,
    'krfs_maxprice' => $krfsapp_maxprice,
    'currency_locale' => str_replace("_", "-",determine_locale()),
    'currency_code' => get_woocommerce_currency()
]);

wp_localize_script( 'diamond-listing-page-script', 'KRFTranslation', [
    'results' => esc_html__('All Results', 'keyideas-jewelry-ring-filter-search'),
    'single_set' => esc_html__('Single Set', 'keyideas-jewelry-ring-filter-search'),
    'bridal_set' => esc_html__('Bridal Set', 'keyideas-jewelry-ring-filter-search'),
    'finishMessage' => esc_html__('These results are the closest match to your search. Use the filters at the top of the page to refine your results.', 'keyideas-jewelry-ring-filter-search'),
]);

// START: New filter code variables

// All attributes mapping keys
$krfs_style_attributes_mapping_key = "";
$krfs_metal_attributes_mapping_key = "metal_terms";
$krfs_sidestone_attributes_mapping_key = "engagement_ring_sidestone_terms";
$krfs_shape_attributes_mapping_key = "shape_terms";

$krfs_attributes_mapping = json_decode(krfsapp_getMeta('attributes_mapping'), true);

// var_dump($krfs_attributes_mapping); exit;

$krfs_style_attributes_mapping_key = "engagement_ring_style_terms";
$ring_type = "eng";

if($krfsapp_current_category == "wedding-women-rings") { 
    $krfs_style_attributes_mapping_key = "wedding_ring_terms_wedwomen";
    $ring_type = "women";
} else if($krfsapp_current_category == "wedding-men-rings") { 
    $krfs_style_attributes_mapping_key = "wedding_ring_terms_wedmen";
    $ring_type = "men";
}

// For metal filters
if(isset($_GET['metal'])) {
    $metals = isset($_GET['metal']) ? (array) wp_unslash($_GET['metal']) : [];

    $white_active   = in_array('metal_white_gold', $metals) ? 'active' : '';
    $yellow_active  = in_array('metal_yellow_gold', $metals) ? 'active' : '';
    $rose_active    = in_array('metal_rose_gold', $metals) ? 'active' : '';
    $platinum_active = in_array('metal_platinum', $metals) ? 'active' : '';
}else {
    $white_active = '';
    $yellow_active = '';
    $rose_active = '';
    $platinum_active = '';
}

function getMappedSlug(array $mapping, string $key, string $default): string
{
    $value = $mapping[$key] ?? $default;
    $value = !empty($value) ? $value : $default;
    $pos = strpos($value, '_');
    return $pos !== false ? substr($value, 0, $pos) : $value;
}

$metals = [
    'white_gold_14k' => 'white',
    'yellow_gold_14k' => 'yellow',
    'rose_gold_14k' => 'rose',
    'platinum' => 'platinum',
];

$mapped_slugs = [];

foreach ($metals as $metal_key => $default_slug) {
    $mapped_slugs[$metal_key] = getMappedSlug($krfs_attributes_mapping[$krfs_metal_attributes_mapping_key] ?? [], $metal_key, $default_slug);
}

$white_mapped_slug = $mapped_slugs['white_gold_14k'];
$yellow_mapped_slug = $mapped_slugs['yellow_gold_14k'];
$rose_mapped_slug = $mapped_slugs['rose_gold_14k'];
$platinum_mapped_slug = $mapped_slugs['platinum'];

// END: New filter code variables


?>
<div class="diamond-list-padding">
<div class="pera-content text-center pb-3">
        <?php echo esc_html($subtitle);?>
      </div>
    <?php
        if (shortcode_exists('KIRB-RingBuilder-BYORStrip') && $krfsapp_current_category == "engagement-rings") { 
            echo do_shortcode(
                sprintf(
                    '[KIRB-RingBuilder-BYORStrip category="%s"]',
                    esc_attr($krfsapp_current_category) 
                )
            );
        }
    ?>
    <div class="filter-div-ab">
        <?php if ($krfsapp_current_category == "wedding-men-rings" || $krfsapp_current_category == "wedding-women-rings") { ?> 
            <div class="men-button" style="">
                <div class="men-button-inner">
                    <button id="men-ring" class="" name="<?php echo esc_attr('wedding-men-rings'); ?>">MEN</button>
                    <button id="women-ring" class="" name="<?php echo esc_attr('wedding-women-rings'); ?>">WOMEN</button>
                </div>
            </div>
        <?php } ?>

        <!-- new -->
        <div class="krfs-new-filter-section krfs-new-filter-section-laptop">
            <!-- START: Ring Style filter -->
            <?php 
                if ($isRingStyleEnabled) {
            ?>
                <div class="krfs-inner-ring-filter">
                    <div class="heading-fiter">
                        <span>Style</span>
                    </div>
                    
                    <div class="krfs-ring-section krfs_scrollable_div" data-max-items="6">
                        <?php
                            $styles = isset($_GET['style']) ? (array) $_GET['style'] : [];

                            foreach ($RingStyleItems as $RingItem) {
                                if ($RingItem['enabled'] == "true") {

                                    // Removing everything before first underscore
                                    $pos = strpos($RingItem['slug'], '_');
                                    $shape_name = $pos !== false ? substr($RingItem['slug'], $pos + 1) : $RingItem['slug'];
                                    
                                    $mapped_slug = isset($krfs_attributes_mapping[$krfs_style_attributes_mapping_key][$shape_name]) 
                                        && !empty($krfs_attributes_mapping[$krfs_style_attributes_mapping_key][$shape_name])
                                        ? $krfs_attributes_mapping[$krfs_style_attributes_mapping_key][$shape_name] 
                                        : esc_attr($RingItem['slug']);
                                    
                                    $active = (
                                        in_array(
                                            strtolower("style_".$mapped_slug), 
                                            array_map('strtolower', array_map('sanitize_text_field', array_map('wp_unslash', $styles)))
                                        )
                                    ) ? 'active' : '';

                                    $shape_class = ($ring_type == "eng") ? $ring_type : $ring_type."-ring";

                                    $style_type = ($ring_type == "eng") ? "style_" : "wed".$ring_type."_";

                        ?>
                            <div class="krfs-ring-item">
                                <div class="krfs-ring-item-img krfs-ring-style-name <?php echo esc_attr($active); ?>" data-style="<?php echo esc_attr($style_type . $mapped_slug); ?>">
                                    <div class="shape-<?php echo esc_attr($shape_class); ?>-sprite <?php echo esc_attr(strtolower($ring_type . '-' . $shape_name)); ?>"></div>
                                </div>
                                <span class="<?php echo esc_attr($active); ?>"><?php echo esc_html($RingItem['name']); ?></span>
                            </div>
                        <?php
                                }
                            }
                        ?>
                    </div>
                </div>
            <?php } ?>
            <!-- END: Ring Style filter -->


            <!-- START: Metal filter -->
            <?php if ($isMetalTermItemsEnabled) { ?>
                <div class="krfs-inner-metal-filter">
                    <div class="heading-fiter"> 
                        <span>Metal</span>
                    </div>

                    <div class="krfs-metal-section">
                        <div class="krfs-metal-item">
                <div class="krfs-metal-item-img krfs-metal-name white-gold <?php echo esc_attr($white_active); ?>" data-metal="metal_<?php echo esc_attr($white_mapped_slug); ?>_gold"></div>
                <span class="<?php echo esc_attr($white_active); ?>">White Gold</span>
                        </div>
                        <div class="krfs-metal-item">
                <div class="krfs-metal-item-img krfs-metal-name yellow-gold <?php echo esc_attr($yellow_active); ?>" data-metal="metal_<?php echo esc_attr($yellow_mapped_slug); ?>_gold"></div>
                <span class="<?php echo esc_attr($yellow_active); ?>">Yellow Gold</span>
                        </div>
                        <div class="krfs-metal-item">
                <div class="krfs-metal-item-img krfs-metal-name rose-gold <?php echo esc_attr($rose_active); ?>" data-metal="metal_<?php echo esc_attr($rose_mapped_slug); ?>_gold"></div>
                <span class="<?php echo esc_attr($rose_active); ?>">Rose Gold</span>
                        </div>
                        <div class="krfs-metal-item">
                            <div class="krfs-metal-item-img krfs-metal-name platinum <?php echo esc_attr($platinum_active); ?>" data-metal="<?php echo esc_attr('metal_' . $platinum_mapped_slug); ?>"></div>
                            <span class="<?php echo esc_attr($platinum_active); ?>">Platinum</span>
                        </div>
                    </div>
                </div>
            <?php } ?>
            <!-- END: Metal filter -->

            <button class="open-filter-btn" id="openFilterBtn">
              Filters 
              <img src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/new-filter-icon.svg" loading="lazy" alt="cancel" width="20">
            </button>
        </div>

        <!-- mobile -->
        <div class="krfs-new-filter-section-mobile" id="filterContainer">
            <div class="krfs-new-filter-section krfs-no-scrollbar">
            <div class="krfs_filter-main-section <?php echo esc_attr(is_user_logged_in() && current_user_can('administrator') && is_admin_bar_showing() ? 'krfs_filter-pedding-top' : ''); ?>">
                    <div class="filter-main-heading">FILTERS</div>    
                    <div class="filter-main-reset" style="display: none;">Reset All</div>    
                </div>
                
                <!-- <div class="selected-filter-div krfs-select-filter-show" style="display:none;"></div> -->

                <!-- START: Sidebar > Ring Style filter -->
                <div class="krfs-inner-ring-filter krfs-inner-ring-filter-toggle">

                    <?php if ($isRingStyleEnabled) { ?>
                        <div class="heading-fiter krfs-filter-show-button"> 
                            <div>
                                <span>Style</span>
                            </div>
                            <img class="arrow-image rotated" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/down-arrow.svg" loading="lazy" alt="cancel" width="15">
                        </div>

                        <div class="krfs-ring-section krfs-filter-show-section show">
                            <?php
                                $styles = isset($_GET['style']) ? (array) $_GET['style'] : [];
                                
                                foreach ($RingStyleItems as $RingItem) {
                                    if ($RingItem['enabled'] == "true") {
                                        // Removing everything before first underscore
                                        $pos = strpos($RingItem['slug'], '_');
                                        $shape_name = $pos !== false ? substr($RingItem['slug'], $pos + 1) : $RingItem['slug'];

                                        $mapped_slug = isset($krfs_attributes_mapping[$krfs_style_attributes_mapping_key][$shape_name]) 
                                            && !empty($krfs_attributes_mapping[$krfs_style_attributes_mapping_key][$shape_name])
                                            ? $krfs_attributes_mapping[$krfs_style_attributes_mapping_key][$shape_name] 
                                            : esc_attr($RingItem['slug']);

                                        $active = (
                                            in_array(
                                                strtolower("style_".$mapped_slug), 
                                                array_map('strtolower', array_map('sanitize_text_field', array_map('wp_unslash', $styles)))
                                            )
                                        ) ? 'active' : '';

                                        $shape_class = ($ring_type == "eng") ? $ring_type : $ring_type."-ring";
                                        $style_type = ($ring_type == "eng") ? "style_" : "wed".$ring_type."_";
                            ?>
                                <div class="krfs-ring-item">
                                    <div class="krfs-ring-item-img krfs-ring-style-name <?php echo esc_attr($active); ?>" data-style="<?php echo esc_attr($style_type . $mapped_slug); ?>">
                                        <div class="shape-<?php echo esc_attr($shape_class); ?>-sprite <?php echo esc_attr(strtolower($ring_type . '-' . $shape_name)); ?>"></div>
                                    </div>
                                    <span class="<?php echo esc_attr($active); ?>"><?php echo esc_html($RingItem['name']); ?></span>
                                </div>
                            <?php
                                    }
                                }
                            ?>
                        </div>
                    <?php } ?>
                    
                </div>
                <!-- END: Sidebar > Ring Style filter -->

                <div class="krfs-inner-metal-filter krfs-inner-ring-filter-toggle">

                    <!-- START: Sidebar > Metal filter -->
                    <?php if ($isMetalTermItemsEnabled) { ?>
                        <div class="heading-fiter krfs-filter-show-button">
                            <div>
                                <span>Metal</span>
                            </div>
                            <img class="arrow-image" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/down-arrow.svg" loading="lazy" alt="cancel" width="15">
                        </div>

                        <div class="krfs-metal-section krfs-filter-show-section">
                            <div class="krfs-metal-item">
                                <div class="krfs-metal-item-img krfs-metal-name white-gold <?php echo esc_attr($white_active); ?>" data-metal="<?php echo esc_attr('metal_' . $white_mapped_slug . '_gold'); ?>"></div>
                                <span class="<?php echo esc_attr($white_active); ?>">White Gold</span>
                            </div>
                            <div class="krfs-metal-item">
                                <div class="krfs-metal-item-img krfs-metal-name yellow-gold <?php echo esc_attr($yellow_active); ?>" data-metal="<?php echo esc_attr('metal_' . $yellow_mapped_slug . '_gold'); ?>"></div>
                                <span class="<?php echo esc_attr($yellow_active); ?>">Yellow Gold</span>
                            </div>
                            <div class="krfs-metal-item">
                                <div class="krfs-metal-item-img krfs-metal-name rose-gold <?php echo esc_attr($rose_active); ?>" data-metal="<?php echo esc_attr('metal_' . $rose_mapped_slug . '_gold'); ?>"></div>
                                <span class="<?php echo esc_attr($rose_active); ?>">Rose Gold</span>
                            </div>
                            <div class="krfs-metal-item">
                                <div class="krfs-metal-item-img krfs-metal-name platinum <?php echo esc_attr($platinum_active); ?>" data-metal="<?php echo esc_attr('metal_' . $platinum_mapped_slug); ?>"></div>
                                <span class="<?php echo esc_attr($platinum_active); ?>">Platinum</span>
                            </div>
                        </div>
                    <?php } ?>
                </div>
                <!-- END: Sidebar > Metal filter --> 

                <?php if($krfsapp_current_category == "engagement-rings") { ?> 
                    <!-- START: Sidebar > Diamond Shape filter -->
                    <div class="krfs-inner-ring-filter krfs-inner-ring-filter-toggle">
                        <div class="heading-fiter krfs-filter-show-button"> 
                            <div>
                                <span>Diamond Shape</span>
                            </div>
                            <img class="arrow-image" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/down-arrow.svg" loading="lazy" alt="cancel" width="15">
                        </div>

                        <div class="krfs-ring-section krfs-filter-show-section">
                            <?php
                                foreach ($ShapesTerm as $shape) {
                                    if ($shape['enabled'] == "true") {
                                        // Removing everything before first underscore
                                        $pos = strpos($shape['slug'], '_');
                                        $shape_type = $pos !== false ? substr($shape['slug'], $pos + 1) : $shape['slug'];

                                        $shape_data =  isset($krfs_attributes_mapping[$krfs_shape_attributes_mapping_key][$shape_type])
                                            && !empty($krfs_attributes_mapping[$krfs_shape_attributes_mapping_key][$shape_type])
                                            ? $krfs_attributes_mapping[$krfs_shape_attributes_mapping_key][$shape_type]
                                            : esc_attr($shape['slug']);
                                        
                                        $active = (
                                                isset($_GET['shape']) 
                                                && strtolower($shape_data) == strtolower(sanitize_text_field(wp_unslash($_GET['shape'])))
                                            )
                                            ? 'active' 
                                            : '';

                            ?>
                                <div class="krfs-ring-item">
                                    <div class="krfs-ring-item-img krfs-filter-shape <?php echo esc_attr($active); ?>" data-shape="<?php echo esc_attr($shape_data); ?>">
                                        <div class="shape-diamond-sprite <?php echo esc_attr($shape_type); ?>"></div>
                                    </div>
                                    <span class="<?php echo esc_attr($active); ?>"><?php echo esc_html($shape['name']); ?></span>
                                </div>
                            <?php 
                                    }
                                }
                            ?>
                        </div>
                    </div>
                    <!-- END: Sidebar > Diamond Shape filter -->
                

                    <!-- START: Sidebar > Side Stone filter -->
                    <?php if($isSidestoneTermEnabled) { ?>
                        <div class="krfs-inner-ring-filter krfs-inner-ring-filter-toggle">
                            <div class="heading-fiter krfs-filter-show-button"> 
                                <div>
                                    <span>Side Stone Accents</span>
                                </div>
                                <img class="arrow-image" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/down-arrow.svg" loading="lazy" alt="cancel" width="15">
                            </div>

                            <div class="krfs-ring-section krfs-filter-show-section">
                                <?php 
                                    foreach($sidestoneTerm as $sidestone) {
                                        // Removing everything before first underscore
                                        $pos = strpos($sidestone['slug'], '_');
                                        $shape_type = $pos !== false ? substr($sidestone['slug'], $pos + 1) : $sidestone['slug'];

                                        $mapped_slug = isset($krfs_attributes_mapping[$krfs_sidestone_attributes_mapping_key][$shape_type]) 
                                            && !empty($krfs_attributes_mapping[$krfs_sidestone_attributes_mapping_key][$shape_type])
                                            ? $krfs_attributes_mapping[$krfs_sidestone_attributes_mapping_key][$shape_type]
                                            : esc_attr($sidestone['slug']);

                                        $active = (isset($_GET['stone']) 
                                            && strtolower($mapped_slug) == strtolower(sanitize_text_field(wp_unslash($_GET['stone'])))) 
                                            ? 'active' : '';

                                        $sidestone_type = strtolower(explode(' ', $sidestone['name'])[0]);
                                ?>
                                    <div class="krfs-ring-item">
                                        <div class="krfs-ring-item-img krfs-sidestone-btn <?php echo esc_attr($active); ?>" data-stone="<?php echo esc_attr($mapped_slug); ?>">
                                            <div class="stone-diamond-sprite <?php echo esc_attr($sidestone_type); ?>"></div>
                                        </div>
                                        <span class="<?php echo esc_attr($active); ?>"><?php echo esc_html(ucwords($sidestone['name'])); ?></span>
                                    </div>
                                <?php } ?>                            
                            </div>
                        </div>
                    <?php } ?>
                    <!-- START: Sidebar > Side Stone filter -->
                <?php } ?>

                <!-- START: Sidebar > Homr Preview filter -->
                <?php
                    if($isHomePreviewSettingEnabled) {
                        $active = $_GET['home_preview'] ?? false;
                ?>
                    <div class="krfs-inner-ring-filter">
                        <div class="heading-fiter aval-home"> 
                        <span>Available for home preview</span>
                        <div class="switch-container">
                                <button type="button" role="switch" aria-checked="<?php echo esc_attr($active ? 'true' : 'false'); ?>" data-state="<?php echo esc_attr($active ? 'checked' : 'unchecked'); ?>" value="<?php echo esc_attr($active ? 'on' : 'off'); ?>" class="krfs-addon-toggle-switch krfs-home-review" data-type="homepreview">
                                    <span data-state="<?php echo esc_attr($active ? 'checked' : 'unchecked'); ?>" class="toggle-slider"></span>
                                </button>
                                <input type="hidden" class="homepreviewfield" value="">
                            </div>
                        </div>
                    </div>
                <?php } ?>
                <!-- END: Sidebar > Homr Preview filter -->

                <div class="krfs-inner-ring-filter border-none krfs-inner-ring-filter-toggle">
                    <div class="heading-fiter krfs-filter-show-button"> 
                    <div>
                        <span>Price</span>
                    </div>
                    <img class="arrow-image" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/down-arrow.svg" loading="lazy" alt="cancel" width="15">
                    </div>

                    <div class="price__inner-eng krfs-filter-show-section filter_div filter__slider price__filter filter-price-fast-section">
                        <div class="slider-section input-width-full filter_inner">
                            <div id="price-range" class="slider"></div>
                            <div class="input-div price_inp_div">
                                <input type="text" class="price_inp" name="min_price" id="min_price" value="" />
                                <input type="text" class="price_inp" name="max_price" id="max_price" value="" />
                            </div>
                        </div>
                    </div>  
                </div>
                <div class="view-result-button" id="filtercloseBtn">
                    <button>VIEW RESULTS</button>
                </div>
            </div>
        </div>

        <div class="moreless__div-eng">
            <div class="keyideas-logo-eng" id="keyideas-logo-main">
                <img id="info-icon" class="pointer-image" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/powered-by-keyideas.png" height="15" alt="info-icon">
            </div>
        </div>
    
    </div>
    
    <div class="main-section-img mt-4">
        <div class="Product-tab_main">
            <div class="nav nav-tabs tab-section" id="main_tabs">
                <div data-type="all_results" class="tab-section-btn nav-link <?php echo esc_attr((isset($_GET['result_set']) && $_GET['result_set'] != 'bridal_sets') || !isset($_GET['result_set'])? 'active' : ''); ?>" data-bs-toggle="tab" data-bs-target="#all_diamond"
                    id="all_diamond_label" aria-selected="true"><?php echo esc_html__('All Results', 'keyideas-jewelry-ring-filter-search'); ?>
                </div>
                <?php if($isBridalSetsEnabled) {?>
                <div data-type="bridal_sets" class="tab-section-btn nav-link <?php echo esc_attr(isset($_GET['result_set']) && $_GET['result_set'] == 'bridal_sets'? 'active' : ''); ?>" data-bs-toggle="tab" data-bs-target="#all_diamond"
                    id="krfs_bridal_set_tab" aria-selected="false"><?php echo esc_html__('Bridal Set', 'keyideas-jewelry-ring-filter-search'); ?>
                </div>
                <?php }?>
                <input id="result_set" type="hidden" name="result_set" />
            </div>

            <div class="show__short short-margin-show krfs_search_bar_strip">
                <div class="short">
                    <div class="d-flex search-section">
                        <div class="input-wraper diam-listing-search-btn">
                           
                            <input type="search" class="w-full search-input-txt"
                                placeholder="<?php echo esc_html__('Search', 'keyideas-jewelry-ring-filter-search'); ?> <?php echo esc_html__('Ring', 'keyideas-jewelry-ring-filter-search'); ?>"
                                id="krfs_search_txt">
                            <button class="btn btn-search w-full" id="krfs_search_btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
                            <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001q.044.06.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1 1 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0"/>
                            </svg>
                            </button>
                        </div>
                    </div>
                    <!-- <div class="grid-list-tab Product-List__tab nav nav-tabs"></div> -->
                    <div class="d-flex align-items-center">
                        <div class="sort-width"><?php echo esc_html__('Sort By', 'keyideas-jewelry-ring-filter-search'); ?>:</div>
                        <img id="sort-filter-icon" class="" src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR); ?>/assets/images/new-filter.svg" alt="info-icon">

                        <select class="sortby" filter_name="orderby" name="sortby" id="krfs_prods_sort">
                            <?php
                                $sort_by_values = array('Orderbyupdatedate-desc', 'Orderbydate-desc', 'Orderbyprice-asc', 'Orderbyprice-desc');
                                $sort_by_labels = array(__('Best Match', 'keyideas-jewelry-ring-filter-search'), __('Latest', 'keyideas-jewelry-ring-filter-search'), __('Price: Low to High', 'keyideas-jewelry-ring-filter-search'), __('Price: High to Low', 'keyideas-jewelry-ring-filter-search'));

                                $i = 0;
                                foreach ($sort_by_values as $sort) {
                                    $selected = !isset($_GET['sort']) && $i == 0 ? 'selected' : (isset($_GET['sort']) && $_GET['sort'] == $sort ? 'selected' : '');
                                    ?>
                                    <option value="<?php echo esc_attr($sort); ?>" <?php echo esc_attr($selected); ?>><?php echo esc_html($sort_by_labels[$i]); ?>
                                    </option>
                                    <?php
                                    $i++;
                                }
                            ?>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="selected-filter-div krfs-select-filter-show" style="display:none;"></div>
        
        <div class="krfs-main-tab-section tab-content">
            <div id="all_diamond" class="tab-pane show active">
                <div class="tab-content" id="diamond_content">
                    <div id="griddesign" class="tab-pane  show active">

                        <div class="diamond-section">
                            <div class="product-list list-gap-pad" id="krfs_product_grid">
                                <?php
                                    $all_uri_comp_arr = array('shape', 'stone', 'style', 'metal', 'minprice', 'maxprice', 'sort','result_set','home_preview');
                                    $uri_comp_arr = array();
                                    foreach ($all_uri_comp_arr as $uri_comp) {
                                        if (isset($_GET[$uri_comp])) {
                                            $uri_comp_arr[$uri_comp] = esc_html(sanitize_text_field($_GET[$uri_comp]));
                                        }
                                    }

                                    $grid_data = krfsapp_initial_product_listing($krfsapp_current_category, $uri_comp_arr); 
                                    if (isset($grid_data['html'])) {
                                        echo wp_kses_post($grid_data['html']);
                                    }

                                    // Check if pagination and 'total_pages' exist before assigning
                                    if (isset($grid_data['pagination']['total_pages'])) {
                                        $krfsapp_max_pages = $grid_data['pagination']['total_pages']; 
                                    } else {
                                        $krfsapp_max_pages = 0; // Set a default value if 'total_pages' is not defined 
                                    }
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div id="single_set" class="tab-pane krfs-listing-tab"><p>This is single set</p></div>

            <div id="bridal_set" class="tab-pane krfs-listing-tab"><p>This is Bridal set</p></div>

        </div>
        <div class="krfs_listing_loader loading-overlay__spinner listing_loader" style="display:none;">
            <svg width="50" height="50" viewBox="0 0 234 234" fill="none" xmlns="http://www.w3.org/2000/svg"
                class="krfs_highlight_svg spinner">
                <path fill-rule="evenodd" clip-rule="evenodd"
                    d="M222.001 105C228.629 105 234.001 110.373 234.001 117C234.001 146.68 222.722 175.25 202.447 196.925C182.173 218.6 154.418 231.76 124.805 233.739C118.192 234.182 112.473 229.179 112.031 222.567C111.589 215.954 116.591 210.235 123.204 209.793C146.743 208.219 168.804 197.759 184.92 180.53C201.036 163.301 210.001 140.591 210.001 117C210.001 110.373 215.374 105 222.001 105Z"
                    fill="#000" />
                <path fill-rule="evenodd" clip-rule="evenodd"
                    d="M11.9987 129C5.37132 129 -0.00126648 123.627 -0.00126648 117C-0.00126648 87.3205 11.2782 58.7502 31.5528 37.075C51.8275 15.3999 79.5819 2.24004 109.195 0.260513C115.808 -0.181503 121.527 4.82079 121.969 11.4334C122.411 18.0461 117.409 23.7651 110.796 24.2071C87.2571 25.7805 65.1959 36.241 49.0802 53.4699C32.9645 70.6989 23.9987 93.4086 23.9987 117C23.9987 123.627 18.6261 129 11.9987 129Z"
                    fill="#000" />
            </svg>
        </div>
    </div>
</div>
<?php
    wp_localize_script( 'diamond-listing-page-script', 'KRFStats', [
        'max_pages' => $krfsapp_max_pages, 
        'currentProductCount' => isset($grid_data['count']) ? $grid_data['count'] : 0,
        'totalProductsCount' => isset($grid_data['pagination']['total_products']) ? $grid_data['pagination']['total_products'] : 0,
        'bridalSetsCount' => isset($grid_data['pagination']['bridal_sets_count']) ? $grid_data['pagination']['bridal_sets_count'] : 0,
    ]);
?>
</div>
<?php
    wp_localize_script( 'diamond-listing-page-script', 'KRFStats', [
        'max_pages' => $krfsapp_max_pages, 
        'currentProductCount' => isset($grid_data['count']) ? $grid_data['count'] : 0,
        'totalProductsCount' => isset($grid_data['pagination']['total_products']) ? $grid_data['pagination']['total_products'] : 0,
        'bridalSetsCount' => isset($grid_data['pagination']['bridal_sets_count']) ? $grid_data['pagination']['bridal_sets_count'] : 0,
    ]);
?>
