<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\{Helpers, WooCommerce};

class WooItemCartPrice extends \Bricks\Element {
	public $category 	= 'ultimate';
	public $name 		= 'bu-mc-price';
	public $icon 		= 'ti-money';

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

	// Set builder controls
	public function set_controls() {
		$this->controls['source'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Display', 'bricksultimate' ),
			'type'     => 'select',
			'options'      => [
				'product' 				=> esc_html__('Selling price'),
				'itemsubtotal' 			=> esc_html__('Selling price x Quantity'),
				'subtotal' 				=> esc_html__('Cart sub total'),
				'total' 				=> esc_html__('Cart total'),
				'totalnotax' 			=> esc_html__('Cart total without tax'),
				'ordertotal' 			=> esc_html__('Order total'),
				'totaltax' 				=> esc_html__('Total tax'),
			],
			'default' 	=> 'product'
		];

		$this->controls['exclTax'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Exclude tax', 'bricksultimate' ),
			'type'     => 'checkbox',
			'required' => ['source', '=', 'ordertotal']
		];

		//sale price
		$this->controls['salePrice'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Display sale price', 'bricksultimate' ),
			'type'     => 'checkbox',
			'required' => ['source', '=', ['product', 'itemsubtotal']]
		];

		//typography
		$this->controls['priceTypography'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Price Typography', 'bricksultimate' ),
			'type'     => 'typography',
			'css'      => [
				[
					'property' => 'font',
					'selector' => '.woocommerce-Price-amount.amount'
				],
			]
		];

		$this->controls['strikePriceTypography'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Strikethrough Price Typography', 'bricksultimate' ),
			'type'     => 'typography',
			'css'      => [
				[
					'property' => 'font',
					'selector' => 'del .woocommerce-Price-amount.amount'
				],
			],
			'required' => ['salePrice', '=', true]
		];

		$this->controls['gap'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Gap between prices', 'bricksultimate' ),
			'type'     => 'number',
			'units' 	=> true,
			'default' 	=> '5px',
			'css'      => [
				[
					'property' => 'margin-right',
					'selector' => 'del'
				],
			],
			'required' => ['source', '=', 'product']
		];

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

		$this->controls['prefix'] = [
			'tab'   => 'content',
			'type'  => 'text',
			'label' => esc_html__( 'Prefix', 'bricks' )
		];

		$this->controls['suffix'] = [
			'tab'    => 'content',
			'type'   => 'text',
			'label'  => esc_html__( 'Suffix', 'bricks' )
		];

		$this->controls['prefixTg'] = [
			'tab'   => 'content',
			'type'  => 'typography',
			'label' => esc_html__( 'Prefix Typography', 'bricks' ),
			'css' 	=> [
				[
					'property' 	=> 'font',
					'selector' 	=> '.prefix-text'
				]
			]
		];

		$this->controls['suffixTg'] = [
			'tab'   => 'content',
			'type'  => 'typography',
			'label' => esc_html__( 'Suffix Typography', 'bricks' ),
			'css' 	=> [
				[
					'property' 	=> 'font',
					'selector' 	=> '.suffix-text'
				]
			]
		];

		$this->controls['displaySep'] = [
			'tab'   => 'content',
			'type'  => 'separator',
			'label' => esc_html__( 'Display', 'bricks' ),
		];

		// Display
		$this->controls['display'] = [
			'tab'         => 'content',
			'label'       => esc_html__( 'Display', 'bricks' ),
			'type'        => 'select',
			'options'     => [
				'flex'         => 'flex',
				'block'        => 'block',
				'inline-block' => 'inline-block',
				'inline'       => 'inline',
				'none'         => 'none',
			],
			'inline'      => true,
			'lowercase'   => true,
			'css'         => [
				[
					'property' => 'display'
				],
			],
			'default' 		=> 'flex',
			'placeholder' 	=> 'flex',
		];

		$this->controls['flexWrap'] = [
			'tab'         => 'content',
			'label'       => esc_html__( 'Flex wrap', 'bricks' ),
			'tooltip'     => [
				'content'  => 'flex-wrap',
				'position' => 'top-left',
			],
			'type'        => 'select',
			'options'     => $this->control_options['flexWrap'],
			'inline'      => true,
			'css'         => [
				[
					'property' => 'flex-wrap',
				],
			],
			'default' 		=> 'nowrap',
			'placeholder' => esc_html__( 'No wrap', 'bricks' ),
			'required'    => [ 'display', '=', [ '', 'flex' ] ],
		];

		$this->controls['direction'] = [
			'tab'      => 'content',
			'label'    => esc_html__( 'Direction', 'bricks' ),
			'tooltip'  => [
				'content'  => 'flex-direction',
				'position' => 'top-left',
			],
			'type'     => 'direction',
			'css'      => [
				[
					'property' => 'flex-direction',
				],
			],
			'default'  => 'row',
			'inline'   => true,
			'rerender' => true,
			'required' => [ 'display', '=', [ '', 'flex' ] ],
		];

		$this->controls['justifyContent'] = [
			'tab'      		=> 'content',
			'label'    		=> esc_html__( 'Align main axis', 'bricks' ),
			'tooltip'  		=> [
				'content'  => 'justify-content',
				'position' => 'top-left',
			],
			'type'     		=> 'justify-content',
			'css'      		=> [
				[
					'property' => 'justify-content',
				],
			],
			'default' 	=> 'center',
			'required' 	=> [ 'display', '=', [ '', 'flex' ] ],
		];

		$this->controls['alignItems'] = [
			'tab'      		=> 'content',
			'label'    		=> esc_html__( 'Align cross axis', 'bricks' ),
			'tooltip' 		=> [
				'content'  => 'align-items',
				'position' => 'top-left',
			],
			'type'     => 'align-items',
			'css'      => [
				[
					'property' => 'align-items',
				],
			],
			'default' 	=> 'center',
			'required' 	=> [ 'display', '=', [ '', 'flex' ] ],
		];
	}

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

