<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;

class WooShippingMethods extends \Bricks\Element {
	public $category = 'checkout';
	public $name 	= 'bu-shipping-methods';
	public $icon 	= 'ti-truck';

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

	// Set builder control groups
	public function set_control_groups() {
		$this->control_groups['conditions'] = [
			'title' 	=> esc_html__( 'Conditions', 'bricksultimate' ),
			'tab' 		=> 'content'
		];

		$this->control_groups['details'] = [
			'title' 	=> esc_html__( 'Package details', 'bricksultimate' ),
			'tab' 		=> 'content'
		];

		$this->control_groups['notfound'] = [
			'title' 	=> esc_html__( 'Not Found', 'bricksultimate' ),
			'tab' 		=> 'content'
		];
	}

	// Set builder controls
	public function set_controls() {

		$this->controls['pmInfo'] = [
			'type' 		=> 'info',
			'content' 	=> esc_html__( 'Refresh the builder editor for the preview.', 'bricksultimate' ),
		];

		$this->controls['buttonsBG'] = [
			'type'  => 'color',
			'label' => esc_html__( 'Background color', 'bricksultimate' ),
			'css'   => [
				[
					'property' => 'background-color',
					'selector' => 'ul.woocommerce-shipping-methods li',
				]
			],
		];

		$this->controls['borderW'] = [
			'type' 	=> 'number',
			'label' => esc_html__( 'Border width', 'bricksultimate' ),
			'units' => true,
			'css'	=> [
				[
					'property' => 'border-width',
					'selector' => 'ul.woocommerce-shipping-methods'
				],
				[
					'property' => 'border-bottom-width',
					'selector' => 'ul.woocommerce-shipping-methods li'
				]
			],
			'default' => '1px'
		];

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

		$this->controls['borderStyle'] = [
			'type' 	=> 'select',
			'label' => esc_html__( 'Border style', 'bricksultimate' ),
			'options' => [ 'none' => 'none', 'solid' => 'Solid', 'dashed' => 'Dashed', 'dotted' => 'Dotted'],
			'css'	=> [
				[
					'property' => 'border-style',
					'selector' => 'ul.woocommerce-shipping-methods, ul.woocommerce-shipping-methods li'
				]
			],
			'default' => 'solid',
			'inline' => true
		];

		$this->controls['borderRadius'] = [
			'type' 	=> 'number',
			'label' => esc_html__( 'Border radius', 'bricksultimate' ),
			'units' => true,
			'css'	=> [
				[
					'property' => '--bricks-border-radius'
				]
			],
			'default' => '4px'
		];

		$this->controls['btnsSpacing'] = [
			'type'  	=> 'dimensions',
			'label' 	=> esc_html__( 'Spacing', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'padding',
					'selector' => 'ul.woocommerce-shipping-methods li .bu-shipping-method-inner',
				]
			],
		];

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

		$this->controls['methodTitle'] = [
			'type' 	=> 'typography',
			'label' => esc_html__( 'Label', 'bricksultimate' ),
			'css'	=> [
				[
					'property' => 'font',
					'selector' => '.bu-shipping-method-inner label'
				]
			],
		];

		$this->controls['packageTitle'] = [
			'type' 	=> 'typography',
			'label' => esc_html__( 'Package Title', 'bricksultimate' ),
			'css'	=> [
				[
					'property' => 'font',
					'selector' => '.bu-shipping-package-title'
				]
			],
		];

		$this->controls['methodPrice'] = [
			'type' 	=> 'typography',
			'label' => esc_html__( 'Price', 'bricksultimate' ),
			'css'	=> [
				[
					'property' => 'font',
					'selector' => '.bu-shipping-method-inner label .woocommerce-Price-amount'
				]
			],
		];

		$this->controls['methodFree'] = [
			'type' 	=> 'typography',
			'label' => esc_html__( 'Free Text', 'bricksultimate' ),
			'css'	=> [
				[
					'property' => 'font',
					'selector' => '.bu-shipping-method-inner label span.wc-shipping-option--free'
				]
			],
		];

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

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

