<?php
/**
 * "Vehicle Search Form" block.
 *
 * Server-rendered. Delegates to the existing `parts/filter-form.php`
 * template part — same behaviour as the archive sidebar form.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

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

class SearchFormBlock extends AbstractBlock {

	protected string $slug = 'search-form';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$action = (string) ( $attributes['action'] ?? '' );
		if ( '' === $action ) {
			$action = (string) ( get_post_type_archive_link( 'trx_ad_listing' ) ?: home_url( '/' ) );
		}

		$cache   = new AggregationCache();
		$options = $cache->remember(
			'archive_filter_options',
			static function (): array {
				$query     = new VehicleQuery();
				$as_terms  = static fn( array $terms ) => array_map(
					static fn( $t ) => array(
						'id'    => (int) $t->term_id,
						'name'  => $t->name,
						'slug'  => $t->slug,
						'count' => (int) $t->count,
					),
					$terms
				);
				$safeTerms = static function ( string $taxonomy ) {
					$terms = get_terms(
						array(
							'taxonomy'   => $taxonomy,
							'hide_empty' => true,
						)
					);
					return is_array( $terms ) ? $terms : array();
				};
				return array(
					'makes'         => $as_terms( $safeTerms( 'trx_ad_make' ) ),
					'body_styles'   => $as_terms( $safeTerms( 'trx_ad_body_style' ) ),
					'fuel_types'    => $as_terms( $safeTerms( 'trx_ad_fuel_type' ) ),
					'conditions'    => $as_terms( $safeTerms( 'trx_ad_condition' ) ),
					'price_range'   => $query->range( 'price' ),
					'year_range'    => $query->range( 'year' ),
					'mileage_range' => $query->range( 'mileage' ),
				);
			}
		);

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

		$class = 'wp-block-trx-auto-dealer-search-form';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		$heading      = isset( $attributes['heading'] ) ? (string) $attributes['heading'] : '';
		$submit_label = isset( $attributes['submitLabel'] ) ? (string) $attributes['submitLabel'] : '';
		$compact      = ! empty( $attributes['compact'] );

		if ( $compact ) {
			$class .= ' trx-ad-search-form--compact';
		}

		// Per-filter toggles. Default = on. The CSS hides matching child
		// fields via `--hide-{filter}` modifiers on the wrapper, so the
		// template stays untouched.
		$toggle_map = array(
			'showKeyword'      => 'keyword',
			'showMake'         => 'make',
			'showModel'        => 'model',
			'showBodyStyle'    => 'body-style',
			'showFuel'         => 'fuel',
			'showCondition'    => 'condition',
			'showYear'         => 'year',
			'showPrice'        => 'price',
			'showMileage'      => 'mileage',
			'showFeatured'     => 'featured',
			'showAccidentFree' => 'accident-free',
		);
		foreach ( $toggle_map as $attr => $modifier ) {
			$enabled = ! array_key_exists( $attr, $attributes ) || ! empty( $attributes[ $attr ] );
			if ( ! $enabled ) {
				$class .= ' trx-ad-search-form--hide-' . $modifier;
			}
		}

		return self::capture(
			static function () use ( $action, $options, $current, $class, $heading, $submit_label ): void {
				echo '<div class="' . esc_attr( $class ) . '">';
				if ( '' !== $heading ) {
					echo '<h2 class="trx-ad-search-form__heading">' . esc_html( $heading ) . '</h2>';
				}
				TemplateLoader::getTemplatePart(
					'filter-form',
					array(
						'action'       => $action,
						'options'      => $options,
						'current'      => $current,
						'submit_label' => $submit_label,
					)
				);
				echo '</div>';
			}
		);
	}
}
