<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\{Helpers, Compare};

class AddToCompare extends \Bricks\Element {
	public $category = 'compare';
	public $name 	= 'bu-atcomp';
	public $icon 	= 'ti-reload';
	public $compareItems = [];

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Add To Compare', 'bricksultimate' );
	}

	// Set builder controls
	public function set_controls() {
		$this->controls['postType'] = [
			'type'        => 'select',
			'label'       => esc_html__( 'Post type', 'bricks' ),
			'options'     => \Bricks\Helpers::get_registered_post_types(),
			'multiple'    => false,
			'placeholder' => esc_html__( 'Select post type', 'bricks' ),
			'default' 	=> 'post'
		];

		$this->controls['cmpRemoveAction'] = [
			'label' 	=> esc_html__('Disable remove action', 'bricksultimate'),
			'type' 		=> 'checkbox',
		];

		$this->controls['compIcon'] = [
			'label' 	=> esc_html__('Default icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'themify',
				'icon'    => 'ti-reload',
			]
		];

		$this->controls['compAddedIcon'] = [
			'label' 	=> esc_html__('Added icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'themify',
				'icon'    => 'ti-check',
			],
			'rerender' => false
		];

		$this->controls['compSpinnerIcon'] = [
			'label' 	=> esc_html__('Loading icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'themify',
				'icon'    => 'ti-control-record',
			],
			'rerender' => false
		];

		$this->controls['iconSize'] = [
			'label'    => esc_html__( 'Size', 'bricks' ),
			'type'     => 'number',
			'units'    => true,
			'required' => [ 'compIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'font-size',
					'selector' => '.bu-comp-icon'
				],
			],
			'rerender' => false
		];

		$this->controls['iconSpinnerSize'] = [
			'label'    => esc_html__( 'Loading icon size', 'bricks' ),
			'type'     => 'number',
			'units'    => true,
			'required' => [ 'compSpinnerIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'font-size',
					'selector' => '.bu-comp-icon.spinner-icon'
				],
			],
			'rerender' => false
		];

		$this->controls['iconColor'] = [
			'label'    => esc_html__( 'Compare icon color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'compIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.bu-comp-icon.default-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.bu-comp-icon.default-icon'
				],
			],
			'rerender' => false
		];

		$this->controls['iconHColor'] = [
			'label'    => esc_html__( 'Compare icon hover color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'compIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '&:hover .default-icon'
				],
				[
					'property' => 'fill',
					'selector' => '&:hover .default-icon'
				],
			],
			'rerender' => false
		];

		$this->controls['iconAddedColor'] = [
			'label'    => esc_html__( 'Added color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'compIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.compare-action.added .fill-icon, .compare-action.added .default-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.compare-action.added .fill-icon, .compare-action.added .default-icon'
				],
			],
			'rerender' => false
		];

		$this->controls['iconSpinnerColor'] = [
			'label'    => esc_html__( 'Loading icon color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'compSpinnerIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.bu-comp-icon.spinner-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.bu-comp-icon.spinner-icon'
				],
			],
			'rerender' => false
		];

		$this->controls['compSyncAtc'] = [
			'label' 	=> esc_html__('Single Add To Cart button selector', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => '.single-atc-btn',
			'description' => esc_html__('Sync the variations of the variable product with the compare items.','bricksultimate'),
			'hasDynamicData' => true
		];

		$this->controls['compSep'] = [
			'label' 	=> '',
			'type' 		=> 'separator',
		];

		$this->controls['compText'] = [
			'label' 	=> esc_html__('Add to compare', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Add to compare', 'bricksultimate')
		];

		$this->controls['compRemoveText'] = [
			'label' 	=> esc_html__('Delete from compare', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Delete from compare', 'bricksultimate'),
		];

		$this->controls['compAriaLabel'] = [
			'label' 	=> esc_html__('Aria label', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Compare', 'bricksultimate'),
			'rerender' => false
		];

		$this->controls['textFont'] = [
			'label'    => esc_html__( 'Typography', 'bricks' ),
			'type'     => 'typography',
			'required' => [ 'compText', '!=', '' ],
			'css'      => [
				[
					'property' => 'font',
					'selector' => '.compare-text'
				]
			],
			'rerender' => false
		];

		$this->controls['textHoverColor'] = [
			'label'    => esc_html__( 'Hover color', 'bricks' ),
			'type'     => 'color',
			'required' => [ 'compText', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '&:hover .compare-text'
				],
			],
			'rerender' => false
		];

		$this->controls['textGap'] = [
			'label'    => esc_html__( 'Gap', 'bricks' ),
			'type'     => 'number',
			'units'    => true,
			'required' => [ 'compText', '!=', '' ],
			'css'      => [
				[
					'property' => 'gap',
					'selector' => '.compare-action'
				],
			],
			'rerender' => false
		];

		$this->controls['notifySep'] = [
			'type' 		=> 'separator',
		];

		$this->controls['compNotice'] = [
			'type'        => 'select',
			'label'       => esc_html__( 'Notification template', 'bricks' ),
			'options'     => \Bricks\Templates::get_templates_list('section'),
			'multiple'    => false,
			'placeholder' => esc_html__( 'Select a template', 'bricks' ),
		];

		$this->controls['toolTipSep'] = [
			'label' 	=> esc_html__( 'Tooltip', 'bricks' ),
			'type' 		=> 'separator',
		];

		$this->controls['hasTooltip'] = [
			'label' 	=> esc_html__('Enable tooltip', 'bricksultimate'),
			'type' 		=> 'checkbox',
			'inline' 	=> true,
			'reset' 	=> true,
			'rerender' => false
		];

		$this->controls['ttText'] = [
			'label' 	=> esc_html__('Text', 'bricksultimate'),
			'type' 		=> 'text',
			'inline' 	=> true,
			'placeholder' => esc_html__('Compare', 'bricksultimate'),
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttText2'] = [
			'label' 	=> esc_html__('Text - added', 'bricksultimate'),
			'type' 		=> 'text',
			'inline' 	=> true,
			'placeholder' => esc_html__('Added to compare', 'bricksultimate'),
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttBG'] = [
			'label' 	=> esc_html__('Background color', 'bricksultimate'),
			'type' 		=> 'color',
			'inline' 	=> true,
			'css' 	=> [
				[
					'property' => 'background-color', 
					'selector' => '.tippy-box'
				]
			],
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttAcolor'] = [
			'label' 	=> esc_html__('Arrow color', 'bricksultimate'),
			'type' 		=> 'color',
			'inline' 	=> true,
			'css' 	=> [
				[ 
					'property' => 'color', 
					'selector' => '.tippy-arrow'
				]
			],
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttTg'] = [
			'label' 	=> esc_html__('Typography', 'bricksultimate'),
			'type' 		=> 'typography',
			'inline' 	=> true,
			'css' 	=> [
				[
					'property' => 'font', 
					'selector' => '.tippy-content'
				]
			],
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttPlacement'] = [
			'label' 	=> esc_html__('Position', 'bricksultimate'),
			'type' 		=> 'select',
			'options' 	=> [
				'top' 			=> __( 'Top' ), 
				'top-start' 	=> __( 'Top Start' ), 
				'top-end' 		=> __( 'Top End' ),
				'right' 		=> __( 'Right' ), 
				'right-start' 	=> __( 'Right Start' ), 
				'right-end' 	=> __( 'Right End' ),
				'bottom' 		=> __( 'Bottom' ), 
				'bottom-start' 	=> __( 'Bottom Start' ), 
				'bottom-end' 	=> __( 'Bottom End' ),
				'left' 			=> __( 'Left' ), 
				'left-start' 	=> __( 'Left Start' ), 
				'left-end' 		=> __( 'Left End' ), 
				'auto' 			=> __( 'Auto' ), 
				'auto-start' 	=> __( 'Auto Start' ), 
				'auto-end' 		=> __( 'Auto End' ),
			],
			'inline' 		=> true,
			'placeholder' 	=> 'auto',
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttAnimation'] = [
			'label' 	=> esc_html__('Animation', 'bricksultimate'),
			'type' 		=> 'select',
			'options' 	=> [
				'fade' 			=> __( 'Fade' ), 
				'shift-away' 	=> __( 'Shift Away' ), 
				'shift-toward' 	=> __( 'Shift Toward' ), 
				'perspective' 	=> __( 'Perspective' )
			],
			'inline' 		=> true,
			'placeholder' 	=> 'Fade',
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];
	}

	// Enqueue element styles and scripts
	public function enqueue_scripts() {
		/*if( bricks_is_builder() || bricks_is_builder_iframe() || bricks_is_builder_call() ){
			wp_enqueue_style( 'bu-wishlistcompare' );
		}*/

		if( bricks_is_frontend() ) {
			wp_enqueue_script( 'bu-compare' );
		}

		if( isset($this->settings['hasTooltip']) ) {
			wp_enqueue_style( 'bu-tooltip' );
			wp_enqueue_script( 'bu-popper' );
			wp_enqueue_script( 'bu-tippy' );
		}
	}

	// Render element HTML
	public function render() {
		$settings = $this->settings;

		$postType = Helpers::get_value( $settings, 'postType', 'post' );
		$post = get_post( $this->post_id );
		$flag = false;

		if( ! is_a( $post, '\WP_Post') ) {
			return $this->render_element_placeholder(
				[
					'title'       => esc_html__( 'For better preview select content to show.', 'bricks' ),
					'description' => esc_html__( 'Go to: Settings > Template Settings > Populate Content', 'bricks' ),
				]
			);
		}

		if( empty( $post->post_type ) )
			$flag = true;

		if( isset( $post->post_type ) && $post->post_type != $postType )
			$flag = true;

		if( $flag ) {
			return $this->render_element_placeholder(
				[
					'title'       => esc_html__( 'For better preview select content to show.', 'bricks' ),
					'description' => esc_html__( 'Go to: Settings > Template Settings > Populate Content', 'bricks' ),
				]
			);
		}

		$post_id = $this->post_id == 0 ? $post->ID : $this->post_id;
		$cookie_key = Compare::get_cookie_key( $postType );
		$add_action = ! $this->is_item_in_comparelist( $post_id, $cookie_key );
		$data = [
			'postType' => $postType,
			'product' => $post_id,
			'notify' => Helpers::get_value( $settings, 'compNotice', false ),
			'action' => $add_action ? 'add' : 'delete', 
			'addText' => esc_html( Helpers::get_value( $settings, 'compText', '' ) ),
			'removeText' => esc_html( Helpers::get_value( $settings, 'compRemoveText', '' ) ),
			'cookie_key' => $cookie_key,
			'cmpRemoveAction' => ! empty( $settings['cmpRemoveAction'] ) ? "yes" : "no"
		];

		if( isset( $settings['hasTooltip'] ) ) {
			$tooltipContent = Helpers::get_value($settings, 'ttText', esc_attr__('Compare', 'bricksultimate') );
			$tooltipContent2 = Helpers::get_value($settings, 'ttText2', esc_attr__('Added to compare', 'bricksultimate') );
			$data = array_merge( $data, [
				'content' => wp_kses_post( $tooltipContent ),
				'addedContent' => wp_kses_post( $tooltipContent2 ),
				'animation' => Helpers::get_value($settings, 'ttAnimation', 'fade'),
				'placement' => Helpers::get_value($settings, 'ttPlacement', 'auto')
			]);
		}

		if( ! empty( $settings['compSyncAtc'] ) )
			$data['syncSwatches'] = bricks_render_dynamic_data( $settings['compSyncAtc'] );

		$data['compItems'] = $this->compareItems;

		$linkHTML = ! empty( $settings['compIcon'] ) ? self::render_icon( $settings['compIcon'], ['bu-comp-icon default-icon'] ) : '';

		$linkHTML .= ! empty( $settings['compAddedIcon'] ) ? self::render_icon( $settings['compAddedIcon'], ['bu-comp-icon fill-icon'] ) : '';

		$linkHTML .= ! empty( $settings['compSpinnerIcon'] ) ? self::render_icon( $settings['compSpinnerIcon'], ['bu-comp-icon spinner-icon'] ) : '';

		if( $add_action && ! empty($settings['compText']) ) {
			$linkHTML .= '<span class="compare-text">' . Helpers::get_value( $settings, 'compText', '' ) . '</span>';
		} elseif( ! $add_action && ! empty($settings['compRemoveText']) ) {
			$linkHTML .= '<span class="compare-text">' . Helpers::get_value( $settings, 'compRemoveText', '' ) . '</span>';
		}

		$title = Helpers::get_value( $settings, 'compAriaLabel', esc_html__('Compare', 'bricksultimate') );

		$href = add_query_arg( ($add_action ? 'add_to_compare' : 'delete_from_compare'), $post_id, get_permalink() );

		$this->set_attribute('_root', 'data-comp-config', wp_json_encode($data));

		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		printf( '<a href="%1$s" aria-label="%2$s" class="compare-action compare-item-%5$s action-%4$s" role="button">%3$s</a>', get_permalink(), $title, $linkHTML, ( $add_action ? 'add' : 'delete added' ), $post_id );
		echo "</{$this->tag}>";
	}

	public function is_item_in_comparelist( $product, $cookie_key ) {
		if( is_user_logged_in() ) {
			$saved_products = get_user_meta( get_current_user_id(), $cookie_key, true );
			if( $saved_products )
				$this->compareItems = explode(",", $saved_products );
		} elseif( !empty($_COOKIE[ $cookie_key ]) ) {
			$this->compareItems = explode(",", $_COOKIE[ $cookie_key ] );
		} else {
			$this->compareItems = [];
		}

		return in_array( $product, $this->compareItems );
	}
}