<?php
// Fetch product categories
$product_categories = get_terms([
    'taxonomy' => 'product_cat',
    'hide_empty' => true,
]);

$product_tags = get_terms([
    'taxonomy' => 'product_tag',
    'hide_empty' => true,
]);

// Fetch brands (correct taxonomy: product_brand)
$product_brands = get_terms([
    'taxonomy' => 'product_brand',
    'hide_empty' => true,
]);


// Get current query parameters to maintain state
$current_min_price = isset($_GET['min_price']) ? intval($_GET['min_price']) : 20;
$current_max_price = isset($_GET['max_price']) ? intval($_GET['max_price']) : 100;



// Ratings array
$ratings = [5, 4, 3, 2, 1];

// Get active filters
$active_categories = isset($_GET['product_cat']) ? explode(',', sanitize_text_field($_GET['product_cat'])) : [];
$active_tags = isset($_GET['product_tag']) ? explode(',', sanitize_text_field($_GET['product_tag'])) : [];
$active_brands = isset($_GET['product_brand']) ? explode(',', sanitize_text_field($_GET['product_brand'])) : [];
$active_prices = isset($_GET['price_range']) ? explode(',', sanitize_text_field($_GET['price_range'])) : [];
$active_rating = isset($_GET['rating_filter']) ? explode(',', $_GET['rating_filter']) : [];

?>

<!-- Categories -->
<div class="cs_filter_widget">
    <h3 class="cs_filter_widget_title cs_fs_18 cs_normal cs_secondary_font">
        <?php esc_html_e('Categories', 'glowify-wp'); ?>
        <svg width="9" height="5" viewBox="0 0 9 5" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.434142 5H8.56588C8.95069 5 9.14672 4.52889 8.87082 4.24917L4.80495 0.126978C4.63796 -0.042326 4.36206 -0.042326 4.195 0.126978L0.129129 4.24917C-0.146696 4.52889 0.0493364 5 0.434142 5Z" fill="currentColor"></path>
        </svg>
    </h3>
    <div class="cs_filter_widget_content">
        <ul class="cs_filter_widget_list cs_mp_0">
            <?php foreach ($product_categories as $category) : ?>
                <li>
                    <div class="cs_custom_checkbox">
                        <input type="checkbox" class="filter-category" value="<?php echo esc_attr($category->slug); ?>" id="cat-<?php echo esc_attr($category->term_id); ?>" <?php checked(in_array($category->slug, $active_categories)); ?>>
                        <span><?php echo esc_html($category->name); ?></span>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>

<!-- Brands -->
<div class="cs_filter_widget">
    <h3 class="cs_filter_widget_title cs_fs_18 cs_normal cs_secondary_font">
        <?php esc_html_e('Brands', 'glowify-wp'); ?>
        <svg width="9" height="5" viewBox="0 0 9 5" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.434142 5H8.56588C8.95069 5 9.14672 4.52889 8.87082 4.24917L4.80495 0.126978C4.63796 -0.042326 4.36206 -0.042326 4.195 0.126978L0.129129 4.24917C-0.146696 4.52889 0.0493364 5 0.434142 5Z" fill="currentColor"></path>
        </svg>
    </h3>
    <div class="cs_filter_widget_content">
        <ul class="cs_filter_widget_list cs_mp_0">
            <?php foreach ($product_brands as $brand) : ?>
                <li>
                    <div class="cs_custom_checkbox">
                        <input type="checkbox" class="filter-brand" value="<?php echo esc_attr($brand->slug); ?>" id="brand-<?php echo esc_attr($brand->term_id); ?>" <?php checked(in_array($brand->slug, $active_brands)); ?>>
                        <span><?php echo esc_html($brand->name); ?></span>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>

<!-- Price Range -->
<div class="cs_filter_widget">
    <h3 class="cs_filter_widget_title cs_fs_18 cs_normal cs_secondary_font">
        <?php esc_html_e('Price Range', 'glowify-wp'); ?>
        <svg width="9" height="5" viewBox="0 0 9 5" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.434142 5H8.56588C8.95069 5 9.14672 4.52889 8.87082 4.24917L4.80495 0.126978C4.63796 -0.042326 4.36206 -0.042326 4.195 0.126978L0.129129 4.24917C-0.146696 4.52889 0.0493364 5 0.434142 5Z" fill="currentColor"></path>
        </svg>
    </h3>

    <div class="cs_filter_widget_content">
        <div class="cs_price_range cs_light">
            <form method="get" action="<?php echo esc_url(wc_get_page_permalink('shop')); ?>" class="price-filter-form">
                <!-- Preserve existing query parameters -->
                <?php
                foreach ($_GET as $key => $value) {
                    if ($key !== 'min_price' && $key !== 'max_price' && $key !== 'apply_price') {
                        echo '<input type="hidden" name="' . esc_attr($key) . '" value="' . esc_attr($value) . '">';
                    }
                }
                ?>
                <div class="cs_price_range_in">
                    <div class="cs_price_range_left">
                        <span><?php esc_html_e('Min Price', 'glowify-wp');?></span>
                        <input type="text" name="min_price" placeholder="$20" value="<?php echo esc_attr($current_min_price); ?>">
                    </div>
                    <div class="cs_price_range_right">
                        <span><?php esc_html_e('Max Price', 'glowify-wp');?></span>
                        <input type="text" name="max_price" placeholder="$100" value="<?php echo esc_attr($current_max_price); ?>">
                    </div>
                </div>
                <button type="submit" name="apply_price" value="1" class="cs_btn cs_style_1 cs_medium cs_size_md w-100"><span>APPLY</span></button>
            </form>
        </div>
     </div>
