<?php
//Filter output function
if ( ! function_exists( 'stm_get_filter' ) ) {
	function stm_get_filter( $get_title = false ) {

		//Get filter links
		$filter_links = stm_get_car_filter_links();

		//Get all filter options from STM listing plugin - Listing - listing categories
		$filter_options = stm_get_car_filter();

		//Create assoc array for more flexibility
		$filter_options_associative = array();

		//Creating new array for tax query and meta query
		$tax_query_args = array();

		$terms_args = array(
			'orderby'    => 'name',
			'order'      => 'ASC',
			'hide_empty' => true,
			'fields'     => 'all',
			'pad_counts' => false,
		);
		
		if(stm_is_listing()) {
			$terms_args['hide_empty'] = false;
		}

		foreach ( $filter_options as $filter_option ) {

			$filter_options_associative[ $filter_option['slug'] ] = array(
				'single_name' => $filter_option['single_name'],
				'plural_name' => $filter_option['plural_name'],
				'slug'        => $filter_option['slug']
			);

			if ( empty( $filter_option['numeric'] ) ) {
				$terms = get_terms( $filter_option['slug'], $terms_args );

				$terms = array_values($terms);

				$tax_query_args[ $filter_option['slug'] ] = $terms;
			} else {
				$terms = get_terms( $filter_option['slug'], $terms_args );
				foreach ( $terms as $term ) {
					$term->numeric = true;
				}

				$tax_query_args[ $filter_option['slug'] ] = $terms;
			}

			if(!empty($filter_option['number_field_affix'])) {
				$filter_options_associative[ $filter_option['slug'] ]['affix'] = $filter_option['number_field_affix'];
			}
		}

		//Getting all args from GET assigned by user
		$filter_user_args = array();

		if ( ! empty( $_GET ) ) {
			foreach ( $_GET as $key => $value ) {
				if ( ! empty( $value ) ) {
					$filter_user_args[ $key ] = $value;
				}
			}
		}

		$paged = get_query_var( 'paged', 1 );

		$args_query = array(
			'paged' => $paged
		);

		$post_args_query = array(
			'posts_per_page' => - 1
		);

		$args = array(
			'post_type'   => 'listings',
			'post_status' => 'publish',
		);

		$http_query_args = array();
		$filter_badges   = array();


		//If numeric field, splitting for min and max single taxonomy
		//Checking if get exists in filter options in order to prevent filtering by others GET's, such as ?page='2' or ?view="plite"
		foreach ( $filter_user_args as $filter_user_key => $filter_user_arg ) {

			if ( strpos( $filter_user_key, 'min_price' ) !== 0 and strpos( $filter_user_key, 'max_price' ) !== 0 ) {
				if ( strpos( $filter_user_key, 'max_' ) !== 0 ) {
					if ( ! empty ( $filter_user_arg ) and array_key_exists( $filter_user_key, $tax_query_args ) ) {
						$http_query_args[ $filter_user_key ] = $filter_user_arg;
						$args['tax_query'][]                 = array(
							'taxonomy' => $filter_user_key,
							'field'    => 'slug',
							'terms'    => array( $filter_user_arg )
						);

						$filter_single_link_name = get_term_by( 'slug', $filter_user_arg, $filter_user_key );

						if ( ! empty( $filter_single_link_name->name ) ) {
							$filter_badges[ ucfirst( $filter_user_key ) ]['text'] = $filter_single_link_name->name;
							$filter_badges[ ucfirst( $filter_user_key ) ]['slug'] = $filter_user_key;
						}
					}
					//If user selected something from filter list links (single value, generated by js)
					if ( ! empty ( $filter_user_arg ) ) {
						foreach ( $filter_links as $value ) {
							if ( $filter_user_key == $value['slug'] ) {
								$http_query_args[ $filter_user_key ] = $filter_user_arg;
								$args['tax_query'][]                 = array(
									'taxonomy' => $filter_user_key,
									'field'    => 'slug',
									'terms'    => array( $filter_user_arg )
								);

								$filter_single_link_name = get_term_by( 'slug', $filter_user_arg, $filter_user_key );

								if ( ! empty( $filter_single_link_name->name ) ) {
									$filter_badges[ ucfirst( $filter_user_key ) ]['text'] = $filter_single_link_name->name;
									$filter_badges[ ucfirst( $filter_user_key ) ]['slug'] = $filter_user_key;
								}
							}
						}
					}
				} else {
					if ( strpos( $filter_user_key, 'max_' ) === 0 ) {
						$original_key                              = str_replace( "max_", "", $filter_user_key );
						$http_query_args[ 'max_' . $original_key ] = $filter_user_args[ 'max_' . $original_key ];

						$number_affix = '';
						if(!empty($filter_options_associative[$original_key]['affix'])) {
							$number_affix = esc_html__($filter_options_associative[$original_key]['affix'], 'motors');
						}

						//If range
						if ( strpos( $filter_user_arg, '-' ) !== false ) {
							$values = explode( '-', $filter_user_arg );

							if ( ! empty( $values[0] ) and ! empty( $values[1] ) ) {
								$args['meta_query'][] = array(
									'relation' => 'AND',
									array(
										'key'     => $original_key,
										'value'   => $values[0],
										'type'    => 'numeric',
										'compare' => '>='
									),
									array(
										'key'     => $original_key,
										'value'   => $values[1],
										'type'    => 'numeric',
										'compare' => '<='
									)
								);

								$filter_badges[ ucfirst( $original_key ) ]['text'] = $values[0] . ' - ' . $values[1] . ' ' . $number_affix;
								$filter_badges[ ucfirst( $original_key ) ]['slug'] = 'max_' . $original_key;
							}
						}
						/*If only less*/
						if ( strpos( $filter_user_arg, '<' ) !== false ) {
							$value = str_replace( '<', '', $filter_user_arg );
							if ( ! empty( $value ) ) {
								$args['meta_query'][]                              = array(
									'key'     => $original_key,
									'value'   => $value,
									'type'    => 'numeric',
									'compare' => '<='
								);



								$filter_badges[ ucfirst( $original_key ) ]['text'] = esc_html__( 'Less than', 'motors' ) . ' ' . $value . ' ' . $number_affix;
								$filter_badges[ ucfirst( $original_key ) ]['slug'] = 'max_' . $original_key;
							}
						}
						/*If only more*/
						if ( strpos( $filter_user_arg, '>' ) !== false ) {
							$value = str_replace( '>', '', $filter_user_arg );
							if ( ! empty( $value ) ) {
								$args['meta_query'][]                              = array(
									'key'     => $original_key,
									'value'   => $value,
									'type'    => 'numeric',
									'compare' => '>='
								);
								$filter_badges[ ucfirst( $original_key ) ]['text'] = esc_html__( 'More than', 'motors' ) . ' ' . $value . ' ' . $number_affix;
								$filter_badges[ ucfirst( $original_key ) ]['slug'] = 'max_' . $original_key;
							}
						}
					}
				}
				//If price another query args
			} else {

				if ( strpos( $filter_user_key, 'min_' ) === 0 ) {
					$original_key                              = str_replace( "min_", "", $filter_user_key );
					$http_query_args[ 'min_' . $original_key ] = $filter_user_args[ 'min_' . $original_key ];
					$args['meta_query'][]                      = array(
						'relation' => 'OR',
						array(
							'key'     => 'sale_' . $original_key,
							'value'   => intval( $filter_user_args[ 'min_' . $original_key ] ),
							'type'    => 'numeric',
							'compare' => '>='
						),
						array(
							'key'     => $original_key,
							'value'   => intval( $filter_user_args[ 'min_' . $original_key ] ),
							'type'    => 'numeric',
							'compare' => '>='
						),
					);
				}
				if ( strpos( $filter_user_key, 'max_' ) === 0 ) {
					$original_key                              = str_replace( "max_", "", $filter_user_key );
					$http_query_args[ 'max_' . $original_key ] = $filter_user_args[ 'max_' . $original_key ];
					$args['meta_query'][]                      = array(
						'relation' => 'OR',
						array(
							'key'     => 'sale_' . $original_key,
							'value'   => intval( $filter_user_args[ 'max_' . $original_key ] ),
							'type'    => 'numeric',
							'compare' => '<='
						),
						array(
							'key'     => $original_key,
							'value'   => intval( $filter_user_args[ 'max_' . $original_key ] ),
							'type'    => 'numeric',
							'compare' => '<='
						),
					);
				}

				if ( ! empty( $filter_user_args['min_price'] ) and ! empty( $filter_user_args['max_price'] ) ) {
					$price_check_args = array(
						'orderby'    => 'name',
						'order'      => 'ASC',
						'hide_empty' => false,
						'fields'     => 'all',
					);

					$price_check_min_max = array();
					$price_terms         = get_terms( 'price', $price_check_args );
					if ( ! empty( $price_terms ) ) {
						foreach ( $price_terms as $term ) {
							$price_check_min_max[] = intval( $term->name );
						}
					}
					sort( $price_check_min_max );

					if ( count( $price_check_min_max ) > 1 ) {
						if ( intval( $filter_user_args['min_price'] ) != intval( $price_check_min_max[0] ) or intval( $filter_user_args['max_price'] ) != intval( $price_check_min_max[ count( $price_check_min_max ) - 1 ] ) ) {
							$filter_badges['Price']['text'] = stm_get_price_currency() . $filter_user_args['min_price'];
							$filter_badges['Price']['text'] .= ' - ';
							$filter_badges['Price']['text'] .= stm_get_price_currency() . $filter_user_args['max_price'];

							$filter_badges['Price']['slug'] = 'price';
						}
					}
				}
			}
		}


		//Checkboxes
		$checkboxes = stm_get_car_filter_checkboxes();


		if(!empty($checkboxes)) {
			$checkbox_params  = array();
			$checkbox_counter = 0;
			$has_checkboxes = false;
			foreach ( $checkboxes as $checkbox ) {
				if ( ! empty( $_GET[ $checkbox['slug'] ] ) ) {
					$has_checkboxes = true;
					$get_checkbox_param = $_GET[ $checkbox['slug'] ];


					if ( ! is_array( $get_checkbox_param ) ) {
						$get_checkbox_param = array(
							$_GET[$checkbox['slug']] => '1'
						);
					}

					foreach ( $get_checkbox_param as $checkbox_key => $checkbox_param ) {
						if ( empty( $checkbox_params[ $checkbox_counter ] ) ) {
							$checkbox_params[ $checkbox_counter ] = array( 'relation' => 'OR' );
						}
						$checkbox_params[ $checkbox_counter ][] = array(
							'taxonomy' => esc_attr( $checkbox['slug'] ),
							'field'    => 'slug',
							'terms'    => array( esc_attr( $checkbox_key ) )
						);


						$term = get_term_by('slug', esc_attr($checkbox_key), $checkbox['slug']);

						if(!empty($term->name)) {
							$filter_badges[ 'stm_hidden_' . $checkbox['slug'] . '[' . $checkbox_key . ']' ] = array(
								'text' => $term->name,
								'slug' => esc_attr($checkbox['slug'] . '[' . $checkbox_key . ']'),
								'taxonomy' => $checkbox['slug'],
								'field' => $checkbox_key
							);
						}

						$http_query_args[$checkbox['slug']][$checkbox_key] = '✓';
					}
				}
				$checkbox_counter ++;
			}

			if($has_checkboxes) {
				if(!empty($args['tax_query'])) {
					array_push( $args['tax_query'], $checkbox_params );
				} else {
					$args['tax_query'] = $checkbox_params;
				}
			}
		}

		if(!empty($_GET['popular']) and $_GET['popular'] == 'true') {
			$args_query['order'] = 'ASC';
			$args_query['orderby'] = 'stm_car_views';

			$filter_badges['Popular'] = array(
				'text' => 'ASC',
				'slug' => 'popular'
			);

			$http_query_args['popular'] = 'true';
		}
		
		if(!empty($_GET['sort_order'])) {
			switch (sanitize_text_field($_GET['sort_order'])) {
			    case "price_low":
			        $args_query['order'] = 'ASC';
					$args_query['orderby'] = 'meta_value_num';
					$args_query['meta_key'] = 'price';
					
					$http_query_args['sort_order'] = 'price_low';
			        break;
			    case "price_high":
			        $args_query['order'] = 'DESC';
					$args_query['orderby'] = 'meta_value_num';
					$args_query['meta_key'] = 'price';
					
					$http_query_args['sort_order'] = 'price_high';
			        break;
			    case "date_low":
			        $args_query['order'] = 'DESC';
					$args_query['orderby'] = 'date';
					
					$http_query_args['sort_order'] = 'date_low';
			        break;
			    case "mileage_low":
			        $args_query['order'] = 'ASC';
					$args_query['orderby'] = 'meta_value_num';
					$args_query['meta_key'] = 'mileage';
					
					$http_query_args['sort_order'] = 'mileage_low';
			        break;
			    case "mileage_high":
			        $args_query['order'] = 'DESC';
					$args_query['orderby'] = 'meta_value_num';
					$args_query['meta_key'] = 'mileage';
					
					$http_query_args['sort_order'] = 'mileage_high';
			        break;
			    default:
			    	$args_query['order'] = 'ASC';
					$args_query['orderby'] = 'date';
					
					$http_query_args['sort_order'] = 'date_high';
			}
		}

		if(!empty($_GET['stm-footer-search-name'])) {
			$args_query['s'] = esc_attr($_GET['stm-footer-search-name']);

			$filter_badges['Keyword'] = array(
				'text' => esc_attr($_GET['stm-footer-search-name']),
				'slug' => 'stm-footer-search-name'
			);

			$http_query_args['stm-footer-search-name'] = esc_attr($_GET['stm-footer-search-name']);
		}


		$merged_query_args = array_merge( $args, $args_query );
		$merged_posts_args = array_merge( $args, $post_args_query );
		
		if(stm_is_listing()) {
			$featured_query_args = $merged_query_args;
			$featured_query_args['posts_per_page'] = '3';
			$featured_query_args['orderby'] = 'rand';
			if(empty($featured_query_args['meta_query'])) {
				$featured_query_args['meta_query'] = array();
			}
			$featured_query_args['meta_query'][] = array(
				'key'     => 'special_car',
				'value'   => 'on',
				'compare' => '='
			);
			
			if(!empty($_GET['featured_top']) and $_GET['featured_top']) {
				$featured_query_args['posts_per_page'] = '-1';
			}
			
			$featured = new WP_Query( $featured_query_args );
		}
		
		
		stm_modify_query_location();


		$listing       = new WP_Query( $merged_query_args );
		$main_response = array();
		$response      = array();
		
		if(!empty($featured)) {
			$main_response['featured'] = $featured;
		}

		$posts = get_posts( $merged_posts_args );


		/*Here we add empty terms in filter*/
		$second_lvl_taxes = array();

		foreach ( $posts as $post ) {
			foreach ( $filter_options as $filter_option ) {
				if ( !empty($filter_option['listing_taxonomy_parent']) ) {
					$second_lvl_taxes[$filter_option['listing_taxonomy_parent']] = $filter_option;
				}
				if ( empty( $filter_option['numeric'] ) ) {
					$categories = get_the_terms( $post->ID, $filter_option['slug'] );
					if ( ! empty( $categories ) ) {
						foreach ( $categories as $category ) {
							$response[ $filter_option['slug'] ][ $category->slug ] = $category->name;
						}
					} else {
						if(stm_is_listing()) {
							$response[ $filter_option['slug'] ] = array();
						}
					}
				}
			}
		}

		/*Adding empty terms*/
		if(stm_is_listing()) {
			if ( ! empty( $second_lvl_taxes ) ) {
				/*Loop through second lvl taxed*/
				foreach ( $second_lvl_taxes as $tax_key => $second_lvl_tax ) {

					/*Check if they parent was already chosen*/
					if ( ! empty( $response[ $tax_key ] ) ) {
						/*It definitely has to have one key*/
						foreach ( $response[ $tax_key ] as $tax_parent_term_slug => $tax_parent_term_value ) {

							$categories        = stm_get_category_by_slug_all($second_lvl_tax['slug']);
							if(!empty($categories)) {
								foreach($categories as $category) {
									$option_name  = 'stm_parent_taxonomy_' . $category->term_id;
									$option_value = get_option( $option_name );
									if($option_value == $tax_parent_term_slug) {
										if( empty($response[$second_lvl_tax['slug']]) ) {
											$response[$second_lvl_tax['slug']] = array();
										}
										if(empty($response[$second_lvl_tax['slug']][$category->slug])) {
											$response[$second_lvl_tax['slug']][$category->slug] = $category->name . ' (0)';
										}
									}
								}
							}
						}
					}

				}
			}
		}


		//Ajax feature will be disabled soon
		$ajax_class = 'ajax-filter';
		ob_start();
		?>
		<form action="" method="get">
			<div class="filter filter-sidebar">
				<?php if ( ! empty( $tax_query_args ) ): ?>
					<div class="sidebar-entry-header">
						<i class="stm-icon-car_search"></i>
						<span class="h4"><?php _e( 'Search Options', 'motors' ); ?></span>
					</div>

					<div class="row row-pad-top-24">
						<?php foreach ( $tax_query_args as $taxonomy_term_key => $taxonomy_term ): ?>
							<?php if ( $taxonomy_term_key != 'price' ): ?>
								<?php if ( empty( $taxonomy_term[0]->numeric ) and ! empty( $taxonomy_term[0] ) ): ?>
									<div class="col-md-12 col-sm-6">
										<div class="form-group">
											<select name="<?php echo esc_attr( $taxonomy_term_key ) ?>"
											        class="form-control">
												<option
													value=""><?php esc_html_e( $filter_options_associative[ $taxonomy_term_key ]['single_name'], 'motors' ); ?></option>
												<?php foreach ( $taxonomy_term as $attr_key => $attr ): ?>
													<option
														value="<?php echo esc_attr( $attr->slug ); ?>" <?php if ( ! empty( $filter_user_args[ $taxonomy_term_key ] ) and $attr->slug == $filter_user_args[ $taxonomy_term_key ] ) {
														echo 'selected';
													} ?><?php /*if ( ! empty( $response[ $taxonomy_term_key ] ) and ! in_array( $attr->name, $response[ $taxonomy_term_key ] ) ) {
														echo 'disabled';
													} */ ?>><?php echo esc_attr( $attr->name ); ?></option>
												<?php endforeach; ?>
											</select>
										</div>
									</div>
								<?php else: ?>
									<?php
									$args = array(
										'orderby'    => 'name',
										'order'      => 'ASC',
										'hide_empty' => false,
										'fields'     => 'all',
									);

									$numbers = array();

									$terms = get_terms( $taxonomy_term_key, $args );
									if ( ! empty( $terms ) ) {
										foreach ( $terms as $term ) {
											$numbers[] = intval( $term->name );
										}
									}
									sort( $numbers );

									?>
									<div class="col-md-12 col-sm-6">
										<div class="row">
											<div class="col-md-12 col-sm-12">
												<div class="form-group">
													<select name="max_<?php echo esc_attr( $taxonomy_term_key ) ?>"
													        class="form-control">
														<option
															value=""><?php echo esc_html__( 'Max', 'motors' ) . ' ' . esc_html__( $filter_options_associative[ $taxonomy_term_key ]['single_name'], 'motors' ); ?></option>
														<?php foreach ( $numbers as $key => $value ): ?>
															<?php

															$number_affix = '';

															if(!empty($filter_options_associative[ $taxonomy_term_key ]['affix'])){
																$number_affix = esc_html__($filter_options_associative[ $taxonomy_term_key ]['affix'], 'motors');
															}

															$option_value = '';
															$option_name  = '';
															if ( $key == 0 ) {
																$option_name  = '>' . $value;
																$option_value = '> ' . $value . ' ' . $number_affix;

															} else {
																$option_name  = $numbers[ ( $key - 1 ) ] . '-' . $value;
																$option_value = $numbers[ ( $key - 1 ) ] . '-' . $value . ' ' . $number_affix;;
															}
															?>

															<option
																value="<?php echo esc_attr( $option_name ) ?>"
																<?php if ( ! empty( $filter_user_args[ 'max_' . $taxonomy_term_key ] ) and $filter_user_args[ 'max_' . $taxonomy_term_key ] == $option_name ) {
																	echo 'selected';
																} ?>
																>
																<?php printf( esc_html__( '%s', 'motors' ), $option_value ); ?>
															</option>

															<?php if ( $key == count( $numbers ) - 1 ): ?>
																<option value="<<?php echo esc_attr( $value ); ?>">
																	< <?php printf( esc_html__( '%s', 'motors' ), $value ); ?> <?php echo esc_attr($number_affix); ?></option>
															<?php endif; ?>
														<?php endforeach; ?>
													</select>
												</div>
											</div>
										</div>
									</div>
								<?php endif; ?>
							<?php endif; ?>
						<?php endforeach; ?>
						<!--Location inputs-->
						<?php
						$stm_lat = $stm_lng = $stm_location = '';
						if ( isset( $_GET['ca_location'] ) ) {
							$stm_location = $_GET['ca_location'];
						}
						if ( isset( $_GET['stm_lng'] ) ) {
							$stm_lng = $_GET['stm_lng'];
						}
						if ( isset( $_GET['stm_lat'] ) ) {
							$stm_lat = $_GET['stm_lat'];
						}
						?>

						<?php if ( stm_enable_location() ): ?>
							<div class="col-md-12 col-sm-12">
								<div class="form-group">
									<div class="stm-location-search-unit">
										<input type="text" id="ca_location_listing_filter"
										       class="stm_listing_search_location" name="ca_location"
										       value="<?php echo esc_attr( $stm_location ); ?>"/>
										<input type="hidden" name="stm_lat"
										       value="<?php echo esc_attr( floatval( $stm_lat ) ); ?>">
										<input type="hidden" name="stm_lng"
										       value="<?php echo esc_attr( floatval( $stm_lng ) ); ?>">
									</div>
								</div>
							</div>
						<?php endif; ?>

						<?php
							if(!stm_is_listing()) {
								stm_filter_price_output( $tax_query_args );
							}
						?>
					</div>
					<div class="sidebar-action-units">
						<input id="stm-classic-filter-submit" class="hidden" type="submit"
						       value="<?php _e( 'Show cars', 'motors' ); ?>"/>

						<a href="<?php echo esc_url( stm_get_listing_archive_link() ); ?>"
						   class="button"><span><?php _e( 'Reset all', 'motors' ); ?></span></a>
					</div>
					<!--View type-->
					<?php
					$view_type = 'list';
					if ( ! empty( $_GET['view_type'] ) and $_GET['view_type'] == 'grid' ) {
						$view_type = 'grid';
					}
					?>
					<input type="hidden" id="stm_view_type" name="view_type"
					       value="<?php echo esc_attr( $view_type ); ?>"/>
					<!--Filter links-->
					<input type="hidden" id="stm-filter-links-input" name="stm_filter_link" value=""/>

					<!--Popular-->
					<?php if(!empty($_GET['popular']) and $_GET['popular'] == 'true') { ?>
						<input type="hidden" name="popular" value="true" />
					<?php } ?>

					<?php if(!empty($_GET['stm-footer-search-name'])): ?>
						<input type="hidden" name="stm-footer-search-name" value="<?php echo esc_attr($_GET['stm-footer-search-name']); ?>" />
					<?php endif; ?>

				<?php endif; ?>
				<!-- Sort order -->
				<?php 
				$sort_order = 'date_high';
				if(!empty($_GET['sort_order'])) {
					$sort_order = sanitize_text_field($_GET['sort_order']);
				} ?>
				
				<input type="hidden" name="sort_order" value="<?php echo sanitize_text_field($sort_order); ?>" />
			</div>
			<?php
			if(stm_is_listing()) { ?>
				<div class="stm-filter-listing-directory-price">
					<?php stm_filter_price_output( $tax_query_args, true ); ?>
				</div>

				<?php
					stm_additional_filter_checkboxes();
				?>
			<?php } ?>
		</form>

		<?php if ( ! empty( $filter_links ) ): ?>
			<div class="stm-filter-links">
				<?php foreach ( $filter_links as $filter_link ): ?>
					<?php $filter_links_cats = get_terms( $filter_link['slug'], $terms_args ); ?>
					<?php if ( ! empty( $filter_links_cats ) ): ?>
						<div class="stm-accordion-single-unit">
							<a class="title collapsed" data-toggle="collapse"
							   href="#<?php echo esc_attr( $filter_link['slug'] ); ?>" aria-expanded="false">
								<h5><?php printf( esc_html__( '%s', 'motors' ), $filter_link['single_name'] ); ?></h5>
								<span class="minus"></span>
							</a>

							<div class="stm-accordion-content">
								<div class="collapsed collapse content"
								     id="<?php echo esc_attr( $filter_link['slug'] ); ?>">
									<ul class="list-style-3">
										<?php foreach ( $filter_links_cats as $filter_links_cat ): ?>
											<li
												class="stm-single-filter-link"
												data-slug="<?php echo esc_attr( $filter_link['slug'] ) ?>"
												data-value="<?php echo esc_attr( $filter_links_cat->slug ) ?>"
												>
												<a href="?<?php echo esc_attr( $filter_link['slug'] . '=' . $filter_links_cat->slug ); ?>">
													<?php echo esc_attr( $filter_links_cat->name ) . ' <span>(' . esc_attr( $filter_links_cat->count ) . ')</span>'; ?>
												</a>
											</li>
										<?php endforeach; ?>
									</ul>
								</div>
							</div>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>

		<?php
		$main_response['filter_html'] = ob_get_contents();
		ob_end_clean(); ?>


		<?php ob_start(); //Filter Badges ?>
		<ul class="stm-filter-chosen-units-list">
			<?php foreach ( $filter_badges as $filter_badge_name => $filter_badge_value ):

				if ( ! empty( $filter_badge_name ) and ! empty( $filter_badge_value ) and ! empty( $filter_badge_value['text'] ) and ! empty( $filter_badge_value['slug'] ) ):

					$http_query_args_clone = $http_query_args;

					if(!empty($filter_badge_value['taxonomy']) and !empty($filter_badge_value['field'])) {
						unset($http_query_args_clone[$filter_badge_value['taxonomy']][$filter_badge_value['field']]);
					} else {
						unset($http_query_args_clone[$filter_badge_value['slug']]);
					}

					$link = add_query_arg($http_query_args_clone, stm_get_listing_archive_link()); ?>
					<li>
						<?php if(count(explode('stm_hidden_', $filter_badge_name)) == 1): ?>
							<span><?php
								if($filter_badge_name == 'Popular') {
									esc_html_e( 'Popular', 'motors' );
								} elseif($filter_badge_name == 'Keyword') {
									esc_html_e( 'Keyword', 'motors' );
								} else {
									esc_html_e( stm_get_name_by_slug( strtolower( $filter_badge_name ) ), 'motors' );
								}
							?>:</span>
						<?php endif; ?>
						<?php printf( esc_html__( '%s', 'motors' ), esc_attr( $filter_badge_value['text'] ) ); ?>
						<i data-url="<?php echo esc_url( $link ); ?>"
						   class="fa fa-close stm-clear-listing-one-unit stm-clear-listing-one-unit-classic"
						   data-select="<?php echo esc_attr( $filter_badge_value['slug'] ); ?>"></i>
					</li>
				<?php endif; ?>
			<?php endforeach; ?>
		</ul>
		<?php $filter_badges = ob_get_contents(); ?>
		<?php ob_end_clean(); ?>

		<?php 
		$main_response['listing_query'] = $listing;
		$main_response['posts']               = $posts;
		$main_response['binding']             = $response;
		$main_response['badges']              = $filter_badges;
		$main_response['merge']               = $merged_query_args;
		
		
		if(stm_is_listing()){
			if(!empty($_GET['featured_top']) and $_GET['featured_top']) {
				$main_response['listing_query'] = '';
			}
		}

		if ( ! empty( $stm_location ) and ! empty( $stm_lat ) and ! empty( $stm_lng ) ) {
			$http_query_args['ca_location'] = $stm_location;
			$http_query_args['stm_lat']     = $stm_lat;
			$http_query_args['stm_lng']     = $stm_lng;
		}

		$grid_list_view_type = $http_query_args;

		$grid_list_view_type['view_type'] = 'list';

		$main_response['list_view_link'] = add_query_arg( $grid_list_view_type, stm_get_listing_archive_link() );

		$grid_list_view_type['view_type'] = 'grid';

		$main_response['grid_view_link'] = add_query_arg( $grid_list_view_type, stm_get_listing_archive_link() );

		if ( ! empty( $_GET['view_type'] ) ) {
			$http_query_args['view_type'] = $_GET['view_type'];
		}

		if ( ! empty( $_GET['popular'] ) and $_GET['popular'] == 'true' ) {
			$http_query_args['popular'] = 'true';
		}
		
		if(!empty($_GET['sort_order'])) {
			switch (sanitize_text_field($_GET['sort_order'])) {
			    case "price_low":
					$http_query_args['sort_order'] = 'price_low';
			        break;
			    case "price_high":
					$http_query_args['sort_order'] = 'price_high';
			        break;
			    case "date_low":
					$http_query_args['sort_order'] = 'date_low';
			        break;
			    case "mileage_low":
					$http_query_args['sort_order'] = 'mileage_low';
			        break;
			    case "mileage_high":
					$http_query_args['sort_order'] = 'mileage_high';
			        break;
			    default:
					$http_query_args['sort_order'] = 'date_high';
			}
		}

		$main_response['url'] = add_query_arg( $http_query_args, stm_get_listing_archive_link() );

		if ( $get_title ) {

			$title_default           = get_theme_mod( 'listing_directory_title_default', esc_html__( 'Cars for sale', 'motors' ) );
			$title_generated_postfix = get_theme_mod( 'listing_directory_title_generated_affix', esc_html__( ' for sale', 'motors' ) );

			$title_response = '';

			$titles_args             = stm_get_filter_title();
			$title_generated_counter = 0;
			foreach ( $titles_args as $title_arg ) {
				if ( ! empty( $_GET[ $title_arg['slug'] ] ) ) {
					$title_generated_counter ++;
					$category = get_term_by( 'slug', $_GET[ $title_arg['slug'] ], $title_arg['slug'] );
					$title_response .= ' ' . $category->name;
				}
			}

			if ( empty( $title_response ) ) {
				$title_response = $title_default;
			} else {
				if ( $title_generated_counter == 1 ) {
					$title_response .= ' ' . strtolower( $title_default );
				} else {
					$title_response .= $title_generated_postfix;
				}
			}

			$main_response['title'] = $title_response;
			$main_response['total'] = count( $posts );
		}

		return $main_response;
	} /*function*/
} /*function exists*/


