<?php
/**
 * Single Listing block — full default vehicle layout via the
 * `parts/single-listing.php` template part.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

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

class SingleListingBlock extends AbstractBlock {

	protected string $slug = 'single-listing';

	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-single-listing';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		return self::capture(
			static function () use ( $post_id, $class ): void {
				echo '<div class="' . esc_attr( $class ) . '">';
				TemplateLoader::getTemplatePart( 'single-listing', array( 'post_id' => $post_id ) );
				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 );
	}
}
