<?php
/**
 * "Vehicle Contact Form" block.
 *
 * Thin wrapper around `Forms\FormRenderer::render()` so editors can drop any
 * of the configured forms (inquiry, test_drive, callback, finance, trade_in)
 * onto a page and bind it to a vehicle.
 *
 * Vehicle resolution (same order as the rest of the suite):
 *   1. Inserter `vehicleId` attribute.
 *   2. Query Loop `postId` context.
 *   3. Global post.
 *
 * Lead handling (validation, sanitisation, email, REST endpoint) lives in
 * `Forms\FormHandler` — this block only renders the markup.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Forms\FormConfig;
use ThemeREX\AutoDealer\Forms\FormRenderer;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class ContactFormBlock extends AbstractBlock {

	protected string $slug = 'contact-form';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$form_id = (string) ( $attributes['formId'] ?? 'inquiry' );
		if ( ! FormConfig::get( $form_id ) ) {
			$form_id = 'inquiry';
		}

		$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();
		}

		// Bind to a vehicle only when the resolved post actually IS a vehicle;
		// otherwise render the form unattached (lead has no vehicle context).
		if ( $post_id > 0 && VehiclePostType::POST_TYPE !== get_post_type( $post_id ) ) {
			$post_id = 0;
		}

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

		$title = isset( $attributes['title'] ) ? (string) $attributes['title'] : '';

		$form_html = FormRenderer::render( $form_id, $post_id );
		if ( '' === trim( $form_html ) ) {
			return '';
		}

		return self::capture(
			static function () use ( $class, $title, $form_html ): void {
				echo '<div class="' . esc_attr( $class ) . '">';
				if ( '' !== $title ) {
					echo '<h2 class="trx-ad-form__heading">' . esc_html( $title ) . '</h2>';
				}
				echo wp_kses( $form_html, \ThemeREX\AutoDealer\allowedHtml() );
				echo '</div>';
			}
		);
	}
}
