<?php
/**
 * Template: archive-vehicle
 *
 * Vehicle listing archive page.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

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

use ThemeREX\AutoDealer\Cache\AggregationCache;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\Search\VehicleQuery;

TemplateLoader::renderHeader();

/**
 * Filter the archive page title.
 *
 * @param string $title The page title.
 */
$archive_title = apply_filters( 'trx_ad_archive_title', __( 'Inventory', 'trx-auto-dealer' ) );

$total = (int) $GLOBALS['wp_query']->found_posts;

$current_filters = array();
foreach ( wp_unslash( $_GET ) as $k => $v ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( is_string( $v ) ) {
		$current_filters[ sanitize_key( $k ) ] = sanitize_text_field( $v );
	}
}

// Narrow the filter sidebar's facet options + ranges by the active
// $_GET filters, so picking "make=ford" hides body styles + fuel types
// not present in any Ford listing AND scopes the year/price/mileage
// range hints. Same logic as /search-options when narrowing params are
// present. Cache key folds in the active filters so each permutation
// caches independently.
$narrow      = array();
$narrow_keys = array( 'make', 'model', 'body_style', 'fuel_type', 'condition', 'transmission', 'drivetrain' );
foreach ( $narrow_keys as $k ) {
	$v = $current_filters[ $k ] ?? '';
	if ( '' !== (string) $v ) {
		$narrow[ $k ] = (string) $v;
	}
}

$cache_name = 'archive_filter_options' . ( ! empty( $narrow ) ? ':' . substr( sha1( (string) wp_json_encode( $narrow ) ), 0, 12 ) : '' );

$cache          = new AggregationCache();
$filter_options = $cache->remember(
	$cache_name,
	static function () use ( $narrow ): array {
		$ctrl     = new \ThemeREX\AutoDealer\REST\SearchController();
		$post_ids = ! empty( $narrow ) ? $ctrl->resolveNarrowingPostIds( $narrow ) : null;
		$query    = new VehicleQuery();
		return array(
			'makes'         => $ctrl->getTaxonomyOptions( 'trx_ad_make', $post_ids ),
			'body_styles'   => $ctrl->getTaxonomyOptions( 'trx_ad_body_style', $post_ids ),
			'fuel_types'    => $ctrl->getTaxonomyOptions( 'trx_ad_fuel_type', $post_ids ),
			'conditions'    => $ctrl->getTaxonomyOptions( 'trx_ad_condition', $post_ids ),
			'price_range'   => $ctrl->rangeFor( $query, 'price', $post_ids ),
			'year_range'    => $ctrl->rangeFor( $query, 'year', $post_ids ),
			'mileage_range' => $ctrl->rangeFor( $query, 'mileage', $post_ids ),
		);
	}
);
?>

<div class="trx-ad-archive">

	<header class="trx-ad-archive__header">
		<h1 class="trx-ad-archive__title"><?php echo esc_html( $archive_title ); ?></h1>
		<p class="trx-ad-archive__count" data-trx-ad-result-count role="status" aria-live="polite">
			<?php
			printf(
				/* translators: %s: number of vehicles */
				esc_html( _n( '%s vehicle found', '%s vehicles found', $total, 'trx-auto-dealer' ) ),
				esc_html( number_format_i18n( $total ) )
			);
			?>
		</p>

		<div class="trx-ad-archive__toolbar">
			<button
				type="button"
				class="trx-ad-archive__filter-toggle"
				data-trx-ad-filter-toggle
				aria-expanded="false"
				aria-controls="trx-ad-archive-sidebar">
				<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
					<line x1="4" y1="6" x2="20" y2="6"/>
					<line x1="7" y1="12" x2="17" y2="12"/>
					<line x1="10" y1="18" x2="14" y2="18"/>
				</svg>
				<?php esc_html_e( 'Filters', 'trx-auto-dealer' ); ?>
			</button>

			<?php
			$current_sort = isset( $_GET['orderby'] ) ? sanitize_key( (string) wp_unslash( $_GET['orderby'] ) ) : (string) \ThemeREX\AutoDealer\getSettings( 'default_sort', 'newest' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$sort_options = array(
				'newest'     => __( 'Newest first', 'trx-auto-dealer' ),
				'price_asc'  => __( 'Price: low to high', 'trx-auto-dealer' ),
				'price_desc' => __( 'Price: high to low', 'trx-auto-dealer' ),
				'year_desc'  => __( 'Year: newest first', 'trx-auto-dealer' ),
			);
			?>
			<label class="trx-ad-archive__sort">
				<span class="trx-ad-archive__sort-label"><?php esc_html_e( 'Sort by', 'trx-auto-dealer' ); ?></span>
				<select data-trx-ad-sort>
					<?php foreach ( $sort_options as $value => $label ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current_sort, $value ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</label>
		</div>
	</header>

	<div class="trx-ad-archive__layout">

		<aside class="trx-ad-archive__sidebar" id="trx-ad-archive-sidebar">
			<button
				type="button"
				class="trx-ad-archive__sidebar-close"
				data-trx-ad-filter-close
				aria-label="<?php esc_attr_e( 'Close filters', 'trx-auto-dealer' ); ?>">
				<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
					<line x1="6" y1="6" x2="18" y2="18"/>
					<line x1="6" y1="18" x2="18" y2="6"/>
				</svg>
			</button>
			<?php
			TemplateLoader::getTemplatePart(
				'filter-form',
				array(
					'current' => $current_filters,
					'options' => $filter_options,
					'action'  => get_post_type_archive_link( 'trx_ad_listing' ),
				)
			);
			?>
		</aside>

		<div class="trx-ad-archive__results" role="region" aria-label="<?php esc_attr_e( 'Vehicle listings', 'trx-auto-dealer' ); ?>">

			<h2 class="trx-ad-archive__results-heading trx-ad-sr-only">
				<?php esc_html_e( 'Vehicle listings', 'trx-auto-dealer' ); ?>
			</h2>

			<?php if ( have_posts() ) : ?>

				<div class="trx-ad-archive__grid">
					<?php
					while ( have_posts() ) :
						the_post();
						TemplateLoader::getTemplatePart(
							'vehicle-card',
							array(
								'post_id' => get_the_ID(),
							)
						);
					endwhile;
					?>
				</div>

				<nav class="trx-ad-archive__pagination" aria-label="<?php esc_attr_e( 'Vehicle listing pagination', 'trx-auto-dealer' ); ?>">
					<?php
					the_posts_pagination(
						array(
							'mid_size'  => 2,
							'prev_text' => '&larr; ' . esc_html__( 'Previous', 'trx-auto-dealer' ),
							'next_text' => esc_html__( 'Next', 'trx-auto-dealer' ) . ' &rarr;',
							'class'     => 'trx-ad-pagination',
						)
					);
					?>
				</nav>

			<?php else : ?>

				<div class="trx-ad-archive__no-results">
					<h2><?php esc_html_e( 'No vehicles found', 'trx-auto-dealer' ); ?></h2>
					<p><?php esc_html_e( 'Try adjusting your search criteria or browse all available vehicles.', 'trx-auto-dealer' ); ?></p>
				</div>

			<?php endif; ?>

		</div>

	</div>

</div>

<?php
TemplateLoader::renderFooter();