</div>

<!-- Rating -->
<div class="cs_filter_widget">
    <h3 class="cs_filter_widget_title cs_fs_18 cs_normal cs_secondary_font">
        <?php esc_html_e('Rating', 'glowify-wp'); ?>
        <svg width="9" height="5" viewBox="0 0 9 5" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.434142 5H8.56588C8.95069 5 9.14672 4.52889 8.87082 4.24917L4.80495 0.126978C4.63796 -0.042326 4.36206 -0.042326 4.195 0.126978L0.129129 4.24917C-0.146696 4.52889 0.0493364 5 0.434142 5Z" fill="currentColor"></path>
        </svg>
    </h3>
    <div class="cs_filter_widget_content">
        <ul class="cs_filter_widget_list cs_mp_0">
            <?php for ($i = 5; $i >= 1; $i--) : ?>
            <li>
                <div class="cs_custom_checkbox">
                    <input type="checkbox" 
                        class="filter-rating"
                        value="<?php echo esc_attr($i); ?>"
                        <?php checked(in_array($i, $active_rating)); ?>>
                    <span>
                        <span class="cs_rating" data-rating="<?php echo esc_attr($i); ?>">
                            <span class="cs_rating_percentage"></span>
                        </span>
                    </span>
                </div>
            </li>
            <?php endfor; ?>
        </ul>
    </div>
</div>

<!-- Skin Type (Dynamic from Product Tags) -->
<div class="cs_filter_widget">
    <h3 class="cs_filter_widget_title cs_fs_18 cs_normal cs_secondary_font">
        <?php esc_html_e('Skin Type', 'glowify-wp'); ?>
        <svg width="9" height="5" viewBox="0 0 9 5" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.434142 5H8.56588C8.95069 5 9.14672 4.52889 8.87082 4.24917L4.80495 0.126978C4.63796 -0.042326 4.36206 -0.042326 4.195 0.126978L0.129129 4.24917C-0.146696 4.52889 0.0493364 5 0.434142 5Z" fill="currentColor"></path>
        </svg>
    </h3>
    <div class="cs_filter_widget_content">
        <ul class="cs_filter_widget_list cs_mp_0">
            <?php foreach ($product_tags as $tag) : ?>
                <li>
                    <div class="cs_custom_checkbox">
                        <input type="checkbox" class="filter-tags" value="<?php echo esc_attr($tag->slug); ?>" id="cat-<?php echo esc_attr($tag->term_id); ?>" <?php checked(in_array($tag->slug, $active_tags)); ?>>
                        <span><?php echo esc_html($tag->name); ?></span>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>


<script>
jQuery(document).ready(function($) {

    function buildFilterURL() {
        let query = [];

        // Categories
        let categories = [];
        $('.filter-category:checked').each(function() {
            categories.push($(this).val());
        });
        if (categories.length) {
            query.push('product_cat=' + categories.join(','));
        }

        // Brands
        let brands = [];
        $('.filter-brand:checked').each(function() {
            brands.push($(this).val());
        });
        if (brands.length) {
            query.push('product_brand=' + brands.join(','));
        }

        // Price Ranges - Multiple price ranges can be selected
        let price_ranges = [];
        $('.filter-price:checked').each(function() {
            price_ranges.push($(this).val());
        });
        if (price_ranges.length) {
            query.push('price_range=' + price_ranges.join(','));
        }

        // Rating (use rating_filter)
        let ratings = [];
        $('.filter-rating:checked').each(function() {
            ratings.push($(this).val());
        });
        if (ratings.length) {
            query.push('rating_filter=' + ratings.join(','));
        }

        // Categories
        let tags = [];
        $('.filter-tags:checked').each(function() {
            tags.push($(this).val());
        });
        if (tags.length) {
            query.push('product_tag=' + tags.join(','));
        }


        // Build the URL and redirect
        let url = '?' + query.join('&');
        window.location.href = url;
    }

    // Bind change event to all checkboxes
    $('.filter-category, .filter-brand, .filter-price, .filter-rating,.filter-tags').on('change', function() {
        buildFilterURL();
    });

    // Initialize price range sliders (if needed)
    // This is a placeholder for any additional price range initialization

});
</script>

<?php
// Add action to filter WooCommerce products by price range
add_action('woocommerce_product_query', 'custom_price_range_filter');
function custom_price_range_filter($q) {
    if (isset($_GET['price_range'])) {
        $price_ranges = explode(',', sanitize_text_field($_GET['price_range']));
        $meta_query = array('relation' => 'OR');

        foreach ($price_ranges as $range) {
            $range_parts = explode('-', $range);
            if (count($range_parts) == 2) {
                $min = floatval($range_parts[0]);
                $max = floatval($range_parts[1]);
                
                $meta_query[] = array(
                    'key' => '_price',
                    'value' => array($min, $max),
                    'compare' => 'BETWEEN',
                    'type' => 'NUMERIC'
                );
            }
        }

        $q->set('meta_query', array_merge($q->get('meta_query') ?? array(), array($meta_query)));
    }
    
  

}