<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\GoogleMaps;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use Throwable;

class GoogleMapsBlockType extends AbstractBlockType {


	public $block_name = 'google-maps';

	public function get_supports(): array {
		return array(
			'align'                => array( 'wide', 'full' ),
			'spacing'              => array(
				'margin'          => true,
				'padding'         => true,
				'defaultControls' => array(
					'margin'  => true,
					'padding' => true,
				),
			),
			'__experimentalBorder' => array(
				'color'  => true,
				'radius' => true,
				'style'  => true,
				'width'  => true,
			),
		);
	}

	public function render_content_block_template( array $attributes, $content, $block ): string {
		$html = '';
		try {
			$address = sanitize_text_field( $attributes['address'] ?? 'London, UK' );
			$zoom    = intval( $attributes['zoom'] ?? 14 );
			$height  = intval( $attributes['height'] ?? 350 );
			$api_key = sanitize_text_field( $attributes['apiKey'] ?? '' );

			if ( ! $address ) {
				return '<div class="thim-blocks-google-maps error">' .
					esc_html__( 'Please provide address or latitude/longitude.', 'thim-blocks' ) . '</div>';
			}

			$src = $api_key
				? sprintf(
					'https://www.google.com/maps/embed/v1/place?q=%s&zoom=%d&key=%s',
					rawurlencode( $address ),
					$zoom,
					$api_key
				)
				: sprintf(
					'https://maps.google.com/maps?q=%s&z=%d&output=embed',
					rawurlencode( $address ),
					$zoom
				);

			ob_start();
			?>
			<?php printf( '<div %s>', wp_kses_post( get_block_wrapper_attributes( array( 'class' => 'thim-blocks-google-maps' ) ) ) ); ?>
				<iframe
					title="Google map"
					src="<?php echo esc_url( $src ); ?>"
					style="width:100%;height:<?php echo esc_attr( $height ); ?>px;border:0;"
					allowfullscreen
					loading="lazy"
					referrerpolicy="no-referrer-when-downgrade"></iframe>
			</div>
			<?php
			$html = ob_get_clean();
		} catch ( Throwable $e ) {
			return $html;
		}
		return $html;
	}

}