if (!function_exists('stm_filter_price_output')) {
	function stm_filter_price_output($tax_query_args, $listing = false) {
		if ( array_key_exists( 'price', $tax_query_args ) ):
			// no default values. using these as examples

			$args = array(
				'orderby'    => 'name',
				'order'      => 'ASC',
				'hide_empty' => false,
				'fields'     => 'all',
			);

			$prices = array();

			$terms = get_terms( 'price', $args );

			if ( ! empty( $terms ) ):
				foreach ( $terms as $term ) {
					$prices[] = intval( $term->name );
				}
				sort( $prices );
				if ( ! empty( $_GET['min_price'] ) and intval( $_GET['min_price'] ) > 0 ) {
					$price_start = intval( $_GET['min_price'] );
				} else {
					$price_start = $prices[0];
				}
				if ( ! empty( $_GET['max_price'] ) and intval( $_GET['max_price'] ) > 0 ) {
					$price_end = intval( $_GET['max_price'] );
				} else {
					$price_end = $prices[ count( $prices ) - 1 ];
				}
				?>

				<?php if(!$listing): ?>

					<div class="col-md-12 col-sm-12">
						<div class="filter-price">
							<h5><?php _e( 'Select Price', 'motors' ); ?></h5>

							<div class="stm-price-range-unit">
								<div class="stm-price-range"></div>
							</div>
							<div class="row">
								<div class="col-md-6 col-sm-6 col-md-wider-right">
									<input type="text" name="min_price" id="stm_filter_min_price"/>
								</div>
								<div class="col-md-6 col-sm-6 col-md-wider-left">
									<input type="text" name="max_price" id="stm_filter_max_price"/>
								</div>
							</div>
						</div>
					</div>

				<?php else: ?>
					<div class="stm-accordion-single-unit price">
						<a class="title" data-toggle="collapse" href="#price" aria-expanded="true">
							<h5><?php _e( 'Select Price', 'motors' ); ?></h5>
							<span class="minus"></span>
						</a>
						<div class="stm-accordion-content">
							<div class="collapse in content" id="price">
								<div class="stm-accordion-content-wrapper">
									<div class="stm-price-range-unit">
										<div class="stm-price-range"></div>
									</div>
									<div class="row">
										<div class="col-md-6 col-sm-6 col-md-wider-right">
											<input type="text" name="min_price" id="stm_filter_min_price"/>
										</div>
										<div class="col-md-6 col-sm-6 col-md-wider-left">
											<input type="text" name="max_price" id="stm_filter_max_price"/>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				<?php endif; ?>

				<script>
					var stmOptions;
					(function ($) {
						$(document).ready(function () {
							var stmMinPrice = <?php echo esc_js($prices[0]); ?>;
							var stmMaxPrice = <?php echo esc_js($prices[count($prices) -1 ]); ?>;
							stmOptions = {
								range: true,
								min: <?php echo esc_js($prices[0]); ?>,
								max: <?php echo esc_js($prices[count($prices) -1 ]); ?>,
								values: [<?php echo esc_js($price_start); ?>, <?php echo esc_js($price_end); ?>],
								step: 100,
								slide: function (event, ui) {
									$("#stm_filter_min_price").val(ui.values[0]);
									$("#stm_filter_max_price").val(ui.values[1]);
								}
							}
							$(".stm-price-range").slider(stmOptions);


							$("#stm_filter_min_price").val($(".stm-price-range").slider("values", 0));
							$("#stm_filter_max_price").val($(".stm-price-range").slider("values", 1));

							$("#stm_filter_min_price").keyup(function () {
								$(".stm-price-range").slider("values", 0, $(this).val());
							});

							$("#stm_filter_min_price").focusout(function () {
								if ($(this).val() < stmMinPrice) {
									$(".stm-price-range").slider("values", 0, stmMinPrice);
									$(this).val(stmMinPrice);
								}
							});

							$("#stm_filter_max_price").keyup(function () {
								$(".stm-price-range").slider("values", 1, $(this).val());
							});

							$("#stm_filter_max_price").focusout(function () {
								if ($(this).val() > stmMaxPrice) {
									$(".stm-price-range").slider("values", 1, stmMaxPrice);
									$(this).val(stmMaxPrice);
								}
							});
						})
					})(jQuery);
				</script>
			<?php endif; ?>
		<?php endif;
	}
}

