<?php
/**
 * Map View widget — embeds an OpenStreetMap iframe centered on a dealer.
 *
 * Free tier: lightweight OSM iframe (no API key, no JS). Per ADR-11, the
 * full interactive Google Maps + Leaflet map is Pro tier; the Pro plugin
 * filters `trx_ad_map_view_render` to swap in the richer implementation.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\PostTypes\DealerPostType;
use function ThemeREX\AutoDealer\getDealerMeta;

class MapViewWidget extends Widget_Base {

	public function get_name(): string {
		return 'trx_ad_map_view';
	}

	public function get_title(): string {
		return __( 'Dealer Map', 'trx-auto-dealer' );
	}

	public function get_icon(): string {
		return 'eicon-google-maps';
	}

	public function get_categories(): array {
		return array( 'trx-auto-dealer' );
	}

	public function get_keywords(): array {
		return array( 'map', 'location', 'dealer', 'address' );
	}

	public function get_style_depends(): array {
		return array( 'trx-ad-frontend' );
	}

	public function get_script_depends(): array {
		return array( 'trx-ad-frontend' );
	}

	protected function register_controls(): void {
		$this->start_controls_section(
			'section_content',
			array(
				'label' => __( 'Content', 'trx-auto-dealer' ),
			)
		);

		$this->add_control(
			'dealer_id',
			array(
				'label'       => __( 'Dealer', 'trx-auto-dealer' ),
				'type'        => Controls_Manager::SELECT2,
				'options'     => WidgetHelpers::dealerOptions( __( '— Use current dealer —', 'trx-auto-dealer' ) ),
				'default'     => '',
				'label_block' => true,
			)
		);

		$this->add_control(
			'zoom',
			array(
				'label'   => __( 'Zoom Level', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'medium',
				'options' => array(
					'tight'  => __( 'Tight (~0.005)', 'trx-auto-dealer' ),
					'medium' => __( 'Medium (~0.02)', 'trx-auto-dealer' ),
					'wide'   => __( 'Wide (~0.08)', 'trx-auto-dealer' ),
				),
			)
		);

		$this->add_responsive_control(
			'height',
			array(
				'label'     => __( 'Map Height', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min' => 200,
						'max' => 800,
					),
				),
				'default'   => array(
					'size' => 320,
					'unit' => 'px',
				),
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-map-view iframe' => 'height: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_style',
			array(
				'label' => __( 'Style', 'trx-auto-dealer' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'border_radius',
			array(
				'label'      => __( 'Border Radius', 'trx-auto-dealer' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px' ),
				'selectors'  => array(
					'{{WRAPPER}} .trx-ad-map-view iframe' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings  = $this->get_settings_for_display();
		$dealer_id = (int) ( $settings['dealer_id'] ?? 0 );
		if ( $dealer_id <= 0 ) {
			$dealer_id = ElementorPreviewContext::resolveDealerId();
		}

		if ( $dealer_id <= 0 || DealerPostType::POST_TYPE !== get_post_type( $dealer_id ) ) {
			if ( ElementorPreviewContext::isEditor() ) {
				echo '<p>' . esc_html__( 'No dealer selected.', 'trx-auto-dealer' ) . '</p>';
			}
			return;
		}

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

		if ( '' === $lat || '' === $lng || ! is_numeric( $lat ) || ! is_numeric( $lng ) ) {
			if ( ElementorPreviewContext::isEditor() ) {
				echo '<p>' . esc_html__( 'Dealer is missing latitude/longitude.', 'trx-auto-dealer' ) . '</p>';
			}
			return;
		}

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

		$zoom_map = array(
			'tight'  => 0.005,
			'medium' => 0.02,
			'wide'   => 0.08,
		);
		$pad      = $zoom_map[ (string) ( $settings['zoom'] ?? 'medium' ) ] ?? 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 )
		);

		$src = (string) apply_filters( 'trx_ad_map_view_iframe_src', $src, $dealer_id, $meta );
		?>
		<div class="trx-ad-map-view">
			<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%; border:0; display:block;"
			></iframe>
		</div>
		<?php
	}
}
