<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;

class WooCost extends \Bricks\Element {
	public $category = 'checkout';
	public $name 	= 'bu-cart-cost';
	public $icon 	= 'ti-money';

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

	// Set builder controls
	public function set_controls() {
		$this->controls['costInfo'] = [
			'type' 		=> 'info',
			'content' 	=> esc_html__( 'Refresh the builder editor for the preview.', 'bricksultimate' ),
		];

		$this->controls['costType'] = [
			'type'  	=> 'select',
			'label' 	=> esc_html__( 'Cost type', 'bricksultimate' ),
			'options'   => [
				'discount' 				=> esc_html__('Discount(coupon)', 'bricksultimate'),
				'fees' 					=> esc_html__('Fees', 'bricksultimate'),
				'subtotal' 				=> esc_html__('Sub total', 'bricksultimate'),
				'shipping' 				=> esc_html__('Shipping', 'bricksultimate'),
				'tax' 					=> esc_html__('Tax', 'bricksultimate'),
				'totaltax' 				=> esc_html__('Total Tax', 'bricksultimate'),
				'total' 				=> esc_html__('Total', 'bricksultimate'),
				'totalnotax' 			=> esc_html__('Total without tax', 'bricksultimate'),
				'ob_price' 				=> esc_html__('Offer Product Price(Order Bumps)', 'bricksultimate'),
			],
			'default' => 'subtotal'
		];

		$this->controls['labelTxt'] = [
			'type'  	=> 'text',
			'label' 	=> esc_html__( 'Label', 'bricksultimate' ),
			'placeholder' => esc_html__('Subtotal', 'woocommerce' ),
			'required' 	=> ['costType', '=', ['discount', 'subtotal', 'shipping', 'totaltax', 'total', 'totalnotax', 'ob_price']]
		];

		$this->controls['removeLabel'] = [
			'type'  	=> 'text',
			'label' 	=> esc_html__( 'Remove text label', 'bricksultimate' ),
			'placeholder' => esc_html__('[Remove]', 'woocommerce' ),
			'required' 	=> ['costType', '=', 'discount']
		];

		$this->controls['disableLabel'] = [
			'type'  	=> 'checkbox',
			'label' 	=> esc_html__( 'Hide label', 'bricksultimate' ),
			'required' 	=> ['costType', '=', ['subtotal', 'shipping', 'totaltax', 'total', 'totalnotax', 'ob_price']]
		];

		$this->controls['labelTg'] = [
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Label Typography', 'bricksultimate' ),
			'css' 		=> [
				[
					'property' 	=> 'font',
					'selector' 	=> '.label'
				]
			]
		];

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

		$this->controls['salePriceTg'] = [
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Sale Price Typography', 'bricksultimate' ),
			'css' 		=> [
				[
					'property' 	=> 'font',
					'selector' 	=> 'ins .woocommerce-Price-amount.amount'
				]
			],
			'required' => ['costType', '=', 'ob_price']
		];

		$this->controls['showShippingOptName'] = [
			'type'  	=> 'checkbox',
			'label' 	=> esc_html__( 'Display shipping option name', 'bricksultimate' ),
			'required' => ['costType', '=', 'shipping']
		];

		$this->controls['shippingOptNameTg'] = [
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Shipping option name typography', 'bricksultimate' ),
			'css' 		=> [
				[
					'property' 	=> 'font',
					'selector' 	=> '.shipping-option-name'
				]
			],
			'required' => [ ['costType', '=', 'shipping'], ['showShippingOptName', '=', true] ]
		];

		$this->controls['freeTg'] = [
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Free Text Typography', 'bricksultimate' ),
			'css' 		=> [
				[
					'property' 	=> 'font',
					'selector' 	=> '.free-shipping-label'
				]
			],
			'required' => ['costType', '=', 'shipping']
		];

		$this->controls['discountRemove'] = [
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Remove Text', 'bricksultimate' ),
			'css' 		=> [
				[
					'property' 	=> 'font',
					'selector' 	=> '.woocommerce-remove-coupon'
				]
			],
			'required' => ['costType', '=', 'discount']
		];
	}

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

		$type = Helpers::get_value( $settings, 'costType', 'subtotal' );

