<?php
/**
 * AJAX handler for Shop With Sidebar widget filters.
 *
 * @package storzen
 */

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

/**
 * Class Storzen_Shop_Sidebar_Ajax
 */
class Storzen_Shop_Sidebar_Ajax {

	const ACTION = 'storzen_shop_sidebar_filter';

	/**
	 * Hooks.
	 */
	public static function init() {
		add_action( 'wp_ajax_' . self::ACTION, array( __CLASS__, 'handle' ) );
		add_action( 'wp_ajax_nopriv_' . self::ACTION, array( __CLASS__, 'handle' ) );
	}

	/**
	 * Handle AJAX request.
	 */
	public static function handle() {
		check_ajax_referer( 'storzen_shop_sidebar', 'nonce' );

		if ( ! function_exists( 'WC' ) ) {
			wp_send_json_error( array( 'message' => __( 'WooCommerce is required.', 'storzen' ) ), 400 );
		}

		$raw_settings = isset( $_POST['settings'] ) ? json_decode( wp_unslash( $_POST['settings'] ), true ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON-decoded then validated/sanitized via storzen_shop_sidebar_sanitize_settings().
		$raw_filters  = isset( $_POST['filters'] ) ? json_decode( wp_unslash( $_POST['filters'] ), true ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON-decoded then sanitized per-key in storzen_shop_sidebar_build_filters().

		if ( ! is_array( $raw_settings ) || ! is_array( $raw_filters ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid request.', 'storzen' ) ), 400 );
		}

		$settings = storzen_shop_sidebar_sanitize_settings( $raw_settings );

		$filters = array(
			'paged'             => isset( $raw_filters['paged'] ) ? max( 1, (int) $raw_filters['paged'] ) : 1,
			'orderby'           => isset( $raw_filters['orderby'] ) ? sanitize_key( (string) $raw_filters['orderby'] ) : '',
			'order'             => isset( $raw_filters['order'] ) ? strtoupper( (string) $raw_filters['order'] ) : '',
			'keyword'           => isset( $raw_filters['keyword'] ) ? sanitize_text_field( (string) $raw_filters['keyword'] ) : '',
			'product_cat_slugs' => isset( $raw_filters['product_cat_slugs'] ) ? storzen_shop_sidebar_normalize_slug_list( $raw_filters['product_cat_slugs'] ) : array(),
			'color_slugs'       => isset( $raw_filters['color_slugs'] ) ? storzen_shop_sidebar_normalize_slug_list( $raw_filters['color_slugs'] ) : array(),
			'brand_slugs'       => isset( $raw_filters['brand_slugs'] ) ? storzen_shop_sidebar_normalize_slug_list( $raw_filters['brand_slugs'] ) : array(),
			'attribute_slugs'   => isset( $raw_filters['attribute_slugs'] ) ? storzen_shop_sidebar_normalize_slug_list( $raw_filters['attribute_slugs'] ) : array(),
			'stock_states'      => isset( $raw_filters['stock_states'] ) ? storzen_shop_sidebar_normalize_slug_list( $raw_filters['stock_states'] ) : array(),
			'rating_values'     => isset( $raw_filters['rating_values'] ) && is_array( $raw_filters['rating_values'] ) ? array_map( 'intval', $raw_filters['rating_values'] ) : array(),
		);

		if ( empty( $filters['product_cat_slugs'] ) && isset( $raw_filters['product_cat_slug'] ) && $raw_filters['product_cat_slug'] !== '' ) {
			$filters['product_cat_slugs'] = storzen_shop_sidebar_normalize_slug_list( $raw_filters['product_cat_slug'] );
		}
		if ( empty( $filters['color_slugs'] ) && isset( $raw_filters['color_slug'] ) && $raw_filters['color_slug'] !== '' ) {
			$filters['color_slugs'] = storzen_shop_sidebar_normalize_slug_list( $raw_filters['color_slug'] );
		}
		if ( empty( $filters['brand_slugs'] ) && isset( $raw_filters['brand_slug'] ) && $raw_filters['brand_slug'] !== '' ) {
			$filters['brand_slugs'] = storzen_shop_sidebar_normalize_slug_list( $raw_filters['brand_slug'] );
		}

		$filters = storzen_shop_sidebar_coerce_filter_arrays( $filters );

		if ( isset( $raw_filters['min_price'], $raw_filters['max_price'] ) ) {
			$filters['min_price'] = (float) $raw_filters['min_price'];
			$filters['max_price'] = (float) $raw_filters['max_price'];
		}

		if ( $filters['orderby'] === '' ) {
			$filters['orderby'] = $settings['wc_orderby'];
		}
		if ( $filters['order'] === '' ) {
			$filters['order'] = $settings['order'];
		}

		$settings['wc_orderby'] = $filters['orderby'];

		$args                     = storzen_shop_sidebar_build_query_args( $settings, $filters );
		$storzen_posts_query = new \WP_Query( $args );

		$szp_shop_sidebar_base_url = isset( $_POST['page_url'] ) ? esc_url_raw( wp_unslash( $_POST['page_url'] ) ) : home_url( '/' );
		$szp_element_id            = isset( $_POST['element_id'] ) ? sanitize_text_field( wp_unslash( $_POST['element_id'] ) ) : 'wcp';
		$szp_filters               = $filters;

		ob_start();
		include storzen_get_template( 'shop-sidebar-main.php' );
		$html = ob_get_clean();

		wp_send_json_success(
			array(
				'html'    => $html,
				'found'   => (int) $storzen_posts_query->found_posts,
				'showing' => (int) $storzen_posts_query->post_count,
			)
		);
	}
}

Storzen_Shop_Sidebar_Ajax::init();
