<?php
/**
 * "Dealer Info" block.
 *
 * Renders the dealer-card template part. Resolves the dealer in this order:
 *
 *   1. Inserter `dealerId` attribute (explicit override).
 *   2. Inserter `vehicleId` attribute → its specs-table `dealer_id`.
 *   3. Query Loop `postId` context — if it's a vehicle, use its dealer;
 *      if it's a dealer, use it directly.
 *   4. Global post — same vehicle/dealer detection as #3.
 *
 * The specs table is the canonical source for `dealer_id` (synced from the
 * `_trx_ad_dealer_id` meta by `VehicleSpecsSync`); reading from it avoids
 * the meta-key naming pitfall.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

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

class DealerInfoBlock extends AbstractBlock {

	protected string $slug = 'dealer-info';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$dealer_id = $this->resolveDealerId( $attributes, $block );

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

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

		// Per-field display toggles. Default = on. The CSS hides the
		// matching child element via descendant selectors so the dealer-
		// card template stays untouched.
		$toggle_map = array(
			'showLogo'        => 'no-logo',
			'showHeading'     => 'no-heading',
			'showPhone'       => 'no-phone',
			'showEmail'       => 'no-email',
			'showAddress'     => 'no-address',
			'showWebsite'     => 'no-website',
			'showHours'       => 'no-hours',
			'showMap'         => 'no-map',
			'showDescription' => 'no-description',
			'showCallBtn'     => 'no-call',
			'showWhatsappBtn' => 'no-whatsapp',
			'showEmailBtn'    => 'no-email-btn',
			'showDealerLink'  => 'no-dealer-link',
		);
		foreach ( $toggle_map as $attr => $modifier ) {
			$enabled = ! array_key_exists( $attr, $attributes ) || ! empty( $attributes[ $attr ] );
			if ( ! $enabled ) {
				$class .= ' trx-ad-dealer-card--' . $modifier;
			}
		}

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

	/**
	 * @param array<string, mixed> $attributes
	 * @param mixed                $block
	 */
	private function resolveDealerId( array $attributes, $block ): int {
		$dealer_id = (int) ( $attributes['dealerId'] ?? 0 );
		if ( $dealer_id > 0 ) {
			return $dealer_id;
		}

		$vehicle_id = (int) ( $attributes['vehicleId'] ?? 0 );
		if ( $vehicle_id > 0 ) {
			return $this->dealerForVehicle( $vehicle_id );
		}

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

		$type = get_post_type( $context_id );
		if ( DealerPostType::POST_TYPE === $type ) {
			return $context_id;
		}
		if ( VehiclePostType::POST_TYPE === $type ) {
			return $this->dealerForVehicle( $context_id );
		}

		return 0;
	}

	private function dealerForVehicle( int $vehicleId ): int {
		$specs = getVehicleSpecs( $vehicleId );
		if ( is_array( $specs ) && ! empty( $specs['dealer_id'] ) ) {
			return (int) $specs['dealer_id'];
		}
		// Fallback to direct meta read (handles unsynced rows).
		return (int) get_post_meta( $vehicleId, '_trx_ad_dealer_id', true );
	}
}
