<?php
namespace Bricks;

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

class Next_Step_Button extends Element {
	public $block    = 'core/button';
	public $category = 'fluxtore';
	public $name     = 'next_button';
	public $icon     = 'ti-control-stop';
	public $tag      = 'span';

	public function get_label() {
		return esc_html__( 'Fluxtore Next Step Button', 'fluxtore' );
	}

	public function set_controls() {
		$this->controls['text'] = [
			'type'        => 'text',
			'default'     => esc_html__( 'Fluxtore Next Step Button', 'fluxtore' ),
			'placeholder' => esc_html__( 'Fluxtore Next Step Button', 'fluxtore' ),
		];

		$this->controls['tag'] = [
			'label'          => esc_html__( 'HTML tag', 'fluxtore' ),
			'type'           => 'text',
			'hasDynamicData' => false,
			'inline'         => true,
			'placeholder'    => 'span',
			'required'       => [ 'link', '=', '' ],
		];

		$this->controls['size'] = [
			'label'       => esc_html__( 'Size', 'fluxtore' ),
			'type'        => 'select',
			'options'     => $this->control_options['buttonSizes'],
			'inline'      => true,
			'reset'       => true,
			'placeholder' => esc_html__( 'Default', 'fluxtore' ),
		];

		$this->controls['style'] = [
			'label'       => esc_html__( 'Style', 'fluxtore' ),
			'type'        => 'select',
			'options'     => $this->control_options['styles'],
			'inline'      => true,
			'reset'       => true,
			'default'     => 'primary',
			'placeholder' => esc_html__( 'None', 'fluxtore' ),
		];

		$this->controls['circle'] = [
			'label' => esc_html__( 'Circle', 'fluxtore' ),
			'type'  => 'checkbox',
			'reset' => true,
		];

		$this->controls['outline'] = [
			'label' => esc_html__( 'Outline', 'fluxtore' ),
			'type'  => 'checkbox',
			'reset' => true,
		];

		// Icon
		$this->controls['iconSeparator'] = [
			'label' => esc_html__( 'Icon', 'fluxtore' ),
			'type'  => 'separator',
		];

		$this->controls['icon'] = [
			'label' => esc_html__( 'Icon', 'fluxtore' ),
			'type'  => 'icon',
		];

		$this->controls['iconTypography'] = [
			'label'    => esc_html__( 'Typography', 'fluxtore' ),
			'type'     => 'typography',
			'css'      => [
				[
					'property' => 'font',
					'selector' => 'i',
				],
			],
			'required' => [ 'icon.icon', '!=', '' ],
		];

		$this->controls['iconPosition'] = [
			'label'       => esc_html__( 'Position', 'fluxtore' ),
			'type'        => 'select',
			'options'     => $this->control_options['iconPosition'],
			'inline'      => true,
			'placeholder' => esc_html__( 'Right', 'fluxtore' ),
			'required'    => [ 'icon', '!=', '' ],
		];

		$this->controls['iconGap'] = [
			'label'    => esc_html__( 'Gap', 'fluxtore' ),
			'type'     => 'number',
			'units'    => true,
			'css'      => [
				[
					'property' => 'gap',
				],
			],
			'required' => [ 'icon', '!=', '' ],
		];

		$this->controls['iconSpace'] = [
			'label'    => esc_html__( 'Space between', 'fluxtore' ),
			'type'     => 'checkbox',
			'css'      => [
				[
					'property' => 'justify-content',
					'value'    => 'space-between',
				],
			],
			'required' => [ 'icon', '!=', '' ],
		];
	}

