<?php
/**
 * "Comparison Table" block — side-by-side spec table for queued vehicles.
 *
 * Same surface as the `[trx_ad_compare]` shortcode + the Elementor
 * "Comparison Bar" widget: heading + empty-state text + a configurable
 * field list. Delegates to `CompareHandler::renderPage()` so output is
 * lock-step with the other surfaces; JS hydrates the table from
 * localStorage on the client.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\CompareHandler;

class ComparisonTableBlock extends AbstractBlock {

	protected string $slug = 'comparison-table';

	public function render( array $attributes, string $content = '', $block = null ): string {
		// Resolve fields. Editor sends an array of selected keys; if empty
		// the renderer falls back to CompareHandler::defaultFields().
		$fields = array();
		if ( isset( $attributes['fields'] ) && is_array( $attributes['fields'] ) ) {
			$valid_keys = CompareHandler::compareFieldConfigKeys();
			foreach ( $attributes['fields'] as $key ) {
				$key = sanitize_key( (string) $key );
				if ( isset( $valid_keys[ $key ] ) ) {
					$fields[] = $key;
				}
			}
		}

		// The block always shows a heading (embeds sit inside arbitrary page
		// content, unlike the shortcode's dedicated titled page): the block
		// attribute when set, the historical default otherwise.
		$heading = isset( $attributes['heading'] ) ? trim( (string) $attributes['heading'] ) : '';
		if ( '' === $heading ) {
			$heading = __( 'Compare Vehicles', 'trx-auto-dealer' );
		}

		$html = CompareHandler::renderPage( $fields, $heading );

		// Optional empty-message override applied via post-process regex so
		// the data-* selectors the JS hydrator hooks onto stay intact.
		$empty = isset( $attributes['emptyMessage'] ) ? trim( (string) $attributes['emptyMessage'] ) : '';
		if ( '' !== $empty ) {
			$html = (string) preg_replace(
				'/(<p[^>]*data-trx-ad-compare-empty[^>]*>)[^<]*(<\\/p>)/',
				'$1' . esc_html( $empty ) . '$2',
				$html,
				1
			);
		}

		// Apply caller-provided className to the outer section so editors can
		// hook block style variations / spacing controls onto it.
		if ( ! empty( $attributes['className'] ) ) {
			$class = sanitize_html_class( (string) $attributes['className'] );
			$html  = (string) preg_replace(
				'/(<section[^>]*class="trx-ad-compare-page)(")/',
				'$1 ' . $class . '$2',
				$html,
				1
			);
		}

		return $html;
	}
}
