<?php defined( 'ABSPATH' ) OR die( 'This script cannot be accessed directly.' );

/**
 * Method for lists: List Filter, List Order, List Search, Post List, Product List
 */

if ( ! function_exists( 'us_apply_orderby_to_list_query' ) ) {
	/**
	 * Apply the orderby params to the provided query_args.
	 */
	function us_apply_orderby_to_list_query( $query_args, $orderby, $orderby_custom_field, $orderby_custom_type, $order_invert ) {

		if ( empty( $orderby ) ) {
			return $query_args;
		}

		// Order by custom field
		if ( $orderby == 'custom' AND ! empty( $orderby_custom_field ) ) {
			$orderby = ! empty( $orderby_custom_type ) ? 'meta_value_num' : 'meta_value';
			$query_args['meta_key'] = $orderby_custom_field;
		}

		// If 'orderby' param is not set by the current query, use the element settings
		if ( $orderby != 'current_wp_query' ) {
			$query_args['orderby'] = $orderby;
			$query_args['order'] = ! empty( $order_invert ) ? 'DESC' : 'ASC';
		}

		if ( isset( $query_args['orderby'] ) ) {

			if ( $query_args['orderby'] == 'price' ) {
				$query_args['orderby'] = 'meta_value_num';
				$query_args['meta_key'] = '_price';

			} elseif ( $query_args['orderby'] == 'total_sales' ) {
				$query_args['orderby'] = 'meta_value_num';
				$query_args['meta_key'] = 'total_sales';

			} elseif ( $query_args['orderby'] == 'rating' ) {
				$query_args['orderby'] = 'meta_value_num';
				$query_args['meta_key'] = '_wc_average_rating';
			}
		}

		return $query_args;
	}
}

if ( ! function_exists( 'us_ajax_output_list_pagination' ) ) {
	/**
	 * Filters a page HTML to return the div with the "for_current_wp_query" class.
	 *
	 * @param string $content The post content.
	 * @return string Returns HTML of div with the "for_current_wp_query" class.
	 */
	function us_ajax_output_list_pagination( $content ) {
		if (
			class_exists( 'DOMDocument' )
			AND strpos( $content, 'for_current_wp_query' ) !== FALSE
		) {
			$document = new DOMDocument;
			// LIBXML_NOERROR is used to disable errors when HTML5 tags are not recognized by DOMDocument (which supports only HTML4).
			$document->loadHTML( '<meta http-equiv="Content-Type" content="text/html; charset="' . bloginfo( 'charset' ) . '">' . $content, LIBXML_NOERROR );
			$nodes = ( new DOMXpath( $document ) )->query('//div[contains(@class,"for_current_wp_query")]');
			if ( $nodes->count() ) {
				$element = $nodes->item( (int) us_arr_path( $_POST, 'us_ajax_list_index' ) );
				$new_document = new DOMDocument;
				$new_document->appendChild( $new_document->importNode( $element, TRUE ) );
				if ( $next_element = $element->nextSibling ) {
					$next_element_class = (string) $next_element->getAttribute( 'class' );
					if ( strpos( $next_element_class, 'w-grid-none' ) !== FALSE ) {
						$new_document->appendChild( $new_document->importNode( $next_element, TRUE ) );
					}
				}
				return $new_document->saveHTML();
			}
		}
		return $content;
	}
}

if ( ! function_exists( 'us_list_search_for_current_wp_query' ) ) {
	add_action( 'pre_get_posts', 'us_list_search_for_current_wp_query', 501 );
	/**
	 * Applies "List Search" query to the global wp_query.
	 */
	function us_list_search_for_current_wp_query( $wp_query ) {
		if (
			! is_admin()
			AND $list_search = (string) us_arr_path( $_REQUEST, 'list_search' )
		) {
			$wp_query->set( 's', sanitize_text_field( $list_search ) );
		}
	}
}

if ( ! function_exists( 'us_list_order_for_current_wp_query' ) ) {
	add_action( 'pre_get_posts', 'us_list_order_for_current_wp_query', 501 );
	/**
	 * Applies "List Order" params to the global wp_query.
	 */
	function us_list_order_for_current_wp_query( $wp_query ) {
		if (
			! is_admin()
			AND $list_order = (string) us_arr_path( $_REQUEST, 'list_order' )
		) {
			$order_params = array_map( 'trim', explode( ',', $list_order ) );

			$orderby = $order_params[0] ?? '';
			$orderby_custom_field = $order_params[1] ?? '';
			$orderby_custom_type = in_array( 'numeric', $order_params );
			$order_invert = in_array( 'asc', $order_params );

			unset( $order_params );

			$query_vars = &$wp_query->query_vars;
			$query_vars = us_apply_orderby_to_list_query(
				$query_vars,
				$orderby,
				$orderby_custom_field,
				$orderby_custom_type,
				$order_invert
			);
		}
	}
}
