<?php
/**
 * Misc funcitons
 */

/**
 * Get min/max for meta key
 */
function jet_smart_filters_normalize_indexed_range_query( $query = array(), $type = 'post' ) {

	if ( empty( $query ) || ! is_array( $query ) ) {
		return array();
	}

	$ignored_keys = array(
		'jet_smart_filters',
		'suppress_filters',
		'paged',
		'page',
		'offset',
		'posts_per_page',
		'posts_per_archive_page',
		'nopaging',
		'no_found_rows',
		'cache_results',
		'update_post_term_cache',
		'update_menu_item_cache',
		'lazy_load_term_meta',
		'update_post_meta_cache',
		'ignore_sticky_posts',
		'comments_per_page',
		'order',
		'orderby',
		'fields',
		'wc_query',
		'error',
		'm',
		'second',
		'minute',
		'hour',
		'day',
		'monthnum',
		'year',
		'w',
		'preview',
		'sentence',
		'title',
		'embed',
	);

	foreach ( $ignored_keys as $key ) {
		unset( $query[ $key ] );
	}

	foreach ( $query as $key => $value ) {
		if ( is_array( $value ) ) {
			$value = array_filter( $value, function( $item ) {
				return '' !== $item && null !== $item && false !== $item;
			} );
		}

		if ( '' === $value || null === $value || false === $value || array() === $value ) {
			unset( $query[ $key ] );
		}
	}

	if ( isset( $query['post_status'] ) ) {
		$post_status = (array) $query['post_status'];
		$post_status = array_values( array_unique( $post_status ) );

		if ( 1 === count( $post_status ) && 'publish' === $post_status[0] ) {
			unset( $query['post_status'] );
		}
	}

	if ( 'post' === $type && isset( $query['post_type'] ) ) {
		$post_type = (array) $query['post_type'];
		$post_type = array_values( array_unique( $post_type ) );

		if ( 1 === count( $post_type ) && 'post' === $post_type[0] ) {
			unset( $query['post_type'] );
		}
	}

	return apply_filters( 'jet-smart-filters/indexed-range/normalized-query', $query, $type );
}

/**
 * Get min/max for meta key
 */
function get_indexed_range( $args = array() ) {

	global $wpdb;

	$table = $wpdb->prefix . 'jet_smart_filters_indexer';

	$defaults = array(
		'meta_key' => '',
		'type'     => 'post',
		'query'    => array(),
	);

	$args = wp_parse_args( $args, $defaults );

	$meta_key = $args['meta_key'];
	$type     = $args['type'];
	$query    = $args['query'];
	$query    = jet_smart_filters_normalize_indexed_range_query( $query, $type );

	if ( ! $meta_key ) {
		return false;
	}

	// Fast query when no WP_Query args
	if ( empty( $query ) ) {

		return $wpdb->get_row(
			$wpdb->prepare(
				"
				SELECT 
					MIN(item_value_num) AS min,
					MAX(item_value_num) AS max
				FROM $table
				WHERE item_key = %s
				AND type = %s
				AND item_value_num IS NOT NULL
				",
				$meta_key,
				$type
			),
			ARRAY_A
		);
	}

	// Build a subquery for the current object type from query args.
	$query_sql = jet_smart_filters()->utils->build_query_sql_from_args( $query, $type );

	if ( ! $query_sql ) {
		return false;
	}

	// Strip clauses that are not needed for the MIN/MAX join subquery.
	$query_sql = str_replace( 'SQL_CALC_FOUND_ROWS', '', $query_sql );
	$query_sql = preg_replace( '/LIMIT\s+\d+(\s*,\s*\d+)?/i', '', $query_sql );
	$query_sql = preg_replace( '/ORDER BY\s.+$/i', '', $query_sql );

	$sql = "
		SELECT
			MIN(i.item_value_num) AS min,
			MAX(i.item_value_num) AS max
		FROM $table i
		INNER JOIN ( $query_sql ) q
			ON q.ID = i.item_id
		WHERE i.item_key = %s
		AND i.type = %s
		AND i.item_value_num IS NOT NULL
	";

	return $wpdb->get_row(
		$wpdb->prepare( $sql, $meta_key, $type ),
		ARRAY_A
	);
}

function jet_smart_filters_woo_prices( $args ) {

	$indexed_range_args = array(
		'meta_key' => '_price',
		'type'     => 'post',
	);

	if ( ! empty( $args['query'] ) ) {
		$indexed_range_args['query'] = $args['query'];
	}

	return get_indexed_range( $indexed_range_args );
}

function jet_smart_filters_meta_values( $args = array() ) {

	if ( empty( $args['meta_key'] ) ) {
		return array();
	}

	$indexed_range_args = array(
		'meta_key' => $args['meta_key'] ,
		'type'     => 'post',
	);

	if ( ! empty( $args['query'] ) ) {
		$indexed_range_args['query'] = $args['query'];
	}

	return get_indexed_range( $indexed_range_args );
}

function jet_smart_filters_user_meta_values( $args = array() ) {

	if ( empty( $args['meta_key'] ) ) {
		return array();
	}

	$indexed_range_args = array(
		'meta_key' => $args['meta_key'] ,
		'type'     => 'user',
	);

	if ( ! empty( $args['query'] ) ) {
		$indexed_range_args['query'] = $args['query'];
	}

	return get_indexed_range( $indexed_range_args );
}

function jet_smart_filters_term_meta_values( $args = array() ) {

	if ( empty( $args['meta_key'] ) ) {
		return array();
	}

	$indexed_range_args = array(
		'meta_key' => $args['meta_key'] ,
		'type'     => 'term',
	);

	if ( ! empty( $args['query'] ) ) {
		$indexed_range_args['query'] = $args['query'];
	}

	return get_indexed_range( $indexed_range_args );
}

/**
 * Returns current currency symbol
 */
function jet_smart_filters_woo_currency_symbol() {

	$currency = apply_filters( 'jet-smart-filters/woocommerce/currency-symbol', get_woocommerce_currency_symbol() );

	return $currency;
}

/**
 * Do macros inside string
 */
function jet_smart_filters_macros( $string, $field_value = null ) {

	$macros = apply_filters( 'jet-smart-filters/macros/macros-list', array(
		'woocommerce_currency_symbol' => 'jet_smart_filters_woo_currency_symbol',
	) );

	return preg_replace_callback(
		'/%([a-z_-]+)(\|[a-z0-9_-]+)?%/',
		function ( $matches ) use ( $macros, $field_value ) {

			$found = $matches[1];

			if ( ! isset( $macros[ $found ] ) ) {
				return $matches[0];
			}

			$cb = $macros[ $found ];

			if ( ! is_callable( $cb ) ) {
				return $matches[0];
			}

			$args = isset( $matches[2] ) ? ltrim( $matches[2], '|' ) : false;

			return call_user_func( $cb, $field_value, $args );

		}, $string
	);
}
