<?php
if(!defined('ABSPATH')){ exit; }

if(!class_exists('WCFE_Checkout_Field_Editor_Frontend')):

class WCFE_Checkout_Field_Editor_Frontend extends WCFE_Checkout_Fields_Utils {
	public $sections_extra = array();
	public $options_extra = array();
	public $advanced_settings = array();
	
	public function __construct(){
		if(!isset($_SESSION)){
			session_start();
		}
		
		$advanced_settings = $this->get_advanced_settings();
		
		$hp_cf = apply_filters('thwcfd_woocommerce_checkout_fields_hook_priority', 1000);
		
		add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
		
		//Show Custome Fields in Checkout Page
		add_action('woocommerce_checkout_before_customer_details', array($this, 'woo_checkout_before_customer_details'));
		add_action('woocommerce_checkout_after_customer_details', array($this, 'woo_checkout_after_customer_details'));
		
		add_action('woocommerce_before_checkout_billing_form', array($this, 'woo_before_checkout_billing_form'));
		add_action('woocommerce_after_checkout_billing_form', array($this, 'woo_after_checkout_billing_form'));
		
		add_action('woocommerce_before_checkout_shipping_form', array($this, 'woo_before_checkout_shipping_form'));
		add_action('woocommerce_after_checkout_shipping_form', array($this, 'woo_after_checkout_shipping_form'));
		
		add_action('woocommerce_before_checkout_registration_form', array($this, 'woo_before_checkout_registration_form'));
		add_action('woocommerce_after_checkout_registration_form', array($this, 'woo_after_checkout_registration_form'));
		
		add_action('woocommerce_before_order_notes', array($this, 'woo_before_order_notes'));
		add_action('woocommerce_after_order_notes', array($this, 'woo_after_order_notes'));
		
		add_action('woocommerce_review_order_before_cart_contents', array($this, 'woo_review_order_before_cart_contents'));
		add_action('woocommerce_review_order_after_cart_contents', array($this, 'woo_review_order_after_cart_contents'));
		
		add_action('woocommerce_review_order_before_order_total', array($this, 'woo_review_order_before_order_total'));
		add_action('woocommerce_review_order_after_order_total', array($this, 'woo_review_order_after_order_total'));
		
		add_action('woocommerce_checkout_before_terms_and_conditions', array($this, 'woo_checkout_before_terms_and_conditions'));
		add_action('woocommerce_checkout_after_terms_and_conditions', array($this, 'woo_checkout_after_terms_and_conditions'));
		
		add_action('woocommerce_review_order_before_submit', array($this, 'woo_review_order_before_submit'));
		add_action('woocommerce_review_order_after_submit', array($this, 'woo_review_order_after_submit'));
		
		add_action('woocommerce_checkout_before_order_review', array($this, 'woo_checkout_before_order_review'));
		add_action('woocommerce_checkout_after_order_review', array($this, 'woo_checkout_after_order_review'));
		
		add_action('woocommerce_checkout_order_review', array($this, 'woo_checkout_order_review_0'), 0);
		add_action('woocommerce_checkout_order_review', array($this, 'woo_checkout_order_review_99'), 99);
		
		$this->render_sections_added_to_custom_positions();
		
		add_filter('woocommerce_enable_order_notes_field', array($this, 'woo_enable_order_notes_field'), 1000);
		
		// Checkout init
		add_filter('woocommerce_checkout_fields', array($this, 'woo_checkout_fields'), $hp_cf);
		add_filter('woocommerce_billing_fields', array($this, 'woo_billing_fields'), $hp_cf, 2);
		add_filter('woocommerce_shipping_fields', array($this, 'woo_shipping_fields'), $hp_cf, 2);
		add_filter('woocommerce_default_address_fields', array($this, 'woo_default_address_fields'), $hp_cf);
		add_filter('woocommerce_get_country_locale', array($this, 'woo_get_country_locale'), $hp_cf);
		add_filter('woocommerce_get_country_locale_base', array($this, 'woo_prepare_country_locale'), $hp_cf);
		add_filter('woocommerce_get_country_locale_default', array($this, 'woo_prepare_country_locale'), $hp_cf);
		
		//Checkout Process(Validate checkout fields, save user meta and save order meta
		add_action('woocommerce_checkout_process', array($this, 'woo_checkout_process'));
		add_action('woocommerce_after_checkout_validation', array($this, 'woo_checkout_fields_validation'), 10, 2); 
		add_action('woocommerce_checkout_update_user_meta', array($this, 'woo_checkout_update_user_meta'), 10, 2); 
		add_action('woocommerce_checkout_update_order_meta', array($this, 'woo_checkout_update_order_meta'), 10, 2); 
		
		//Show in Order Details Page - Customer view (Thankyou Page & My Order Page)
		add_action('woocommerce_order_details_after_order_table', array($this, 'display_custom_fields_in_order_details_page_customer'), 20, 1);
		//add_action('woocommerce_order_details_after_customer_details', array($this, 'woo_order_details_after_customer_details'), 20, 1);
		
		//Show in Email
		add_filter('woocommerce_email_customer_details_fields', array($this, 'woo_hide_default_customer_fields_in_emails'), 10, 3);
		if($this->get_setting_value($advanced_settings, 'custom_fields_position_email') === 'woocommerce_email_customer_details_fields' ){
			add_filter('woocommerce_email_customer_details_fields', array($this, 'woo_display_custom_fields_in_emails'), 10, 3);
		}else{
			add_filter('woocommerce_email_order_meta_fields', array($this, 'woo_display_custom_fields_in_emails'), 10, 3);
		}
		
		add_filter('woocommerce_localisation_address_formats', array($this, 'woo_localisation_address_formats'), 20, 2 ); 
		add_filter('woocommerce_formatted_address_replacements', array($this, 'woo_formatted_address_replacements'), 20, 2 ); 
		add_filter('woocommerce_order_formatted_billing_address', array($this, 'woo_order_formatted_billing_address'), 20, 2 );
		add_filter('woocommerce_order_formatted_shipping_address', array($this, 'woo_order_formatted_shipping_address'), 20, 2 );
		//add_filter('woocommerce_my_account_my_address_formatted_address', array($this, 'woo_my_account_my_address_formatted_address'), 20, 3 ); // MOVED TO MY ACCOUNT
		//add_filter('woocommerce_formatted_address_force_country_display', '__return_true' );
		
		// Define address formats
		// woocommerce_localisation_address_formats (WC_Countries)
		// woocommerce_formatted_address_force_country_display
		// woocommerce_formatted_address_replacements
		
		
		//Check Cart Items
		
		//Create Order
		//woocommerce_checkout_update_user_meta
		//woocommerce_checkout_update_order_meta
		//add_action('woocommerce_checkout_update_order_meta', array($this, 'save_order_meta'), 10, 2);
		
		add_action('wp_ajax_thwcfe_calculate_extra_cost', array($this, 'thwcfe_calculate_extra_cost'), 10);
    	add_action('wp_ajax_nopriv_thwcfe_calculate_extra_cost', array($this, 'thwcfe_calculate_extra_cost'), 10);
		add_action('woocommerce_cart_calculate_fees', array($this, 'woo_cart_calculate_fees') );
		add_filter('woocommerce_cart_totals_fee_html', array($this, 'woo_cart_totals_fee_html'), 10, 2);
		
		
		add_filter('woocommerce_form_field_hidden', array($this, 'woo_form_field_hidden'), 10, 4);
		add_filter('woocommerce_form_field_heading', array($this, 'woo_form_field_heading'), 10, 4);
		add_filter('woocommerce_form_field_label', array($this, 'woo_form_field_label'), 10, 4);
		add_filter('woocommerce_form_field_textarea', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_checkbox', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_checkboxgroup', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_password', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_text', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_email', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_tel', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_number', array($this, 'woo_form_field'), 10, 4);		
		add_filter('woocommerce_form_field_select', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_multiselect', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_radio', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_datepicker', array($this, 'woo_form_field'), 10, 4);
		add_filter('woocommerce_form_field_timepicker', array($this, 'woo_form_field'), 10, 4);
		//add_filter('woocommerce_form_field_file', array($this, 'woo_form_field'), 10, 4);
		
		if($this->get_setting_value($advanced_settings, 'enable_conditions_country') === 'yes'){
			add_filter('woocommerce_form_field_country', array($this, 'woo_form_field'), 10, 4);
		}
		if($this->get_setting_value($advanced_settings, 'enable_conditions_state') === 'yes'){
			add_filter('woocommerce_form_field_state', array($this, 'woo_form_field'), 10, 4);
		}
		
		// Deprecated
		//add_filter('woocommerce_email_order_meta_keys', array($this, 'woo_display_custom_fields_in_emails'), 10, 1);
		
		//Custom user meta data
		add_filter( 'woocommerce_checkout_get_value', array($this, 'woo_checkout_get_value'), 10, 2 );
		//add_filter( 'woocommerce_address_to_edit', array($this, 'woo_address_to_edit'), 10, 2 ); MOVED TO MY ACCOUNT
		//add_action( 'woocommerce_edit_account_form', array($this, 'woo_edit_account_form') ); MOVED TO MY ACCOUNT
		//add_action( 'woocommerce_save_account_details', array($this, 'woo_save_account_details') ); MOVED TO MY ACCOUNT
		//add_action( 'woocommerce_customer_save_address', array($this, 'woo_customer_save_address'), 10, 2 ); MOVED TO MY ACCOUNT
		//add_action( 'woocommerce_before_edit_account_address_form', array($this, 'woo_before_edit_account_address_form') );
	}
	
	public function enqueue_scripts(){	
		global $wp_scripts;

		if(is_checkout()){
			$jquery_version = isset($wp_scripts->registered['jquery-ui-core']->ver) ? $wp_scripts->registered['jquery-ui-core']->ver : '1.9.2';
			$in_footer = apply_filters( 'thwcfe_enqueue_script_in_footer', true );
			
			wp_register_script('wcfe-timepicker', TH_WCFE_ASSETS_URL.'js/timepicker/jquery.timepicker.min.js', array('jquery'), '1.0.1', $in_footer);
			
			$deps = array();
			
			if( apply_filters( 'thwcfe_include_jquery_ui_i18n', TRUE ) ) {
				wp_register_script('jquery-ui-i18n', '//ajax.googleapis.com/ajax/libs/jqueryui/'.$jquery_version.'/i18n/jquery-ui-i18n.min.js',
				array('jquery','jquery-ui-datepicker'), $in_footer);
				
				$deps[] = 'jquery-ui-i18n';
			}else{
				$deps[] = 'jquery';
				$deps[] = 'jquery-ui-datepicker';
			}
			
			if($this->get_settings('disable_select2_for_select_fields') != 'yes'){
				$deps[] = 'select2';
			}
			
			wp_register_script('wcfe-field-editor-script', TH_WCFE_ASSETS_URL.'js/thwcfe-checkout-field-editor-frontend.js', $deps, TH_WCFE_VERSION, $in_footer);
			
			/*wp_register_script('jquery-ui-i18n', '//ajax.googleapis.com/ajax/libs/jqueryui/'.$jquery_version.'/i18n/jquery-ui-i18n.min.js',
			array('jquery','jquery-ui-datepicker'), true);
			wp_register_script('wcfe-field-editor-script', TH_WCFE_ASSETS_URL.'js/thwcfe-checkout-field-editor-frontend.js', array('jquery-ui-i18n', 'select2'), 
			TH_WCFE_VERSION, true);*/
			
			if(apply_filters( 'thwcfe_force_register_date_picker_script', false )){
				wp_register_script('wcfe-datepicker', 'https://code.jquery.com/ui/'.$jquery_version.'/jquery-ui.js', array('jquery'), '1.0.1', $in_footer);
				wp_enqueue_script('wcfe-datepicker');
			}
			
			wp_enqueue_script('wcfe-timepicker');
			wp_enqueue_script('wcfe-field-editor-script');	
			
			wp_enqueue_style('wcfe-timepicker-style', TH_WCFE_ASSETS_URL.'js/timepicker/jquery.timepicker.css');
			wp_enqueue_style('jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/'. $jquery_version .'/themes/smoothness/jquery-ui.css');
			
			$enable_conditions_payment_shipping = THWCFE_Utils::get_settings('enable_conditions_payment_shipping') ? true : false;
			
			$data = array(
				'lang' => array( 
							'am' => $this->__wcfe('am'), 
							'pm' => $this->__wcfe('pm'),  
							'AM' => $this->__wcfe('AM'), 
							'PM' => $this->__wcfe('PM'),
							'decimal' => $this->__wcfe('.'), 
							'mins' => $this->__wcfe('mins'), 
							'hr'   => $this->__wcfe('hr'), 
							'hrs'  => $this->__wcfe('hrs'),
						),
				'language' 	  => $this->get_locale_code(),
				'date_format' => $this->get_jquery_date_format(wc_date_format()),
				'readonly_date_field' => apply_filters( 'thwcfe_date_picker_field_readonly', true ),
				'restrict_time_slots_for_same_day' => apply_filters( 'thwcfe_time_picker_restrict_slots_for_same_day', true ),
				'rebind_all_cfields' => apply_filters( 'thwcfe_enable_conditions_based_on_review_panel_fields', $enable_conditions_payment_shipping ),
				'ajax_url'    => admin_url( 'admin-ajax.php' ),
			);

			wp_localize_script('wcfe-field-editor-script', 'wcfe_checkout_fields', $data);
		}
	}
	
	public function is_local_field( $field_name ){
		if($field_name && in_array($field_name, array(
			'billing_country', 'billing_state', 'billing_city', 'billing_postcode',
			'shipping_country', 'shipping_state', 'shipping_city', 'shipping_postcode',
			'order_comments'
		))){
			return true;
		}
		return false;
	}
	
	public function get_product_categories($product_id){
		$categories = array();
		$assigned_categories = wp_get_post_terms($product_id, 'product_cat');
		
		$ingnore_translation = apply_filters('thwcfe_ingnore_wpml_translation_for_product_category', false);
		$is_wpml_active = function_exists('icl_object_id');
		if($is_wpml_active && $ingnore_translation){
			global $sitepress;
			global $icl_adjust_id_url_filter_off;
			$orig_flag_value = $icl_adjust_id_url_filter_off;
			$icl_adjust_id_url_filter_off = true;
			$default_lang = $sitepress->get_default_language();
		}
		
		foreach($assigned_categories as $category){
			$parent_categories = get_ancestors( $category->term_id, 'product_cat' ); 
			if(is_array($parent_categories)){
				foreach($parent_categories as $pcat_id){
					$pcat = get_term( $pcat_id, 'product_cat' );
					$categories[] = $pcat->slug;
				}
			}
			
			$cat_slug = $category->slug;
			if($is_wpml_active && $ingnore_translation){
				$default_cat_id = icl_object_id($category->term_id, 'category', true, $default_lang);
				$default_cat = get_term($default_cat_id);
				$cat_slug = $default_cat->slug;
			}
			$categories[] = $cat_slug;
		}
		
		if($is_wpml_active && $ingnore_translation){
			$icl_adjust_id_url_filter_off = $orig_flag_value;
		}
		
		return $categories;
	}
	
	public function require_shipping_address($posted){
		if((WC()->cart->ship_to_billing_address_only() || !empty($posted['shiptobilling']) || 
			(!WC()->cart->needs_shipping() && get_option('woocommerce_require_shipping_address') === 'no'))){
			return false;
		}
		return true;
	}
	
	public function get_cart_summary(){
		$items = WC()->cart->get_cart();
		
		$cart = array();
		$cart['products'] = array();
		$cart['categories'] = array();
		$cart['variations'] = array();
		
		foreach($items as $item => $values) { 
			//$_product = $values['data']->post; 
			$cart['products'][] = $values['product_id'];
			$cart['categories'] = array_merge($cart['categories'], $this->get_product_categories($values['product_id']));
			if($values['variation_id']){
				$cart['variations'][] = $values['variation_id'];
			}
		} 
		
		$cart['products'] = array_values($cart['products']);
		$cart['categories'] = apply_filters('thwcfe_cart_product_categories', array_values($cart['categories']));
		$cart['variations'] = array_values($cart['variations']);
		
		return $cart;
	}
	
	public function get_fieldset($section, $ignore_conditions = false){
		$cart       = $this->get_cart_summary();
		$products   = $cart['products'];
		$categories = $cart['categories'];
		$variations = $cart['variations'];
		
		$fieldset = array();
		if(WCFE_Section_Utils::is_valid_section($section) && $section->get_property('enabled')){
			if($ignore_conditions){
				$fieldset = WCFE_Section_Utils::get_fieldset_all($section);
			}else{
				$fieldset = WCFE_Section_Utils::get_fieldset($section, $products, $categories, $variations);
			}
		}
		
		return !empty($fieldset) ? $fieldset : false;
	}
	
	public function get_fieldset_all($section, $exclude_disabled = true){
		$fieldset = array();
		if(WCFE_Section_Utils::is_valid_section($section) && $section->get_property('enabled')){
			$fieldset = WCFE_Section_Utils::get_fieldset_all($section, $exclude_disabled);
		}
		
		return !empty($fieldset) ? $fieldset : false;
	}
	
	/*public function get_user_fields_full(){
		$user_fields = array();
		
		$sections = $this->get_checkout_sections();	
		foreach($sections as $sname => $section){	
			$fields = WCFE_Section_Utils::get_fields($section);
			if($fields && is_array($fields)){
				foreach($fields as $key => $field){
					if($field->is_custom_field() && $field->is_enabled() && $field->get_property('user_meta')){
						$user_fields[$key] = $field;
					}
				}
			}
		}
		
		return $user_fields;
	}*/
	
	
   /*********************************************************
	******* DISPLAY DEFAULT SECTIONS & FIELDS - START *******
	*********************************************************/
	public function prepare_address_fields_my_account($fieldset, $original_fieldset = false, $sname = 'billing'){
		if(!empty($fieldset) && !empty($original_fieldset) && is_array($fieldset) && is_array($original_fieldset)){
			$priority = 0;
			foreach($original_fieldset as $okey => $ofield) {
				$priority = isset($ofield['priority']) && is_numeric($ofield['priority']) && $ofield['priority'] > $priority ? $ofield['priority'] : $priority;
			}
			
			foreach($fieldset as $key => $field) {
				$show = apply_filters('thwcfe_show_edit_address_form_field_'.$key, true, $sname, $field);
				
				if(isset($field['custom']) && $field['custom'] && $show){
					$priority += 10;
					$required = isset($field['required']) && $field['required'] ? true : false;
					$ftype = isset($field['type']) ? $field['type'] : 'text';
					$ftype = $ftype === 'hidden' ? 'text' : $ftype;
									
					$custom_field = array();
					$custom_field['type'] = $ftype;
					$custom_field['label'] = $this->__wcfe($field['label']);
					$custom_field['placeholder'] = $this->__wcfe($field['placeholder']);
					$custom_field['class'] = $field['class'];
					$custom_field['description'] = $this->__wcfe($field['description']);
					$custom_field['label_class'] = $field['label_class'];
					$custom_field['input_class'] = $field['input_class'];
					//$custom_field['default'] = $field['default'];
					$custom_field['validate'] = $field['validate'];
					//$custom_field['required'] = $field['required'];
					$custom_field['required'] = isset($field['rules']) && !empty($field['rules']) ? false : $required;
					$custom_field['priority'] = $priority;
					$custom_field['user_meta'] = $field['user_meta'];
					
					if($ftype === 'select' || $ftype === 'multiselect' || $ftype === 'radio' || $ftype === 'checkboxgroup'){
						$custom_field['options'] = $field['options'];
						$custom_field['options_object'] = $field['options_object'];
					}else if($ftype === 'checkbox'){
						$custom_field['on_value'] = $field['on_value'];
						$custom_field['off_value'] = $field['off_value'];
					}
					
					if(isset($field['rules']) && !empty($field['rules'])){
						$custom_field['required'] = false;
						$custom_field['validate'] = '';
					}
										
					$original_fieldset[$key] = $custom_field;
				}
			}
		}
		return $original_fieldset;
	}
	
	public function prepare_address_fields($fieldset, $original_fieldset = false, $sname = 'billing', $country){
		$locale = WC()->countries->get_country_locale();
		if(isset($locale[ $country ]) && is_array($locale[ $country ])) {
			foreach($locale[ $country ] as $key => $value){
				if(is_array($value) && isset($fieldset[$sname.'_'.$key])){
					if(isset($value['required'])){
						$fieldset[$sname.'_'.$key]['required'] = $value['required'];
					}
				}
			}
		}
		return $fieldset;
	}
	
	/*public function prepare_address_fields($fieldset, $original_fieldset = false, $sname = 'billing'){
		if(!empty($fieldset) && !empty($original_fieldset)){
			$default_address_fields = $this->get_default_address_fields();
			
			if(is_array($default_address_fields)){
				foreach($default_address_fields as $afname) {
					$fname = $sname.'_'.$afname;
					
					$new_field = isset($fieldset[$fname]) ? $fieldset[$fname] : false;
					$original_field = isset($original_fieldset[$fname]) ? $original_fieldset[$fname] : false;
					
					if($new_field && $original_field){
						$new_field['label'] = $this->__wcfe($new_field['label']);
						if(isset($new_field['required']) && $new_field['required']){
							$new_field['required'] = isset($original_field['required']) && $original_field['required'] ? true : false;
						}
						
						$fieldset[$fname] = $new_field;
					}
				}
			}
		}
		return $fieldset;
	}*/
	
	public function woo_checkout_fields( $checkout_fields ) {
		$sections = $this->get_checkout_sections();
		
		foreach($sections as $sname => $section) {
			if($sname !== 'billing' && $sname !== 'shipping'){
				$fieldset = $this->get_fieldset($section);
				$fieldset = $fieldset ? $fieldset : array();
				
				if(is_array($fieldset)){
					$sname = $sname === 'additional' ? 'order' : $sname;
					$checkout_fields[$sname] = $fieldset; //TODO merge instead repolacing existing fields to avoid losing any other non identified property
				}
			}
		}
		return $checkout_fields;
	}
	
	public function woo_billing_fields($fields, $country){
		$section_name = 'billing';
		$section = $this->get_checkout_section('billing');
		$use_default = apply_filters('thwcfe_use_default_fields_if_empty', true, $section_name);
		
		if(WCFE_Section_Utils::is_valid_section($section)){
			if(is_wc_endpoint_url('edit-address')){
				$fieldset = WCFE_Section_Utils::get_fieldset_all($section);
				if($fieldset || !$use_default){
					if(apply_filters('thwcfe_ignore_address_field_changes', false)) {
						$fieldset = $this->prepare_address_fields_my_account($fieldset, $fields, $section_name);
					}else{
						$fieldset = $this->prepare_address_fields($fieldset, $fields, $section_name, $country);
					}
					$fields = $fieldset;
				}
			}else{
				$fieldset = $this->get_fieldset($section);
				if($fieldset || !$use_default){
					$fieldset = $this->prepare_address_fields($fieldset, $fields, $section_name, $country);
					$fields = $fieldset;
				}
			}
		}
				
		return $fields;
	}
	
	public function woo_shipping_fields($fields, $country){
		$section_name = 'shipping';
		$section = $this->get_checkout_section('shipping');
		$use_default = apply_filters('thwcfe_use_default_fields_if_empty', true, $section_name);
		
		if(WCFE_Section_Utils::is_valid_section($section)){
			if(is_wc_endpoint_url('edit-address')){
				$fieldset = WCFE_Section_Utils::get_fieldset_all($section);
				if($fieldset || !$use_default){
					if(apply_filters('thwcfe_ignore_address_field_changes', false)) {
						$fieldset = $this->prepare_address_fields_my_account($fieldset, $fields, $section_name);
					}else{
						$fieldset = $this->prepare_address_fields($fieldset, $fields, $section_name, $country);
					}
					$fields = $fieldset;
				}
			}else{
				$fieldset = $this->get_fieldset($section);
				if($fieldset || !$use_default){
					$fieldset = $this->prepare_address_fields($fieldset, $fields, $section_name, $country);
					$fields = $fieldset;
				}
			}
		
			/*$fieldset = $this->get_fieldset($section);
			if($fieldset || !$use_default){
				if(is_wc_endpoint_url('edit-address')){
					if(apply_filters('thwcfe_ignore_address_field_changes', false)) {
					    $fieldset = $this->prepare_address_fields_my_account($fieldset, $fields, 'shipping');
				    }else{
					    $fieldset = $this->prepare_address_fields($fieldset, $fields, 'shipping', $country);
				    }
					$fields = $fieldset;
				}else{
					$fieldset = $this->prepare_address_fields($fieldset, $fields, 'shipping', $country);
					$fields = $fieldset;
				}
			}*/
		}
				
		return $fields;
	}
	
	public function woo_default_address_fields($fields){
		global $supress_field_modification;
		if($supress_field_modification){
			return $fields;
		}
		
		$sname = apply_filters('thwcfe_address_field_override_with', 'billing');
		if($sname === 'billing' || $sname === 'shipping'){
			$section = $this->get_checkout_section($sname);
			
			if(WCFE_Section_Utils::is_valid_section($section)){
				$address_fields = $this->get_fieldset($section);
				
				foreach($fields as $name => $field) {
					if($this->is_default_address_field($name)){
						$custom_field = isset($address_fields[$sname.'_'.$name]) ? $address_fields[$sname.'_'.$name] : false;
						
						if($custom_field && !( isset($custom_field['enabled']) && $custom_field['enabled'] == false )){
							$fields[$name]['required'] = isset($custom_field['required']) && $custom_field['required'] ? true : false;
						}
					}
				}
			}
		}
		return $fields;
	}
	
	/*public function woo_default_address_fields($original){
		global $supress_field_modification;
		if($supress_field_modification){
			return $original;
		}
		
		$sname = 'billing';
		$fields = $original;
		$section = $this->get_checkout_section($sname);
		if($this->is_valid_section($section)){
			$address_fields = $this->get_fieldset($section);
			
			foreach($original as $name => $ofield) {
				if($this->is_default_address_field($name)){
					$new_field = isset($address_fields[$sname.'_'.$name]) ? $address_fields[$sname.'_'.$name] : false;
					
					$new_field['label'] = $this->__wcfe($new_field['label']);
					
					if($new_field && !( isset($new_field['enabled']) && $new_field['enabled'] == false )){
						if(isset($ofield['autocomplete'])){
							$new_field['autocomplete'] = $ofield['autocomplete'];
						}
						
						if(isset($new_field['required']) && $new_field['required']){
							$new_field['required'] = isset($ofield['required']) ? $ofield['required'] : 0;
						}
						
						$fields[$name] = $new_field;
					}
				}
			}
		}
		
		return $fields;
	}*/
	/*public function woo_default_address_fields($original){
		global $supress_field_modification;
		if($supress_field_modification){
			return $original;
		}
		
		$sname = 'billing';
		$section = $this->get_checkout_section($sname);
		
		if(!$this->is_valid_section($section)){
			$sname = 'shipping';
			$section = $this->get_checkout_section($sname);
		}
		
		if($this->is_valid_section($section)){
			$address_fields = $this->get_fieldset($section);
			
			foreach($original as $name => $ofield) {
				if(is_array($ofield)){
					$cfield = isset($address_fields[$sname.'_'.$name]) ? $address_fields[$sname.'_'.$name] : false;
					
					if($cfield && !( isset($cfield['enabled']) && $cfield['enabled'] == false )){
						if(isset($ofield['label']) && isset($cfield['label'])){
							$original[$name]['label'] = $this->__wcfe($cfield['label']);
						}
						if(isset($ofield['required']) && isset($cfield['required'])){
							$original[$name]['required'] = $cfield['required'];
						}
						if(isset($ofield['class']) && isset($cfield['class'])){
							$original[$name]['class'] = !empty($cfield['class']) ? $cfield['class'] : $ofield['class'];
						}
						if(isset($ofield['placeholder']) && isset($cfield['placeholder'])){
							$original[$name]['placeholder'] = $this->__wcfe($cfield['placeholder']);
						}
						if(isset($ofield['validate']) && isset($cfield['validate'])){
							$original[$name]['validate'] = !empty($cfield['validate']) ? $cfield['validate'] : $ofield['validate'];
						}
						if(isset($ofield['priority']) && isset($cfield['priority'])){
							$original[$name]['priority'] = is_numeric($cfield['priority']) ? $cfield['priority'] : $ofield['priority'];
						}
					}else{
						//unset($original[$name]);
					}
				}
			}
		}
		
		return $original;
	}*/
		
	public function woo_get_country_locale($locale) {
		if(is_array($locale)){
			foreach($locale as $country => $fields){
				$locale[$country] = $this->woo_prepare_country_locale($fields, $country);
			}
		}
		return $locale;
	}
	
	public function woo_prepare_country_locale($fields, $country=false) {
		if(is_array($fields)){
			$override_ph = apply_filters('thwcfe_address_field_override_placeholder', true, $country);
			$override_label = apply_filters('thwcfe_address_field_override_label', true, $country);
			$override_required = apply_filters('thwcfe_address_field_override_required', false, $country);
			$override_priority = apply_filters('thwcfe_address_field_override_priority', true, $country);
				
			foreach($fields as $key => $props){
				if($override_ph && isset($props['placeholder'])){
					unset($fields[$key]['placeholder']);
				}
				if($override_label && isset($props['label'])){
					unset($fields[$key]['label']);
				}
				if($override_required && isset($props['required'])){
					unset($fields[$key]['required']);
				}
				
				if($override_priority && isset($props['priority'])){
					unset($fields[$key]['priority']);
				}
			}
		}
		return $fields;
	}
	/*public function woo_get_country_locale($locale){
		if(is_array($locale)){
			$address_fields = array();
			$sname = 'billing';
			$section = $this->get_checkout_section($sname);
			if($this->is_valid_section($section)){
				$address_fields = $this->get_fieldset($section);
			}
			
			foreach($locale as $key => $value){
				if(is_array($value)){
					foreach($value as $fname => $field){
						$cfield = isset($address_fields[$sname.'_'.$fname]) ? $address_fields[$sname.'_'.$fname] : false;
						
						if(is_array($field) && isset($field['label'])){
							$locale[$key][$fname]['label'] = $this->__wcfe($field['label']);
						}
						
						if(is_array($cfield) && isset($cfield['priority'])){
							$locale[$key][$fname]['priority'] = $cfield['priority'];
						}
					}
				}
			}
		}
		return $locale;
	}*/
	
	/* Hide Additional Fields title if no fields available. */
	public function woo_enable_order_notes_field() {
		global $supress_field_modification;
		if($supress_field_modification){
			return $original;
		}
		
		$section = $this->get_checkout_section('additional');
		if(WCFE_Section_Utils::is_valid_section($section)){
			$fieldset = $this->get_fieldset($section);
			if($fieldset){
				$enabled = 0;
				foreach($fieldset as $field){
					if($field['enabled']){
						$enabled++;
					}
				}
				return $enabled > 0 ? true : false;
			}else{
				return false;
			}
		}
		return true;
	}
   /*********************************************************
	******* DISPLAY DEFAULT SECTIONS & FIELDS - END *********
	*********************************************************/
	
	
   /********************************************************
	******** DISPLAY CUSTOM SECTIONS & FIELDS - START ******
	********************************************************/
	public function get_custom_sections_by_hook($hook_name){
		$section_hook_map = $this->get_section_hook_map();
		
		$sections = false;
		if(is_array($section_hook_map) && isset($section_hook_map[$hook_name])){
			$sections = $section_hook_map[$hook_name];
		}	
						
		return empty($sections) ? false : $sections;
	}
	
	public function output_custom_section($sections, $checkout=false){
		if($sections && is_array($sections)){
			foreach($sections as $sname){
				$section = $this->get_checkout_section($sname);
				
				if(WCFE_Section_Utils::is_valid_section($section)){
					$fields = $this->get_fieldset($section);
					//$fields = $this->prepare_checkout_fields($fields);
					
					if(is_array($fields) && sizeof($fields) > 0){
						$wrap_with_div = $this->get_settings('wrap_custom_sections_with_div');
						
						if($wrap_with_div === 'yes'){
							$css_class = $section->get_property('cssclass');
							$css_class = !empty($css_class) ? str_replace(" ", "", $css_class) : '';
							$css_class = !empty($css_class) ? str_replace(",", " ", $css_class) : '';
							echo '<div class="thwcfe-checkout-section '. $css_class .' '. $section->get_property('name') .'" >';
						}						
						if($section->get_property('show_title')){
							echo WCFE_Section_Utils::get_title_html($section);
						}
						
						//echo '<div class="thwcfe-checkout-section '. $section->get_property('name') .'" >';
						foreach($fields as $name => $field){
							if(!(isset($field['enabled']) && $field['enabled'] == false)) {
								//$value = is_object($checkout) ? $checkout->get_value($name) : false;
								$value = null;
								if($checkout instanceof WC_Checkout){
									$value = $checkout->get_value($name);
								}else if(is_array($checkout) && isset($checkout['post_data'])){
									$value = THWCFE_Utils::get_value_from_query_string($checkout['post_data'], $name);
								}
								
								if(!$value && is_user_logged_in() && isset($field['user_meta']) && $field['user_meta']){
									$current_user = wp_get_current_user();
									if(metadata_exists('user', $current_user->ID, $field['name'])){
										$value = get_user_meta($current_user->ID, $field['name'], true);
									}
									/*$meta_value = get_user_meta($current_user->ID, $field['name'], true);
									if($meta_value){
									    $value = $meta_value;
									}*/
								}
								
								woocommerce_form_field($name, $field, $value);
							}
						}
						//echo '</div>';
						
						if($wrap_with_div === 'yes'){
							echo '</div>';
						}
					}
				}
			}
		}
	}
		
	public function woo_before_checkout_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('before_checkout_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_after_checkout_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('after_checkout_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_checkout_before_customer_details() {
		$sections = $this->get_custom_sections_by_hook('before_customer_details');
		$this->output_custom_section($sections);	
	}
	public function woo_checkout_after_customer_details() {
		$this->output_disabled_field_names_hidden_field();
		
		$sections = $this->get_custom_sections_by_hook('after_customer_details');
		$this->output_custom_section($sections);	
	}
	public function woo_before_checkout_billing_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('before_checkout_billing_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_after_checkout_billing_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('after_checkout_billing_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_before_checkout_shipping_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('before_checkout_shipping_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_after_checkout_shipping_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('after_checkout_shipping_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_before_checkout_registration_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('before_checkout_registration_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_after_checkout_registration_form($checkout) {
		$sections = $this->get_custom_sections_by_hook('after_checkout_registration_form');
		$this->output_custom_section($sections, $checkout);	
	}
	public function woo_before_order_notes($checkout) {
		$sections = $this->get_custom_sections_by_hook('before_order_notes');
		$this->output_custom_section($sections, $checkout);	
	}		
	public function woo_after_order_notes($checkout) {	
		$sections = $this->get_custom_sections_by_hook('after_order_notes');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_review_order_before_cart_contents($checkout) {	
		$sections = $this->get_custom_sections_by_hook('before_cart_contents');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_review_order_after_cart_contents($checkout) {	
		$sections = $this->get_custom_sections_by_hook('after_cart_contents');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_review_order_before_order_total($checkout) {	
		$sections = $this->get_custom_sections_by_hook('before_order_total');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_review_order_after_order_total($checkout) {	
		$sections = $this->get_custom_sections_by_hook('after_order_total');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_checkout_before_terms_and_conditions($checkout) {	
		$sections = $this->get_custom_sections_by_hook('before_terms_and_conditions');
		$this->output_custom_section($sections, $_POST);	
	}	
	public function woo_checkout_after_terms_and_conditions($checkout) {	
		$sections = $this->get_custom_sections_by_hook('after_terms_and_conditions');
		$this->output_custom_section($sections, $_POST);	
	}	
	public function woo_review_order_before_submit($checkout) {	
		$sections = $this->get_custom_sections_by_hook('before_submit');
		$this->output_custom_section($sections, $_POST);	
	}	
	public function woo_review_order_after_submit($checkout) {	
		$sections = $this->get_custom_sections_by_hook('after_submit');
		$this->output_custom_section($sections, $_POST);	
	}	
	public function woo_checkout_before_order_review($checkout) {	
		$sections = $this->get_custom_sections_by_hook('before_order_review');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_checkout_after_order_review($checkout) {	
		$sections = $this->get_custom_sections_by_hook('after_order_review');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_checkout_order_review_0($checkout) {	
		$sections = $this->get_custom_sections_by_hook('order_review_0');
		$this->output_custom_section($sections, $checkout);	
	}	
	public function woo_checkout_order_review_99($checkout) {	
		$sections = $this->get_custom_sections_by_hook('order_review_99');
		$this->output_custom_section($sections, $checkout);	
	}
	
	public function render_sections_added_to_custom_positions(){
		$positions = apply_filters('thwcfe_custom_section_positions', array());
		if(is_array($positions)){
			foreach($positions as $hook_name => $label){
				add_action($hook_name, array($this, 'woo_checkout_custom_hook'));
			}
		}
	}
	public function woo_checkout_custom_hook($hook_name, $checkout=false){
		$sections = $this->get_custom_sections_by_hook($hook_name);
		$this->output_custom_section($sections, $checkout);
	}
   /*********************************************************
	******** DISPLAY CUSTOM SECTIONS & FIELDS - END *********
	*********************************************************/
	
	
   /*******************************************
	******** CHECKOUT PROCESS - START *********
	*******************************************/
	// Prepare Checkout Fields
	public function woo_checkout_process(){
		$disabled_fields = isset( $_POST['thwcfe_disabled_fields'] ) ? wc_clean( $_POST['thwcfe_disabled_fields'] ) : '';
		$dis_fields = $disabled_fields ? explode(",", $disabled_fields) : false;
		
		$dis_sections = array();
		$dis_hooks = array();
		
		$ship_to_different_address = isset($_POST['ship_to_different_address']) ? $_POST['ship_to_different_address'] : false;
		
		if(($ship_to_different_address == false || ! WC()->cart->needs_shipping_address())){
			$dis_hooks = array_merge($dis_hooks, array('before_checkout_shipping_form','after_checkout_shipping_form'));
		}		
		if(is_user_logged_in()){
			$dis_hooks = array_merge($dis_hooks, array('before_checkout_registration_form','after_checkout_registration_form'));
		}		
		if(!(isset($_POST['terms-field']) && $_POST['terms-field'])){
			$dis_hooks = array_merge($dis_hooks, array('before_terms_and_conditions','after_terms_and_conditions'));
		}
		
		if(!empty($dis_hooks)){
			foreach($dis_hooks as $hname){
				$hooked_sections = $this->get_custom_sections_by_hook($hname);
				if(is_array($hooked_sections)){
					foreach($hooked_sections as $sname){
						if(!in_array($sname, WCFE_Section_Utils::$DEFAULT_SECTIONS)){
							$dis_sections[] = $sname;
						}
					}
				}
			}
		}
			
		if( (is_array($dis_fields) && !empty($dis_fields)) || (is_array($dis_sections) && !empty($dis_sections)) ){
			$checkout_fields = WC()->checkout->checkout_fields;
			$modified = false;
			
			if(is_array($checkout_fields)){
				foreach($checkout_fields as $fieldset_key => $fieldset) {
					if(in_array($fieldset_key, $dis_sections)){
						unset($checkout_fields[$fieldset_key]);
						$modified = true;
						continue;
					}
				
					foreach($dis_fields as $fname){
						if(isset($fieldset[$fname])){
							unset($checkout_fields[$fieldset_key][$fname]);
							$modified = true;
						}
					}
				}
			}
			
			if($modified){
				WC()->checkout->checkout_fields = $checkout_fields;
			}
		}
	}
	
	// Validate Checkout Fields
	public function woo_checkout_fields_validation($posted, $errors){
		$checkout_fields = WC()->checkout->checkout_fields;
		
		foreach($checkout_fields as $fieldset_key => $fieldset){
			$ship_to_different_address = isset($posted['ship_to_different_address']) ? $posted['ship_to_different_address'] : false;
			
			if($fieldset_key == 'shipping' && ($ship_to_different_address == false || ! WC()->cart->needs_shipping_address())){
				continue;
			}
				
			foreach($fieldset as $key => $field) {
				//Fix for checkbox field required validation issue				
				/*if(isset($field['custom']) && $field['custom'] && isset($field['type']) && $field['type'] === 'checkbox'){	
					if(isset($field['required']) && $field['required'] && ( !isset($posted[$key]) || !$posted[$key]) ){
						wc_add_notice( apply_filters( 'woocommerce_checkout_required_field_notice', sprintf( _x( '%s is a required field.', 'FIELDNAME is a required field.', 'woocommerce' ), '<strong>' . $field['label'] . '</strong>' ), $field['label'] ), 'error' );
					}
				}*/
						
				if(isset($posted[$key]) && !$this->is_blank($posted[$key])){
					$value = $posted[$key];
					$validate = isset($field['validate']) ? $field['validate'] : '';
					
					if(is_array($validate) && !empty($validate)){
						foreach($validate as $rule){
							switch($rule) {
								case 'number' :
									if(!is_numeric($value)){
										$err_msg = '<strong>'. $this->__wcfe($field['label']) .'</strong> '. $this->__wcfe( 'is not a valid number.' );							
										$this->wcfe_add_error($err_msg, $errors);
									}
									break;
								default:
									$custom_validators = $this->get_settings('custom_validators');
									$validator = is_array($custom_validators) && isset($custom_validators[$rule]) ? $custom_validators[$rule] : false;
									if(is_array($validator)){
										$pattern = $validator['pattern'];
										
										if(preg_match($pattern, $value) === 0) {
											$err_msg = sprintf( $this->__wcfe( $validator['message'] ), $this->__wcfe($field['label']) );
											$this->wcfe_add_error($err_msg, $errors);
										}
										break;
									}else{
										$con_validators = $this->get_settings('confirm_validators');
										$cnf_validator = is_array($con_validators) && isset($con_validators[$rule]) ? $con_validators[$rule] : false;
										if(is_array($cnf_validator)){
											$cfield = $cnf_validator['pattern'];
											$cvalue = $posted[$cfield];
											
											if($value && $cvalue && $value != $cvalue) {
												$err_msg = sprintf( $this->__wcfe( $cnf_validator['message'] ), $this->__wcfe($field['label']) );
												$this->wcfe_add_error($err_msg, $errors);
											}
											break;
										}
									}
							}
						}
					}
				}
			}
		}
	}
	
	public function validate_and_filter_fields($price_infos) {
		if($price_infos && is_array($price_infos)){
			$checkout_fields = $this->get_all_checkout_fields_map();
			
			if(!empty($checkout_fields)){
				$f_labels = array();
				
				foreach($price_infos as $name => $price_info){
					$field = isset($checkout_fields[$name]) && is_array($checkout_fields[$name]) ? $checkout_fields[$name] : false;
					if($field){
						$value = isset($price_info['value']) && !empty($price_info['value']) ? trim($price_info['value']) : '';
						$valid = $this->validate_field($name, $value, $field);
						
						$label = $price_info['label'];
						if(in_array($label, $f_labels)){
							$label = $name.'_'.$label;
						}
						$f_labels[] = $label;
						$price_infos[$name]['label'] = $label;
						
						if(!$valid){
							unset($price_infos[$name]);
						}
					}
				}
			}
		}
		return $price_infos;
	}
	
	// Validate Checkout Fields
	public function validate_field($name, $value, $field){
		$valid = true;
		if($value && !$this->is_blank($value)){
			$validation = isset($field['validate']) ? $field['validate'] : '';
			
			if(is_array($validation) && !empty($validation)){
				foreach($validation as $rule){
					switch($rule) {
						case 'number' :
							if(!is_numeric($value)){
								$valid = false;
							}
							break;
						default:
							$custom_validators = $this->get_settings('custom_validators');
							$validator = is_array($custom_validators) && isset($custom_validators[$rule]) ? $custom_validators[$rule] : false;
							if(is_array($validator)){
								$pattern = $validator['pattern'];
								
								if(preg_match($pattern, $value) === 0) {
									$valid = false;
								}
								break;
							}
					}
				}
			}
		}
		return $valid;
	}
	
	// Save User Meta
	public function woo_checkout_update_user_meta($customer_id, $posted){
		$checkout_fields = WC()->checkout->checkout_fields;
		
		foreach($checkout_fields as $fieldset_key => $fieldset){
			if($fieldset_key === 'shipping' && !WC()->cart->needs_shipping()){
				continue;
			}
			
			foreach($fieldset as $key => $field) {
				if(isset($field['custom']) && $field['custom'] && isset($posted[$key])){	
					if(isset($field['user_meta']) && $field['user_meta']){
						$value  = $posted[$key];
						$value  = is_array($value) ? implode(",", $value) : $value;
						$fvalue = $field['default'];
						
						if($field['type'] === 'checkbox' && !empty($field['on_value'])){
							$value = $value == 1 ? $field['on_value'] : ''; 
						}
						
						$value = apply_filters( 'thwcfe_woocommerce_checkout_user_meta_posted_value_'.$key, $value, $customer_id, $posted );
						update_user_meta($customer_id, $key, $value );
					}
				}
			}
		}
	}
	
	// Save Order Meta
	public function woo_checkout_update_order_meta($order_id, $posted){
		$checkout_fields = WC()->checkout->checkout_fields;
		$ship_to_different_address = isset($posted['ship_to_different_address']) ? $posted['ship_to_different_address'] : false;
		
		if(!$ship_to_different_address || !WC()->cart->needs_shipping_address()){
			update_post_meta($order_id, 'thwcfe_ship_to_billing', 1);
		}else{
			update_post_meta($order_id, 'thwcfe_ship_to_billing', 0);
		}
		
		$disabled_fields = isset( $_POST['thwcfe_disabled_fields'] ) ? wc_clean( $_POST['thwcfe_disabled_fields'] ) : '';
		if($disabled_fields){
			$dis_fields = $disabled_fields ? explode(",", $disabled_fields) : false;
			if(is_array($dis_fields) && !empty($dis_fields)){
				$dis_fields = array_unique($dis_fields);
				$dis_fields = implode(",", $dis_fields);
				update_post_meta($order_id, '_thwcfe_disabled_fields', $dis_fields);
			}
		}
		
		foreach($checkout_fields as $fieldset_key => $fieldset){
			if($fieldset_key === 'shipping' && (!$ship_to_different_address || !WC()->cart->needs_shipping_address())){
				continue;
			}
			
			foreach($fieldset as $key => $field) {
				if(isset($field['custom']) && $field['custom'] && isset($posted[$key]) && !empty($posted[$key])){	
					if(isset($field['order_meta']) && $field['order_meta']){
						$value  = $posted[$key];
						$value  = is_array($value) ? implode(",", $value) : $value;
						$fvalue = $field['default'];
						
						if($field['type'] === 'checkbox' && !empty($field['on_value'])){
							$value = $value == 1 ? $field['on_value'] : ''; 
							/*$values = explode("|", $fvalue);
							if(is_array($values)){
								$true_val = isset($values[0]) ? $values[0] : '';
								$false_val = isset($values[1]) ? $values[1] : '';
								$value = $value == 1 ? $true_val : $false_val; 
							}*/
						}
						
						$value = apply_filters( 'thwcfe_woocommerce_checkout_order_meta_posted_value_'.$key, $value, $order_id, $posted );
						update_post_meta($order_id, $key, $value);
					}
				}
			}
		}
	}
   /*******************************************
	******** CHECKOUT PROCESS - END ***********
	*******************************************/
	
	
   /*******************************************************
	******** DISPLAY CUSTOM FIELDS VALUES - START *********
	*******************************************************/
	
	/*
	 * Display custom fields in order details page for customers.
	 * - Thank You page, after customet details.
	 * - My Account order details page, after customer details.
	 */
	public function display_custom_fields_in_order_details_page_customer($order){
		$fieldset = $this->get_all_checkout_fields();
		$fieldset = $this->exclude_address_fields($fieldset);
		
		if(is_array($fieldset) && !empty($fieldset)){
			$fields_html = '';
			$is_nl2br = apply_filters('thwcfe_nl2br_custom_field_value', true);
			
			$order_id = false;
			if($this->woo_version_check()){
				$order_id = $order->get_id();
			}else{
				$order_id = $order->id;
			}
			$dis_fields = WCFE_Checkout_Fields_Utils::get_disabled_fields($order_id);
			
			foreach($fieldset as $key => $field) {
				if(WCFE_Field_Utils::is_valid_field($field) && WCFE_Field_Utils::is_custom_field($field) && 
						WCFE_Field_Utils::is_enabled($field) && $field->get_property('show_in_thank_you_page')){	
					
					$type = $field->get_property('type');
					
					if($type === 'label' || $type === 'heading'){
						if(!in_array($key, $dis_fields)){
							$label = $field->get_property('title') ? $field->get_property('title') : false;
							$subtitle = $field->get_property('subtitle') ? $field->get_property('subtitle') : false;
							if($label || $subtitle){
								if(apply_filters('thwcfe_esc_attr_custom_field_label_thankyou_page', false)){
									$label = $label ? $this->esc_attr__wcfe($label) : '';
									$subtitle = $subtitle ? $this->esc_attr__wcfe($subtitle) : '';
								}else{
									$label = $label ? $this->__wcfe($label) : '';
									$subtitle = $subtitle ? $this->__wcfe($subtitle) : '';
								}
								
								if($subtitle){
									$label .= '<br/><span style="font-size:80%">'.$subtitle.'</span>';
								}
								
								if(is_account_page()){
									$fields_html .= '<tr><th colspan="2" class="thwcfe-html-'.$type.'">'. $label .'</th></tr>';
								}else{
									$fields_html .= '<tr><th colspan="2" class="thwcfe-html-'.$type.'">'. $label .'</th></tr>';
								}
							}
						}
					}else{
						$value = get_post_meta( $order_id, $key, true );
						if(!empty($value)){
							$value = $this->get_option_text_from_value($field, $value);
							$value = is_array($value) ? implode(", ", $value) : $value;
						
							if(($type === 'multiselect' || $type === 'checkboxgroup') && apply_filters('thwcfe_align_field_value_in_separate_lines', false)){
								$value = str_replace(",", ",<br/>", $value);
							}
							
							if($is_nl2br && $type === 'textarea'){
								$value = nl2br($value);
							}
							
							$label = $field->get_property('title') ? $field->get_property('title') : $key;
							$label = apply_filters('thwcfe_esc_attr_custom_field_label_thankyou_page', false) ? $this->esc_attr__wcfe($label) : $this->__wcfe($label);
							
							if(apply_filters( 'thwcfe_view_order_customer_details_table_view', true )){
								$fields_html .= '<tr><th>'. $label .':</th><td>'. wptexturize($value) .'</td></tr>';
							}else{
								$fields_html .= '<br/><dt>'. $label .':</dt><dd>'. wptexturize($value) .'</dd>';
							}									
						}
					}
				}
			}
			
			if($fields_html){
				do_action( 'thwcfe_order_details_before_custom_fields_table', $order ); 
				?>
				<table class="woocommerce-table woocommerce-table--custom-fields shop_table custom-fields">
					<?php
						do_action( 'thwcfe_order_details_before_custom_fields', $order );
						echo $fields_html;
						do_action( 'thwcfe_order_details_after_custom_fields', $order ); 
					?>
				</table>
				<?php
				do_action( 'thwcfe_order_details_after_custom_fields_table', $order ); 
			}
		}
	}
			
	/*public function woo_localisation_address_formats($formats){
		$address_formats_str = $this->get_settings('address_formats');
		
		$custom_formats = array();
		if(!empty($address_formats_str)){
			$address_formats_arr = explode("|", $address_formats_str);
			
			if(is_array($address_formats_arr) && !empty($address_formats_arr)){
				foreach($address_formats_arr as $address_format) {
					if(!empty($address_format)){
						$format_arr = explode("=>", $address_format);
						if(is_array($format_arr) && count($format_arr) == 2){
							$frmt = str_replace('\n', "\n", $format_arr[1]);
							$custom_formats[$format_arr[0]] = $frmt;
						}
					}
				}
			}
		}
		//$custom_formats['IN'] = "{name}\n{company}\n{address_1}\n{address_2}\n{city}, {state} {postcode}\n{country}\n{billing_add_1}\n{shipping_add1}";
		
		if(is_array($formats) && $custom_formats && is_array($custom_formats)){
			$formats = array_merge($formats, $custom_formats);
		}

		return $formats;
	}
	
	public function woo_order_formatted_billing_address($address, $wc_order){
		$billing_keys  = $this->get_settings('custom_billing_address_keys');
		
		if($billing_keys && is_array($billing_keys)){
			foreach($billing_keys as $key) {
				if($this->startsWith($key, 'billing_')){
					$address[$key] = $wc_order->{$key};
				}else{
					$value = get_post_meta( $wc_order->id, $key, true );
					$value = is_array($value) ? implode(",", $value) : $value;
					$address[$key] = $value;
				}
			}
		}
	
		return $address;
	}
	
	public function woo_order_formatted_shipping_address($address, $wc_order){
		$shipping_keys = $this->get_settings('custom_shipping_address_keys');
		
		if($shipping_keys && is_array($shipping_keys)){
			foreach($shipping_keys as $key) {
				if($this->startsWith($key, 'shipping_')){
					$address[$key] = $wc_order->{$key};
				}else{
					$value = get_post_meta( $wc_order->id, $key, true );
					$value = is_array($value) ? implode(",", $value) : $value;
					$address[$key] = $value;
				}
			}
		}
	
		return $address;
	}
	
	public function woo_formatted_address_replacements( $array, $args ) { 
		$billing_keys  = $this->get_settings('custom_billing_address_keys');
		$shipping_keys = $this->get_settings('custom_shipping_address_keys');
		
		$replacement_keys = $billing_keys && is_array($billing_keys) ? $billing_keys : array();
		$replacement_keys = $shipping_keys && is_array($shipping_keys) ? array_merge($replacement_keys, $shipping_keys) : $replacement_keys;
		
		if($replacement_keys && is_array($replacement_keys)){
			foreach($replacement_keys as $key) {
				$array['{'.$key.'}'] = isset($args[$key]) ? $args[$key] : '';
			}
		}
		
		return $array; 
	}*/
   /*******************************************************
	******** DISPLAY CUSTOM FIELDS VALUES - END ***********
	*******************************************************/
	

	public function save_extra_cost_in_session($price_info) {
		if(!isset($_SESSION)|| apply_filters('thwcfe_force_start_session', false)){
			session_start();
		}
		$this->clear_extra_cost_info_from_session();
		$_SESSION['thwcfe-extra-cost-info'] = $price_info;
	}
	
	public function get_extra_cost_from_session() {
		if(!isset($_SESSION)){
			session_start();
		}
    	$extra_cost = isset($_SESSION['thwcfe-extra-cost-info']) ? $_SESSION['thwcfe-extra-cost-info'] : false;
		return is_array($extra_cost) ? $extra_cost : array();
	}
	
	public function clear_extra_cost_info_from_session() {
		unset($_SESSION['thwcfe-extra-cost-info']);
	}
	
	public function thwcfe_calculate_extra_cost() {
		$price_info_json = isset($_POST['price_info']) ? stripslashes($_POST['price_info']) : '';
		
		if($price_info_json) {
			$price_info = json_decode($price_info_json, true);
			$price_info = $this->validate_and_filter_fields($price_info);
			$this->save_extra_cost_in_session($price_info);
		}else{
			$this->clear_extra_cost_info_from_session();
		}
	}
	
	public function calculate_extra_cost($price_info){
		$fprice = 0;
		$price_type = isset($price_info['price_type']) ? $price_info['price_type'] : '';
		$price 		= isset($price_info['price']) ? $price_info['price'] : 0;
		$multiple   = isset($price_info['multiple']) ? $price_info['multiple'] : 0;
		$name 		= isset($price_info['name']) && !empty($price_info['name']) ? $price_info['name'] : false;
		$value 		= isset($price_info['value']) ? $price_info['value'] : false;
		
		if($name){
			$price = apply_filters('thwcfe_checkout_field_extra_price_'.$name, $price, $value);
		}
		
		global $woocommerce;
		$cart_total = $woocommerce->cart->cart_contents_total; //$woocommerce->cart->get_cart_total();
		if($price_type === 'percentage_subtotal'){
			$cart_total = $woocommerce->cart->subtotal;
		}else if($price_type === 'percentage_subtotal_ex_tax'){
			$cart_total = $woocommerce->cart->subtotal_ex_tax;
		}else if($price_type === 'percentage_total'){
			//$cart_total = $woocommerce->cart->subtotal_ex_tax;
		}else if($price_type === 'percentage_total_ex_tax'){
			//$cart_total = $woocommerce->cart->subtotal_ex_tax;
		}
		
		if($multiple == 1){
			$price_arr = explode(",", $price);
			$price_type_arr = explode(",", $price_type);
			
			foreach($price_arr as $index => $oprice){
				$oprice_type = isset($price_type_arr[$index]) ? $price_type_arr[$index] : 'normal';
				
				if($oprice_type === 'percentage' || $oprice_type === 'percentage_subtotal' || $oprice_type === 'percentage_subtotal_ex_tax'){
					if(is_numeric($oprice) && is_numeric($cart_total)){
						$fprice = $fprice + ($oprice/100)*$cart_total;
					}
				}else{
					if(is_numeric($oprice)){
						$fprice = $fprice + $oprice;
					}
				}	
			}
		}else{
			if($price_type === 'percentage' || $price_type === 'percentage_subtotal' || $price_type === 'percentage_subtotal_ex_tax'){
				if(is_numeric($price) && is_numeric($cart_total)){
					$fprice = ($price/100)*$cart_total;
				}
			}else if($price_type === 'dynamic'){
				$price_unit = isset($price_info['price_unit']) ? $price_info['price_unit'] : false;
				
				$qty   = isset($price_info['qty_field']) ? $price_info['qty_field'] : false;
				$qty   = apply_filters('thwcfe_dynamic_price_quantity', $qty, $name);
				$value = !empty($qty) && is_numeric($qty) ? $qty : $value;
				
				if(is_numeric($price) && is_numeric($value) && is_numeric($price_unit) && $price_unit > 0){
					$fprice = $price*($value/$price_unit);
				}
			}else if($price_type === 'custom'){
				if(is_numeric($value)){
					$fprice = $value;
				}
			}else{
				if(is_numeric($price)){
					$fprice = $price;
				}
			}
		}
		
		if($name){
			$fprice = apply_filters('thwcfe_checkout_field_extra_cost_'.$name, $fprice, $value);
		}
		
		return $fprice;
	}
	
	public function woo_cart_calculate_fees(){
		if(is_checkout()){
			global $woocommerce;
			$extra_cost = $this->get_extra_cost_from_session();
			
			foreach($extra_cost as $name => $price_info){
				$taxable = isset($price_info['taxable']) && $price_info['taxable'] === 'yes' ? true : false ;
				$tax_class = isset($price_info['tax_class']) && !empty($price_info['tax_class']) ? trim($price_info['taxable']) : '';
				
				$fee = $this->calculate_extra_cost($price_info);
				if($fee != 0){
					$woocommerce->cart->add_fee($price_info['label'], $fee, $taxable, $tax_class);
				}
			}
		}
	}
	
	public function woo_cart_totals_fee_html($cart_totals_fee_html, $fee){
		$cart_fee_names = $this->get_cart_fee_names();
		$show_tax_label = apply_filters('thwcfe_show_tax_label_in_cart_totals_fee_html', true);
		
		if($show_tax_label && $cart_fee_names && in_array($fee->name, $cart_fee_names)){
			if($fee && is_numeric($fee->total) && $fee->total != 0){
				if(wc_prices_include_tax()){
					if(!$this->display_prices_including_tax()){
						$cart_totals_fee_html .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
					}
				}else{
					if($this->display_prices_including_tax()){
						$cart_totals_fee_html .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
					}
				}
			}
		}
		return $cart_totals_fee_html;
	}
	
	public function display_prices_including_tax() {
		if($this->woo_version_check('3.3.0')){
			return WC()->cart->display_prices_including_tax();
		}
		return 'incl' === WC()->cart->tax_display_cart ? true : false;
	}
   	
	public function get_cart_fee_names(){
		$names = array();
		$extra_cost = $this->get_extra_cost_from_session();
		if(is_array($extra_cost)){
			foreach($extra_cost as $name => $price_info){
				if(isset($price_info['label'])){
					$names[] = $price_info['label'];
				}
			}
		}
		return !empty($names) ? $names : false;
	}
	
   /****************************************
	******** CUSTOM FIELD TYPES - START ****
	****************************************/	
	public function output_disabled_field_names_hidden_field(){
		echo '<input type="hidden" id="thwcfe_disabled_fields" name="thwcfe_disabled_fields" value=""/>';
	}
	
	public function prepare_price_data_string($args){
		$price_info = '';
		if($this->is_price_field($args)){
			$label = !empty($args['title']) ? $this->__wcfe($args['title']) : $args['name'];
			$taxable = isset($args['taxable']) ? $args['taxable'] : 'no';
			$tax_class = isset($args['tax_class']) ? $args['tax_class'] : '';
			
			$price_type = isset($args['price_type']) && !empty($args['price_type']) ? $args['price_type'] : 'normal';
			$price 		= isset($args['price']) && is_numeric($args['price']) ? $args['price'] : 0; 
			$price_unit = isset($args['price_unit']) && !empty($args['price_unit']) ? $args['price_unit'] : 0;
			
			$price_info  = 'data-price="'.$price.'" data-price-type="'.$price_type.'" data-price-label="'.esc_attr($label).'" ';
			$price_info .= 'data-price-unit="'.$price_unit.'" data-taxable="'.$taxable.'" data-tax-class="'.$tax_class.'"';
		}
		return $price_info;
	}
	
	public function prepare_price_data_option_field_string($args){
		$price_data = '';
		$label     = isset($args['title']) && !empty($args['title']) ? $this->__wcfe($args['title']) : $args['name'];
		$taxable   = isset($args['taxable']) ? $args['taxable'] : 'no';
		$tax_class = isset($args['tax_class']) ? $args['tax_class'] : '';
		
		$price_data = 'data-price-label="'.esc_attr($label).'" data-taxable="'.$taxable.'" data-tax-class="'.$tax_class.'"';
				
		return $price_data;
	}
	
	public function prepare_price_data_option_string($args){
		$price_info = '';
		if( isset($args['price']) && !empty($args['price']) ){
			$price_info = 'data-price="'.$args['price'].'" data-price-type="'.$args['price_type'].'"';
		}
		return $price_info;
	}
	
	public function woo_form_field_heading($field = '', $key, $args, $value){
		//$field = '<h3 class="form-row '.esc_attr(implode(' ', $args['class'])).'" id="'.esc_attr($key).'_field">'. $this->__wcfe($args['label']) .'</h3>';
		$rules = '';
		$rules_action = '';
		if(isset($args['rules']) && !empty($args['rules'])){
			$rules_action = isset($args['rules_action']) ? $args['rules_action'] : 'show';
			$rules = urldecode($args['rules']);
			$rules = esc_js($rules);
			$args['class'][] = 'thwcfe-conditional-field';
		}
		$data_rules = 'data-rules="'.$rules.'" data-rules-action="'.$rules_action.'"';
		
		$title_html = $this->get_title_html($args);
		$field  = '';
		if(!empty($title_html)){
			$field .= '<div class="form-row '.esc_attr(implode(' ', $args['class'])).'" id="'.esc_attr($key).'_field" data-name="'.esc_attr($key).'" '.$data_rules.' >'. $title_html .'</div>';
		}
		return $field;
		
		//$field = $this->get_title_html($args);
		//return $field;
	}
	
	public function woo_form_field_label($field = '', $key, $args, $value){
		$rules = '';
		$rules_action = '';
		if(isset($args['rules']) && !empty($args['rules'])){
			$rules_action = isset($args['rules_action']) ? $args['rules_action'] : 'show';
			$rules = urldecode($args['rules']);
			$rules = esc_js($rules);
			$args['class'][] = 'thwcfe-conditional-field';
		}
		$data_rules = 'data-rules="'.$rules.'" data-rules-action="'.$rules_action.'"';
		
		$title_html = $this->get_title_html($args);
		$field  = '';
		if(!empty($title_html)){
			$field .= '<div class="form-row '.esc_attr(implode(' ', $args['class'])).'" id="'.esc_attr($key).'_field" data-name="'.esc_attr($key).'" '.$data_rules.' >'. $title_html .'</div>';
		}
		return $field;
	}
	
	public function get_title_html($args){
		$title_html = '';
		if(isset($args['label']) && !empty($args['label'])){
			$title_type  = isset($args['title_type']) && !empty($args['title_type']) ? $args['title_type'] : 'label';
			$title_style = isset($args['title_color']) && !empty($args['title_color']) ? 'style="display:block; color:'.$args['title_color'].';"' : 'style="display:block;"';
			
			$title_html .= '<'. $title_type .' class="'. implode(' ', $args['label_class']) .'" '. $title_style .'>'. $this->__wcfe($args['label']) .'</'. $title_type .'>';
		}
		
		$subtitle_html = '';
		if(isset($args['subtitle']) && !empty($args['subtitle'])){
			$subtitle_type  = isset($args['subtitle_type']) && !empty($args['subtitle_type']) ? $args['subtitle_type'] : 'span';
			$subtitle_style = isset($args['subtitle_color']) && !empty($args['subtitle_color']) ? 'style="color:'. $args['subtitle_color'] .';"' : '';
			$subtitle_class = isset($args['subtitle_class']) && is_array($args['subtitle_class']) ? implode(' ', $args['subtitle_class']) : $args['subtitle_class'];
			
			$subtitle_html .= '<'. $subtitle_type .' class="'. $subtitle_class .'" '. $subtitle_style .'>';
			$subtitle_html .= $this->__wcfe($args['subtitle']) .'</'. $subtitle_type .'>';
		}
		
		$html = $title_html;
		if(!empty($subtitle_html)){
			$html .= $subtitle_html;
		}
	
		return $html;
	}
	
	/**
     * Outputs a checkout/address form field.
     *
     * @subpackage  Forms
     * @param string $key
     * @param mixed $args
     * @param string $value (default: null)
     * @todo This function needs to be broken up in smaller pieces
     */
    public function woo_form_field($ofield = '', $key, $args, $value = null ) {
        $defaults = array(
            'type'              => 'text',
            'label'             => '',
            'description'       => '',
            'placeholder'       => '',
            'maxlength'         => false,
            'required'          => false,
            'id'                => $key,
            'class'             => array(),
            'label_class'       => array(),
            'input_class'       => array(),
            'return'            => false,
            'options'           => array(),
            'custom_attributes' => array(),
            'validate'          => array(),
            'default'           => '',
			'autofocus'         => '',
			'priority'          => '',
        );
		
		$value = apply_filters( 'thwcfe_woocommerce_form_field_value_'.$key, $value );

        $args = wp_parse_args( $args, $defaults );
		$args['name'] = $key;
        $args = apply_filters( 'woocommerce_form_field_args', $args, $key, $value );
		
		if(isset($args['label'])){
			$args['label'] = $this->__wcfe($args['label']);
			$args['label'] = stripslashes($args['label']);
		}
		if(isset($args['description'])){
			$args['description'] = $this->__wcfe($args['description']);
		}
		if(isset($args['placeholder'])){
			$args['placeholder'] = $this->__wcfe($args['placeholder']);
		}
		
		$args['input_class'][] = 'thwcfe-input-field';
		$validations = array();
		
        if($args['required'] ) {
            $args['class'][] = 'validate-required';
			$validations[] = 'validate-required';
			$required = ' <abbr class="required" title="' . esc_attr__( 'required', 'woocommerce' ) . '">*</abbr>';
        } else {
            $required = '';
        }

        if(is_string($args['label_class'])) {
            $args['label_class'] = array( $args['label_class'] );
        }

        if(is_null($value)){
            $value = $args['default'];
        }

        // Custom attribute handling
        $custom_attributes = array();
		$args['custom_attributes'] = array_filter( (array) $args['custom_attributes'] );

		if ( $args['maxlength'] && is_numeric($args['maxlength']) ) {
			if(isset($args['type']) && $args['type'] === 'multiselect'){
				$args['custom_attributes']['data-maxselections'] = absint( $args['maxlength'] );
			}else{
				$args['custom_attributes']['maxlength'] = absint( $args['maxlength'] );
			}
		}

		if ( ! empty( $args['autocomplete'] ) ) {
			$args['custom_attributes']['autocomplete'] = $args['autocomplete'];
		}

		if ( true === $args['autofocus'] ) {
			$args['custom_attributes']['autofocus'] = 'autofocus';
		}
		
		if ( (isset($args['readonly']) && true === $args['readonly']) || true === apply_filters('thwcfe_is_readonly_field_'.$key, false)) {
			$args['custom_attributes']['readonly'] = 'readonly';
		}

        if ( ! empty( $args['custom_attributes'] ) && is_array( $args['custom_attributes'] ) ) {
            foreach ( $args['custom_attributes'] as $attribute => $attribute_value ) {
                $custom_attributes[] = esc_attr( $attribute ) . '="' . esc_attr( $attribute_value ) . '"';
            }
        }

        if ( ! empty( $args['validate'] ) ) {
            foreach ( $args['validate'] as $validate ) {
                $args['class'][] = 'validate-' . $validate;
            }
        }
		
		$rules = '';
		$rules_action = '';
		if(isset($args['rules']) && !empty($args['rules'])){
			$rules_action = isset($args['rules_action']) ? $args['rules_action'] : 'show';
			$rules = urldecode($args['rules']);
			$rules = esc_js($rules);
			$args['class'][] = 'thwcfe-conditional-field';
		}

        $field = '';
        $label_id = $args['id'];
		$validations_str = implode(" ", $validations);
		$priority        = is_numeric($args['priority']) ? $args['priority'] : '';
        $field_container = '<p class="form-row %1$s" id="%2$s" data-sort="' . esc_attr( $priority ) . '" data-rules="'.$rules.'" data-rules-action="'.$rules_action.'" data-validations="'.$validations_str.'" data-priority="'. esc_attr( $priority ) .'">%3$s</p>';

        switch ( $args['type'] ) {
            case 'country' :
                $field .= $this->woo_form_field_fragment_country( $key, $args, $value, $custom_attributes );
                break;
				
            case 'state' :
				$field .= $this->woo_form_field_fragment_state( $key, $args, $value, $custom_attributes );
                break;
				
            case 'textarea' :
				$field .= $this->woo_form_field_fragment_textarea( $key, $args, $value, $custom_attributes );
                break;
				
            case 'checkbox' :
                $field = $this->woo_form_field_fragment_checkbox( $key, $args, $value, $custom_attributes, $required );
                break;
			
			case 'checkboxgroup' :
                $field = $this->woo_form_field_fragment_checkboxgroup( $key, $args, $value, $custom_attributes, $required );
                break;	
				
            case 'password' :
            case 'text' :
            case 'email' :
            case 'tel' :
            case 'number' :
                $field .= $this->woo_form_field_fragment_general( $key, $args, $value, $custom_attributes );
                break;
				
            case 'select' :
				$field .= $this->woo_form_field_fragment_select( $key, $args, $value, $custom_attributes );
                break;
				
			case 'multiselect' :
				$field .= $this->woo_form_field_fragment_multiselect( $key, $args, $value, $custom_attributes );
                break;	
				
            case 'radio' :
				$label_id = current( array_keys( $args['options'] ) );
				$field .= $this->woo_form_field_fragment_radio( $key, $args, $value);
                break;
				
			case 'datepicker' :
				$field .= $this->woo_form_field_fragment_datepicker( $key, $args, $value, $custom_attributes );
                break;
				
			case 'timepicker' :
				$field .= $this->woo_form_field_fragment_timepicker( $key, $args, $value, $custom_attributes );
                break;
				
			case 'file' :
				$field .= $this->woo_form_field_fragment_file( $key, $args, $value, $custom_attributes );
                break;
        }

        if ( ! empty( $field ) ) {
            $field_html = '';

            if ( $args['label'] && 'checkbox' != $args['type'] ) {
                $field_html .= '<label for="'. esc_attr( $label_id ) .'" class="'. esc_attr(implode(' ', $args['label_class'])) .'">'. $args['label'] . $required .'</label>';
            }

            $field_html .= $field;

            if ( $args['description'] ) {
                $field_html .= '<span class="description">' . $args['description'] . '</span>';
            }
			
			if ( in_array("thwcfe-char-count", $args['input_class']) || in_array("thwcfe-char-left", $args['input_class']) ) {
                $field_html .= '<span id="'.$args['id'].'-char-count" class="thpl-char-count" style="float: right;"></span><div class="clear"></div>';
            }

            $container_class = esc_attr( implode( ' ', $args['class'] ) );
            $container_id = esc_attr( $args['id'] ) . '_field';

            $field = sprintf( $field_container, $container_class, $container_id, $field_html );
			
			return $field;
        }

		return $ofield;
    }
	
	public function woo_form_field_fragment_country( $key, $args, $value, $custom_attributes ) { 
		$field = '';
		$countries = 'shipping_country' === $key ? WC()->countries->get_shipping_countries() : WC()->countries->get_allowed_countries();
		
		if ( 1 === sizeof( $countries ) ) {
			$field .= '<strong>' . current( array_values( $countries ) ) . '</strong>';
	
			$field .= '<input type="hidden" name="'. esc_attr( $key ) .'" id="'. esc_attr( $args['id'] ) .'" value="'. current( array_keys($countries ) ) .'" ';
			$field .= implode( ' ', $custom_attributes ) . ' class="country_to_state" />';
	
		} else {
			$field  = '<select name="'.esc_attr($key).'" id="'.esc_attr($args['id']).'" class="country_to_state country_select '.esc_attr(implode(' ', $args['input_class'])).'" ';
			$field .= implode( ' ', $custom_attributes ) . '><option value="">'.esc_html__( 'Select a country&hellip;', 'woocommerce' ) .'</option>';
	
			foreach ( $countries as $ckey => $cvalue ) {
				$field .= '<option value="' . esc_attr( $ckey ) . '" '. selected( $value, $ckey, false ) . '>' . $cvalue . '</option>';
			}
	
			$field .= '</select>';
			$field .= '<noscript><input type="submit" name="woocommerce_checkout_update_totals" value="' . esc_attr__( 'Update country', 'woocommerce' ) . '" /></noscript>';
		}
		return $field;
	}
	
	public function woo_form_field_fragment_state( $key, $args, $value, $custom_attributes ) { 
		$field = '';
		
		/* Get Country */
		$country_key = 'billing_state' === $key ? 'billing_country' : 'shipping_country';
		$current_cc  = WC()->checkout->get_value( $country_key );
		$states      = WC()->countries->get_states( $current_cc );
		
		if ( is_array( $states ) && empty( $states ) ) {
			$field_container = '<p class="form-row %1$s" id="%2$s" style="display: none">%3$s</p>';

			$field .= '<input type="hidden" class="hidden" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" value="" ';
			$field .= implode( ' ', $custom_attributes ) . ' placeholder="' . esc_attr( $args['placeholder'] ) .'" />';

		} elseif ( is_array( $states ) ) {
			$field .= '<select name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" class="state_select ' . esc_attr( implode( ' ', $args['input_class'] ) ) .'" ';
			$field .= implode( ' ', $custom_attributes ) . ' data-placeholder="' . esc_attr( $args['placeholder'] ) . '">';
			$field .= '<option value="">' . esc_html__( 'Select a state&hellip;', 'woocommerce' ) . '</option>';

			foreach ( $states as $ckey => $cvalue ) {
				$field .= '<option value="' . esc_attr( $ckey ) . '" ' . selected( $value, $ckey, false ) . '>' . $cvalue . '</option>';
			}

			$field .= '</select>';
		} else {
			$field .= '<input type="text" class="input-text ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" value="' . esc_attr( $value ) . '" ';
			$field .= 'placeholder="'. esc_attr($args['placeholder']) .'" name="'. esc_attr($key) .'" id="'. esc_attr($args['id']) .'" '. implode(' ', $custom_attributes) .' />';
		}
		return $field;
	}
	
	public function woo_form_field_fragment_textarea( $key, $args, $value, $custom_attributes ) {
		$price_info = $this->prepare_price_data_string($args);
		if($this->is_price_field($args)){
			$args['input_class'][] = 'thwcfe-price-field';
		}
	
		$field  = '<textarea name="' . esc_attr( $key ) . '" class="input-text ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" id="' . esc_attr( $args['id'] ) . '" ';
		$field .= 'placeholder="' . esc_attr( $args['placeholder'] ) . '" '. $args['maxlength'] .' ';
		$field .= ( empty( $args['custom_attributes']['rows'] ) ? ' rows="2"' : '');
		$field .= ( empty( $args['custom_attributes']['cols'] ) ? ' cols="5"' : '');
		$field .= implode( ' ', $custom_attributes ) .' '.$price_info.'>'. esc_textarea( $value ) .'</textarea>';
		
		return $field;
	}
	
	public function woo_form_field_fragment_checkbox( $key, $args, $value, $custom_attributes, $required ) {  
		$price_info = $this->prepare_price_data_string($args);
		if($this->is_price_field($args)){
			$args['input_class'][] = 'thwcfe-price-field';
		}
		
		/*$args['default'] = !empty($args['default']) ? $args['default'] : 1;
		$checked = (isset($args['checked']) && $args['checked']) ? 'checked' : '';*/
		
		$on_value = !empty($args['on_value']) ? $args['on_value'] : 1;
		if(is_user_logged_in() && isset($args['user_meta']) && $args['user_meta']){
			$checked = checked( $value, $on_value, false );
		}else{
			$checked = checked( $value, $on_value, false );
			if(!$checked){
				$checked = (isset($args['checked']) && $args['checked']) ? 'checked="checked"' : '';
			}
		}
		
		$field  = '<label class="checkbox ' . implode( ' ', $args['label_class'] ) . '" ' . implode( ' ', $custom_attributes ) . '>';  
        $field .= '<input type="' . esc_attr( $args['type'] ) .'" class="input-checkbox '. esc_attr(implode(' ', $args['input_class'])) .'" name="' . esc_attr( $key ) . '" '; 
		$field .= 'id="' .esc_attr($args['id']). '" value="'. $on_value .'" '. $checked .' '.$price_info.' /> '. $args['label'] . $required . '</label>';
		
		return $field;
	}
	
	public function woo_form_field_fragment_checkboxgroup( $key, $args, $value, $custom_attributes, $required ) {  
		$field = '';
		if(!empty($args['options_object'])) {
			$options_list = apply_filters( 'thwcfe_input_field_options_'.$key, $args['options_object'] );
			$options_per_line = apply_filters('thwcfe_checkboxgroup_options_per_line', 1, $key);
			
			//$value = empty($value) ? $args['default'] : $value;
			$value = is_array($value) ? $value : explode(',', $value);
			$value = !empty($value) ? array_map('trim', $value) : $value;
			
			$index = 1;		
			foreach($options_list as $option) {
				$option_key = $option['key'];
				$option_text = $this->__wcfe($option['text']);
				
				$price_info = $this->prepare_price_data_option_string($option);
				$price_data = '';
				if( isset($option['price']) && !empty($option['price']) ){
					$args['input_class'][] = 'thwcfe-price-field';
					
					//$label = !empty($args['title']) ? $this->__wcfe($args['title']) : $args['name'];
					//$price_data = 'data-price-label="'.esc_attr($label).'"';
					$price_data = $this->prepare_price_data_option_field_string($args);
				}
				
				$checked = in_array($option_key, $value) ? 'checked="checked"' : '';
				
				$field .= '<label for="'. esc_attr($args['id']) .'_'. esc_attr($option_key) .'" style="display:inline; margin-right: 10px;" '; 
				$field .= 'class="checkbox ' . implode( ' ', $args['label_class'] ) .'" '. implode( ' ', $custom_attributes ) .'>';  
        		$field .= '<input type="checkbox" data-multiple="1" class="input-checkbox '. esc_attr(implode(' ', $args['input_class'])) .'" name="'. esc_attr($key) .'[]" '; 
				$field .= $price_info.' '.$price_data.' ';
				$field .= 'id="' .esc_attr($args['id']) .'_'. esc_attr($option_key). '" value="'. $option_key .'" '. $checked .' /> '. $option_text .'</label>';
				
				if(is_array($args['class']) && in_array("valign", $args['class'])){
					$breakline = (is_numeric($options_per_line) && $options_per_line > 0 && fmod($index, $options_per_line) == 0) ? true : false;
					$field .= $breakline ? '<br/>' : '';
				}
				
				$index++;
			}
		}
		return $field;
	}
		
	public function woo_form_field_fragment_general( $key, $args, $value, $custom_attributes ) {
		$price_info = $this->prepare_price_data_string($args);
		if($this->is_price_field($args)){
			$args['input_class'][] = 'thwcfe-price-field';
		}
		
		$field  = '<input type="' . esc_attr( $args['type'] ) . '" class="input-text ' . esc_attr( implode( ' ', $args['input_class'] ) ) .'" name="' . esc_attr( $key ) . '" '; 
		$field .= 'id="' . esc_attr( $args['id'] ) . '" placeholder="' . esc_attr( $args['placeholder'] ) . '" ' . $args['maxlength'] . ' value="' . esc_attr( $value ) . '" ';
		$field .= implode( ' ', $custom_attributes ) . ' '.$price_info.' />';
		
		return $field;
	}
	
	public function woo_form_field_hidden($field = '', $key, $args, $value){
		$price_info = $this->prepare_price_data_string($args);
		
		$css_class = array();
		$css_class[] = 'thwcfe-input-field';
		if($this->is_price_field($args)){
			$css_class[] = 'thwcfe-price-field';
		}
		
		$value = apply_filters( 'thwcfe_woocommerce_form_field_value_'.$key, $value );
		if(is_null($value)){
            $value = $args['default'];
        }
		
		$rules = '';
		$rules_action = '';
		if(isset($args['rules']) && !empty($args['rules'])){
			$rules_action = isset($args['rules_action']) ? $args['rules_action'] : 'show';
			$rules = urldecode($args['rules']);
			$rules = esc_js($rules);
			$css_class[] = 'thwcfe-conditional-field';
		}

		$field  = '<input type="hidden" id="'. esc_attr($key) .'" name="'. esc_attr($key) .'" value="'. esc_attr( $value ) .'" ';
		$field .= 'class="'.esc_attr(implode(' ', $css_class)).'" '.$price_info.' data-rules="'.$rules.'" data-rules-action="'.$rules_action.'" />';
		return $field;
	}
	
	public function woo_form_field_fragment_select( $key, $args, $value, $custom_attributes ) { 
		$options = $field = '';
		
		if(!empty($args['options_object'])){
			//$options_list = apply_filters( 'thwcfe_input_field_options_'.$key, $args['options_object'] ); //DEPRECATED 26-03-2018
			$options_list = apply_filters( 'thwcfe_input_field_options', $args['options_object'], $key );
			$price_field = false;
			
			/*if(isset($args['placeholder']) && !empty( $args['placeholder'])){
				$options .= '<option disabled="">'. esc_attr( $args['placeholder'] ) .'</option>';
			}*/
			
			foreach($options_list as $option){
				$option_key = $option['key'];
				$option_text = $this->__wcfe($option['text']);
				
				$price_info = $this->prepare_price_data_option_string($option);
				if( isset($option['price']) && !empty($option['price']) ){
					$price_field = true;
				}
				
				if('' === $option_key){ // If we have a blank option, select2 needs a placeholder
					if(empty( $args['placeholder'])) {
						$args['placeholder'] = $option_text ? $option_text : __( 'Choose an option', 'woocommerce' );
					}
					$custom_attributes[] = 'data-allow_clear="true"';
				}
				$options .= '<option value="'. esc_attr($option_key) .'" '. selected($value, $option_key, false) .' '.$price_info.' >'. esc_attr( $option_text ) .'</option>';
			}
			
			$price_data = '';
			if($price_field){
				$args['input_class'][] = 'thwcfe-price-field';
				$args['input_class'][] = 'thwcfe-price-option-field';
				
				//$label = !empty($args['title']) ? $this->__wcfe($args['title']) : $args['name'];
				//$price_data = 'data-price-label="'.esc_attr($label).'"';
				$price_data = $this->prepare_price_data_option_field_string($args);
			}
			
			if($this->get_settings('disable_select2_for_select_fields') != 'yes'){
				$args['input_class'][] = 'thwcfe-enhanced-select';
			}

			$field .= '<select name="'.esc_attr($key).'" id="'.esc_attr($args['id']).'" class="select '.esc_attr(implode(' ', $args['input_class'])).'" '; 
			$field .= implode(' ', $custom_attributes) .' data-placeholder="'. esc_attr($args['placeholder']) .'" '.$price_data.'>'. $options .'</select>';
		}
		return $field;
	}
	
	public function woo_form_field_fragment_multiselect( $key, $args, $value, $custom_attributes ) { 
		$options = $field = '';

		if(!empty($args['options_object'])){
			$options_list = apply_filters( 'thwcfe_input_field_options_'.$key, $args['options_object'] );
			
			$price_field = false;
			$value = is_array($value) ? $value : explode(',', $value);
			$value = !empty($value) ? array_map('trim', $value) : $value;
						
			foreach($options_list as $option){
				$option_key = $option['key'];
				$option_text = $this->__wcfe($option['text']);
				
				$selected = in_array($option_key, $value) ? 'selected="selected"' : '';
				
				$price_info = $this->prepare_price_data_option_string($option);
				if( isset($option['price']) && !empty($option['price']) ){
					$price_field = true;
				}
				
				if('' === $option_key){  // If we have a blank option, select2 needs a placeholder
					if(empty( $args['placeholder'])) {
						$args['placeholder'] = $option_text ? $option_text : __( 'Choose an option', 'woocommerce' );
					}
					$custom_attributes[] = 'data-allow_clear="true"';
				}
				$options .= '<option value="'. esc_attr($option_key) .'" '. $selected .' '.$price_info.' >'. esc_attr( $option_text ) .'</option>';
			}
			
			$price_data = '';
			if($price_field){
				$args['input_class'][] = 'thwcfe-price-field';
				$args['input_class'][] = 'thwcfe-price-option-field';
				
				//$label = !empty($args['title']) ? $this->__wcfe($args['title']) : $args['name'];
				//$price_data = 'data-price-label="'.esc_attr($label).'"';
				$price_data = $this->prepare_price_data_option_field_string($args);
			}

			$field .= '<select multiple="multiple" name="'. esc_attr($key) .'[]" id="'. esc_attr($args['id']) .'" '; 
			$field .= 'class="thwcfe-enhanced-multi-select '. esc_attr(implode(' ', $args['input_class'])) .'" ';
			$field .= implode(' ', $custom_attributes) .' data-placeholder="'. esc_attr($args['placeholder']) .'" '.$price_data.'>'. $options .'</select>';
		}
		return $field;
	}
	
	public function woo_form_field_fragment_radio( $key, $args, $value) { 
		$field = '';
		if(!empty($args['options_object'])) {
			$options_list = apply_filters( 'thwcfe_input_field_options_'.$key, $args['options_object'] );
			
			$is_price_field = $this->is_price_option($options_list);
			
			foreach($options_list as $option) {
				$option_key = $option['key'];
				$option_text = $this->__wcfe($option['text']);
				
				$price_info = $this->prepare_price_data_option_string($option);
				$price_data = '';
				//if( isset($option['price']) && !empty($option['price']) ){
				if($is_price_field){
					$args['input_class'][] = 'thwcfe-price-field';
					
					//$label = !empty($args['title']) ? $this->__wcfe($args['title']) : $args['name'];
					//$price_data = 'data-price-label="'.esc_attr($label).'"';
					$price_data = $this->prepare_price_data_option_field_string($args);
				}
				
				$field .= '<input type="radio" class="input-radio '. esc_attr(implode(' ', $args['input_class'])) .'" value="'. esc_attr( $option_key ) .'" '; 
				$field .= $price_info.' '.$price_data.' ';
				$field .= 'name="'. esc_attr($key) .'" id="'. esc_attr($args['id']) .'_'. esc_attr($option_key) .'"'. checked($value, $option_key, false) .' />';
				$field .= '<label for="'. esc_attr($args['id']) .'_'. esc_attr($option_key) .'" '; 
				$field .= 'class="radio '. implode(' ', $args['label_class']) .'" style="display:inline; margin-right: 10px;"> '. $option_text .'</label>';
				
				if(in_array("valign", $args['class'])){
					$field .= '<br/>';
				}
			}
		}
		return $field;
	}
	
	public function woo_form_field_fragment_datepicker( $key, $args, $value, $custom_attributes ) { 
		$price_info = $this->prepare_price_data_string($args);
		if($this->is_price_field($args)){
			$args['input_class'][] = 'thwcfe-price-field';
		}
		
		$dateFormat = isset($args['date_format']) ? $args['date_format'] : $this->get_jquery_date_format(wc_date_format());	
		$defaultDate = isset($args['default_date']) ? $args['default_date'] : '';
		$maxDate = isset($args['max_date']) ? $args['max_date'] : '';
		$minDate = isset($args['min_date']) ? $args['min_date'] : '';
		$yearRange = isset($args['year_range']) ? $args['year_range'] : '-100:+1';
		$numberOfMonths = isset($args['number_months']) ? $args['number_months'] : 1; 
		$disabledDays = isset($args['disabled_days']) ? $args['disabled_days'] : '';
		$disabledDates = isset($args['disabled_dates']) ? $args['disabled_dates'] : '';
		
		$minDate = apply_filters( 'thwcfe_min_date_date_picker_'.$key, $minDate );
		$maxDate = apply_filters( 'thwcfe_max_date_date_picker_'.$key, $maxDate );
		$disabledDays = apply_filters( 'thwcfe_disabled_days_date_picker_'.$key, $disabledDays );
		$disabledDates = apply_filters( 'thwcfe_disabled_dates_date_picker_'.$key, $disabledDates );
		$firstDay = apply_filters( 'thwcfe_date_picker_first_day', 0, $key );
				
		$field  = '<input type="text" class="thwcfe-checkout-date-picker input-text '. esc_attr(implode(' ', $args['input_class'])) .'" name="'. esc_attr($key) .'" ';
		$field .= 'id="'. esc_attr($args['id']) .'" placeholder="'. esc_attr($args['placeholder']) .'" '. $args['maxlength'] .' value="'. esc_attr($value) .'" ';
		$field .= implode(' ', $custom_attributes) .' '.$price_info.' ';
		$field .= 'data-date-format="'. $dateFormat .'" data-default-date="'. $defaultDate .'" data-max-date="'. $maxDate .'" data-min-date="'. $minDate .'" ';
		$field .= 'data-year-range="'. $yearRange .'" data-number-months="'. $numberOfMonths .'" data-first-day="'. $firstDay .'" ';
		$field .= 'data-disabled-days="'. $disabledDays .'" data-disabled-dates="'. $disabledDates .'" />';
		
		return $field;
	}
	
	public function woo_form_field_fragment_timepicker( $key, $args, $value, $custom_attributes ) { 
		$price_info = $this->prepare_price_data_string($args);
		if($this->is_price_field($args)){
			$args['input_class'][] = 'thwcfe-price-field';
		}
		
		$args['min_time']  = isset($args['min_time']) ? $args['min_time'] : '';
		$args['max_time']  = isset($args['max_time']) ? $args['max_time'] : '';
		$args['start_time']  = isset($args['start_time']) ? $args['start_time'] : '';
		$args['time_step'] = isset($args['time_step']) ? $args['time_step'] : '';
		$args['time_format'] = isset($args['time_format']) ? $args['time_format'] : '';
		$args['linked_date'] = isset($args['linked_date']) ? $args['linked_date'] : '';
		
		$args['min_time'] = apply_filters( 'thwcfe_min_time_time_picker_'.$key, $args['min_time'] );
		$args['max_time'] = apply_filters( 'thwcfe_max_time_time_picker_'.$key, $args['max_time'] );
		$args['start_time'] = apply_filters( 'thwcfe_start_time_time_picker_'.$key, $args['start_time'] );
		$args['time_step'] = apply_filters( 'thwcfe_time_step_time_picker_'.$key, $args['time_step'] );
		$args['linked_date'] = apply_filters( 'thwcfe_linked_date_time_picker_'.$key, $args['linked_date'] );
		
		if(!empty($args['linked_date'])){
			$args['input_class'][] = 'thwcfe-linked-date-'.$args['linked_date'];
		}
		
		$field  = '<input type="text" class="thwcfe-checkout-time-picker input-text '. esc_attr(implode(' ', $args['input_class'])) .'" name="'. esc_attr($key) .'" '; 
		$field .= 'id="'. esc_attr($args['id']) .'" placeholder="'. esc_attr($args['placeholder']) .'" '. $args['maxlength'] .' value="'. esc_attr($value) .'" ';
		$field .= implode(' ', $custom_attributes) .' '.$price_info.' data-start-time="'.$args['start_time'].'" data-linked-date="'.$args['linked_date'].'" ';
		$field .= 'data-min-time="'.$args['min_time'].'" data-max-time="'.$args['max_time'].'" data-step="'.$args['time_step'].'" data-format="'.$args['time_format'].'" />';
		
		return $field;
	}
	
	public function woo_form_field_fragment_file( $key, $args, $value, $custom_attributes ) {
		$price_info = $this->prepare_price_data_string($args);
		if($this->is_price_field($args)){
			$args['input_class'][] = 'thwcfe-price-field';
		}
		
		$field  = '<input type="' . esc_attr( $args['type'] ) . '" class="input-text ' . esc_attr( implode( ' ', $args['input_class'] ) ) .'" name="' . esc_attr( $key ) . '" '; 
		$field .= 'id="' . esc_attr( $args['id'] ) . '" placeholder="' . esc_attr( $args['placeholder'] ) . '" ' . $args['maxlength'] . ' value="' . esc_attr( $value ) . '" ';
		$field .= implode( ' ', $custom_attributes ) . ' '.$price_info.' />';
		
		return $field;
	}
   /****************************************
	******** CUSTOM FIELD TYPES - END ******
	****************************************/
	

   /***********************************************************
	******** DISPLAY & SAVE CUSTOM USER META FIELDS - START ***
	***********************************************************/
	public function woo_checkout_get_value($value, $key){
		$user_fields = WCFE_Section_Utils::get_user_fields_full();
		
		if(is_user_logged_in() && is_array( $user_fields ) && array_key_exists( $key, $user_fields )) {
			$current_user = wp_get_current_user();

			if($meta = get_user_meta( $current_user->ID, $key, true )){
				return $meta;
			}
		}
		
		return $value;
	}
	
	public function woo_address_to_edit($address, $load_address = 'billing'){
		$section = $this->get_checkout_section($load_address);
		$fieldset = WCFE_Section_Utils::get_fieldset_all($section);
		
		if($fieldset && is_array($fieldset)){
			foreach($fieldset as $key => $field) {
				if(isset($field['custom']) && $field['custom']){
					if(apply_filters('thwcfe_ignore_custom_fields_in_address_to_edit', false)) {
						unset($address[$key]);
					}else{
						$ftype = isset($field['type']) ? $field['type'] : 'text';
						
						if($ftype === 'label' || $ftype === 'heading'){
							$show_in_my_account_page = isset($field['show_in_my_account_page']) && $field['show_in_my_account_page'] ? 1 : 0;
							if(!$show_in_my_account_page){
								unset($address[$key]);
							}
						}else if(isset($field['user_meta']) && !$field['user_meta']){
							unset($address[$key]);
						}
					}
				}
			}
		}
		
		return $address;
	}
	
	/*public function woo_address_to_edit($address, $load_address){
		$sections = $this->get_checkout_sections();
		if($sections && is_array($sections)){
			foreach($sections as $sname => $section) {
				if($sname === 'billing' || $sname === 'shipping'){
					$fieldset = $this->get_fieldset($section);
					
					if($fieldset && is_array($fieldset)){
						foreach($fieldset as $key => $field) {
							//if(isset($field['custom']) && $field['custom'] && isset($field['user_meta']) && !$field['user_meta']){	
								//unset($address[$key]);
							//}
							if(isset($field['custom']) && $field['custom']){
							    if(apply_filters('thwcfe_ignore_custom_fields_in_address_to_edit', false)) {
								    unset($address[$key]);
							    }else{
							        if(isset($field['user_meta']) && !$field['user_meta']){
							            unset($address[$key]);
							        }
							    }
							}
						}
					}
					
				}
			}
		}
		
		return $address;
	}*/
	
	public function woo_edit_account_form() {
	  	$user_id = get_current_user_id();
	  	$user = get_userdata( $user_id );
	 
	  	if ( !$user )
			return;
			
		$html = '';
			
		$sections = $this->get_checkout_sections();
		foreach($sections as $sname => $section) {
			$fieldset = $this->get_fieldset_all($section);
			
			if($fieldset && $sname != 'billing' && $sname != 'shipping'){
				foreach($fieldset as $key => $field) {
					if(isset($field['custom']) && $field['custom']){
						$ftype = isset($field['type']) ? $field['type'] : 'text';
							
						if(isset($field['user_meta']) && $field['user_meta']){
							$value = get_user_meta( $user_id, $key, true );
							$value = is_array($value) ? implode(",", $value) : $value;
							//$label = $this->get_field_display_name($field);
							
							if($ftype === 'hidden' || $ftype === 'datepicker' || $ftype === 'timepicker' || $ftype === 'checkbox'){
								$field['type'] = 'text';
							}
							
							if(isset($field['rules']) && !empty($field['rules'])){
								$field['required'] = false;
								$field['validate'] = '';
							}
							
							woocommerce_form_field( $key, $field, $value );
							
						}else if(($ftype === 'label' || $ftype === 'heading') && (isset($field['show_in_my_account_page']) && $field['show_in_my_account_page'])){
							woocommerce_form_field( $key, $field, false );
						}
						
						/*$cssclass = 'woocommerce-Input woocommerce-Input--text input-text';
						$required = '<span class="required">*</span>';
						
						$field_html  = '<p class="woocommerce-FormRow woocommerce-FormRow--wide form-row form-row-wide">';
						$field_html .= '<label for="'.$key.'">'. $label . $required .'</label>';
						$field_html .= '<input type="text" class="'. $cssclass .'" name="'. $key .'" id="'. $key .'" value="'. $value .'" />';
						$field_html .= '</p>';
						
						$html .= $field_html;*/
					}
				
					/*if(isset($posted[$key]) && !empty($posted[$key])){
						$value = $posted[$key];
						$validate = isset($field['validate']) ? $field['validate'] : '';
					}*/
				}
			}
		}

	 	/*if(!empty($html)){
	  		<fieldset>
                echo $html;
            </fieldset>
		}*/
	}
	
	public function woo_save_account_details( $user_id ) {
		$sections = $this->get_checkout_sections();
		foreach($sections as $sname => $section) {
			$fieldset = $this->get_fieldset($section, true);
			
			if($fieldset){
				foreach($fieldset as $key => $field) {
					if(isset($field['custom']) && $field['custom'] && isset($field['user_meta']) && $field['user_meta']){	
						if(isset($_POST[ $key ])){
							$value = is_array($_POST[ $key ]) ? implode(',', $_POST[ $key ]) : $_POST[ $key ];
							update_user_meta( $user_id, $key, htmlentities( $value ) );
						}
					}
				}
			}
		}
	}
	
	public function woo_customer_save_address( $user_id, $load_address ) {
		$sections = $this->get_checkout_sections();
		foreach($sections as $sname => $section) {
			if($sname === $load_address){
				$fieldset = $this->get_fieldset($section, true);
				
				if($fieldset){
					foreach($fieldset as $key => $field) {
						if(isset($field['custom']) && $field['custom'] && isset($field['user_meta']) && $field['user_meta']){	
							if(isset($_POST[ $key ])){
								$value = is_array($_POST[ $key ]) ? implode(',', $_POST[ $key ]) : $_POST[ $key ];
								update_user_meta( $user_id, $key, htmlentities( $value ) );
							}
						}
					}
				}
			}
		}
	}
	
	public function prepare_woo_address_fields($fields){
		if($fields && !empty($fields)){
			foreach ( $fields as $key => $field ) {
				if(isset($field['rules']) && !empty($field['rules']) && isset($field['required']) && $field['required']){
					$fields[$key]['required'] = false;
				}
			}
		}
		
		return $fields;
	}
	
	/*public function woo_before_edit_account_address_form(){
		global $wp;
		$user_id = get_current_user_id();
	 
	  	if ( !$user_id )
			return;
		
		$load_address = isset( $wp->query_vars['edit-address'] ) ? wc_edit_address_i18n( sanitize_title( $wp->query_vars['edit-address'] ), true ) : 'billing';
		$country = get_user_meta( $user_id, $load_address . '_country', true );
		$address = WC()->countries->get_address_fields( $country, $load_address . '_' );
		
		if($address && !empty($address)){
			foreach ( $address as $key => $field ) {
				if(isset($field['rules']) && !empty($field['rules']) && isset($field['required']) && $field['required']){
					$address[$key]['required'] = 0;
					$modified = true;
					
					print_r($field);echo '<br/><br/>';
				}
			}
		}
	}*/
	
   /***********************************************************
	******** DISPLAY & SAVE CUSTOM USER META FIELDS - END *****
	***********************************************************/
	
}

endif;