<?php
namespace BricksUltimate\Elements;

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

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

class WooBillingFields extends \Bricks\Element {
	use WooCheckoutFieldControls;

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

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Billing 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['bfInfo'] = [
			'type' 		=> 'info',
			'content' 	=> esc_html__( 'Refresh the builder editor for the preview.', 'bricksultimate' ),
		];

		$billing_checkout_fields = [];
		$checkout = WC()->checkout()||false;
		
		if( $checkout ) {
			$billing_fields = WC()->checkout()->get_checkout_fields( 'billing' );
			foreach( $billing_fields as $key => $billing_field ) {
				if( ! empty( $billing_field['label'] ) )
					$billing_checkout_fields[ $key ] = wp_kses_post( $billing_field['label'] );
			}
		}

		$billing_checkout_fields[ 'createaccount' ] = esc_html__('Create an account?', 'bricksultimate');
		$billing_checkout_fields[ 'account_username' ] = esc_html__('Account Username', 'bricksultimate');
		$billing_checkout_fields[ 'account_password' ] = esc_html__('Account Password', 'bricksultimate');
		$billing_checkout_fields[ 'custom' ] = esc_html__('Custom field', 'bricksultimate');

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

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

		/**
		 * Checkbox
		 * ----------------------------------------*/
		$cb_selector = '.bu-checkbox-buttons input[type=checkbox]';

		$this->controls['acc_cbsize'] = [
			'group' 	=> 'acc_checkbox',
			'type'  	=> 'number',
			'label' 	=> esc_html__( 'Size', 'bricksultimate' ),
			'placeholder' => '15px',
			'units' 	=> true,
			'css'   	=> [
				[
					'property' => 'width',
					'selector' => $cb_selector,
				],
				[
					'property' => 'height',
					'selector' => $cb_selector,
				]
			],
			'required' => ['billing_field', '=', 'createaccount']
		];

		$this->controls['acc_cbbg'] = [
			'group' 	=> 'acc_checkbox',
			'type'  	=> 'color',
			'label' 	=> esc_html__( 'Background Color', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'background-color',
					'selector' => $cb_selector,
				]
			],
			'required' => ['billing_field', '=', 'createaccount']
		];

		$this->controls['acc_cbbrd'] = [
			'group' 	=> 'acc_checkbox',
			'type'  	=> 'border',
			'label' 	=> esc_html__( 'Border', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'border',
					'selector' => $cb_selector,
				]
			],
			'required' => ['billing_field', '=', 'createaccount']
		];

		$cb_checked = '.bu-checkbox-buttons input[type=checkbox]:checked';
		$this->controls['acc_cbcbg'] = [
			'group' 	=> 'acc_checkbox',
			'type'  	=> 'color',
			'label' 	=> esc_html__( 'Background color(checked)', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'background-color',
					'selector' => $cb_checked,
				]
			],
			'required' => ['billing_field', '=', 'createaccount']
		];

		$this->controls['acc_cbcbrd'] = [
			'group' 	=> 'acc_checkbox',
			'type'  	=> 'border',
			'label' 	=> esc_html__( 'Border(checked)', 'bricksultimate' ),
			'css'   	=> [
				[
					'property' => 'border',
					'selector' => $cb_checked,
				]
			],
			'required' => ['billing_field', '=', 'createaccount']
		];
	}

	// 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, 'billing_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( $this->field['type'] == "radio" ) {
					$this->field['class'][] = 'bu-radio-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( 'createaccount' == $key ) {
				$isChecked = false;
				 if( true === $checkout->get_value( 'createaccount' ) || ( true === apply_filters( 'woocommerce_create_account_default_checked', false ) ) ) {
					$isChecked = true;
				}

				$isChecked =  ! empty( $settings['accIsChecked'] ) ? true : $isChecked;

				if( ! empty( $settings['hideAccountFields'] ) ) {
					$this->set_attribute( '_root', 'class', [ "screen-reader-text" ] );
				}

				echo "<{$this->tag} {$this->render_attributes('_root')}>";
			?>
				<p class="form-row form-row-wide create-account bu-checkbox-buttons">
					<input class="input-checkbox" id="createaccount" <?php checked( $isChecked, true ); ?> type="checkbox" name="createaccount" value="1" /> <span><?php esc_html_e( 'Create an account?', 'woocommerce' ); ?></span>
				</p>
			<?php
				echo "</{$this->tag}>";

				return;
			} elseif( 'account_username' == $key ) {
				$this->field = array(
					'type'         => 'text',
					'label'        => __( 'Account username', 'woocommerce' ),
					'required'     => true,
					'placeholder'  => esc_attr__( 'Username', 'woocommerce' ),
					'autocomplete' => 'username',
				);
			} elseif( 'account_password' == $key ) {
				$this->field = array(
					'type'         => 'password',
					'label'        => __( 'Create account password', 'woocommerce' ),
					'required'     => true,
					'placeholder'  => esc_attr__( 'Password', 'woocommerce' ),
					'autocomplete' => 'new-password',
				);

			} else {
				$billing_fields = $checkout->get_checkout_fields( 'billing' );
				
				if( empty( $billing_fields[ $key ] ) )
					return;

				$this->field = $billing_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'] = [];
			}
			
			$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 billing fields.', 'bricksultimate' ) ] );
		}
	}
}