if ( ! function_exists('stm_additional_filter_checkboxes') ) {
	function stm_additional_filter_checkboxes() {
		$checkboxes = stm_get_car_filter_checkboxes();

		$selected_options = array();

		if(!empty($checkboxes)) {
			foreach($checkboxes as $checkbox) {
				if(!empty($_GET[$checkbox['slug']])) {
					$selected_options = $_GET[$checkbox['slug']];
					if(!is_array($selected_options)) {
						$selected_options = array('0' => $selected_options);
					}
				}

				if(!empty($checkbox['enable_checkbox_button']) and $checkbox['enable_checkbox_button'] == 1) {
					$stm_checkbox_ajax_button = 'stm-ajax-checkbox-button';
				} else {
					$stm_checkbox_ajax_button = 'stm-ajax-checkbox-instant';
				}
				?>

				<?php
					$terms_args = array(
						'orderby'    => 'name',
						'order'      => 'ASC',
						'hide_empty' => false,
						'fields'     => 'all',
						'pad_counts' => false,
					);
				?>

				<div class="stm-accordion-single-unit stm-listing-directory-checkboxes stm-<?php echo esc_attr($checkbox['listing_rows_numbers'] . ' ' . $stm_checkbox_ajax_button) ?>">
					<a class="title" data-toggle="collapse" href="#accordion-<?php echo esc_attr($checkbox['slug']); ?>" aria-expanded="true">
						<h5><?php esc_html_e($checkbox['single_name'], 'motors'); ?></h5>
						<span class="minus"></span>
					</a>
					<div class="stm-accordion-content">
						<div class="collapse in content" id="accordion-<?php echo esc_attr($checkbox['slug']); ?>">
							<div class="stm-accordion-content-wrapper stm-accordion-content-padded">
								<div class="stm-accordion-inner">
								<?php
									$terms = get_terms($checkbox['slug'], $terms_args);

									if(!empty($terms)){
										foreach($terms as $term) {
											$image = get_option( 'stm_taxonomy_listing_image_' . $term->term_id );
											if(!empty($image)): ?>
											<label class="stm-option-label">
													<?php
													$image = wp_get_attachment_image_src( $image, 'stm-img-190-132' );
													$category_image = $image[0];
													?>
													<div class="stm-option-image">
														<img src="<?php echo esc_url($category_image); ?>" />
													</div>
													<input type="checkbox" name="<?php echo esc_attr($checkbox['slug']) ?>[<?php echo esc_attr($term->slug); ?>]" value="1" <?php if(!empty($selected_options[$term->slug])): ?>checked<?php endif; ?> <?php if(!empty($_GET[$checkbox['slug']]) and $_GET[$checkbox['slug']] == $term->slug): ?>checked<?php endif; ?>/>
													<span><?php echo esc_attr($term->name); ?></span>
												<?php endif; ?>
											</label>
										<?php }
										foreach($terms as $term) {
											$image = get_option( 'stm_taxonomy_listing_image_' . $term->term_id );
											if(empty($image)): ?>
												<label class="stm-option-label">
												<input type="checkbox" name="<?php echo esc_attr($checkbox['slug']) ?>[<?php echo esc_attr($term->slug); ?>]" value="1" <?php if(!empty($selected_options[$term->slug])): ?>checked<?php endif; ?>/>
												<span><?php echo esc_attr($term->name); ?></span>
											<?php endif; ?>
											</label>
										<?php }
									}

									if(!empty($checkbox['enable_checkbox_button']) and $checkbox['enable_checkbox_button'] == 1): ?>
										<div class="clearfix"></div>
										<div class="stm-checkbox-submit">
											<a class="button" href="#"><?php echo esc_html_e('Apply', 'motors'); ?></a>
										</div>
									<?php endif; ?>
								</div>
							</div>
						</div>
					</div>
				</div>
			<?php }
		}
	}
}