		$source = Helpers::get_value( $settings, 'source', 'product' );
		$prefix = Helpers::get_value( $settings, 'prefix', false );
		$suffix = Helpers::get_value( $settings, 'suffix', false );

		echo "<{$this->tag} {$this->render_attributes("_root")}>";

			if( $prefix ) {
				$this->set_attribute( 'pricePrefixText', 'class', 'prefix-text');
				echo "<span {$this->render_attributes( "pricePrefixText" )}>{$prefix}</span>&nbsp;";
			}

			if( $source == 'subtotal') {
				echo "<span class='bu-cart-subtotal'>";
				echo WooCommerce::calculate_cart_subtotal();
				echo "</span>";
			} elseif( $source == 'itemsubtotal') {
				$hasPrice = false;

				if( is_object( WC()->cart ) ) {
					do_action('woocommerce_before_item_price', WC()->cart );
					foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
						if( $cart_item['product_id'] == $this->post_id || $cart_item['variation_id'] == $this->post_id ) {
							if( class_exists( '\SW_WQM_PRO\Includes\Services\Product_Service' ) && \SW_WQM_PRO\Includes\Services\Product_Service::can_do_tiered_pricing_for_product( $cart_item['data'] )
							) {
								$cart_item['data']->set_price( \SW_WQM_PRO\Includes\Services\Product_Service::get_product_unit_price($cart_item['data'], $cart_item['quantity'], true) );
							}

							if( $cart_item['data']->is_on_sale() && ! empty( $settings['salePrice'] ) ) {
								$regular_price = (float) $cart_item['data']->get_regular_price();
								$sale_price = (float) $cart_item['data']->get_sale_price();

								if( $regular_price )
									echo '<del aria-hidden="true">' . wc_price( $regular_price * $cart_item['quantity'] ) . '</del>';

								if( $sale_price )
									echo '<ins aria-hidden="true">' . wc_price( $sale_price * $cart_item['quantity'] ) . '</ins>';
							} else {
								echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $cart_item['data'], $cart_item['quantity'] ), $cart_item, $cart_item_key );
							}

							$hasPrice = true;
							break;
						}
					}
					do_action('woocommerce_after_item_price', WC()->cart);
				}

				if( $hasPrice === false && Helpers::isBricksBuilderActive() )
					echo wc_price( 45 );
			} elseif( $source == 'total') {
				echo "<span class='bu-cart-order-total'>";
				echo WC()->cart->get_total();
				echo "</span>";
			} elseif( $source == 'totalnotax') {
				echo "<span class='bu-cart-order-total-no-tax'>";
				if( $order = $this->getOrder() ) {
					echo wc_price( $order->get_total() - $order->get_total_tax() );
				} else {
					echo wc_price( WC()->cart->get_total( 'edit' ) - WC()->cart->get_total_tax() );
				}
				echo "</span>";
			} elseif( $source == 'totaltax') {
				echo "<span class='bu-total-tax'>";
				if( $order = $this->getOrder() ) {
					echo wc_price( $order->get_total_tax() );
				} else {
					echo wc_price( is_object( WC()->cart ) ? WC()->cart->get_total_tax() : 0 );
				}
				echo "</span>";
			} elseif( $source == 'ordertotal' ) {
				if( $order = $this->getOrder() ) {
					$hasTax = ! empty( $settings['exclTax'] ) ? 'excl' : get_option( 'woocommerce_tax_display_cart' );
					echo $order->get_formatted_order_total( $hasTax );
				} else {
					echo WC()->cart->get_total();
				}
			} else {
				$hasPrice = false;
				if( is_object( WC()->cart ) ) {
					do_action('woocommerce_before_item_price', WC()->cart );
					foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
						$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
						$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
						if( $product_id == $this->post_id || $cart_item['variation_id'] == $this->post_id ) {
							
							if( $_product->is_on_sale() && ! empty( $settings['salePrice'] ) ) {
								$regular_price = (float) $_product->get_regular_price();
								$sale_price = (float) $_product->get_sale_price();

								if( $regular_price )
									echo '<del aria-hidden="true">' . wc_price( $regular_price ) . '</del>';

								if( $sale_price )
									echo '<ins aria-hidden="true">' . wc_price( $sale_price ) . '</ins>';
							} else {
								echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
							}

							$hasPrice = true;
							break;
						}
					}
					do_action('woocommerce_after_item_price', WC()->cart);
				}

				if( $hasPrice === false && Helpers::isBricksBuilderActive() )
					echo wc_price( 15 );
			}

			if( $suffix ) {
				$this->set_attribute( 'priceSuffixText', 'class', 'suffix-text');
				echo "&nbsp;<span {$this->render_attributes( "priceSuffixText" )}>{$suffix}</span>";
			}

		echo "</{$this->tag}>";
	}

	private function getOrder() {
		global $wp;

		$loopObject = $order = false;
		$looping_query_id = \Bricks\Query::is_any_looping();

		if ( ! empty( $looping_query_id ) ) {
			$loopObject = \Bricks\Query::get_loop_object( $looping_query_id );
		}

		if( isset( $wp->query_vars['view-order'] ) ) {
			$order = wc_get_order( $wp->query_vars['view-order'] );
		} elseif( isset( $_GET['view_order'] ) ) {
			$order = wc_get_order( $_GET['view_order'] );
		} elseif( $loopObject ) {
			$order = wc_get_order( $loopObject->ID );
		}

		return $order;
	}
}