<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class ButtonWidget extends WidgetBase {

	public function get_type(): string {
		return 'button';
	}

	public function get_title(): string {
		return 'Botão';
	}

	public function get_icon(): string {
		return 'mouse-pointer-click';
	}

	public function get_defaults(): array {
		return array(
			'text'  => 'Saiba mais',
			'url'   => '#',
			'align' => 'left',
		);
	}

	public function get_controls(): array {
		return array(
			array( 'type' => 'text', 'name' => 'text', 'label' => 'Texto' ),
			array( 'type' => 'url', 'name' => 'url', 'label' => 'Link' ),
			array(
				'type'    => 'select',
				'name'    => 'align',
				'label'   => 'Alinhamento',
				'options' => array(
					array( 'value' => 'left', 'label' => 'Esquerda' ),
					array( 'value' => 'center', 'label' => 'Centro' ),
					array( 'value' => 'right', 'label' => 'Direita' ),
				),
			),
		);
	}

	public function sanitize_settings( array $settings ): array {
		$align = isset( $settings['align'] ) ? (string) $settings['align'] : 'left';
		if ( ! in_array( $align, array( 'left', 'center', 'right' ), true ) ) {
			$align = 'left';
		}
		return array(
			'text'  => sanitize_text_field( (string) ( $settings['text'] ?? 'Saiba mais' ) ),
			'url'   => esc_url_raw( (string) ( $settings['url'] ?? '#' ) ),
			'align' => $align,
		);
	}

	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$text  = esc_html( (string) ( $s['text'] ?? 'Botão' ) );
		$url   = esc_url( (string) ( $s['url'] ?? '#' ) );
		$align = esc_attr( (string) ( $s['align'] ?? 'left' ) );
		$extra = ! empty( $context['editor'] ) ? ' onclick="return false"' : '';
		// wp-element-button: theme link color (a:not(.wp-element-button)) must NOT recolor us.
		return '<div class="ab-btn-wrap" style="text-align:' . $align . '">'
			. '<a class="ab-btn wp-element-button" href="' . $url . '"' . $extra . '>' . $text . '</a></div>';
	}
}
