<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\Icon;

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

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

/**
 * Class IconBlockType
 *
 * Handle register, render block template
 */
class IconBlockType extends AbstractBlockType {


	public $block_name = 'icon';

	public function get_supports(): array {
		return array(
			'align'                => true,
			'html'                 => false,
			'spacing'              => array(
				'margin'  => true,
				'padding' => true,
			),
			'__experimentalBorder' => array(
				'color'  => true,
				'radius' => true,
				'style'  => true,
				'width'  => true,
			),
			'typography'           => array(
				'fontSize'        => true,
				'fontWeight'      => true,
				'fontStyle'       => true,
				'textTransform'   => true,
				'defaultControls' => array(
					'fontSize' => true,
				),
			),
			'color'                => array(
				'text'            => true,
				'link'            => true,
				'background'      => true,
				'defaultControls' => array(
					'text'       => true,
					'background' => true,
					'link'       => false,
				),
			),
		);
	}

	/**
	 * Render content of block tag
	 *
	 * @param array $attributes | Attributes of block tag.
	 *
	 * @return false|string
	 */
	public function render_content_block_template( array $attributes, $content, $block ): string {
		$html = '';

		try {
			$iconSVG        = $attributes['iconSVG'] ?? '';
			$iconClass      = esc_attr( $attributes['iconClass'] ?? '' );
			$iconLink       = esc_url( $attributes['iconLink'] ?? '' );
			$iconLinkTarget = ! empty( $attributes['iconLinkTarget'] ) ? ' target="_blank" rel="noopener noreferrer"' : '';

			ob_start();

			$textAlign = $attributes['textAlign'] ?? '';
			$style     = $textAlign ? 'text-align: ' . esc_attr( $textAlign ) . ';' : '';

			$wrapper_args = array(
				'class' => 'thim-blocks-icon',
			);
			if ( $style ) {
				$wrapper_args['style'] = $style;
			}

			$wrapper_attributes = get_block_wrapper_attributes( $wrapper_args );
			echo '<div ' . wp_kses_post( $wrapper_attributes ) . '>';

			if ( $iconLink ) {
				echo '<a href="' . esc_url( $iconLink ) . '"' . esc_attr( $iconLinkTarget ) . '>';
			}

			$svg_output = SVGHelper::render_svg( $iconSVG );

			if ( $svg_output ) {
				echo wp_kses( $svg_output, SVGHelper::allowed_tags() );
			} else {
				echo '<i class="' . esc_attr( $iconClass ?: 'tb-icon-map-pin' ) . '" ></i>';
			}

			if ( $iconLink ) {
				echo '</a>';
			}

			echo '</div>';
			$html = ob_get_clean();
		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

}
