<?php
namespace BricksUltimate\ElementControls;

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

use BricksUltimate\Helpers;

class Wishlist {
	public $syncELements = [];

	public function __construct() {
		$this->syncELements = [ 'woocommerce-products', 'product-upsells', 'product-related' ];
		foreach( $this->syncELements as $element ) {
			add_filter( "bricks/elements/$element/control_groups", array( $this, 'add_wishlist_control_groups' ) );
			add_filter( "bricks/elements/$element/controls", [ $this, 'add_wishlist_controls' ] );
		}

		add_action( 'bricks/frontend/before_render_data', [ $this, 'element_before_render_data' ], 10, 2 );
		add_action( 'woocommerce_product_loop_end', [ $this, 'remove_hooks' ] );
	}

	public function add_wishlist_control_groups( $control_groups ) {
		$control_groups['buwsl'] = [
				'tab'      => 'content',
				'title'    => esc_html__( 'Wishlist', 'bricksultimate' ),
		];

		return $control_groups;
	}

	public function add_wishlist_controls( $controls ) {
		$controls['enabledWishlist'] = [
			'group' 	=> 'buwsl',
			'type'      => 'checkbox',
			'label'     => esc_html__( 'Enable add to wishlist button', 'bricksultimate' ),
			'reset' 	=> true,
		];

		/*$controls['postType'] = [
			'group' 	=> 'buwsl',
			'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' 	=> 'product',
			'required' 		=> ['enabledWishlist', '=', true]
		];*/

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

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

		$controls['wslSpinnerIcon'] = [
			'group' 	=> 'buwsl',
			'label' 	=> esc_html__('Spinner icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'themify',
				'icon'    => 'ti-control-record',
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

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

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

		$controls['iconColor'] = [
			'group' 	=> 'buwsl',
			'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,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['iconHColor'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Default icon hover color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'wslIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.brxe-bu-atwsl:hover .default-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.brxe-bu-atwsl:hover .default-icon'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['iconAddedColor'] = [
			'group' 	=> 'buwsl',
			'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,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['iconSpinnerColor'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Spinner 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,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslSep'] = [
			'group' 	=> 'buwsl',
			'label' 	=> '',
			'type' 		=> 'separator',
			'required' 	=> ['enabledWishlist', '=', true]
		];

		$controls['wslText'] = [
			'group' 	=> 'buwsl',
			'label' 	=> esc_html__('Add to wishlist', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Add to wishlist', 'bricksultimate'),
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslRemoveText'] = [
			'group' 	=> 'buwsl',
			'label' 	=> esc_html__('Remove from wishlist', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Remove from wishlist', 'bricksultimate'),
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslAriaLabel'] = [
			'group' 	=> 'buwsl',
			'label' 	=> esc_html__('Aria label', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Add to wishlist', 'bricksultimate'),
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

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

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

		$controls['textGap'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Gap', 'bricks' ),
			'type'     => 'number',
			'units'    => true,
			'required' => [ 'wslText', '!=', '' ],
			'css'      => [
				[
					'property' => 'gap',
					'selector' => 'a'
				],
			],
			'rerender' 		=> false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['notifySep'] = [
			'group' 	=> 'buwsl',
			'type' 		=> 'separator',
			'required' 	=> ['enabledWishlist', '=', true]
		];

		$controls['wslNotice'] = [
			'group' 	=> 'buwsl',
			'type'        => 'select',
			'label'       => esc_html__( 'Notification template', 'bricks' ),
			'options'     => \Bricks\Templates::get_templates_list('section'),
			'multiple'    => false,
			'placeholder' => esc_html__( 'Select a template', 'bricks' ),
			'rerender' 		=> false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['styleSep'] = [
			'group' 	=> 'buwsl',
			'type' 		=> 'separator',
			'label'     => esc_html__( 'Styles', 'bricks' ),
			'required' 	=> ['enabledWishlist', '=', true]
		];

		$controls['wrapperBG'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Background', 'bricks' ),
			'type'     => 'color',
			'css'      => [
				[
					'property' => 'background-color',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wrapperBrd'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Border', 'bricks' ),
			'type'     => 'border',
			'css'      => [
				[
					'property' => 'border',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wrapperW'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Width', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'width',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wrapperH'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Height', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'height',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslPosition'] = [
			'group'    => 'buwsl',
			'label'    => esc_html__( 'Position', 'bricks' ),
			'type'     => 'select',
			'options'  => [
				'static' 	=> esc_html__('Static', 'bricks'),
				'relative' 	=> esc_html__('Relative', 'bricks'),
				'absolute' 	=> esc_html__('Absolute', 'bricks'),
			],
			'default' 		=> 'absolute',
			'placeholder' 	=> 'absolute',
			'css'      => [
				[
					'property' => 'position',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'inline' => true,
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslPositionTop'] = [
			'group'    => 'buwsl',
			'label'    => esc_html__( 'Top', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'top',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslPositionRight'] = [
			'group'    => 'buwsl',
			'label'    => esc_html__( 'Right', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'right',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslPositionBottom'] = [
			'group'    => 'buwsl',
			'label'    => esc_html__( 'Bottom', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'bottom',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wslPositionLeft'] = [
			'group'    => 'buwsl',
			'label'    => esc_html__( 'Left', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'left',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['wrapperPad'] = [
			'group' 	=> 'buwsl',
			'label'    => esc_html__( 'Padding', 'bricks' ),
			'type'     => 'dimensions',
			'css'      => [
				[
					'property' => 'padding',
					'selector' => '.brxe-bu-atwsl'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledWishlist', '=', true]
		];

		$controls['toolTipSep'] = [
			'group' 	=> 'buwsl',
			'label' 	=> esc_html__( 'Tooltip', 'bricks' ),
			'type' 		=> 'separator',
			'required' 	=> ['enabledWishlist', '=', true]
		];

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

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

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

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

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

		$controls['ttPlacement'] = [
			'group' 	=> 'buwsl',
			'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], ['enabledWishlist', '=', true]],
			'rerender' => false
		];

		$controls['ttAnimation'] = [
			'group' 	=> 'buwsl',
			'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], ['enabledWishlist', '=', true]],
			'rerender' => false
		];

		return $controls;
	}

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

		return in_array( $product, $wishlistItems );
	}

	public function render_wishlist() {
		global $product, $buelement;

		$element_name = ! empty( $buelement['name'] ) ? $buelement['name'] : false;

		if ( ! $element_name ) {
			return;
		}

		$element_class_name = isset( \Bricks\Elements::$elements[ $element_name ]['class'] ) ? \Bricks\Elements::$elements[ $element_name ]['class'] : $element_name;

		if ( class_exists( $element_class_name ) ) {
			$element_instance = new $element_class_name( null );
		}

		$settings = $buelement['settings'];
		$postType = 'product'; //Helpers::get_value( $settings, 'postType', 'product' );
		/*$post = get_post( $product->get_id() );

		if( ! is_a( $post, '\WP_Post') && $post->post_type != $postType ) {
			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 = \BricksUltimate\Wishlist::get_cookie_key( $postType );
		$add_action = ! $this->is_product_in_wishlist( $product->get_id(), $cookie_key );
		$data = [
			'postType' => $postType,
			'product' => $product->get_id(),
			'notify' => Helpers::get_value( $settings, 'wslNotice', 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
		];

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

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

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

		$linkHTML .= ! empty( $settings['wslSpinnerIcon'] ) ? $element_instance::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') );

		$element_instance->set_attribute('_wishlist', 'data-wsl-config', wp_json_encode($data));

		echo "<div class=\"brxe-bu-atwsl\" {$element_instance->render_attributes('_wishlist')}>";
		printf( '<span aria-label="%1$s" class="wishlist-action wishlist-item-%4$s action-%3$s" role="button">%2$s</span>', $title, $linkHTML, ( $add_action ? 'add' : 'remove added' ), $product->get_id() );
		echo "</div>";
	}

	public function element_before_render_data( $elements, $area ) {
		global $buelement;

		foreach ( $elements as $element ) {
			$settings = $element['settings'];
			if( in_array( $element['name'], $this->syncELements ) && ! empty( $settings['enabledWishlist'] ) )
			{
				$buelement = $element;
				add_action( 'woocommerce_after_shop_loop_item_title', [ $this, 'render_wishlist' ] );

				wp_enqueue_style( 'bu-wishlistcompare' );

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

				wp_enqueue_script( 'bu-wishlist' );
			}
		}
	}

	public function remove_hooks() {
		remove_action( 'woocommerce_after_shop_loop_item_title', [ $this, 'render_wishlist' ] );
	}
}