<?php
namespace ThimPress\ThimBlocks\Gutenberg\Blocks\TeamItem;

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

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

/**
 * Class TeamItemBlockType
 *
 * Handle register, render block template for team member item.
 */
class TeamItemBlockType extends AbstractBlockType {
	public $block_name = 'team-item';

	public function get_supports(): array {
		return array(
			'align'                => false,
			'anchor'               => false,
			'customClassName'      => true,
			'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 {
			$wrapper_attributes = get_block_wrapper_attributes(
				array(
					'class' => 'thim-blocks-team-item',
				)
			);

			ob_start();
			echo '<div ' . wp_kses_post( $wrapper_attributes ) . '>';

			// Image
			$default_image = Thim_Blocks::$plugin_url . 'assets/images/default.jpg';

			$image_url = ! empty( $attributes['imageUrl'] )
			? $attributes['imageUrl']
			: $default_image;

			echo '<div class="team-item-image">';
			echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( $attributes['name'] ?? '' ) . '">';
			echo '</div>';

			// Content
			echo '<div class="team-item-content">';

			if ( ! empty( $attributes['name'] ) ) {
				echo '<h5 class="team-item-name">' . esc_html( $attributes['name'] ) . '</h5>';
			}

			if ( ! empty( $attributes['position'] ) ) {
				echo '<p class="team-item-position">' . esc_html( $attributes['position'] ) . '</p>';
			}

			if ( ! empty( $attributes['description'] ) ) {
				echo '<div class="team-item-description">' . wp_kses_post( $attributes['description'] ) . '</div>';
			}

			// Socials
			if ( ! empty( $attributes['socials'] ) && is_array( $attributes['socials'] ) ) {
				echo '<ul class="team-item-socials">';
				foreach ( $attributes['socials'] as $item ) {
					if ( empty( $item['icon'] ) || empty( $item['url'] ) ) {
						continue;
					}
					$icon_class = sanitize_html_class( $item['icon'] );
					echo '<li class="social-item ' . esc_attr( $icon_class ) . '">';
					echo '<a href="' . esc_url( $item['url'] ) . '" target="_blank" rel="noopener noreferrer">';
					echo '<i class="tb-icon-' . esc_attr( $icon_class ) . '"></i>';
					echo '</a></li>';
				}
				echo '</ul>';
			}

			echo '</div>';
			echo '</div>';

			$html = ob_get_clean();

		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

}