	public function render() {
      global $post;
		$post_id = $post->ID;
		$post_meta = get_post_meta($post_id);
		$page_id = isset($post_meta['__fluxtore__flow'][0]) ? $post_meta['__fluxtore__flow'][0] : null;

		if ($page_id) {
			$page_meta = get_post_meta($page_id);
			if (isset($page_meta['__fluxtore__steps'][0])) {
				$steps = unserialize($page_meta['__fluxtore__steps'][0]);
				$current_step_index = array_search($post_id, $steps);

				if ($current_step_index !== false && isset($steps[$current_step_index + 1])) {
					$next_step_id = $steps[$current_step_index + 1];
					$next_step_url = get_permalink($next_step_id);
				}

		} 
		}
		
		$next_step_url= isset($next_step_url) ? $next_step_url :  '#';
		$settings = $this->settings;

		$this->set_attribute( '_root', 'class', 'bricks-button' );

		if ( ! empty( $settings['size'] ) ) {
			$this->set_attribute( '_root', 'class', $settings['size'] );
		}

		if ( ! empty( $settings['style'] ) ) {
			// Outline
			if ( isset( $settings['outline'] ) ) {
				$this->set_attribute( '_root', 'class', 'outline' );
				$this->set_attribute( '_root', 'class', "bricks-color-{$settings['style']}" );
			}

			// Fill (= default)
			else {
				$this->set_attribute( '_root', 'class', "bricks-background-{$settings['style']}" );
			}
		}

		// Button circle
		if ( isset( $settings['circle'] ) ) {
			$this->set_attribute( '_root', 'class', 'circle' );
		}

		if ( isset( $settings['block'] ) ) {
			$this->set_attribute( '_root', 'class', 'block' );
		}

	
		 $settings['link'] = array("type" => "external", "url" => $next_step_url);
		
		if ( ! empty( $settings['link'] ) ) {
			$this->tag = 'a';

			$this->set_link_attributes( '_root', $settings['link'] );
		}

		$output = "<{$this->tag} {$this->render_attributes( '_root' )}>";

		$icon          = ! empty( $settings['icon'] ) ? self::render_icon( $settings['icon'] ) : false;
		$icon_position = ! empty( $settings['iconPosition'] ) ? $settings['iconPosition'] : 'right';

		if ( $icon && $icon_position === 'left' ) {
			$output .= $icon;
		}

		if ( isset( $settings['text'] ) ) {
			$output .= trim( $settings['text'] );
		}

		if ( $icon && $icon_position === 'right' ) {
			$output .= $icon;
		}

		$output .= "</{$this->tag}>";

		echo $output;
	}

	public static function render_builder() { ?>
		<script type="text/x-template" id="tmpl-bricks-next-button">
			<component
				:is="settings.link ? 'a' : settings.tag ? settings.tag : 'span'"
				:class="[
					'bricks-button',
					settings.size ? settings.size : null,
					settings.style ? settings.outline ? `outline bricks-color-${settings.style}` : `bricks-background-${settings.style}` : null,
					settings.circle ? 'circle' : null,
					settings.block ? 'block' : null,
					settings.icon && settings.iconPosition ? `icon-${settings.iconPosition}` : null,
					settings.icon && !settings.iconPosition ? 'icon-right' : null
				]">
				<icon-svg v-if="settings.iconPosition === 'left' && (settings?.icon?.icon || settings?.icon?.svg)" :iconSettings="settings.icon"/>
				<contenteditable tag="span" :name="name" controlKey="text" toolbar="style" :settings="settings"/>
				<icon-svg v-if="settings.iconPosition !== 'left' && (settings?.icon?.icon || settings?.icon?.svg)" :iconSettings="settings.icon"/>
			</component>
		</script>
		<?php
	}

	public function convert_element_settings_to_block( $settings ) {
		$text = isset( $settings['text'] ) ? trim( $settings['text'] ) : false;

		if ( ! $text ) {
			return;
		}

		$text = str_replace( 'draggable="false"', '', $text );
		$text = str_replace( 'draggable="true"', '', $text );

		$block = [ 'blockName' => 'core/buttons' ];

		$attributes = [];

		$html = '<div class="wp-block-buttons"><!-- wp:button -->';

		if ( isset( $settings['outline'] ) ) {
			$attributes['className'] = 'is-style-outline';
			$html                   .= '<div class="wp-block-button is-style-outline">';
		} else {
			$html .= '<div class="wp-block-button"><a class="wp-block-button__link">';
		}

		if ( isset( $settings['_border']['radius']['top'] ) ) {
			$attributes['borderRadius'] = intval( $settings['_border']['radius']['top'] );
		}

		$html .= $text . '</a></div><!-- /wp:button --></div>';

		$block['attrs']        = $attributes;
		$block['innerContent'] = [ $html ];

		return $block;
	}

	public function convert_block_to_element_settings( $block, $attributes ) {
		$text = strip_tags( $block['innerHTML'] );

		$element_settings = [
			'text'  => $text,
			'style' => 'dark',
		];

		$border_radius = isset( $attributes['borderRadius'] ) ? intval( $attributes['borderRadius'] ) : false;

		// Outline
		if ( isset( $attributes['className'] ) && strpos( $attributes['className'], 'is-style-outline' ) !== false ) {
			$element_settings['outline'] = true;
		}

		if ( $border_radius ) {
			$element_settings['_border'] = [
				'radius' => [
					'top'    => $border_radius,
					'right'  => $border_radius,
					'bottom' => $border_radius,
					'left'   => $border_radius,
				],
			];
		}

		return $element_settings;
	}
}
