<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class IconBoxWidget extends WidgetBase {
	public function get_type(): string { return 'icon_box'; }
	public function get_title(): string { return 'Caixa de ícone'; }
	public function get_icon(): string { return 'icon_box'; }
	public function get_defaults(): array {
		return array(
			'icon'        => '◆',
			'title'       => 'Título',
			'description' => 'Descrição da caixa de ícone.',
			'link'        => '',
			'align'       => 'center',
		);
	}
	public function sanitize_settings( array $settings ): array {
		$align = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true ) ? (string) $settings['align'] : 'center';
		$icon  = wp_strip_all_tags( (string) ( $settings['icon'] ?? '◆' ) );
		if ( mb_strlen( $icon ) > 8 ) {
			$icon = mb_substr( $icon, 0, 8 );
		}
		return array(
			'icon'        => $icon !== '' ? $icon : '◆',
			'title'       => sanitize_text_field( (string) ( $settings['title'] ?? '' ) ),
			'description' => sanitize_textarea_field( (string) ( $settings['description'] ?? '' ) ),
			'link'        => esc_url_raw( (string) ( $settings['link'] ?? '' ) ),
			'align'       => $align,
		);
	}
	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$align = esc_attr( (string) ( $s['align'] ?? 'center' ) );
		$body  = '<div class="ab-icon-box__icon">' . esc_html( (string) ( $s['icon'] ?? '◆' ) ) . '</div>'
			. '<div class="ab-icon-box__body">'
			. '<h3 class="ab-icon-box__title">' . esc_html( (string) ( $s['title'] ?? '' ) ) . '</h3>'
			. '<p class="ab-icon-box__desc">' . esc_html( (string) ( $s['description'] ?? '' ) ) . '</p>'
			. '</div>';
		$link = (string) ( $s['link'] ?? '' );
		if ( $link !== '' ) {
			$body = '<a class="ab-icon-box__link" href="' . esc_url( $link ) . '">' . $body . '</a>';
		}
		return '<div class="ab-icon-box" style="text-align:' . $align . '">' . $body . '</div>';
	}
}
