<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;
use BricksUltimate\Trait\WooCheckoutFieldControls;

class WooShippingFields extends \Bricks\Element {
	use WooCheckoutFieldControls;

	public $category = 'checkout';
	public $name 	= 'bu-shipping-fields';
	public $icon 	= 'ti-layout-list-post';
	public $scripts = [ 'buCheckout' ];
	public $field 	= [];

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

	// Set builder control groups
	public function set_control_groups() {
		$this->control_groups = $this->bu_checkout_field_control_groups( $this->control_groups );
	}

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

		$shipping_checkout_fields = [];
		$checkout = WC()->checkout()||false;
		
		if( $checkout ) {
			$shipping_fields = WC()->checkout()->get_checkout_fields( 'shipping' );
			foreach( $shipping_fields as $key => $shipping_field ) {
				if( ! empty( $shipping_field['label'] ) )
					$shipping_checkout_fields[ $key ] = wp_kses_post( $shipping_field['label'] );
			}

			$order_fields = WC()->checkout()->get_checkout_fields( 'order' );
			foreach( $order_fields as $key => $order_field ) {
				if( ! empty( $order_field['label'] ) )
					$shipping_checkout_fields[ $key ] = wp_kses_post( $order_field['label'] );
			}
		}

		$shipping_checkout_fields[ 'ship_to_diff' ] = esc_html__('Ship to different address', 'bricksultimate');
		$shipping_checkout_fields[ 'custom' ] = esc_html__('Custom field', 'bricksultimate');

		$this->controls['shipping_field'] = [
			'type'        => 'select',
			'label'       => esc_html__( 'Field', 'bricksultimate' ),
			'options'     => $shipping_checkout_fields,
			'multiple'    => false,
			'placeholder' => esc_html__( 'Select a field', 'bricksultimate' ),
		];

		$this->controls = $this->bu_checkout_fields_controls( $this->controls, 'shipping' );
	}

	// 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') );
	}*/

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

		$checkout = WC()->checkout();
		
		if( ! $checkout )
			return;

		$key = Helpers::get_value( $settings, 'shipping_field', false);
		if( $key ) {
			if( $key == 'custom' ) {
				$this->field = [
					'type'              => 'text',
					'label'             => '',
					'description'       => '',
					'placeholder'       => '',
					'maxlength'         => Helpers::get_value( $settings, 'maxlength', false ),
					'minlength'         => Helpers::get_value( $settings, 'minlength', false ),
					'required'          => true,
					'custom_attributes' => array(),
					'default' 			=> Helpers::get_value( $settings, 'hiddenValue', '' ),
					'class' 			=> array(),
					'options' 			=> array(),
				];

				$this->field['type'] = Helpers::get_value( $settings, 'field_type', 'text');
				$key = Helpers::get_value( $settings, 'field_key', false);
				if( ! $key ) {
					return $this->render_element_placeholder( 
						[ 'title' => esc_html__( 'Enter field key.', 'bricksultimate' ) ] 
					);
				}

				if( $this->field['type'] == "checkbox" ) {
					if( ! empty( $settings['isChecked'] ) ) {
						$this->field['value'] = 1;
					}

					if( ! empty( $settings['willHide'] ) ) {
						$this->field['class'][] = "screen-reader-text";
					}

					$this->field['class'][] = 'bu-checkbox-buttons';
				}

				if( isset( $settings['fieldOptions'] ) ) {
					$options = explode("\n", $settings['fieldOptions'] );
					if( is_array( $options ) ) {
						foreach( $options as $keyval ) {
							$option = explode(":", $keyval);
							if( !empty( $option[0] ) )
								$this->field['options'][ trim($option[0]) ] = trim($option[1]);
						}
					}
				}
			} elseif( 'ship_to_diff' === $key ){
				$this->set_attribute('_root', 'class', ['bu-checkout-fields'] );
				echo "<{$this->tag} {$this->render_attributes('_root')}>";
				$class =  (! empty( $settings['hideShipDiff'] ) && ( ! bricks_is_builder() && ! bricks_is_builder_iframe() && !bricks_is_builder_call() ) ) ? "bu-checkbox-buttons screen-reader-text" : 'bu-checkbox-buttons';
				$value = ! empty( $settings['valueShipDiff'] ) ? 1 : 0;
				$value = 'shipping' === get_option( 'woocommerce_ship_to_destination' ) ? 1 : $value;
			?>
				<p id="ship-to-different-address" class="<?php echo $class; ?>">
					<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
						<input id="ship-to-different-address-checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" <?php checked( apply_filters( 'woocommerce_ship_to_different_address_checked', $value ), 1 ); ?> type="checkbox" name="ship_to_different_address" value="1" /> <span><?php esc_html_e( 'Ship to a different address?', 'woocommerce' ); ?></span>
					</label>
				</p>
			<?php
				echo "</{$this->tag}>";

				return;
			} else {
				$shipping_fields = ( $key != 'order_comments' ) ? $checkout->get_checkout_fields( 'shipping' ) : $checkout->get_checkout_fields( 'order' );

				if( empty( $shipping_fields[ $key ] ) )
					return;
				
				$this->field = $shipping_fields[ $key ];
			}

			$this->field['label'] = Helpers::get_value( $settings, 'label', $this->field['label']);
			$this->field['description'] = Helpers::get_value( $settings, 'field_description', false);
			$this->field['placeholder'] = Helpers::get_value( $settings, 'placeholder', '' );
			$aria_label = Helpers::get_value( $settings, 'aria_label', $this->field['label'] );

			if( ! empty( $settings['optional'] ) ) {
				$this->field['required'] = false;
				$this->field['validate'] = [];
			}

			if( ! empty( $settings['isMandatory'] ) ) {
				$this->field['required'] = true;
			}

			$this->field['custom_attributes']['aria-label'] = $aria_label;
			$this->field['custom_attributes']['aria-invalid'] = "false";

			if( isset( $this->field['type'] ) && $this->field['type'] == 'textarea' ) {
				$this->field['custom_attributes']['rows'] = Helpers::get_value( $settings, 'rows');
				$this->field['custom_attributes']['cols'] = Helpers::get_value( $settings, 'cols');
			}

			$class = ( $checkout->get_value( $key ) || isset( $this->field['default'] ) ) ? 'is-active' : '';
			$class = ( isset( $this->field['type'] ) && ( $this->field['type'] == 'time' || $this->field['type'] == 'date' ) ) ? 'is-active' : $class;
			$design = Helpers::get_value( $settings, 'field_design', 'bu-default');

			$design = ( isset( $this->field['type']) && ( $this->field['type'] == "radio" || $this->field['type'] == "checkbox" ) ) ? '' : $design;

			if( $design == 'bu-default' && ! empty( $this->field['placeholder'] ) ) {
				$class = 'is-active';
			}

			$this->set_attribute('_root', 'class', ['bu-checkout-fields', $design, $class] );

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

			$this->field['class'][] = $class;

			woocommerce_form_field( $key, $this->field, $checkout->get_value( $key ) );

			echo "</{$this->tag}>";
		} else {
			return $this->render_element_placeholder( [ 'title' => esc_html__( 'Select checkout fields.', 'bricksultimate' ) ] );
		}
	}
}