		$this->controls['methodDescSpacing'] = [
			'type'  	=> 'dimensions',
			'label' 	=> esc_html__( 'Spacing', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'margin',
					'selector' => '.method-description',
				]
			],
		];

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

		$rd_selector = 'ul.woocommerce-shipping-methods input[type=radio]';
		$this->controls['rdsize'] = [
			'type'  	=> 'number',
			'label' 	=> esc_html__( 'Size', 'bricksultimate' ),
			'placeholder' => '15px',
			'units' 	=> true,
			'css'   	=> [
				[
					'property' => 'width',
					'selector' => $rd_selector,
				],
				[
					'property' => 'height',
					'selector' => $rd_selector,
				]
			],
		];

		$this->controls['rdbg'] = [
			'type'  	=> 'color',
			'label' 	=> esc_html__( 'Background Color', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'background-color',
					'selector' => $rd_selector,
				]
			],
		];

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

		$rdc_checked = 'ul.woocommerce-shipping-methods input[type=radio]:checked:after';
		$this->controls['rdcbg'] = [
			'type'  	=> 'color',
			'label' 	=> esc_html__( 'Background color(checked)', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'background-color',
					'selector' => 'ul.woocommerce-shipping-methods input[type=radio]:checked',
				]
			],
		];

		$this->controls['rdCheckedBrd'] = [
			'type'  	=> 'border',
			'label' 	=> esc_html__( 'Border(checked)', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'border',
					'selector' => 'ul.woocommerce-shipping-methods input[type=radio]:checked',
				]
			]
		];

		$this->controls['rdwrdsz'] = [
			'type'  	=> 'number',
			'label' 	=> esc_html__( 'Mini bullet size', 'bricksultimate' ),
			'placeholder' 	=> '6px',
			'min' 		=> 1,
			'max' 		=> 30,
			'step' 		=> 1,
			'units' 	=> true,
			'css'   	=> [
				[
					'property' => 'width',
					'selector' => $rdc_checked
				],
				[
					'property' => 'height',
					'selector' => $rdc_checked
				]
			],
		];

		$this->controls['rdwbcolor'] = [
			'type'  	=> 'color',
			'label' 	=> esc_html__( 'Mini bullet color', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'background-color',
					'selector' => $rdc_checked
				]
			],
		];

		$this->controls['rdBulletPos'] = [
			'group' 	=> 'radio',
			'type'  	=> 'text',
			'label' 	=> esc_html__( 'Bullet position(Translate)', 'bricksultimate' ),
			'placeholder' => '-50%,-50%',
			'css'   	=> [
				[
					'property' => '--bullet-position',
				]
			],
		];

		/**
		 * Conditions
		 ********************************/
		if( ! is_null( WC()->cart ) ) {
			WC()->cart->calculate_shipping();

			$packages = WC()->shipping()->get_packages();
			$options = ['none' => esc_html__('Select') ];

			if( ! empty( $packages ) ) {
				foreach ( $packages as $i => $package ) {
					$available_methods 	= $package['rates'];
					foreach ( $available_methods as $method ) :
						$label = $method->get_label();
						$options[ esc_attr( $method->id ) ] = $label;
					endforeach;
				}

				$this->controls['smConditions'] = [
					'group' 		=> 'conditions',
					'placeholder'   => esc_html__( 'Conditions', 'bricksultimate' ),
					'type'          => 'repeater',
					'titleProperty' => 'condition',
					'fields'        => [
						'condition' => [
							'label'     => esc_html__( 'Shipping options', 'bricksultimate' ),
							'type'      => 'select',
							'options' 	=> $options,
							'default' 	=> 'none'
						],
						'selector' => [
							'label'     => esc_html__( 'Selectors', 'bricksultimate' ),
							'type' => 'text',
							'required' 	=> [ 'condition', '!=', 'none' ]
						],
						'toggleType' => [
							'label'     => esc_html__( 'Toggle type', 'bricksultimate' ),
							'type'      => 'select',
							'options' 	=> ['hide' => esc_html__('Hide'), 'show' => esc_html__('Show')],
							'required' 	=> [ 'condition', '!=', 'none' ]
						]
					]
				];
			}
		}


		$selector = ".woocommerce-shipping-contents";
		$this->controls['dtlPadding'] = [
			'group' 	=> 'details',
			'type'  	=> 'dimensions',
			'label' 	=> esc_html__( 'Padding', 'bricks' ),
			'css'   	=> [
				[
					'property' => 'padding',
					'selector' => $selector
				]
			]
		];

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

		$this->controls['dtlTg'] = [
			'group' 	=> 'details',
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Typography', 'bricks' ),
			'css'   	=> [
				[
					'property' => 'font',
					'selector' => $selector
				]
			]
		];

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

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

		$selector = ".shipping-message";
		$this->controls['nfPadding'] = [
			'group' 	=> 'notfound',
			'type'  	=> 'dimensions',
			'label' 	=> esc_html__( 'Padding', 'bricks' ),
			'css'   	=> [
				[
					'property' => 'padding',
					'selector' => $selector
				]
			]
		];

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

		$this->controls['nfTg'] = [
			'group' 	=> 'notfound',
			'type'  	=> 'typography',
			'label' 	=> esc_html__( 'Typography', 'bricks' ),
			'css'   	=> [
				[
					'property' => 'font',
					'selector' => $selector
				]
			]
		];

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

		$this->controls['nfBorder'] = [
			'group' 	=> 'notfound',
			'type'  	=> 'number',
			'label' 	=> esc_html__( 'Border', 'bricks' ),
			'css'   	=> [
				[
					'property' => 'border',
					'selector' => $selector
				]
			]
		];
	}

	// 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-checkout', Helpers::get_asset_url('css') . 'checkout.min.css', [], filemtime(Helpers::get_asset_path('css') . 'checkout.min.css') );
		}*/

		wp_enqueue_script( 'bu-checkout', Helpers::get_asset_url('js') . 'checkout.min.js', [], filemtime(Helpers::get_asset_path('js') . 'checkout.min.js') );
	}

	public function add_filters() {
		if( ! Helpers::isBricksBuilderActive() ) {
			add_filter('woocommerce_update_order_review_fragments', [$this,'update_order_review_fragments'], 99 );
		}
	}

	public function update_order_review_fragments( $fragments ) {
		parse_str( $_POST['post_data'], $params );

		if( empty( $params ) )
			return $fragments;

		if( empty( $params['ship_post_id'] ) )
			return $fragments;

		$element_id = isset( $params['ship_element_id'] ) ? $params['ship_element_id'] : 0;
		$post_id = isset( $params['ship_post_id'] ) ? $params['ship_post_id'] : 0;

		\WC()->cart->calculate_shipping();
		$data = \Bricks\Helpers::get_element_data( $post_id, $element_id );
		$shipping_packages = \Bricks\Frontend::render_element( $data['element'] );

		$fragments[ '.brxe-bu-shipping-methods' ] = $shipping_packages;

		return $fragments;
	}

	// Render element HTML
	public function render() {
		$settings = $this->settings;
		if( Helpers::isBricksBuilderActive() && \WC()->cart->needs_shipping() && \WC()->cart->show_shipping() ):
			echo "<{$this->tag} {$this->render_attributes('_root')}>";
	?>
				<ul id="shipping_method" class="woocommerce-shipping-methods">
					<li>
						<div class="bu-shipping-method-inner">
							<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_free_shipping1" value="free_shipping:1" class="shipping_method" checked="checked">
								<label for="shipping_method_0_free_shipping1">
									<?php echo esc_html__( 'Free shipping', 'woocommerce' ); ?>
									<?php printf( '<span class="wc-shipping-option--free">%s</span>', esc_html__('Free', 'woocommerce') ); ?>
								</label>
								<span class="method-description">Shipping to your home within 3 days</span>
						</div>
					</li>
					<li>
						<div class="bu-shipping-method-inner">
							<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate5" value="flat_rate:5" class="shipping_method"><label for="shipping_method_0_flat_rate5">Overnight Shipping<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">₹</span>20.00</bdi></span></label>
						</div>
					</li>
				</ul>
	<?php
			echo "</{$this->tag}>";
			return;
		endif;

		if ( ! empty( $settings['smConditions'] ) ) {
			$this->set_attribute('_root', 'data-sm-conditions', wp_json_encode( $settings['smConditions'] ) );
		}

		if ( ! wp_doing_ajax() ) {
			echo "<input type=\"hidden\" value=\"{$this->id}\" name=\"ship_element_id\" >";
			echo "<input type=\"hidden\" value=\"{$this->post_id}\" name=\"ship_post_id\" >";
		}

		//$this->set_attribute('_root', 'class', 'woocommerce-shipping-totals shipping' );

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

		if ( WC()->cart->needs_shipping() && WC()->cart->show_shipping() ) :

			if( Helpers::isBricksBuilderEditor() ) {
				\WC()->cart->calculate_shipping();
			}

			$packages = WC()->shipping()->get_packages();

			if( empty( $packages ) )
				return;

			ob_start();
			do_action( 'woocommerce_review_order_before_shipping' );
			$before_shipping = ob_get_clean();

			if ( ! empty( trim( $before_shipping ) ) && preg_match( '/<thead|<tbody|<tfoot|<th|<tr/', $before_shipping ) && substr( trim( $before_shipping ), 0, 6 ) !== '<table' ) :
				?>
				<table class="shop-table">
					<?php echo $before_shipping; ?>
				</table>
			<?php else : ?>
				<?php echo $before_shipping; ?>
			<?php endif;

			$show_package_details = count( $packages ) > 1;
			$first = true;
			foreach ( $packages as $i => $package ) {
				$product_names = array();

				if ( $show_package_details ) {
					foreach ( $package['contents'] as $item_id => $values ) {
						$product_names[ $item_id ] = $values['data']->get_name() . ' &times;' . $values['quantity'];
					}
					$product_names = apply_filters( 'woocommerce_shipping_package_details_array', $product_names, $package );
				}

				$available_methods 	= $package['rates'];
				$package_details 	= implode( ', ', $product_names );
				$package_name 		= sprintf( _n( 'Shipping', 'Shipping %d', ( $i + 1 ), 'shipping packages', 'woocommerce' ), ( $i + 1 ) );
				//$index 				= $i;
				$chosen_method 		= WC()->session->chosen_shipping_methods[ $i ] ?? '';
				$selected_method_found = false;

				foreach ( $available_methods as $available_method ) {
					if ( $available_method->id === $chosen_method ) {
						$selected_method_found = true;
						break;
					}
				}

				reset( $available_methods );
				$first_method = current( $available_methods );

				if ( ! $selected_method_found && is_object( $first_method ) && method_exists( $first_method, 'get_id' ) && $first ) {
					$chosen_method = $first_method->get_id();

					$new_chosen_methods       = WC()->session->get( 'chosen_shipping_methods' );
					$new_chosen_methods[ $i ] = $chosen_method;
					WC()->session->set( 'chosen_shipping_methods', $new_chosen_methods );
					WC()->cart->calculate_totals();

					$first = false;
				}

				if ( count( $available_methods ) > 0 ) : ?>
					<?php if ( 1 < count( $packages ) ) : ?>
						<h4 class="bu-shipping-package-title"><?php echo esc_html( $package_name ); ?></h4>
					<?php endif; ?>

					<ul id="shipping_method" class="woocommerce-shipping-methods">
						<?php
						foreach ( $available_methods as $method ) :
							$after_shipping_method = '';
							ob_start();
							do_action( 'woocommerce_after_shipping_rate', $method, $i );
							$after_shipping_method = ob_get_clean();
							$label = wc_cart_totals_shipping_method_label( $method );
							if( in_array( $method->get_method_id(), array( 'free_shipping', 'local_pickup' ) ) ) {
								$label .=  sprintf( 
									'<span class="wc-shipping-option--free">%s</span></label>', 
									apply_filters( 'woocommerce_free_shipping_label', esc_html__('Free', 'woocommerce'), $method->get_method_id() )
								);
							}
							$label = str_replace( ': <span', '<span', $label );
							$id = $method->get_method_id();
							$instance_id = $method->get_instance_id();
							$options = get_option("woocommerce_{$id}_{$instance_id}_settings");
							if( ! empty( $options['description'] ) ) {
								$method_description = sprintf('<span class="method-description">%s</span>', wp_kses_post( $options['description'] ) );
							} else {
								$method_description = '';
							}
							?>
							<li>
								<div class="bu-shipping-method-inner">
									<?php printf( '<input type="radio" name="shipping_method[%1$d]" data-index="%1$d" id="shipping_method_%1$d_%2$s" value="%3$s" class="shipping_method" %4$s />', $i, esc_attr( sanitize_title( $method->id ) ), esc_attr( $method->id ), checked( $method->id, $chosen_method, false ) ); // WPCS: XSS ok. ?>
									<?php printf( '<label for="shipping_method_%1$s_%2$s">%3$s</label>%4$s', $i, esc_attr( sanitize_title( $method->id ) ), $label, $method_description ); // WPCS: XSS ok. ?>
								</div>
								<?php
								if ( ! empty( trim( $after_shipping_method ) ) && preg_match( '/<thead|<tbody|<tfoot|<th|<tr/', $after_shipping_method ) && substr( trim( $after_shipping_method ), 0, 6 ) !== '<table' ) :
									?>
									<table>
										<?php echo $after_shipping_method; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
									</table>
								<?php else : ?>
									<?php echo $after_shipping_method; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php endif; ?>
							</li>
						<?php endforeach; ?>
					</ul>
				<?php else : ?>
					<div class="shipping-message">
						<?php echo apply_filters( 'woocommerce_no_shipping_available_html', wpautop( esc_html__( 'There are no shipping options available. Please ensure that your address has been entered correctly, or contact us if you need any help.', 'woocommerce' ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
					</div>
				<?php endif; ?>

				<?php if ( $show_package_details ) : ?>
					<?php echo '<p class="woocommerce-shipping-contents">' . esc_html( $package_details ) . '</p>'; ?>
				<?php endif; ?>
				<?php
			}
			
			ob_start();
			do_action( 'woocommerce_review_order_after_shipping' );
			$after_shipping = ob_get_clean();

			if ( ! empty( trim( $after_shipping ) ) && preg_match( '/<thead|<tbody|<tfoot|<th|<tr/', $after_shipping ) && substr( trim( $after_shipping ), 0, 6 ) !== '<table' ) :
				?>
				<table class="shop-table">
					<?php echo $after_shipping; ?>
				</table>
			<?php else : ?>
				<?php echo $after_shipping; ?>
			<?php endif;
		endif;

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