<?php
/**
 * "Dealer Map" block — OpenStreetMap iframe centered on a dealer.
 *
 * Same surface as the Elementor "Dealer Map" widget. Free tier emits a
 * lightweight OSM iframe (no API key, no JS). Per ADR-11, the richer
 * interactive Google Maps + Leaflet implementation is Pro tier — it
 * filters `trx_ad_map_view_iframe_src` to swap in its own URL/iframe.
 *
 * Dealer resolution chain:
 *   1. explicit `dealerId` attribute
 *   2. context vehicle's `_trx_ad_dealer_id` meta
 *   3. context dealer post directly
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\PostTypes\DealerPostType;

use function ThemeREX\AutoDealer\getDealerMeta;

class MapViewBlock extends AbstractBlock {

	protected string $slug = 'map-view';

	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 '';
		}

		$meta = getDealerMeta( $dealer_id );
		$lat  = (string) ( $meta['latitude'] ?? '' );
		$lng  = (string) ( $meta['longitude'] ?? '' );

		if ( '' === $lat || '' === $lng || ! is_numeric( $lat ) || ! is_numeric( $lng ) ) {
			return '';
		}

		$lat_f = (float) $lat;
		$lng_f = (float) $lng;

		$zoom_map = array(
			'tight'  => 0.005,
			'medium' => 0.02,
			'wide'   => 0.08,
		);
		$zoom     = (string) ( $attributes['zoom'] ?? 'medium' );
		$pad      = $zoom_map[ $zoom ] ?? 0.02;

		$bbox   = sprintf( '%f,%f,%f,%f', $lng_f - $pad, $lat_f - $pad / 2, $lng_f + $pad, $lat_f + $pad / 2 );
		$marker = sprintf( '%f,%f', $lat_f, $lng_f );
		$src    = sprintf(
			'https://www.openstreetmap.org/export/embed.html?bbox=%s&layer=mapnik&marker=%s',
			rawurlencode( $bbox ),
			rawurlencode( $marker )
		);

		// Pro plugin swaps in an interactive Google Maps / Leaflet iframe here.
		$src = (string) apply_filters( 'trx_ad_map_view_iframe_src', $src, $dealer_id, $meta );

		$height = max( 200, min( 800, (int) ( $attributes['height'] ?? 320 ) ) );
		$class  = 'trx-ad-map-view';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		ob_start();
		?>
		<div class="<?php echo esc_attr( $class ); ?>">
			<iframe
				src="<?php echo esc_url( $src ); ?>"
				loading="lazy"
				referrerpolicy="no-referrer-when-downgrade"
				title="<?php echo esc_attr( get_the_title( $dealer_id ) ); ?>"
				style="width:100%; height:<?php echo (int) $height; ?>px; border:0; display:block;"
			></iframe>
		</div>
		<?php
		return (string) ob_get_clean();
	}

	/**
	 * Resolve dealer ID: explicit attribute → context vehicle's dealer →
	 * context dealer post itself.
	 *
	 * @param array<string, mixed> $attributes
	 * @param mixed                $block
	 */
	private function resolveDealerId( array $attributes, $block ): int {
		$id = (int) ( $attributes['dealerId'] ?? 0 );
		if ( $id > 0 ) {
			return $id;
		}

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

		$post_type = get_post_type( $context_post_id );
		if ( DealerPostType::POST_TYPE === $post_type ) {
			return $context_post_id;
		}
		if ( 'trx_ad_listing' === $post_type ) {
			$linked = (int) get_post_meta( $context_post_id, '_trx_ad_dealer_id', true );
			if ( $linked > 0 ) {
				return $linked;
			}
		}
		return 0;
	}
}
