<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;

class WooDropdownQty extends \Bricks\Element {
	public $category 	= 'ultimate';
	public $name 		= 'bu-dd-qty';
	public $icon 		= 'ti-angle-down';
	public $called 		= false;

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Dropdown Quantity', 'bricksultimate' );
	}

	// Set builder control groups
	public function set_controls() {
		$this->controls['builderPreview'] = array(
			'type'  	=> 'checkbox',
			'label' 	=> esc_html__( 'Dropdown preview', 'bricksultimate' ),
			'description' 	=> esc_html__( 'Dropdown preview in the builder editor', 'bricksultimate' ),
		);

		$this->controls['qtyText'] = [
			'type'  => 'text',
			'label' => esc_html__( 'Quantity text', 'bricks' ),
			'placeholder' => esc_html__( 'Qty', 'bricksultimate' ),
		];

		$this->controls['qtyLimit'] = [
			'type'  => 'number',
			'label' => esc_html__( 'Max quantity limit', 'bricks' ),
			'unitless' => true,
			'hasDynamicData' => true,
			'placeholder' => 5
		];

		$this->controls['qtyAction'] = [
			'type'  => 'select',
			'label' => esc_html__( 'Using for', 'bricksultimate' ),
			'default' => 'atc',
			'options' => [
				'atc' 		=> esc_html__('Sync with Add To Cart Button', 'bricksultimate'),
				'minicart' 	=> esc_html__('Mini Cart Item Quantity', 'bricksultimate'),
				'cart'		=> esc_html__('Cart page', 'bricksultimate'),
			]
		];

		$this->controls['atcSelector'] = [
			'type'   	=> 'text',
			'label'		=> esc_html__('Add to cart button selector', 'bricksultimate'),
			'required' 	=> ['qtyAction', '=', 'atc'],
			'placeholder' => '.brxe-product-add-to-cart a'
		];

		$this->controls['disableCartUpdate'] = [
			'type'   	=> 'checkbox',
			'label'		=> esc_html__('Disable autoupdate', 'bricksultimate'),
			'required' 	=> ['qtyAction', '=', 'cart']
		];

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

		$this->controls['qtyTextFont'] = [
			'type'  => 'typography',
			'label' => esc_html__( 'Text', 'bricks' ),
			'css' => [
				[
					'property' => 'font',
					'selector' => '.qty-text'
				]
			]
		];

		$this->controls['qtyNumFont'] = [
			'type'  => 'typography',
			'label' => esc_html__( 'Number', 'bricks' ),
			'css' => [
				[
					'property' => 'font',
					'selector' => '.trigger-qty'
				]
			]
		];

		$this->controls['qtyDDNumFont'] = [
			'type'  => 'typography',
			'label' => esc_html__( 'Dropdown numbers', 'bricks' ),
			'css' => [
				[
					'property' => 'font',
					'selector' => '.dd-qty-content'
				]
			]
		];

		$this->controls['qtySelNumFont'] = [
			'type'  => 'typography',
			'label' => esc_html__( 'Selected number', 'bricks' ),
			'css' => [
				[
					'property' => 'font',
					'selector' => '.current-item .dd-qty-content'
				]
			]
		];

		$this->controls['ddSep'] = [
			'type' 		=> 'separator',
			'label' => esc_html__( 'Dropdown wrapper', 'bricks' ),
		];

		$selector = '.bu-qty-dropdown';

		$this->controls['ddPad'] = [
			'type'  => 'dimensions',
			'label' => esc_html__( 'Padding', 'bricks' ),
			'css' => [
				[
					'property' => 'padding',
					'selector' => $selector
				]
			]
		];

		$this->controls['ddW'] = [
			'type'  => 'number',
			'label' => esc_html__( 'Width', 'bricks' ),
			'units' => true,
			'css' => [
				[
					'property' => 'width',
					'selector' => $selector
				]
			]
		];

		$this->controls['ddH'] = [
			'type'  => 'number',
			'label' => esc_html__( 'Height', 'bricks' ),
			'units' => true,
			'css' => [
				[
					'property' => 'height',
					'selector' => $selector
				]
			]
		];

		$this->controls['ddBG'] = [
			'type'  => 'color',
			'label' => esc_html__( 'Background', 'bricks' ),
			'css' => [
				[
					'property' => 'background-color',
					'selector' => $selector
				]
			]
		];

		$this->controls['ddBrd'] = [
			'type'  => 'border',
			'label' => esc_html__( 'Border', 'bricks' ),
			'css' => [
				[
					'property' => 'border',
					'selector' => $selector
				]
			]
		];

		$this->controls['ddBS'] = [
			'type'  => 'box-shadow',
			'label' => esc_html__( 'Box shadow', 'bricks' ),
			'css' => [
				[
					'property' => 'box-shadow',
					'selector' => $selector
				]
			]
		];

		$this->controls['scrollThumbBg'] = [
			'label'    => esc_html__( 'Scrollbar thumb background', 'bricksultimate' ),
			'type'     => 'color',
			'css'      => [
				[
					'property' => '--scrollbar-thumb-bg'
				],
			],
			'rerender' => false
		];

		$this->controls['scrollTrackBg'] = [
			'label'    => esc_html__( 'Scrollbar track background', 'bricksultimate' ),
			'type'     => 'color',
			'css'      => [
				[
					'property' => '--scrollbar-track-bg'
				],
			],
			'rerender' => false
		];

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

		/**
		 * Dropdown arrow
		 -------------------------------*/
		$this->controls['arrowIcon'] = [
			'label' 	=> esc_html__('Arrow icon', 'bricksultimate'),
			'type' 		=> 'icon',
			'default' => [
				'library' => 'themify',
				'icon'    => 'ti-angle-down',
			]
		];

		$this->controls['arrowSize'] = [
			'label' 	=> esc_html__( 'Arrow size', 'bricksultimate' ),
			'type' 		=> 'number',
			'units' 	=> true,
			'required' 	=> [ 'arrowIcon.icon', '!=', '' ],
			'css' 		=> [
				[
					'property' => 'font-size',
					'selector' => '.bu-qty--icon'
				],
			],
			'rerender' => false
		];

		$this->controls['arrowColor'] = [
			'label' 	=> esc_html__( 'Arrow color', 'bricksultimate' ),
			'type' 		=> 'color',
			'required' 	=> [ 'arrowIcon.icon', '!=', '' ],
			'css' 		=> [
				[
					'property' => 'color',
					'selector' => '.bu-qty--icon'
				],
				[
					'property' => 'fill',
					'selector' => '.bu-qty--icon'
				],
			],
			'rerender' => false
		];

		$this->controls['arrowTD'] = [
			'label'    => esc_html__( 'Transition duration(rotate)', 'bricksultimate' ),
			'type'     => 'number',
			'unitless' => false,
			'placeholder' 	=> 0.3,
			'css'      => [
				[
					'property' => 'transition-duration',
					'selector' => '.bu-qty--icon',
					'value' => '%ss'
				],
			],
			'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-item-qty', 
				Helpers::get_asset_url('css') . 'buitemqty.min.css', 
				[], 
				filemtime(Helpers::get_asset_path('css') . 'buitemqty.min.css' )
			);
		}*/

		wp_enqueue_script( 
			'bu-item-qty', 
			Helpers::get_asset_url('js') . 'buitemqty.min.js', 
			['wc-cart-fragments'], 
			filemtime(Helpers::get_asset_path('js') . 'buitemqty.min.js' ),
			true
		);
	}

	// Render element HTML
	public function render() {
		global $product;

		if( ! is_a( $product, 'WC_Product' ) )
			$product = wc_get_product( $this->post_id );

		if( $product == false && ( bricks_is_builder() || bricks_is_builder_iframe() || Helpers::isBricksBuilderActive() ) ) {
			$product = wc_get_products(
				[
					'limit'   => 1,
					'orderby' => 'date',
					'order'   => 'DESC',
				]
			)[0];
		}

		if ( empty( $product ) ) {
			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( $product->is_in_stock() && in_array($product->get_type(), [ 'simple', 'variation' ]) && $product->is_purchasable()) {
			$settings = $this->settings;
			$args = array(
				'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
				'min_value' => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
				'step' => apply_filters( 'woocommerce_quantity_input_step', 1, $product ),
			);

			$args = apply_filters( 'woocommerce_quantity_input_args', $args, $product );

			// Apply sanity to min/max args - min cannot be lower than 0.
			$args['min_value'] = max( $args['min_value'], 0 );
			$args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : '';

			// Max cannot be lower than min if defined.
			if ( '' !== $args['max_value'] && $args['max_value'] < $args['min_value'] ) {
				$args['max_value'] = $args['min_value'];
			}
			
			if( class_exists( 'Morningtrain\WooAdvancedQTY\Plugin\Controllers\InputArgsController' ) ) {
				$advnargs = Morningtrain\WooAdvancedQTY\Plugin\Controllers\InputArgsController::applyArgs(array(), $cart_item['product_id'], true);
				if( isset( $advnargs['min_value'] ) && $advnargs['min_value'] > $args['min_value'] )
					$args['min_value'] = $advnargs['min_value'];
				
				if( isset( $advnargs['max_value'] ) && $advnargs['max_value'] > $args['max_value'] )
					$args['max_value'] = $advnargs['max_value'];
			}

			$using_for = Helpers::get_value($this->settings, 'qtyAction', 'atc');
			$quantity = $args['min_value'];
			$product_id = $this->post_id;

			if( $using_for !== 'atc' ) {
				$item_key = $cart_item_arr = null;

				foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
					if( $cart_item['product_id'] == $product_id || $cart_item['variation_id'] == $product_id ) {
						$quantity = $cart_item['quantity'];
						$item_key = $cart_item_key;
						$cart_item_arr = $cart_item;
						break;
					}
				}

				$this->set_attribute( '_root', 'data-cart_item_key', $item_key );
				$this->set_attribute( '_root', 'data-product_id', $product_id );
				if( $using_for === 'cart' ) {
					$this->set_attribute( '_root', 'data-cartupdate', ( isset($settings['disableCartUpdate']) ? 'yes' : 'no') );
				}
			}

			$qtyLimit = Helpers::get_value($settings, 'qtyLimit', 5);
			if ( '' !== $args['max_value'] )
				$qtyLimit = $args['max_value'] >= $qtyLimit ? $qtyLimit : $args['max_value'];

			$this->set_attribute( '_root', 'data-qty-action', $using_for );
			if( $using_for == 'atc' ) {
				$this->set_attribute( '_root', 'data-atc-selector', Helpers::get_value( $settings,'atcSelector', '.brxe-product-add-to-cart a') );
			}

			echo "<{$this->tag} {$this->render_attributes('_root')}>";
			echo "<span class='qty-text'>" . Helpers::get_value( $settings,'qtyText', 'Qty' ) . "</span>";
			?>
			<a href="#" rel="nofollow" data-val="<?php echo $quantity; ?>" class="trigger-qty">
				<span><?php echo $quantity; ?></span>
				<?php 
					//* display arrow icon
					if( isset( $settings['arrowIcon'] ) ) {
						echo self::render_icon( $settings['arrowIcon'], ['bu-qty--icon'] );
					}
				?>
			</a>
			<div class="bu-qty-dropdown<?php echo ( ! empty($settings['builderPreview']) && (bricks_is_builder() || bricks_is_builder_iframe() || Helpers::isBricksBuilderActive() ) ? ' bu-qty-dd-opened' : ''); ?>">
				<ul class="bu-qty-list">
					<li style="display:none;">
						<a href="#" data-val="1"><?php echo $args['min_value']; ?></a>
					</li>
					<?php
						for($i = $args['min_value']; $i <= $qtyLimit; $i = $i + $args['step']) { 
							printf(
								"<li class=\"%s\"><a href=\"#\" data-val=\"%d\" class=\"dd-qty-content\">%s</a></li>", 
								( ($i == $quantity) ? 'current-item' : 'qty-val' ),
								$i, 
								$i
							);
						}
					?>
				</ul>
			</div>
			<?php
			echo "</{$this->tag}>";
		}
	}
}