		switch( $type ){
			case 'subtotal':
				$this->get_sub_total( $settings );
			break;

			case 'discount':
				$this->get_discount( $settings );
			break;

			case 'fees':
				$this->get_fees( $settings );
			break;

			case 'shipping':
				$this->get_shipping_cost( $settings );
			break;

			case 'tax':
				$this->get_tax( $settings );
			break;

			case 'totaltax':
				$this->get_total_tax( $settings );
			break;

			case 'total':
				$this->get_total( $settings );
			break;

			case 'totalnotax':
				$this->get_total_without_tax( $settings );
			break;

			case 'ob_price':
				$this->get_ob_price( $settings );
			break;
		}
	}

	public function get_sub_total( $settings ) {
		$label = Helpers::get_value( $settings, 'labelTxt', esc_html__( 'Subtotal', 'woocommerce' ) );
		$this->set_attribute( '_root', 'class', ['cart-subtotal'] );
		echo "<{$this->tag} {$this->render_attributes('_root')}>";
	?>

		<?php if( empty( $settings['disableLabel'] ) ): ?>
		<span class="cart-total-label label"><?php echo $this->render_dynamic_data( $label ); ?></span>
		<?php endif; ?>

		<?php wc_cart_totals_subtotal_html(); ?>
	<?php
		echo "</{$this->tag}>";
	}

	public function get_ob_price( $settings ) {
		global $product;

		$product_id = get_post_meta( $this->post_id, '_buob_offer_product', true );
		$product = wc_get_product( $product_id );

		if( $product === false )
			return;

		$label =  Helpers::get_value( $settings, 'labelTxt', false );
		$this->set_attribute( '_root', 'class', ['order-bumps-price'] );
		echo "<{$this->tag} {$this->render_attributes('_root')}>";
	?>

		<?php if( $label && empty( $settings['disableLabel'] ) ): ?>
		<span class="cart-total-label label"><?php echo $this->render_dynamic_data( $label ); ?></span>
		<?php endif; ?>

		<?php echo \BricksUltimate\WooCommerce\WooOrderBumps::get_instance()->get_offer_product_price( $product, $this->post_id ); ?>
	<?php
		echo "</{$this->tag}>";
	}

	public function get_fees( $settings ) {
		$fees = \WC()->cart->get_fees();

		if( empty( $fees ) )
			return;

		$this->set_attribute( '_root', 'class', ['fee'] );
		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		
		foreach ( $fees as $fee ) :
	?>	
			<?php if( empty( $settings['disableLabel'] ) ): ?>
			<span class="cart-fee-label label"><?php echo esc_html( $fee->name ); ?></span>
			<?php endif; ?>
			
			<?php \wc_cart_totals_fee_html( $fee ); ?>
	<?php
		endforeach;

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

	public function get_discount( $settings ) {
		if( bricks_is_builder() || bricks_is_builder_iframe() || bricks_is_builder_call() ) {
			$label = Helpers::get_value($settings, 'removeLabel', __( '[Remove]', 'woocommerce' ));
			echo "<{$this->tag} {$this->render_attributes('_root')}>";
			?>
			<div class="cart-discount">
				<span class="coupon-code label coupon-bu15">
					Coupon: test123	
				</span>
				-<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>3.30</span> <a href="#" class="woocommerce-remove-coupon" data-coupon="test123"><?php echo $label; ?></a>	
			</div>
			<?php
			echo "</{$this->tag}>";
			return;
		}

		$coupons = \WC()->cart->get_coupons();

		if( empty( $coupons ) )
			return;

		$this->set_attribute( '_root', 'class', ['coupon-details'] );

		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		foreach ( $coupons as $code => $coupon ) :
			add_filter('woocommerce_cart_totals_coupon_label', [ $this, 'bu_coupon_label'], 10, 2 );
			add_filter('woocommerce_cart_totals_coupon_html', [ $this, 'bu_coupon_remove_label'], 10, 3 );
	?>
		<div class="cart-discount">
			<span class="coupon-code label coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
				<?php wc_cart_totals_coupon_label( $coupon ); ?>	
			</span>
			<?php wc_cart_totals_coupon_html( $coupon ); ?>
		</div>
	<?php
			remove_filter('woocommerce_cart_totals_coupon_label', [ $this, 'bu_coupon_label'], 10, 2 );
			remove_filter('woocommerce_cart_totals_coupon_html', [ $this, 'bu_coupon_remove_label'], 10, 3 );
		endforeach;

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


	public function bu_coupon_remove_label( $coupon_html, $coupon, $discount_amount_html ) {
		$settings = $this->settings;
		$label =  Helpers::get_value( $settings, 'removeLabel', false );
		if( $label ) {
			$coupon_html = str_replace('[Remove]', wp_kses_post( $label ), $coupon_html);
		}

		return $coupon_html;
	}

	public function bu_coupon_label($couponLabel, $coupon ) {
		$settings = $this->settings;
		$label =  Helpers::get_value( $settings, 'labelTxt', false );
		if( $label ) {
			$couponLabel = $label . ': ' . $coupon->get_code();
		}

		return $couponLabel;
	}

	public function get_tax( $settings ) {
		if ( wc_tax_enabled() /* && ! WC()->cart->display_prices_including_tax() */ ) :
			$this->set_attribute( '_root', 'class', ['order-tax'] );

			if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) :
				$hasTax = \WC()->cart->get_tax_totals();

				if( empty( $hasTax ) )
					return;

				echo "<{$this->tag} {$this->render_attributes('_root')}>";
				foreach ( WC()->cart->get_tax_totals() as $code => $tax ) :
			?>
					<div class="cart-tax-rate tax-rate-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
						<span class="tax-rate-label label"><?php echo esc_html( $tax->label ); ?></th>
						<?php echo wp_kses_post( $tax->formatted_amount ); ?>
					</div>
				<?php endforeach; echo "</{$this->tag}>"; ?>
			<?php else :
				$hasTax = \WC()->cart->get_taxes_total();
				if( $hasTax ) {
					$this->set_attribute( '_root', 'class', ['tax-total'] ); 
					echo "<{$this->tag} {$this->render_attributes('_root')}>";
			?>
					<div class="tax-label label"><?php echo esc_html( \WC()->countries->tax_or_vat() ); ?></th>
						<?php wc_cart_totals_taxes_total_html(); ?>
					</div>
			<?php 
					echo "</{$this->tag}>"; 
				}
				endif;
		endif;
	}

	public function get_total( $settings ) {
		$label =  Helpers::get_value( $settings, 'labelTxt', esc_html__( 'Total', 'woocommerce' ) );

		$this->set_attribute( '_root', 'class', ['order-total'] );
		
		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		
		if( empty( $settings['disableLabel'] ) ):
			printf('<span class="cart-total-label label">%s</span>', $this->render_dynamic_data( $label ) );
		endif;

		do_action( 'woocommerce_review_order_before_order_total' );

		echo \WC()->cart->get_total();

		do_action( 'woocommerce_review_order_after_order_total' );

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

	public function get_total_without_tax( $settings ) {
		$label = Helpers::get_value( $settings, 'labelTxt', esc_html__( 'Total', 'woocommerce' ) );

		$this->set_attribute( '_root', 'class', ['order-total-without-tax'] );
		
		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		
		if( empty( $settings['disableLabel'] ) ):
			printf('<span class="cart-total-label label">%s</span>', $this->render_dynamic_data( $label ) );
		endif;

		do_action( 'woocommerce_review_order_before_order_total' );

		echo wc_price( \WC()->cart->get_total( 'edit' ) - \WC()->cart->get_total_tax() );

		do_action( 'woocommerce_review_order_after_order_total' );

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

	public function get_total_tax( $settings ) {
		$label = Helpers::get_value( $settings, 'labelTxt', esc_html__( 'Tax', 'woocommerce' ) );

		$this->set_attribute( '_root', 'class', ['order-total-tax'] );
		
		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		
		if( empty( $settings['disableLabel'] ) ):
			printf('<span class="cart-total-tax-label label">%s</span>', $this->render_dynamic_data( $label ) );
		endif;

		echo wc_price( \WC()->cart->get_total_tax() );

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

	public function get_shipping_cost( $settings ) {
		$label = Helpers::get_value( $settings, 'labelTxt', esc_html__( 'Shipping', 'woocommerce' ) );

		if( bricks_is_builder() || bricks_is_builder_iframe() || bricks_is_builder_call() ) {
			echo "<{$this->tag} {$this->render_attributes('_root')}>";
			?>
			<?php if( empty( $settings['disableLabel'] ) ): ?>
			<span class="cart-shipping-label label"><?php echo $this->render_dynamic_data( $label ); if( ! empty( $settings['showShippingOptName'] ) ) echo "<br/><p class=\"shipping-option-name\">Ground Shipping</p>";?></span>
			<?php endif; ?>
			<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">$</span>15.00</bdi></span>
			<?php
			echo "</{$this->tag}>";
			return;
		}

		if ( \WC()->cart->needs_shipping() && \WC()->cart->show_shipping() ) : 
			
			$label =  Helpers::get_value( $settings, 'labelTxt', esc_html__( 'Shipping', 'woocommerce' ) );

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

			$total = 0;
			$shipping_name = $chosen_method = '';
			$packages = \WC()->shipping()->get_packages();

			if( $packages ) {
				foreach ( $packages as $i => $package ) {
					$chosen_method     = WC()->session->chosen_shipping_methods[ $i ] ?? '';
					$available_methods = empty( $package['rates'] ) ? array() : $package['rates'];

					foreach ( $available_methods as $method ) {
						if ( (string) $method->id !== (string) $chosen_method ) { 
							continue;
						}

						$shipping_name .= '<br><p class="shipping-option-name">' . $method->get_label() . '</p>';
						$total += $method->cost;

						if ( \WC()->cart->display_prices_including_tax() ) {
							$total += $method->get_shipping_tax();
						}
					}
				}
			}
		?>
			<?php if( empty( $settings['disableLabel'] ) ): ?>
			<span class="cart-shipping-label label">
				<?php 
					echo $this->render_dynamic_data( $label ); 
					if( ! empty( $settings['showShippingOptName'] ) ) echo $shipping_name;
				?>
			</span>
			<?php endif; ?>
		<?php
			if ( 0 < $total ) {
				echo wc_price( $total );
			} else {
				echo '<span class="free-shipping-label">' . apply_filters( 'woocommerce_free_shipping_label', esc_html__( 'Free', 'woocommerce' ), $chosen_method ) . '</span>';
			}

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