<?php
/**
 * Similar Vehicles block — N listings similar to the current vehicle.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class SimilarVehiclesBlock extends AbstractBlock {

	protected string $slug = 'similar-vehicles';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$post_id = $this->resolveVehicleId( $attributes, $block );
		if ( $post_id <= 0 || VehiclePostType::POST_TYPE !== get_post_type( $post_id ) ) {
			return '';
		}

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

		$limit = max( 1, min( 12, (int) ( $attributes['limit'] ?? 4 ) ) );

		return self::capture(
			static function () use ( $post_id, $limit, $class ): void {
				echo '<div class="' . esc_attr( $class ) . '">';
				TemplateLoader::getTemplatePart(
					'vehicle-similar',
					array(
						'post_id' => $post_id,
						'limit'   => $limit,
					)
				);
				echo '</div>';
			}
		);
	}

	/**
	 * @param array<string, mixed> $attributes
	 * @param mixed                $block
	 */
	private function resolveVehicleId( array $attributes, $block ): int {
		$id = (int) ( $attributes['vehicleId'] ?? 0 );
		if ( $id > 0 ) {
			return $id;
		}
		if ( $block && isset( $block->context['postId'] ) ) {
			return (int) $block->context['postId'];
		}
		return (int) ( get_the_ID() ?: 0 );
	}
}
