<?php
namespace BricksUltimate\ElementControls;

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

use BricksUltimate\Helpers;

class Compare {
	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_compare_control_groups' ) );
			add_filter( "bricks/elements/$element/controls", [ $this, 'add_compare_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_compare_control_groups( $control_groups ) {
		$control_groups['bucomp'] = [
				'tab'      => 'content',
				'title'    => esc_html__( 'Compare', 'bricksultimate' ),
		];

		return $control_groups;
	}

	public function add_compare_controls( $controls ) {
		$controls['enabledCompare'] = [
			'group' 	=> 'bucomp',
			'type'      => 'checkbox',
			'label'     => esc_html__( 'Enable compare button', 'bricksultimate' ),
			'reset' 	=> true,
		];

		/*$controls['postType'] = [
			'group' 	=> 'bucomp',
			'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' 		=> ['enabledCompare', '=', true]
		];*/

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

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

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

		$controls['comSpinnenSize'] = [
			'group' 	=> 'bucomp',
			'tab'      => 'content',
			'label'    => esc_html__( 'Spinner icon size', 'bricks' ),
			'type'     => 'number',
			'units'    => true,
			'required' => [ 'compSpinnerIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'font-size',
					'selector' => '.bu-comp-icon.spinner-icon'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compIconColor'] = [
			'group' 	=> 'bucomp',
			'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,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compIconHColor'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Compare icon hover color', 'bricksultimate' ),
			'type'     => 'color',
			'required' => [ 'compIcon.icon', '!=', '' ],
			'css'      => [
				[
					'property' => 'color',
					'selector' => '.brxe-bu-atcomp:hover .default-icon'
				],
				[
					'property' => 'fill',
					'selector' => '.brxe-bu-atcomp:hover .default-icon'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

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

		$controls['compSpinnerColor'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Spinner 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,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compSep'] = [
			'group' 	=> 'bucomp',
			'label' 	=> '',
			'type' 		=> 'separator',
			'required' 	=> ['enabledCompare', '=', true]
		];

		$controls['compText'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Add to compare', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Add to compare', 'bricksultimate'),
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compRemoveText'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Remove from compare', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Remove from compare', 'bricksultimate'),
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compAriaLabel'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Aria label', 'bricksultimate'),
			'type' 		=> 'text',
			'placeholder' => esc_html__('Compare', 'bricksultimate'),
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

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

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

		$controls['compbtnGap'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Gap', 'bricks' ),
			'type'     => 'number',
			'units'    => true,
			'required' => [ 'compText', '!=', '' ],
			'css'      => [
				[
					'property' => 'gap',
					'selector' => 'a'
				],
			],
			'rerender' 		=> false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compNotifySep'] = [
			'group' 	=> 'bucomp',
			'type' 		=> 'separator',
			'required' 	=> ['enabledCompare', '=', true]
		];

		$controls['compNotice'] = [
			'group' 	=> 'bucomp',
			'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' 		=> ['enabledCompare', '=', true]
		];

		$controls['compStyleSep'] = [
			'group' 	=> 'bucomp',
			'type' 		=> 'separator',
			'label'     => esc_html__( 'Styles', 'bricks' ),
			'required' 	=> ['enabledCompare', '=', true]
		];

		$controls['compWrapperBG'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Background', 'bricks' ),
			'type'     => 'color',
			'css'      => [
				[
					'property' => 'background-color',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compwrapperBrd'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Border', 'bricks' ),
			'type'     => 'border',
			'css'      => [
				[
					'property' => 'border',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compwrapperW'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Width', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'width',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compwrapperH'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Height', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'height',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compPosition'] = [
			'group'    => 'bucomp',
			'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-atcomp'
				],
			],
			'inline' => true,
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compPositionTop'] = [
			'group'    => 'bucomp',
			'label'    => esc_html__( 'Top', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'top',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compPositionRight'] = [
			'group'    => 'bucomp',
			'label'    => esc_html__( 'Right', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'right',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compPositionBottom'] = [
			'group'    => 'bucomp',
			'label'    => esc_html__( 'Bottom', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'bottom',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compPositionLeft'] = [
			'group'    => 'bucomp',
			'label'    => esc_html__( 'Left', 'bricks' ),
			'type'     => 'number',
			'css'      => [
				[
					'property' => 'left',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['compwrapperPad'] = [
			'group' 	=> 'bucomp',
			'label'    => esc_html__( 'Padding', 'bricks' ),
			'type'     => 'dimensions',
			'css'      => [
				[
					'property' => 'padding',
					'selector' => '.brxe-bu-atcomp'
				],
			],
			'rerender' => false,
			'required' 		=> ['enabledCompare', '=', true]
		];

		$controls['comptoolTipSep'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__( 'Tooltip', 'bricks' ),
			'type' 		=> 'separator',
			'required' 	=> ['enabledCompare', '=', true]
		];

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

		$controls['cttText'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Text', 'bricksultimate'),
			'type' 		=> 'text',
			'inline' 	=> true,
			'placeholder' => esc_html__('Compare', 'bricksultimate'),
			'required' 	=> [['cbtnHasTooltip', '=', true], ['enabledCompare', '=', true]],
			'rerender' => false,
		];

		$controls['cttBG'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Background color', 'bricksultimate'),
			'type' 		=> 'color',
			'inline' 	=> true,
			'css' 	=> [
				[
					'property' => 'background-color', 
					'selector' => '.tippy-box'
				]
			],
			'required' 	=> [['cbtnHasTooltip', '=', true], ['enabledCompare', '=', true]],
			'rerender' => false,
		];

		$controls['cttAcolor'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Arrow color', 'bricksultimate'),
			'type' 		=> 'color',
			'inline' 	=> true,
			'css' 	=> [
				[ 
					'property' => 'color', 
					'selector' => '.tippy-arrow'
				]
			],
			'required' 	=> [['cbtnHasTooltip', '=', true], ['enabledCompare', '=', true]],
			'rerender' => false,
		];

		$controls['cttTg'] = [
			'group' 	=> 'bucomp',
			'label' 	=> esc_html__('Typography', 'bricksultimate'),
			'type' 		=> 'typography',
			'inline' 	=> true,
			'css' 	=> [
				[
					'property' => 'font', 
					'selector' => '.tippy-content'
				]
			],
			'required' 	=> [['cbtnHasTooltip', '=', true], ['enabledCompare', '=', true]],
			'rerender' => false
		];

		$controls['cttPlacement'] = [
			'group' 	=> 'bucomp',
			'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' 	=> [['cbtnHasTooltip', '=', true], ['enabledCompare', '=', true]],
			'rerender' => false
		];

		$controls['cttAnimation'] = [
			'group' 	=> 'bucomp',
			'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' 	=> [['cbtnHasTooltip', '=', true], ['enabledCompare', '=', true]],
			'rerender' => false
		];

		return $controls;
	}

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

		return in_array( $product, $compareItems );
	}

	public function render_compare_button() {
		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\Compare::get_cookie_key( $postType );
		$add_action = ! $this->is_item_in_compare( $product->get_id(), $cookie_key );
		$data = [
			'postType' => $postType,
			'product' => $product->get_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
		];

		if( isset( $settings['cbtnHasTooltip'] ) ) {
			$tooltipContent = Helpers::get_value($settings, 'cttText', esc_attr__('Compare', 'bricksultimate') );
			$data = array_merge( $data, [
				'content' => wp_kses_post( $tooltipContent ),
				'animation' => Helpers::get_value($settings, 'cttAnimation', 'fade'),
				'placement' => Helpers::get_value($settings, 'cttPlacement', 'auto')
			]);
		}

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

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

		$linkHTML .= ! empty( $settings['compSpinnerIcon'] ) ? $element_instance::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__('Add to compare', 'bricksultimate') );

		$element_instance->set_attribute('_compare', 'data-comp-config', wp_json_encode($data));

		echo "<div class=\"brxe-bu-atcomp\" {$element_instance->render_attributes('_compare')}>";
		printf( '<span aria-label="%1$s" class="compare-action compare-item-%4$s action-%3$s" role="button">%2$s</span>', $title, $linkHTML, ( $add_action ? 'add' : 'delete 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['enabledCompare'] ) )
			{
				$buelement = $element;
				add_action( 'woocommerce_after_shop_loop_item_title', [ $this, 'render_compare_button' ] );

				wp_enqueue_style( 'bu-wishlistcompare' );

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

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

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