<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\{Helpers, Wishlist};

class AddToWishlist extends \Bricks\Element {
	public $category = 'wishlist';
	public $name 	= 'bu-atwsl';
	public $icon 	= 'ti-heart';
	public $wishlistItems = [];

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

	public function set_control_groups() {
		$this->control_groups['icons'] = [
			'title' 	=> esc_html__( 'Icons', 'bricksultimate' ),
			'tab' 		=> 'content',
		];
		$this->control_groups['button'] = [
			'title' 	=> esc_html__( 'Button text', 'bricksultimate' ),
			'tab' 		=> 'content',
		];
		$this->control_groups['notice'] = [
			'title' 	=> esc_html__( 'Notification', 'bricksultimate' ),
			'tab' 		=> 'content',
		];
		$this->control_groups['tooltip'] = [
			'title' 	=> esc_html__( 'Tooltip', 'bricksultimate' ),
			'tab' 		=> 'content',
		];
	}

	// 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',
			'description' => esc_html__( 'Select the correct post type to getting the valid result.', 'bricksultimate' ),
		];

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

		$this->controls['wslLinktoUrl'] = [
			'label' 	=> esc_html__('Link to URL', 'bricksultimate'),
			'type' 		=> 'link',
			'exclude' 	=> [
				'title',
				'ariaLabel',
				'newTab',
				'rel'
			],
			'required' 	=> ['wslRemoveAction', '=', true]
		];

		/*$this->controls['iconsSep'] = [
			'label' 	=> esc_html__('Icons', 'bricksultimate'),
			'type' 		=> 'separator',
		];*/

		$this->controls['wslIcon'] = [
			'group' 	=> 'icons',
			'label' 	=> esc_html__('Default icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'fontawesomeRegular',
				'icon'    => 'fa fa-regular fa-heart',
			]
		];

		$this->controls['wslAddedIcon'] = [
			'group' 	=> 'icons',
			'label' 	=> esc_html__('Added icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'fontawesomeRegular',
				'icon'    => 'fa fa-solid fa-heart',
			],
			'rerender' => false
		];

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

		$this->controls['iconstyleSep'] = [
			'group' 	=> 'icons',
			'label' 	=> esc_html__('Icons style', 'bricksultimate'),
			'type' 		=> 'separator',
		];

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

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

		$this->controls['iconColor'] = [
			'group' 	=> 'icons',
			'label'    => esc_html__( 'Default icon color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'wslIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.bu-wsl-icon.default-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.bu-wsl-icon.default-icon'
				],
			],
			'rerender' => false
		];

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

		$this->controls['iconAddedColor'] = [
			'group' 	=> 'icons',
			'label'    => esc_html__( 'Added icon color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'wslAddedIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.bu-wsl-icon.fill-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.bu-wsl-icon.fill-icon'
				],
			],
			'rerender' => false
		];

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

		$this->controls['syncSep'] = [
			'label' 	=> esc_html__('Sync with variable products', 'bricksultimate'),
			'type' 		=> 'separator',
		];

		$this->controls['wslSyncAtc'] = [
			'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 wishlist','bricksultimate'),
			'hasDynamicData' => true
		];

		/*$this->controls['wslSep'] = [
			'label' 	=> '',
			'type' 		=> 'separator',
		];*/

		$this->controls['wslText'] = [
			'group' 	=> 'button',
			'label' 	=> esc_html__('Text', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Add to wishlist', 'bricksultimate')
		];

		$this->controls['wslRemoveText'] = [
			'group' 	=> 'button',
			'label' 	=> esc_html__('Text: Added', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Added to wishlist', 'bricksultimate'),
		];

		$this->controls['wslAriaLabel'] = [
			'group' 	=> 'button',
			'label' 	=> esc_html__('Aria label', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Add to wishlist', 'bricksultimate'),
			'rerender' => false
		];

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

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

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

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

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

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

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

		$this->controls['ttText2'] = [
			'group' 	=> 'tooltip',
			'label' 	=> esc_html__('Added to wishlist text', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Added', 'bricksultimate'),
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

		$this->controls['ttBG'] = [
			'group' 	=> 'tooltip',
			'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'] = [
			'group' 	=> 'tooltip',
			'label' 	=> esc_html__('Arrow color', 'bricksultimate'),
			'type' 		=> 'color',
			'inline' 	=> true,
			'css' 	=> [
				[ 
					'property' => 'color', 
					'selector' => '.tippy-arrow'
				]
			],
			'required' 	=> ['hasTooltip', '=', true],
			'rerender' => false
		];

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

		$this->controls['ttPlacement'] = [
			'group' 	=> 'tooltip',
			'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'] = [
			'group' 	=> 'tooltip',
			'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', Helpers::get_asset_url('css') . 'wishlistcompare.min.css', [], filemtime(Helpers::get_asset_path('css') . 'wishlistcompare.min.css') );
		}*/

		if( bricks_is_frontend() ) {
			wp_enqueue_script( 'bu-atci', Helpers::get_asset_url('js') . 'buatci.min.js', ['jquery','wc-add-to-cart'], filemtime(Helpers::get_asset_path('js') . 'buatci.min.js'), true );
			wp_enqueue_script( 'bu-wishlist' );
		}

		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' ),
				]
			);
		}

		$cookie_key = Wishlist::get_cookie_key( $postType );
		$add_action = ! $this->is_product_in_wishlist( $this->post_id, $cookie_key );
		$data = [
			'product' => $this->post_id,
			'postType' => $postType,
			'notify' => Helpers::get_value( $settings, 'wslNotice', false ),
			'rmnotice' => Helpers::get_value( $settings, 'wslRmNotice', false ),
			'action' => $add_action ? 'add' : 'remove', 
			'addText' => esc_html( Helpers::get_value( $settings, 'wslText', '' ) ),
			'removeText' => esc_html( Helpers::get_value( $settings, 'wslRemoveText', '' ) ),
			'cookie_key' => $cookie_key,
			'wslItems' => $this->wishlistItems,
			'wslRemoveAction' => ! empty( $settings['wslRemoveAction'] ) ? "yes" : "no"
		];
		if( ! empty( $settings['wslRemoveAction'] ) && isset( $settings['wslLinktoUrl'] ) ) {
			$this->set_link_attributes( 'pagelink', $settings['wslLinktoUrl'] );
			$redirectUrl = $this->attributes['pagelink'];
			$data['url'] = esc_url( $redirectUrl['href'][0] );
		}

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

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

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

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

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

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

		$title = Helpers::get_value( $settings, 'wslAriaLabel', esc_html__('Add to wishlist', 'bricksultimate') );

		$href = add_query_arg( ($add_action ? 'add_to_wishlist' : 'remove_from_wishlist'), $this->post_id, get_permalink() );

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

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

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

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