<?php
/**
 * "Vehicle Grid" block.
 *
 * Server-rendered grid of listings honouring inserter-set filters.
 * Routes through `VehicleQuery` per ADR-03 so the block surface returns
 * the same set as the REST and archive paths for the same inputs.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\Search\FilterParams;
use ThemeREX\AutoDealer\Search\VehicleQuery;

class VehicleGridBlock extends AbstractBlock {

	protected string $slug = 'vehicle-grid';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$args = array_filter(
			array(
				'per_page'   => (int) ( $attributes['perPage'] ?? FilterParams::configuredPerPage() ),
				'make'       => (string) ( $attributes['make'] ?? '' ),
				'body_style' => (string) ( $attributes['bodyStyle'] ?? '' ),
				'condition'  => (string) ( $attributes['condition'] ?? '' ),
				'status'     => (string) ( $attributes['status'] ?? '' ),
				'featured'   => ! empty( $attributes['featured'] ) ? 1 : '',
				'orderby'    => (string) ( $attributes['orderby'] ?? 'date' ),
				'order'      => (string) ( $attributes['order'] ?? 'DESC' ),
			),
			static fn( $v ) => '' !== $v && 0 !== $v
		);

		$params = FilterParams::fromArray( $args );
		$rows   = ( new VehicleQuery() )->fetch( $params );

		if ( empty( $rows ) ) {
			return self::capture(
				static function (): void {
					echo '<div class="wp-block-trx-auto-dealer-vehicle-grid trx-ad-grid--empty">';
					echo '<p>' . esc_html__( 'No vehicles match these filters.', 'trx-auto-dealer' ) . '</p>';
					echo '</div>';
				}
			);
		}

		$columns = max( 1, min( 6, (int) ( $attributes['columns'] ?? 3 ) ) );
		$class   = 'wp-block-trx-auto-dealer-vehicle-grid trx-ad-archive__grid';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		// Same display toggles as VehicleCardBlock — applying them to the
		// grid wrapper makes them cascade to every card inside it via the
		// shared `.trx-ad-card-display--*` modifier classes.
		$class .= VehicleCardBlock::renderToggles( $attributes );

		return self::capture(
			static function () use ( $rows, $columns, $class ): void {
				printf(
					'<div class="%1$s" style="--trx-ad-grid-cols: %2$d;">',
					esc_attr( $class ),
					(int) $columns
				);
				foreach ( $rows as $row ) {
					TemplateLoader::getTemplatePart(
						'vehicle-card',
						array(
							'post_id' => (int) $row['ID'],
						)
					);
				}
				echo '</div>';
			}
		);
	}
}
