<?php
/**
 * Template part: filter-form
 *
 * Renders the inventory filter sidebar. Submission is a normal GET with
 * filter keys that match the REST API (see FilterParams::TEXT_FILTERS).
 * The JS layer then handles cascading make→model and the live count
 * preview without taking over the form's submit behaviour.
 *
 * Variables in scope (from TemplateLoader::getTemplatePart):
 *   $current   array<string,mixed>  Sanitised current filter values from $_GET.
 *   $options   array<string,mixed>  Same shape as /search-options REST.
 *   $year_min  int   Min year known across listings.
 *   $year_max  int   Max year known across listings.
 *   $price_max int   Max price known across listings.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

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

$current   = isset( $current ) && is_array( $current ) ? $current : array();
$options   = isset( $options ) && is_array( $options ) ? $options : array();
$action    = (string) ( $action ?? get_post_type_archive_link( 'trx_ad_listing' ) ?: home_url( '/' ) );

$makes       = $options['makes'] ?? array();
$body_styles = $options['body_styles'] ?? array();
$fuel_types  = $options['fuel_types'] ?? array();
$conditions  = $options['conditions'] ?? array();
$price_range = $options['price_range'] ?? array(
	'min' => 0,
	'max' => 0,
);
$year_range  = $options['year_range'] ?? array(
	'min' => 0,
	'max' => (int) gmdate( 'Y' ),
);
$mileage_range = $options['mileage_range'] ?? array(
	'min' => 0,
	'max' => 0,
);

$value = static function ( string $key ) use ( $current ): string {
	return isset( $current[ $key ] ) ? (string) $current[ $key ] : '';
};
?>
<form
	class="trx-ad-filter-form"
	method="get"
	action="<?php echo esc_url( $action ); ?>"
	data-trx-ad-filters
	role="search"
	aria-label="<?php esc_attr_e( 'Filter inventory', 'trx-auto-dealer' ); ?>">

	<?php
	// GET forms replace the action's query string with the form data, so any
	// args baked into the action URL (post_type=trx_ad_listing on plain
	// permalinks) must be re-emitted as hidden inputs or they are lost on
	// submit — both by the browser and by the AJAX URL builder.
	$trx_ad_action_query = (string) wp_parse_url( $action, PHP_URL_QUERY );
	if ( '' !== $trx_ad_action_query ) {
		$trx_ad_action_args = array();
		wp_parse_str( $trx_ad_action_query, $trx_ad_action_args );
		foreach ( $trx_ad_action_args as $trx_ad_arg_key => $trx_ad_arg_value ) {
			if ( is_scalar( $trx_ad_arg_value ) ) {
				printf(
					'<input type="hidden" name="%s" value="%s" />',
					esc_attr( (string) $trx_ad_arg_key ),
					esc_attr( (string) $trx_ad_arg_value )
				);
			}
		}
	}
	?>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--keyword">
		<label for="trx-ad-filter-search"><?php esc_html_e( 'Keyword', 'trx-auto-dealer' ); ?></label>
		<input
			type="search"
			id="trx-ad-filter-search"
			name="search"
			value="<?php echo esc_attr( $value( 'search' ) ); ?>"
			placeholder="<?php esc_attr_e( 'Search by title, VIN or stock #', 'trx-auto-dealer' ); ?>" />
	</div>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--make">
		<label for="trx-ad-filter-make"><?php esc_html_e( 'Make', 'trx-auto-dealer' ); ?></label>
		<select id="trx-ad-filter-make" name="make" data-trx-ad-make>
			<option value=""><?php esc_html_e( 'Any make', 'trx-auto-dealer' ); ?></option>
			<?php foreach ( $makes as $term ) : ?>
				<option
					value="<?php echo esc_attr( (string) $term['slug'] ); ?>"
					data-id="<?php echo esc_attr( (string) $term['id'] ); ?>"
					<?php selected( $value( 'make' ), $term['slug'] ); ?>>
					<?php echo esc_html( (string) $term['name'] ); ?>
					<span class="trx-ad-filter-form__count">(<?php echo (int) $term['count']; ?>)</span>
				</option>
			<?php endforeach; ?>
		</select>
	</div>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--model">
		<label for="trx-ad-filter-model"><?php esc_html_e( 'Model', 'trx-auto-dealer' ); ?></label>
		<select id="trx-ad-filter-model" name="model" data-trx-ad-model
			<?php disabled( '' === $value( 'make' ) ); ?>>
			<option value=""><?php esc_html_e( 'Any model', 'trx-auto-dealer' ); ?></option>
			<?php
			// Initial population happens server-side only when a make is selected,
			// so the form is usable without JS. JS will swap this list on change.
			//
			// Models link to makes via the `_trx_ad_model_make` term meta
			// (managed by `Taxonomies\ModelMakeLink`), NOT via the WP
			// taxonomy parent — `parent` would always return empty here
			// since the taxonomies are flat. Mirror DealersController::get_models
			// strategies so the dropdown stays in sync with the REST endpoint.
			if ( '' !== $value( 'make' ) ) {
				$make_term = get_term_by( 'slug', $value( 'make' ), 'trx_ad_make' );
				if ( $make_term instanceof \WP_Term ) {
					$model_terms = get_terms(
						array(
							'taxonomy'   => 'trx_ad_model',
							'hide_empty' => false,
							'meta_query' => array(
								array(
									'key'   => \ThemeREX\AutoDealer\Taxonomies\ModelMakeLink::META_KEY,
									'value' => (string) $make_term->term_id,
								),
							),
						)
					);
					// Intersect with models that actually appear on a
					// published listing tagged with this make. Sites with
					// 30 model terms linked to "Ford" but only 2 in stock
					// would otherwise surface all 30 in the dropdown.
					if ( is_array( $model_terms ) && ! empty( $model_terms ) ) {
						$mk_ids = get_posts(
							array(
								'post_type'      => 'trx_ad_listing',
								'post_status'    => 'publish',
								'fields'         => 'ids',
								'posts_per_page' => 500,
								'no_found_rows'  => true,
								'tax_query'      => array(
									array(
										'taxonomy' => 'trx_ad_make',
										'field'    => 'term_id',
										'terms'    => (int) $make_term->term_id,
									),
								),
							)
						);
						$in_use = array();
						foreach ( $mk_ids as $lid ) {
							$ids = wp_get_object_terms( (int) $lid, 'trx_ad_model', array( 'fields' => 'ids' ) );
							if ( ! is_wp_error( $ids ) && is_array( $ids ) ) {
								foreach ( $ids as $id ) {
									$in_use[ (int) $id ] = true;
								}
							}
						}
						if ( ! empty( $in_use ) ) {
							$model_terms = array_filter(
								$model_terms,
								static fn( $t ) => isset( $in_use[ (int) $t->term_id ] )
							);
						}
					}
					if ( ! is_array( $model_terms ) || empty( $model_terms ) || is_wp_error( $model_terms ) ) {
						// Fallback: derive models from listings tagged with this make.
						$listing_ids = get_posts(
							array(
								'post_type'      => 'trx_ad_listing',
								'post_status'    => 'publish',
								'fields'         => 'ids',
								'posts_per_page' => 500,
								'no_found_rows'  => true,
								'tax_query'      => array(
									array(
										'taxonomy' => 'trx_ad_make',
										'field'    => 'term_id',
										'terms'    => (int) $make_term->term_id,
									),
								),
							)
						);
						$model_ids = array();
						foreach ( $listing_ids as $lid ) {
							$ids = wp_get_object_terms( (int) $lid, 'trx_ad_model', array( 'fields' => 'ids' ) );
							if ( ! is_wp_error( $ids ) && is_array( $ids ) ) {
								foreach ( $ids as $id ) {
									$model_ids[ (int) $id ] = true;
								}
							}
						}
						if ( ! empty( $model_ids ) ) {
							$model_terms = get_terms(
								array(
									'taxonomy'   => 'trx_ad_model',
									'hide_empty' => false,
									'include'    => array_keys( $model_ids ),
								)
							);
						}
					}
					if ( is_array( $model_terms ) ) {
						foreach ( $model_terms as $mt ) {
							printf(
								'<option value="%1$s" data-id="%2$d" %3$s>%4$s</option>',
								esc_attr( $mt->slug ),
								(int) $mt->term_id,
								selected( $value( 'model' ), $mt->slug, false ),
								esc_html( $mt->name )
							);
						}
					}
				}
			}
			?>
		</select>
	</div>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--body-style">
		<label for="trx-ad-filter-body-style"><?php esc_html_e( 'Body style', 'trx-auto-dealer' ); ?></label>
		<select id="trx-ad-filter-body-style" name="body_style">
			<option value=""><?php esc_html_e( 'Any body style', 'trx-auto-dealer' ); ?></option>
			<?php foreach ( $body_styles as $term ) : ?>
				<option value="<?php echo esc_attr( (string) $term['slug'] ); ?>" <?php selected( $value( 'body_style' ), $term['slug'] ); ?>>
					<?php echo esc_html( (string) $term['name'] ); ?>
				</option>
			<?php endforeach; ?>
		</select>
	</div>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--fuel">
		<label for="trx-ad-filter-fuel"><?php esc_html_e( 'Fuel type', 'trx-auto-dealer' ); ?></label>
		<select id="trx-ad-filter-fuel" name="fuel_type">
			<option value=""><?php esc_html_e( 'Any fuel', 'trx-auto-dealer' ); ?></option>
			<?php foreach ( $fuel_types as $term ) : ?>
				<option value="<?php echo esc_attr( (string) $term['slug'] ); ?>" <?php selected( $value( 'fuel_type' ), $term['slug'] ); ?>>
					<?php echo esc_html( (string) $term['name'] ); ?>
				</option>
			<?php endforeach; ?>
		</select>
	</div>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--condition">
		<label for="trx-ad-filter-condition"><?php esc_html_e( 'Condition', 'trx-auto-dealer' ); ?></label>
		<select id="trx-ad-filter-condition" name="condition">
			<option value=""><?php esc_html_e( 'Any condition', 'trx-auto-dealer' ); ?></option>
			<?php foreach ( $conditions as $term ) : ?>
				<option value="<?php echo esc_attr( (string) $term['slug'] ); ?>" <?php selected( $value( 'condition' ), $term['slug'] ); ?>>
					<?php echo esc_html( (string) $term['name'] ); ?>
				</option>
			<?php endforeach; ?>
		</select>
	</div>

	<fieldset class="trx-ad-filter-form__field trx-ad-filter-form__field--range trx-ad-filter-form__field--year">
		<legend><?php esc_html_e( 'Year', 'trx-auto-dealer' ); ?></legend>
		<input type="number" name="year_from" min="<?php echo (int) $year_range['min']; ?>" max="<?php echo (int) $year_range['max']; ?>"
			value="<?php echo esc_attr( $value( 'year_from' ) ); ?>"
			placeholder="<?php echo esc_attr( __( 'From', 'trx-auto-dealer' ) . ' ' . (int) $year_range['min'] ); ?>"
			aria-label="<?php esc_attr_e( 'Year from', 'trx-auto-dealer' ); ?>" />
		<input type="number" name="year_to" min="<?php echo (int) $year_range['min']; ?>" max="<?php echo (int) $year_range['max']; ?>"
			value="<?php echo esc_attr( $value( 'year_to' ) ); ?>"
			placeholder="<?php echo esc_attr( __( 'To', 'trx-auto-dealer' ) . ' ' . (int) $year_range['max'] ); ?>"
			aria-label="<?php esc_attr_e( 'Year to', 'trx-auto-dealer' ); ?>" />
	</fieldset>

	<fieldset class="trx-ad-filter-form__field trx-ad-filter-form__field--range trx-ad-filter-form__field--price">
		<legend><?php esc_html_e( 'Price', 'trx-auto-dealer' ); ?></legend>
		<input type="number" name="price_from" min="0" step="100"
			value="<?php echo esc_attr( $value( 'price_from' ) ); ?>"
			placeholder="<?php esc_attr_e( 'Min', 'trx-auto-dealer' ); ?>"
			aria-label="<?php esc_attr_e( 'Price from', 'trx-auto-dealer' ); ?>" />
		<input type="number" name="price_to" min="0" step="100"
			value="<?php echo esc_attr( $value( 'price_to' ) ); ?>"
			placeholder="<?php echo esc_attr( __( 'Max', 'trx-auto-dealer' ) . ' ' . (int) $price_range['max'] ); ?>"
			aria-label="<?php esc_attr_e( 'Price to', 'trx-auto-dealer' ); ?>" />
	</fieldset>

	<fieldset class="trx-ad-filter-form__field trx-ad-filter-form__field--range trx-ad-filter-form__field--mileage">
		<legend><?php esc_html_e( 'Mileage', 'trx-auto-dealer' ); ?></legend>
		<input type="number" name="mileage_from" min="0" step="1000"
			value="<?php echo esc_attr( $value( 'mileage_from' ) ); ?>"
			placeholder="<?php esc_attr_e( 'Min', 'trx-auto-dealer' ); ?>"
			aria-label="<?php esc_attr_e( 'Mileage from', 'trx-auto-dealer' ); ?>" />
		<input type="number" name="mileage_to" min="0" step="1000"
			value="<?php echo esc_attr( $value( 'mileage_to' ) ); ?>"
			placeholder="<?php echo esc_attr( __( 'Max', 'trx-auto-dealer' ) . ' ' . (int) $mileage_range['max'] ); ?>"
			aria-label="<?php esc_attr_e( 'Mileage to', 'trx-auto-dealer' ); ?>" />
	</fieldset>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--checkbox trx-ad-filter-form__field--featured">
		<label>
			<input type="checkbox" name="featured" value="1" <?php checked( $value( 'featured' ), '1' ); ?> />
			<?php esc_html_e( 'Featured listings only', 'trx-auto-dealer' ); ?>
		</label>
	</div>

	<div class="trx-ad-filter-form__field trx-ad-filter-form__field--checkbox trx-ad-filter-form__field--accident-free">
		<label>
			<input type="checkbox" name="accident_free" value="1" <?php checked( $value( 'accident_free' ), '1' ); ?> />
			<?php esc_html_e( 'Accident-free only', 'trx-auto-dealer' ); ?>
		</label>
	</div>

	<div class="trx-ad-filter-form__actions">
		<button type="submit" class="trx-ad-filter-form__submit">
			<?php
			$label = isset( $submit_label ) && '' !== $submit_label
				? (string) $submit_label
				: __( 'Apply', 'trx-auto-dealer' );
			echo esc_html( $label );
			?>
			<span class="trx-ad-filter-form__count-pill" data-trx-ad-count hidden></span>
		</button>
		<a class="trx-ad-filter-form__reset" href="<?php echo esc_url( $action ); ?>">
			<?php esc_html_e( 'Reset', 'trx-auto-dealer' ); ?>
		</a>
	</div>
</form>
