<?php
/**
 * "Specs Table" block.
 *
 * Renders the grouped vehicle-specs-table template part for a vehicle.
 * Resolves which vehicle to render the same way as VehicleCardBlock:
 *
 *   1. Inserter `vehicleId` attribute (explicit override).
 *   2. The Query Loop's `postId` context.
 *   3. The current global post (single-vehicle template fallback).
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

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

class SpecsTableBlock extends AbstractBlock {

	protected string $slug = 'specs-table';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$post_id = (int) ( $attributes['vehicleId'] ?? 0 );

		if ( $post_id <= 0 && $block instanceof \WP_Block && isset( $block->context['postId'] ) ) {
			$post_id = (int) $block->context['postId'];
		}
		if ( $post_id <= 0 ) {
			$post_id = (int) get_the_ID();
		}

		if ( $post_id <= 0 || VehiclePostType::POST_TYPE !== get_post_type( $post_id ) ) {
			return '';
		}

		$specs = getVehicleSpecs( $post_id );
		if ( ! is_array( $specs ) || empty( $specs ) ) {
			return '';
		}

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

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