<?php
if ( !defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

function mobile_api_shortcode_vehicle_archive( $atts = array() ) {
	/* $has_request_params = isset( $_REQUEST['fuel'] ) || isset( $_REQUEST['gearbox'] ) || isset( $_REQUEST['category'] ) || isset( $_REQUEST['mileageMin'] ) || isset( $_REQUEST['mileageMax'] ) || isset( $_REQUEST['firstRegistrationMin'] ) || isset( $_REQUEST['firstRegistrationMax'] );

	if ( $has_request_params ) :
		if ( empty( $_REQUEST['mobile_api_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['mobile_api_nonce'] ) ), 'mobile_api-shortcode-nonce' ) )
			return esc_html__( 'Your session has expired. Please reload page and try again.', 'ad-integration-for-mobile-de-api' );
	endif; */

	$content = '';

	// Attributes
	$category = ( !empty( $atts ) && array_key_exists( 'category', $atts ) ) ? sanitize_key( $atts['category'] ) : '';
	$category = is_array( $category ) ? implode( ',', $category ) : $category; // Blocks
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$category = isset( $_REQUEST['category'] ) ? sanitize_key( wp_unslash( $_REQUEST['category'] ) ) : $category; // Filter via GET Parameter
	$page = ( !empty( $atts ) && array_key_exists( 'page', $atts ) ) ? absint( $atts['page'] ) : 1;
	$ajax = ( !empty( $atts ) && array_key_exists( 'ajax', $atts ) ) ? $atts['ajax'] : false;
	$align = ( !empty( $atts ) && array_key_exists( 'align', $atts ) ) ? 'align'.sanitize_html_class( $atts['align'] ) : '';

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$fuel = isset( $_REQUEST['fuel'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['fuel'] ) ) : '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$gearbox = isset( $_REQUEST['gearbox'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['gearbox'] ) ) : '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$firstRegistrationMin = isset( $_REQUEST['firstRegistrationMin'] ) && $_REQUEST['firstRegistrationMin'] > 1990 ? sanitize_key( wp_unslash( $_REQUEST['firstRegistrationMin'] ) ) : 0;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$firstRegistrationMax = isset( $_REQUEST['firstRegistrationMax'] ) ? sanitize_key( wp_unslash( $_REQUEST['firstRegistrationMax'] ) ) : gmdate( 'Y' );
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$mileageMin = isset( $_REQUEST['mileageMin'] ) ? intval( $_REQUEST['mileageMin'] ) : 0;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$mileageMax = isset( $_REQUEST['mileageMax'] ) ? intval( $_REQUEST['mileageMax'] ) : 200000;

	if ( !$ajax ) :
		$content .= '<div class="vehicle-archive-grid '.esc_attr( $align ).'">';

		if ( !array_key_exists( 'mobileadid', $atts ) && !array_key_exists( 'filter', $atts ) ) {
			$action_url = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ).'#vehicle-filter' : '';
			$content .= '<form id="vehicle-filter" action="'.esc_url( $action_url ).'" method="GET">';
				$filter = get_option( 'mobile_api_filter', array( 'category' ) );

				if ( in_array( 'category', $filter ) ) :
					// translators: %s is the filter attribute
					$content .= '<p class="vehicle-filter-form-element"><label for="category">'.sprintf( esc_html__( 'Filter by %s:', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Model', 'ad-integration-for-mobile-de-api' ) ).'</label><select name="category" id="category">';
						// translators: %s is the filter attribute
						$content .= '<option value="0">'.sprintf( esc_html__( 'Filter by %s', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Model', 'ad-integration-for-mobile-de-api' ) ).'</option>';
						$terms = get_terms( array( 'taxonomy' => 'mobile_api_vehicle_category' ) );
						foreach ( $terms AS $term )
							$content .= sprintf( '<option value="%s" %s>%s (%d)</option>', esc_attr( $term->slug ), selected( $category, $term->slug, false ), esc_html( $term->name ), absint( $term->count ) );
					$content .= '</select></p>';
				endif;

				if ( mobile_api_is_licensed() && in_array( 'fuel', $filter ) ) :
					// translators: %s is the filter attribute
					$content .= '<p class="vehicle-filter-form-element"><label for="fuel">'.sprintf( esc_html__( 'Filter by %s:', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Fuel', 'ad-integration-for-mobile-de-api' ) ).'</label><select name="fuel" id="fuel">';
						// translators: %s is the filter attribute
						$content .= '<option value="0">'.sprintf( esc_html__( 'Filter by %s', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Fuel', 'ad-integration-for-mobile-de-api' ) ).'</option>';

						$fuels = mobile_api_get_available_meta_options( 'fuel' );
						foreach ( $fuels AS $key => $value )
							$content .= sprintf( '<option value="%s" %s>%s</option>', esc_attr( $value ), selected( $fuel, $value, false ), esc_html( mobile_api_translate_data_value( $value ) ) );
					$content .= '</select></p>';
				endif;

				if ( mobile_api_is_licensed() && in_array( 'gearbox', $filter ) ) :
					// translators: %s is the filter attribute
					$content .= '<p class="vehicle-filter-form-element"><label for="gearbox">'.sprintf( esc_html__( 'Filter by %s:', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Gear', 'ad-integration-for-mobile-de-api' ) ).'</label><select name="gearbox" id="gearbox">';
						// translators: %s is the filter attribute
						$content .= '<option value="0">'.sprintf( esc_html__( 'Filter by %s', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Gear', 'ad-integration-for-mobile-de-api' ) ).'</option>';

						$gearboxes = mobile_api_get_available_meta_options( 'gearbox' );
						foreach ( $gearboxes AS $key => $value )
							$content .= sprintf( '<option value="%s" %s>%s</option>', esc_attr( $value ), selected( $gearbox, $value, false ), esc_html( mobile_api_translate_data_value( $value ) ) );
					$content .= '</select></p>';
				endif;

				if ( mobile_api_is_licensed() && in_array( 'firstRegistration', $filter ) ) :
					// translators: %s is the filter attribute
					$content .= '<div class="vehicle-filter-form-element"><label>'.sprintf( esc_html__( 'Filter by %s:', 'ad-integration-for-mobile-de-api' ), esc_html__( 'First Registration', 'ad-integration-for-mobile-de-api' ) ).'</label>';
						$content .= '<div class="dual-range-slider">';
							$content .= '<div class="dual-range-slider-output">';
								$content .= '<output id="firstRegistrationMinOutput">'.number_format_i18n( intval( $firstRegistrationMin ), 0 ).'</output>';
								$content .= '<output id="firstRegistrationMaxOutput">'.number_format_i18n( intval( $firstRegistrationMax ), 0 ).'</output>';
							$content .= '</div>';
							$content .= '<div class="dual-range-slider-track">';
								$content .= '<input type="range" name="firstRegistrationMin" id="firstRegistrationMin" min="1990" max="'.intval( gmdate( 'Y' ) ).'" step="1" value="'.intval( $firstRegistrationMin ).'">';
								$content .= '<input type="range" name="firstRegistrationMax" id="firstRegistrationMax" min="1990" max="'.intval( gmdate( 'Y' ) ).'" step="1" value="'.intval( $firstRegistrationMax ).'">';
							$content .= '</div>';
						$content .= '</div>';
					$content .= '</div>';
				endif;

				if ( mobile_api_is_licensed() && in_array( 'mileage', $filter ) ) :
					// translators: %s is the filter attribute
					$content .= '<div class="vehicle-filter-form-element"><label>'.sprintf( esc_html__( 'Filter by %s:', 'ad-integration-for-mobile-de-api' ), esc_html__( 'Mileage', 'ad-integration-for-mobile-de-api' ) ).'</label>';
						$content .= '<div class="dual-range-slider">';
							$content .= '<div class="dual-range-slider-output">';
								$content .= '<output id="mileageMinOutput">'.number_format_i18n( intval( $mileageMin ), 0 ).'</output>';
								$content .= '<output id="mileageMaxOutput">'.number_format_i18n( intval( $mileageMax ), 0 ).'</output>';
							$content .= '</div>';
							$content .= '<div class="dual-range-slider-track">';
								$content .= '<input type="range" name="mileageMin" id="mileageMin" min="0" max="200000" step="5000" value="'.intval( $mileageMin ).'">';
								$content .= '<input type="range" name="mileageMax" id="mileageMax" min="0" max="200000" step="5000" value="'.intval( $mileageMax ).'">';
							$content .= '</div>';
						$content .= '</div>';
					$content .= '</div>';
				endif;

				$content .= '<input type="hidden" name="mobile_api_nonce" value="' . esc_attr( wp_create_nonce( 'mobile_api-shortcode-nonce' ) ) . '">';
			$content .= '</form>';
		}
	endif;

	$args = array( 'post_type' => 'mobile-api-vehicle', 'paged' => $page );

	if ( !empty( $category ) ) :
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
		$args['tax_query'] = array( array(
			'taxonomy' => 'mobile_api_vehicle_category',
			'field'    => 'slug',
			'terms'    => array_map( 'sanitize_key', explode( ',', $category ) )
		) );
	endif;

	if ( !empty( $fuel ) )
		$atts['fuel'] = $fuel;

	if ( !empty( $gearbox ) )
		$atts['gearbox'] = $gearbox;

	if ( !empty( $firstRegistrationMin ) && !empty( $firstRegistrationMax ) )
		$atts['firstRegistration'] = $firstRegistrationMin.'01,'.$firstRegistrationMax.'12';

	if ( !empty( $mileageMin ) && !empty( $mileageMax ) )
		$atts['mileage'] = $mileageMin.','.$mileageMax;

	unset( $atts['category'], $atts['page'], $atts['ajax'], $atts['align'], $atts['limit'], $atts['posts'] );

	if ( !empty( $atts ) ) :
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
		$args['meta_query'] = array( 'RELATION' => 'AND' );
		foreach ( $atts AS $key => $value ) :
			if ( $key == 'filter' )
				continue;

			if ( str_contains( $value, ',' ) ) :
				$args['meta_query'][] = array(
					'key'     => 'mobile_api_'.sanitize_key( $key ),
					'value'   => explode( ',', $value ),
					'type'    => 'NUMERIC',
					'compare' => 'BETWEEN',
				);
			else :
				$args['meta_query'][] = array(
					'key'     => 'mobile_api_'.sanitize_key( $key ),
					'value'   => sanitize_text_field( $value ),
					'compare' => '=',
				);
			endif;
		endforeach;
	endif;

	$orderby = get_option( 'mobile_api_orderby' );
	if ( !empty( $orderby ) && $orderby == 'title' ) :
		$args['order'] = 'ASC';
		$args['orderby'] = $orderby;
	elseif ( !empty( $orderby ) && $orderby == 'mileage' ) :
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		$args['meta_key'] = 'mobile_api_'.$orderby;
		$args['order'] = 'ASC';
		$args['orderby'] = 'meta_value_num';
	endif;

	$posts = new WP_Query( $args );

	if ( !$posts->have_posts() )
		return $content.'<p class="no-results">'.esc_html__( 'No vehicle is currently available. Please visit us again soon.', 'ad-integration-for-mobile-de-api' ).'</p></div>';

	while ( $posts->have_posts() ) {
		$posts->the_post();

		$post_id = get_the_ID();
		$terms = get_the_terms( $post_id, 'mobile_api_vehicle_category' );
		$price = maybe_unserialize( get_post_meta( $post_id, 'mobile_api_price', true ) );
		$condition = get_post_meta( $post_id, 'mobile_api_condition', true );
		$mileage = absint( get_post_meta( $post_id, 'mobile_api_mileage', true ) );
		$power = absint( get_post_meta( $post_id, 'mobile_api_power', true ) );
		$fuel = get_post_meta( $post_id, 'mobile_api_fuel', true );
		$firstRegistration = get_post_meta( $post_id, 'mobile_api_firstRegistration', true );
		$consumptions = maybe_unserialize( get_post_meta( $post_id, 'mobile_api_consumptions', true ) );
		$emissions = maybe_unserialize( get_post_meta( $post_id, 'mobile_api_emissions', true ) );

		$content .= '<article class="vehicle-content-container">
			<a class="overlay-link" href="'.esc_url( get_permalink( $post_id ) ).'" title="'.esc_attr( get_the_title( $post_id ) ).'" aria-label="'.esc_attr( get_the_title( $post_id ) ).'"></a>

			<figure>
				<img src="'.esc_url( get_the_post_thumbnail_url( $post_id ) ).'" alt="'.esc_attr( get_the_title( $post_id ) ).'">
				<figcaption>'.esc_html( get_the_title( $post_id ) ).'</figcaption>
			</figure>
			<div>
				<h2>'.esc_html( implode( ' › ', wp_list_pluck( $terms, 'name' ) ) ).'</h2>
				<h3>'.esc_html( get_the_title( $post_id ) ).'</h3>
				<p class="price">
					<span class="woocommerce-Price-amount amount"><bdi>'.esc_html( number_format_i18n( $price->consumerPriceGross, 0 ) ).' <span class="woocommerce-Price-currencySymbol">€</span></bdi></span>';
					if ( property_exists( $price, 'consumerPriceNet' ) && property_exists( $price, 'vatRate' ) ) {
						// translators: %s is the formatted price and the rounded vat rate
						$content .= '<span class="tax-info">'.sprintf( esc_html__( '%s (net)', 'ad-integration-for-mobile-de-api' ), floatval( number_format_i18n( $price->consumerPriceNet, 2 ) ) ).', '.sprintf( esc_html__( '%s VAT', 'ad-integration-for-mobile-de-api' ), round( $price->vatRate ).'%' ).'</span>';
					} else
						$content .= '<span class="tax-info">'.esc_html__( 'VAT not included', 'ad-integration-for-mobile-de-api' ).'</span>';
				$content .= '</p>
				<p>
					<strong>'.esc_html( mobile_api_translate_data_value( $condition ) ).'</strong>';

					if ( !empty( $power ) )
						$content .= ', '.esc_html( $power ).' kW ('.round( $power * 1.35962 ).' PS)';

					if ( !empty( $mileage ) )
						$content .= ', '.esc_html( number_format_i18n( $mileage, 0 ) ).' km';

					if ( !empty( $fuel ) )
						$content .= ', '.esc_html( mobile_api_translate_data_value( $fuel ) );

					if ( !empty( $firstRegistration ) )
						$content .= ', '.esc_html__( 'First Registration', 'ad-integration-for-mobile-de-api' ).' '.esc_html( substr( $firstRegistration, 4, 6 ) ).'/'.esc_html( substr( $firstRegistration, 0, -2 ) );

					if ( !empty( $consumptions ) ) {
						if ( property_exists( $consumptions, 'weightedCombinedFuel' ) && property_exists( $consumptions, 'weightedCombinedPower' ) )
							$content .= ', '.esc_html__( 'Consumptions (weighted combined):', 'ad-integration-for-mobile-de-api' ).' '.esc_html( number_format_i18n( $consumptions->weightedCombinedFuel, 1 ) ).' '.esc_html( mobile_api_translate_consumption_unit( 'fuel' ) ).' + '.esc_html( number_format_i18n( $consumptions->weightedCombinedPower, 1 ) ).' '.esc_html( mobile_api_translate_consumption_unit( 'power' ) );

						foreach ( $consumptions AS $fuel => $consumption ) {
							if ( !empty( $consumption ) && property_exists( $consumption, 'combined' ) ) {
								if ( count( get_object_vars( $consumptions ) ) > 1 )
									$content .= ', '.esc_html( mobile_api_translate_consumption_title( $fuel, true ) );
								else
									$content .= ', '.esc_html__( 'Consumptions:', 'ad-integration-for-mobile-de-api' );

								$content .= ' '.esc_html( number_format_i18n( $consumption->combined, 1 ) ).' '.esc_html( mobile_api_translate_consumption_unit( $fuel ) ).' '.esc_html__( '(combined)', 'ad-integration-for-mobile-de-api' );
							}
						}
					}

					if ( !empty( $emissions ) && property_exists( $emissions, 'combined' ) && count( (array)$emissions->combined ) ) {
						$classes = array();
						foreach ( $emissions as $emission )
							$classes[] = $emission->co2Class;

						$content .= ', '.esc_html__( 'CO₂ emissions (combined):', 'ad-integration-for-mobile-de-api' ).' '.esc_html( $emissions->combined->co2 ).' g/km, '.esc_html__( 'CO₂ class (combined):', 'ad-integration-for-mobile-de-api' ).' '.esc_html( implode( ' + ', $classes ) );
					}
				$content .= '</p>
				<p><a href="'.esc_url( get_the_permalink( $post_id ) ).'" class="'.esc_attr( mobile_api_get_button_classes( $post_id ) ).'">'.esc_html__( 'More details', 'ad-integration-for-mobile-de-api' ).'</a></p>
			</div>
		</article>';
	}
	wp_reset_postdata();

	$page++;
	$posts_per_page = get_option( 'posts_per_page' );
	$limit = $posts->max_num_pages;
	if ( !$ajax && $page <= $limit ) :
		if ( mobile_api_is_licensed() ) {
			$content .= '<div id="skeleton-container">';
				for ( $i = 0; $i < $posts_per_page; $i++ )
					$content .= '<div class="skeleton vehicle-content-container"><figure></figure><div><h2></h2><h3></h3><p class="price"></p><p></p><p><a href="#" class="'.esc_attr( mobile_api_get_button_classes() ).'">'.esc_html__( 'More details', 'ad-integration-for-mobile-de-api' ).'</a></p></div></div>';
			$content .= '</div>';

			$content .= '<p><a href="#" class="load-more-vehicles '.esc_attr( mobile_api_get_button_classes() ).'" data-category="'.esc_attr( $category ).'" data-posts="'.esc_attr( $posts_per_page ).'" data-page="'.esc_attr( $page ).'" data-limit="'.esc_attr( $limit ).'" data-meta="'.esc_attr( maybe_serialize( $atts ) ).'">'.esc_html__( 'Load more vehicles', 'ad-integration-for-mobile-de-api' ).'</a></p>';
		} else {
			$content .= '<p>'.esc_html__( 'Not all vehicles are currently displayed.', 'ad-integration-for-mobile-de-api' ).'</p>';

			if ( current_user_can( 'administrator' ) ) {
				$content .= '<p>'.esc_html__( 'To display all vehicles, <a href="https://commotion.online/en/shop/mobile-api-pro-license/" target="_blank">buy a license in the ComMotion online shop</a>. This notice is only displayed to admins and is not visible publicly.', 'ad-integration-for-mobile-de-api' ).'</p>';
			}
		}
	endif;

	if ( !$ajax && !array_key_exists( 'mobileadid', $atts ) ) {
		// translators: %d is the total amount of vehicles
		$content .= '<p class="vehicle-results">'.sprintf( _n( '%d vehicle total', '%d vehicles total', intval( $posts->found_posts ), 'ad-integration-for-mobile-de-api' ), intval( $posts->found_posts ) ).'</p>';
	}

	if ( !$ajax )
		$content .= '<em>'.wp_kses_post( mobile_api_get_wltp_hint().mobile_api_get_emissions_hint() ).'</em></div>';

	return $content;
}

function mobile_api_add_shortcodes() {
	add_shortcode( 'mobile-api-vehicle-archive', 'mobile_api_shortcode_vehicle_archive' );
}
add_action( 'init', 'mobile_api_add_shortcodes' );
