<?php 
/*
** Filter Ajax For WooCommerce
*/
add_action( 'wp_ajax_wc_ajax_filter', 'wc_ajax_filter_products' );
add_action( 'wp_ajax_nopriv_wc_ajax_filter', 'wc_ajax_filter_products' );
function wc_ajax_filter_products() {
    // Verify nonce for security
	$paged = isset( $_POST['paged'] ) ? absint( $_POST['paged'] ) : 1;
    // Get the query parameters
    $query_args = array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => emarket_options()->getCpanelValue( 'product_number' ),
		'paged'          => $paged,
    );

    if ( ! empty( $_POST['product_cat'] ) ) {
        $categories = array_map( 'sanitize_text_field', (array) $_POST['product_cat'] );
        if ( ! empty( $categories ) ) {
            $query_args['tax_query'][] = array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => $categories,
				'operator' => 'IN',
            );
        }
    }
	
	if ( ! empty( $_POST['product_brand'] ) ) {
        $brands = array_map( 'sanitize_text_field', (array) $_POST['product_brand'] );
        if ( ! empty( $brands ) ) {
			$query_args['tax_query']['relation'] = 'AND';
            $query_args['tax_query'][] = array(
                'taxonomy' => 'product_brand',
                'field'    => 'slug',
                'terms'    => $brands,
				'operator' => 'IN',
            );
        }
    }
	
	$product_visibility_terms  = wc_get_product_visibility_term_ids();
	$product_visibility_not_in = array( is_search() && $main_query ? $product_visibility_terms['exclude-from-search'] : $product_visibility_terms['exclude-from-catalog'] );

	if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
		$product_visibility_not_in[] = $product_visibility_terms[ ProductStockStatus::OUT_OF_STOCK ];
	}
	
	if ( ! empty( $product_visibility_not_in ) ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_visibility',
				'field'    => 'term_taxonomy_id',
				'terms'    => $product_visibility_not_in,
				'operator' => 'NOT IN',
			);
		}

    // Handle price filter
    if ( ! empty( $_POST['min_price'] ) || ! empty( $_POST['max_price'] ) ) {
        $min_price = ! empty( $_POST['min_price'] ) ? floatval( $_POST['min_price'] ) : 0;
        $max_price = ! empty( $_POST['max_price'] ) ? floatval( $_POST['max_price'] ) : PHP_INT_MAX;

        $query_args['meta_query'][] = array(
            'key'     => '_price',
            'value'   => array( $min_price, $max_price ),
            'compare' => 'BETWEEN',
            'type'    => 'NUMERIC',
        );
    }

    // Handle attributes (layered nav)
    if ( ! empty( $_POST['attributes'] ) ) {
        foreach ( $_POST['attributes'] as $taxonomy => $values ) {
            $values = array_filter( array_map( 'sanitize_text_field', (array) $values ) );
            if ( ! empty( $values ) ) {
                $query_args['tax_query'][] = array(
                    'taxonomy' => sanitize_text_field( $taxonomy ),
                    'field'    => 'slug',
                    'terms'    => $values,
                    'operator' => 'IN',
                );
            }
        }
    }

    // Handle sorting
    if ( ! empty( $_POST['orderby'] ) ) {
        $orderby = sanitize_text_field( $_POST['orderby'] );
        switch ( $orderby ) {
            case 'menu_order':
                $query_args['orderby'] = 'menu_order title';
                $query_args['order'] = 'ASC';
                break;
            case 'popularity':
                $query_args['meta_key'] = 'total_sales';
                $query_args['orderby'] = 'meta_value_num';
                $query_args['order'] = 'DESC';
                break;
            case 'rating':
                $query_args['meta_key'] = '_wc_average_rating';
                $query_args['orderby'] = 'meta_value_num';
                $query_args['order'] = 'DESC';
                break;
            case 'date':
                $query_args['orderby'] = 'date';
                $query_args['order'] = 'DESC';
                break;
            case 'price':
                $query_args['meta_key'] = '_price';
                $query_args['orderby'] = 'meta_value_num';
                $query_args['order'] = 'ASC';
                break;
            case 'price-desc':
                $query_args['meta_key'] = '_price';
                $query_args['orderby'] = 'meta_value_num';
                $query_args['order'] = 'DESC';
                break;
			case 'best-sale':
                $query_args['meta_key'] = 'total_sales';
				$query_args['orderby'] = 'meta_value_num';
				$query_args['order'] = 'desc';
                break;
			case 'most-viewed':
                $query_args['meta_key'] = 'post_views_count';
				$query_args['orderby'] = 'meta_value_num';
				$query_args['order'] = 'desc';
                break;
			case '_discount_amount':
                $query_args['meta_key'] = '_discount_amount';
				$query_args['orderby'] = 'meta_value_num';
				$query_args['meta_value'] = 0;
				$query_args['meta_compare'] = '>';
				$query_args['order'] = 'desc';
                break;
        }
    }

    // Ensure tax_query is properly initialized
    if ( ! empty( $query_args['tax_query'] ) ) {
        $query_args['tax_query']['relation'] = 'AND';
    }
	
    // Run the query
    $products_query = new WP_Query( $query_args );

    // Start output buffering
    ob_start();

    if ( $products_query->have_posts() ) {
        while ( $products_query->have_posts() ) {
            $products_query->the_post();
            wc_get_template_part( 'content', 'product' ); // Use WooCommerce product template
        }
    } else {
        echo '<p class="filter-no-product-found">'. esc_html__( 'No products found.', 'sw_core' ) .'</p>';
    }

    // Reset post data
    wp_reset_postdata();

    // Get the buffered content
    $products_html = ob_get_clean();
	
	$loadmore_style = ( emarket_options()->getCpanelValue( 'product_loadmore_style' ) ) ? emarket_options()->getCpanelValue( 'product_loadmore_style' ) : 0;
	$option_number 	= ( emarket_options()->getCpanelValue( 'product_number' ) ) ? emarket_options()->getCpanelValue( 'product_number' ) : 12;
	$posts_per_page = isset( $_GET['product_count'] ) ? $_GET['product_count'] : $option_number;
	$loadmore_text 	= ( emarket_options()->getCpanelValue( 'product_loadmore_text' ) ) ? emarket_options()->getCpanelValue( 'product_loadmore_text' ) : esc_html__( 'Load More', 'emarket' );	 
	$loaded_text 	= ( emarket_options()->getCpanelValue( 'product_loadmore_loaded_text' ) ) ? emarket_options()->getCpanelValue( 'product_loadmore_loaded_text' ) : esc_html__( 'All Item', 'emarket' );	 
	$current_number = ( $option_number*$paged > $products_query->found_posts ) ? $products_query->found_posts : $option_number * $paged;
	$width = ( $products_query->found_posts > 0 ) ? $current_number/$products_query->found_posts * 100 : 100;
	ob_start();
	if( emarket_options()->getCpanelValue( 'product_loadmore' ) ){
	?><div class="pagination-ajax"><button class="button-ajax <?php echo esc_attr( ( ( $products_query->max_num_pages == 1 ) || $paged === $products_query->max_num_pages  ) ? 'loaded' : '' ); ?>" data-number="<?php echo esc_attr( $option_number ); ?>" data-total_products="<?php echo esc_attr( $products_query->found_posts ); ?>" data-loadmore_style="<?php echo esc_attr( $loadmore_style ); ?>" data-maxpage="<?php echo esc_attr( $products_query->max_num_pages ) ?>" data-title="<?php echo esc_attr( $loadmore_text ); ?>" data-loaded="<?php echo esc_attr( $loaded_text ); ?>"></button></div>
	<?php 		
	}else{
		echo wc_get_template_html( 'loop/pagination.php', array( 'current' => max( 1, $query_args['paged'] ), 'total' => $products_query->max_num_pages ) );
	}
	$product_pagination = ob_get_clean();
	ob_start();
		$args = [
			'total' => $products_query->found_posts,
			'per_page' => $option_number,
			'current' => max( 1, $query_args['paged'] ),
			'orderedby' => '',
		];
		wc_get_template( 'loop/result-count.php', $args );
	$product_result = strip_tags( ob_get_clean() );
    // Send JSON response
    wp_send_json_success( array(
        'html' => $products_html,
		'pagination' => $product_pagination,	
		'result_count' => $product_result
    ) );


    wp_die();
}
