(function ($) {

	function getNextBusinessDay(date) {
		const result = new Date( date );
		result.setDate( result.getDate() + 1 );

		// Keep adding days until we get a business day (Mon-Fri).
		while (result.getDay() === 0 || result.getDay() === 6) {
			result.setDate( result.getDate() + 1 );
		}

		return result;
	}

	function alsendo_connect_add_border_to_selected_service() {
		const elements = document.querySelectorAll( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']" );
		if (elements) {

			elements.forEach(
				function (element) {
					if (element.checked) {
						is_any_element_checked = true;
						element.closest( ".apaczka-calculate-item" ).classList.toggle( "selected" );
						element.setAttribute( "checked", "checked" );
					}
					let radioInputs = document.querySelectorAll( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']" );
					radioInputs.forEach(
						function (radioElement) {
							if (radioElement.checked === false) {
								radioElement.closest( ".apaczka-calculate-item" ).classList.remove( "selected" );
								radioElement.removeAttribute( "checked" );
							}
						}
					);
				}
			);

		}
	}

	function formatJSON(obj, indent = 0) {
		const indentStr = '  '.repeat( indent );
		let output      = '';

		if (Array.isArray( obj )) {
			output += 'array:' + obj.length + ' [▼\n';
			obj.forEach(
				function (item, index) {
					output += indentStr + '  ' + index + ' => ' + formatJSON( item, indent + 1 ) + '\n';
				}
			);
			output += indentStr + ']';
		} else if (typeof obj === 'object' && obj !== null) {
			output += 'array:' + Object.keys( obj ).length + ' [▼\n';
			Object.entries( obj ).forEach(
				function (entry) {
					let key   = entry[0];
					let value = entry[1];
					output   += indentStr + '  "' + key + '" => ' + formatJSON( value, indent + 1 ) + '\n';
				}
			);
			output += indentStr + ']';
		} else {
			output += JSON.stringify( obj );
		}

		return output;
	}

	function alsendo_process_api_response(object) {
		let api_response = '';
		if (typeof object === 'string') {
			api_response = object;
		} else if (Array.isArray( object )) {
			let errorsString = '\n\n';
			object.forEach(
				function (errorObj) {
					if (errorObj.field && errorObj.message) {
						errorsString += errorObj.field + ' => ' + errorObj.message + '\n';
					}
				}
			);
			api_response += errorsString;
		} else {
			if (object.status_code) {
				api_response += 'API response code: ' + object.status_code + '\n\n';
			}
			if (object.message) {
				api_response += object.message + '\n\n';
			}
			// Handle errors, whether they're in object.errors or directly in the object.
			let errors = object.errors || object;
			if (typeof errors === 'object' && ! Array.isArray( errors )) {
				let errorsString = '\n\n';
				// Iterate through each error.
				for (let key in errors) {
					if (Object.prototype.hasOwnProperty.call( errors, key )) {
						let errorValue = errors[key];
						if (Array.isArray( errorValue )) {
							errorValue.forEach(
								function (error) {
									errorsString += key + ' => ' + error + '\n';
								}
							);
						} else if (typeof errorValue === 'string') {
							errorsString += key + ' => ' + errorValue + '\n';
						}
					}
				}
				api_response += errorsString;
			}
		}

		api_response = api_response.trim();
		return api_response;
	}

	function changeShippingMethodTriggers(method) {

		let api_type = alsendo_order_metabox.api_type;
	}

	function createOperator(operatorId, operatorName) {
		operatorName = operatorName.toUpperCase();
		return {
			operator: operatorName,
			price: null
		};
	}

	function fillSenderFormByTemplate(templateSlug) {
		console.log( 'templateSlug' );
		console.log( templateSlug );
		let apaczka_sender_templates = alsendo_order_metabox.sender_templates;
		for (const [key, value] of Object.entries( apaczka_sender_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					key2_new = key2.replace( "alsendo_connect_settings_general_sender_", "" );
					$( '#' + '_apaczka\\[sender\\]\\[' + key2_new + '\\]' ).val( value2 )
				}
			}
		}
	}

	function fillPackagePropertiesFormByTemplate(templateSlug) {

		let apaczka_package_properties_templates = alsendo_order_metabox.package_properties_templates;

		let maybe_custom_package_contents = false;
		let custom_package_contents_value = '';
		let package_contents_value        = '';
		let package_contents_tag          = '';
		let package_contents_disabled     = true;

		for (const [key, value] of Object.entries( apaczka_package_properties_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					key2_new = key2.replace( "alsendo_connect_settings_general_", "" );

					if ( 'custom_text_content' === key2_new ) {
						custom_package_contents_value = value2;
					}
					if ( 'package_contents' === key2_new ) {
						package_contents_tag = value2;
						if ( 'custom_text' === value2 ) {
							maybe_custom_package_contents = true;
							package_contents_disabled     = false;
						}
						if ( 'order_id' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_order_id;
						}
						if ( 'product_id' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_product_id;
						}
						if ( 'product_name' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_product_name;
						}
					}

					$( '#' + '_apaczka\\[package_properties\\]\\[' + key2_new + '\\]' ).val( value2 );
				}
			}
		}

		if ( maybe_custom_package_contents ) {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).val( custom_package_contents_value );
		} else {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).val( package_contents_value );
		}

		if ( package_contents_disabled ) {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', true );
			let hidden_input_tag_content = '<input type="hidden" name="_apaczka[package_properties][package_contents_tag]" id="_apaczka[package_properties][package_contents_tag]" value="' + package_contents_tag + '">';
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).append( hidden_input_tag_content );
		} else {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' ).each(
				function (ind, elem) {
					jQuery( elem ).remove();
				}
			);

			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', false );
		}

		$( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).trigger( 'change' );

	}

	function serviceIdToApmSupplierId(serviceId) {

		switch (serviceId) {
			case 14:
			case 15:
			case 16:
				return 'UPS';
			case 20:
			case 23:
			case 26:
			case 29:
				return 'DPD';
			case 50:
			case 53:
				return 'RUCH';
			case 40:
			case 41:
			case 45:
			case 46:
				return 'INPOST';
			case 163:
				return 'POCZTA';
			case 64:
				return 'POCZTA';
			case 66:
				return 'POCZTA';
			case 162:
				return 'POCZTA';
			case 86:
				return 'DHL';
			case 68:
				return 'POCZTA';
			default:
				return null
		}

	}

	function is_cod_amount_defined() {
		return parseInt( $( '#_apaczka\\[additional_options\\]\\[cod_amount\\]' ).val() ) > 0
	}

	function alsendo_debug_print_r(obj) {
		function inpost_intl_format_value(value) {
			if (typeof value === 'string') {
				return '"' + value + '"';
			}
			if (Array.isArray( value )) {
				return 'Array\n' + alsendo_debug_format_object( value );
			}
			if (typeof value === 'object' && value !== null) {
				return alsendo_debug_format_object( value );
			}
			return value;
		}

		function alsendo_debug_format_object(obj) {
			let result = '(\n';
			for (let key in obj) {
				if (obj.hasOwnProperty( key )) {
					result += '    [' + key + '] => ' + inpost_intl_format_value( obj[key] ) + '\n';
				}
			}
			result += ')';
			return result;
		}

		return alsendo_debug_format_object( obj );
	}

	function alsendo_process_api_response(object) {
		let api_response = '';

		// Check if object is a string.
		if (typeof object === 'string') {
			api_response = object;
		} else if (Array.isArray( object )) {
			let errorsString = '\n\n';
			object.forEach(
				function (errorObj) {
					if (errorObj.field && errorObj.message) {
						errorsString += errorObj.field + ' => ' + errorObj.message + '\n';
					}
				}
			);
			api_response += errorsString;
		} else {
			if (object.status_code) {
				api_response += 'API response code: ' + object.status_code + '\n\n';
			}
			if (object.message) {
				api_response += object.message + '\n\n';
			}
			// Handle errors, whether they're in object.errors or directly in the object.
			let errors = object.errors || object;
			if (typeof errors === 'object' && ! Array.isArray( errors )) {
				let errorsString = '\n\n';
				// Iterate through each error.
				for (let key in errors) {
					if (Object.prototype.hasOwnProperty.call( errors, key )) {
						let errorValue = errors[key];
						if (Array.isArray( errorValue )) {
							errorValue.forEach(
								function (error) {
									errorsString += key + ' => ' + error + '\n';
								}
							);
						} else if (typeof errorValue === 'string') {
							errorsString += key + ' => ' + errorValue + '\n';
						}
					}
				}
				api_response += errorsString;
			}
		}

		api_response = api_response.trim();
		return api_response;
	}

	/**
	 * /**
	 *  * UPS Access Point (service id: 14,15, 16)
	 * DPD Pickup (service id: 23, 26)
	 * ORLEN Paczka  (service id: 50)
	 * Paczkomaty InPost  (service id: 41)
	 * Poczta Polska Ekspres24 Punkty  (service id: 163)
	 * DHL POP  (service id: 86)
	 * Poczta Polska Kurier48 Punkty  (service id: 162)
	 * DHL_PARCEL
	 * DPD
	 * INPOST
	 * POCZTA
	 * UPS
	 */
	function handleCalculateDynamicFields(selectedService) {

		console.log( 'handleCalculateDynamicFields: selectedService' );
		console.log( selectedService );

		let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();
		let debug           = serviceIdToApmSupplierId( selectedService );
		console.log( 'serviceIdToApmSupplierId' );
		console.log( debug );

		let api_type = alsendo_order_metabox.api_type;

		let method = null;

		console.log( 'Alsendo connect - selectedService: ' + selectedService );
		console.log( 'api_type: ' + api_type );
		console.log( 'selected_method: ' + method );
		console.log( 'handleCalculateDynamicFields: shipping_method ' + shipping_method );

		// Hide dispatch point field forever.
		$( '#apaczka_delivery_point_id_wrapper' ).addClass( 'apaczka-hidden' );
		let zaslat_supplier = $( '.apaczka-calculate-item[data-service_id="' + selectedService + '"]' ).attr( 'data-supplier' );
		console.log( 'zaslat_supplier: ' + zaslat_supplier );

		let supplier_selected_by_buyer = $( '#alsendo_connect_buyer_supplier' ).val();
		console.log( 'supplier_selected_by_buyer: ' + supplier_selected_by_buyer );
		if ( supplier_selected_by_buyer === zaslat_supplier ) {
			$( '#apaczka_delivery_point_id_wrapper' ).removeClass( 'apaczka-hidden' );
			console.log( 'show zaslat delivery point: ' );
		}

	}

	function alsendoMtaboxChangeParcelTypeActions(type) {

		let apaczka_parcel_length = $( '#_apaczka\\[package_properties\\]\\[package_length\\]' );
		let apaczka_parcel_width  = $( '#_apaczka\\[package_properties\\]\\[package_width\\]' );
		let apaczka_parcel_height = $( '#_apaczka\\[package_properties\\]\\[package_height\\]' );

		switch (type) {
			case 'europalette':
				apaczka_parcel_length.val( 120 );
				apaczka_parcel_width.val( 80 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 );
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			case 'palette_60x80':
				apaczka_parcel_width.val( 60 );
				apaczka_parcel_length.val( 80 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 )
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			case 'palette_120x100':
				apaczka_parcel_width.val( 100 );
				apaczka_parcel_length.val( 120 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 )
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			case 'palette_120x120':
				apaczka_parcel_length.val( 120 );
				apaczka_parcel_width.val( 120 );
				apaczka_parcel_length.prop( 'readonly', true );
				apaczka_parcel_width.prop( 'readonly', true );

				if (apaczka_parcel_height.val() > 220) {
					apaczka_parcel_height.val( 220 )
				}

				apaczka_parcel_height.prop( 'max', 220 );
				break;
			default:
				apaczka_parcel_length.prop( 'readonly', false );
				apaczka_parcel_width.prop( 'readonly', false );
				apaczka_parcel_height.removeAttr( 'max' )
		}
	}

	function alsendo_connect_maybe_need_recalculate() {
		//console.log( 'alsendo_connect_maybe_need_recalculate' );
		$( '#alsendo-recalc-notice' ).remove();
		let send_parcel_button = $( '#apaczka_send' );
		if (typeof send_parcel_button != 'undefined' && send_parcel_button !== null) {
			if ($( '#apaczka_send' ).css( 'display' ) === 'block') {
				let notice = '<span id="alsendo-recalc-notice"><b><pre>' + alsendo_order_metabox.recalc_notice + '</pre></b></span>';
				$( "#apaczka_send" ).prop( "disabled", true );
				$( "#apaczka_send" ).after( notice );

			}
		}
	}

	$( document ).ready(
		function () {
			$( 'body #woocommerce-order-downloads .buttons .select2-container' ).css( "width", "100% !important" );
		}
	);

	$( document ).ready(
		function () {

			console.log( 'alsendo-connect-order-metabox.js' );
			let api_type = alsendo_order_metabox.api_type;

			let parcelCounter       = 0;
			let is_order_caclulated = $( '#alsendo_connect_calculated' ).val();
			let zaslat_address_id = $( '#alsendo_connect_zaslat_address_id' ).val();
			if (typeof zaslat_address_id != 'undefined' && zaslat_address_id !== null) {
				$( '#_apaczka\\[sender_template\\]' ).val(zaslat_address_id ).trigger('change');
			}

			//let selected_sender_template = alsendo_order_metabox.selected_sender_template;

			$( '#alsendo_connect' ).on(
				'keyup',
				'input',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[sender\\]\\[is_residential\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[pickup_hour_from\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[pickup_hour_to\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);

			if ( 'zaslat' !== api_type) {
				$( '#_apaczka\\[package_properties\\]\\[pickup_date\\]' ).on(
					'change',
					function () {
						alsendo_connect_maybe_need_recalculate();
					}
				);
			}

			let dispatch_point_map_country_param = 'CZ';

			/*if ( ! alsendo_order_metabox.selected_sender_template ) {
				console.log( 'NO selected sender template:' );
				selected_sender_template = Object.keys( alsendo_order_metabox.sender_templates )[0];
				fillSenderFormByTemplate( selected_sender_template );
			}*/

			let pickup_request_checkbox = $( 'input[name="_apaczka\\[package_properties\\]\\[is_pickup_request\\]"]' );

			if (typeof pickup_request_checkbox != 'undefined' && pickup_request_checkbox !== null) {

				let pickup_date_input = $( 'input[name="_apaczka\\[package_properties\\]\\[pickup_date\\]"]' );
				$( pickup_date_input ).attr( 'type', 'text' );
				$( pickup_date_input ).val( '' );
				$( pickup_date_input ).on(
					'click',
					function () {
						$( pickup_date_input ).attr( 'type', 'date' );
						$( pickup_date_input ).val( 'max', '' );
						// Calculate next business day.
						const minDate = getNextBusinessDay( new Date() );

						// Calculate max date (next business day + 14 days).
						const maxDate = new Date( minDate );
						maxDate.setDate( maxDate.getDate() + 14 );

						// Set min and max attributes.
						let min = minDate.toISOString().split( 'T' )[0];
						let max = maxDate.toISOString().split( 'T' )[0];

						$( pickup_date_input ).attr( 'min', min );
						$( pickup_date_input ).attr( 'max', max );

					}
				)

				let pickup_date_wrap = $( 'input[name="_apaczka\\[package_properties\\]\\[pickup_date\\]"]' ).closest( '.form-field' );
				if ($( pickup_request_checkbox ).is( ':checked' )) {
					if (typeof pickup_date_wrap != 'undefined' && pickup_date_wrap !== null) {
						$( pickup_date_wrap ).css( 'display', 'block' );
					}
				} else {
					if (typeof pickup_date_wrap != 'undefined' && pickup_date_wrap !== null) {
						$( pickup_date_wrap ).css( 'display', 'none' );
					}
				}

				$( pickup_request_checkbox ).on(
					'change',
					function () {
						console.log( 'pickup_request_checkbox is checked ?' );
						if ($( this ).is( ':checked' )) {
							if (typeof pickup_date_wrap != 'undefined' && pickup_date_wrap !== null) {
								$( pickup_date_wrap ).css( 'display', 'block' );
							}
						} else {
							if (typeof pickup_date_wrap != 'undefined' && pickup_date_wrap !== null) {
								$( pickup_date_wrap ).css( 'display', 'none' );
							}
						}
					}
				);
			}

			// if ( '1' !== is_order_caclulated ) {
				//fillSenderFormByTemplate( selected_sender_template );
				fillPackagePropertiesFormByTemplate( alsendo_order_metabox.selected_package_template );
			// }

			let iban_order                = $( 'input[name="_apaczka[sender][bank_account_number]"]' );
			let sender_phone_number_order = $( 'input[name="_apaczka[sender][phone]"]' );

			let order_metabox_parcel_type_handle = $( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' );

			if (typeof order_metabox_parcel_type_handle != 'undefined' && order_metabox_parcel_type_handle !== null) {
				alsendoMtaboxChangeParcelTypeActions( order_metabox_parcel_type_handle.val() );
				order_metabox_parcel_type_handle.change(
					function (e) {
						alsendoMtaboxChangeParcelTypeActions( $( this ).val() )
					}
				);
			}

			// let apaczka_calculate_selected_service = 0.
			let apaczka_calculate_selected_service        = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
			let apaczka_dispath_point_handler_to_validate = false;

			let map_country_code          = 'PL';
			let sender_country_code_field = $( '#_apaczka\\[sender\\]\\[country\\]' );
			if (typeof sender_country_code_field != 'undefined' && sender_country_code_field !== null) {
				let sender_country_code = $( sender_country_code_field ).val();
				if (typeof sender_country_code != 'undefined' && sender_country_code !== null) {
					map_country_code = sender_country_code;
				}
			}

			// console.log('map_country_code');
			// console.log(map_country_code);

			$( "#apaczka_calculate_radio > .apaczka-calculate-item > input[type='radio']" ).change(
				function (e) {
					console.log( "change", e );
				}
			);

			$( '#alsendo_connect_calculate_price_btn' ).click(
				function (e) {
					let observer = new MutationObserver(
						function (mutations) {
							if ($( "#apaczka_calculate_radio" ).length) {
								let selected_tile = false;
								$( '.apaczka-calculate-item' ).each(
									function (ind, element) {
										if ( $( element ).hasClass( 'selected' ) ) {
											selected_tile                      = true;
											apaczka_calculate_selected_service = $( element ).attr( 'data-service_id' );
											handleCalculateDynamicFields( parseInt( apaczka_calculate_selected_service ) );
										}
									}
								);
								if ( ! selected_tile ) {
									$( "#apaczka_calculate_radio > .apaczka-calculate-item:first-child" ).click();
									const valOfFirstItem = $( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']:checked" ).val();
									console.log( "valOfFirstItem", valOfFirstItem );
									apaczka_calculate_selected_service = valOfFirstItem;
									handleCalculateDynamicFields( parseInt( valOfFirstItem ) );
								}
								observer.disconnect();
							}
						}
					);
					// Start observing.
					observer.observe(
						document.body,
						{
							childList: true,
							subtree: true
						}
					);
				}
			);

			$( "#alsendo_connect_load_sender_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#_apaczka\\[sender_template\\]' ).val();
					fillSenderFormByTemplate( selectedTemplateSlug );
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( "#alsendo_connect_load_package_properties_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).val();
					fillPackagePropertiesFormByTemplate( selectedTemplateSlug );
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).change(
				function (e) {
					if ($( '#apaczka-calculate-wrapper' ).html() !== '') {
						$( '#apaczka_calculate_price_btn' ).click();
						return false;
					}
				}
			);

			$( ".apaczka_calculate_price" ).click(
				function () {
					let shipment_type = $( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).val();

					$( '#alsendo-recalc-notice' ).remove();

					$( 'div' ).each(
						function () {
							let id = $( this ).attr( 'id' );
							if (id && id.startsWith( 'dispath_point_' )) {
								$( this ).addClass( 'apaczka-hidden' );
							}
							if (id && id.startsWith( 'apaczka_delivery_point_id_wrapper' )) {
								$( this ).addClass( 'apaczka-hidden' );
							}
						}
					);

					$( "#apaczka-calculate-wrapper" ).html( '' );
					$( this ).parent().find( ".spinner_courier" ).hide();
					$( this ).parent().find( ".spinner" ).hide();

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'calculate',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						alsendo_connect_calculate: {
							sender: {},
							receiver: {},
							package_properties: {},
							additional_options: {},
						}
					};

					let package_properties      = $( 'input[id^="_apaczka[package_properties]"], select[id^="_apaczka[package_properties]"]' );
					let sender                  = $( 'input[id^="_apaczka[sender]"]' );
					let receiver                = $( 'input[id^="_apaczka[receiver]"]' );
					let additional_options      = $( 'input[id^="_apaczka[additional_options]"]' );
					let is_residential_sender   = $( 'select[id="_apaczka[sender][is_residential]"]' ).val();
					let is_residential_receiver = $( 'select[id="_apaczka[receiver][is_residential]"]' ).val();

					sender.each(
						function () {
							data.alsendo_connect_calculate.sender[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_calculate.sender['is_residential'] = is_residential_sender;

					receiver.each(
						function () {
							data.alsendo_connect_calculate.receiver[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_calculate.receiver['is_residential'] = is_residential_receiver;

					package_properties.each(
						function () {
							if ( typeof $( this ).data( 'key' ) != 'undefined' ) {
								data.alsendo_connect_calculate.package_properties[$( this ).data( 'key' )] = $( this ).val();
							}
						}
					);

					let may_be_contents_tag_used = $( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' );
					if (typeof may_be_contents_tag_used != 'undefined' && may_be_contents_tag_used !== null) {
						let contents_tag = $( may_be_contents_tag_used ).val();
						if (typeof contents_tag != 'undefined' && contents_tag !== null) {
							data.alsendo_connect_calculate.package_properties['contents_tag'] = contents_tag;
						}
					}

					console.log( 'zaslat from ID::' );
					console.log( $( '#_apaczka\\[sender_template\\]' ).val() );
					data.alsendo_connect_calculate.sender['from_id'] = $( '#_apaczka\\[sender_template\\]' ).val();

					let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();
					console.log( 'shipping_method' );
					console.log( shipping_method );
					if ('' === shipping_method || null === shipping_method || 'undefined' == typeof shipping_method ) {
						alert( alsendo_order_metabox.shipping_method_alert );
						return false;
					}

					let pickup_request_checkbox = $( 'input[name="_apaczka\\[package_properties\\]\\[is_pickup_request\\]"]' );
					if (typeof pickup_request_checkbox != 'undefined' && pickup_request_checkbox !== null) {
						if ( $( pickup_request_checkbox ).is( ':checked' ) ) {
							data.alsendo_connect_calculate.package_properties['pickup_request'] = 1;
							let pickup_date = $( 'input[name="_apaczka\\[package_properties\\]\\[pickup_date\\]"]' );
							if (typeof pickup_date != 'undefined' && pickup_date !== null) {
								data.alsendo_connect_calculate.package_properties['pickup_date'] = $( pickup_date ).val();
							}
						}
					}

					additional_options.each(
						function () {
							data.alsendo_connect_calculate.additional_options[$( this ).data( 'key' )] = $( this ).val()
						}
					);

					let receiver_postal_code = data.alsendo_connect_calculate.receiver.postal_code;

					$( '#alsendo_pre_js_debug' ).remove();
					$( '#apaczka_error' ).html( '' );

					console.log( "alsendo connect evaluation data - prepared:" );
					console.log( data );

					$( this ).attr( 'disabled', true );
					$( '#alsendo_connect_preloader' ).css( 'display', 'inline-block' );
					$( '.apaczka_send' ).css( 'display', 'none' );


                    let zaslat_linked  = $( '#alsendo_connect_zaslat_linked_carrier' );
                    if (typeof zaslat_linked != 'undefined' && zaslat_linked !== null) {
                        let zaslat_linked_carrier  = $( '#alsendo_connect_zaslat_linked_carrier' ).val();
                        data.alsendo_connect_calculate.linked_carrier = zaslat_linked_carrier;
                    }

					if( $(this).hasClass('alsendo_full') ) {
						console.log( 'we need all available services' );
						data.alsendo_connect_calculate.alsendo_full = 1;
					}

					// return;

					$.post(
						ajaxurl,
						data,
						function (response) {
							console.log( 'Alsendo connect: evaluate package response' );
							if (response != 0) {
								response = JSON.parse( response );
								console.log( response.status );
								// console.log( response );
								if (response.status === 'ok') {
									$( '.apaczka_send' ).css( 'display', 'block' );
									$( '#apaczka_error' ).html( '' );
									let calculate_html   = response.calculate_html;
									let calcualted_tiles = $.parseHTML( calculate_html );
									$( "#apaczka-calculate-wrapper" ).html( calcualted_tiles );
									$( "#apaczka_send" ).prop( "disabled", false );
									changeShippingMethodTriggers( $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val() );
									// $('.apaczka-calculate-item[data-item="0"]').click();
								} else {
									console.log( 'Calculation: error:' );
									console.log( response.status );
									console.log( response );
									$( '#apaczka_error' ).html( '' );
									let api_response = '';
									if ( 'errors' in response ) {
										console.log( response.errors );
										if (typeof response.errors === 'object' && response.errors !== null) {
											if ( 'errors' in response.errors ) {
												api_response += '<br>' + alsendo_process_api_response( response.errors.errors );
											}
										} else {
											api_response += '<br>' + alsendo_process_api_response( response.errors );
										}
									}
									if ( 'error_messages' in response ) {
										console.log( response.error_messages );
										api_response += alsendo_process_api_response( response.error_messages );
									}
									if ( 'status' in response && response.status.length > 0 ) {
										// api_response += '<br>' + 'Status: ' + response.status;
									}
									if ( 'status_code' in response && response.status_code.length > 0) {
										api_response += '<br>' + 'Status code: ' + response.status_code;
									}
									if ( 'message' in response ) {
										console.log( response.message );
										api_response += '<br>' + alsendo_process_api_response( response.message );
									}

									console.log( 'Error: api_response' );
									console.log( api_response );

									if (typeof api_response != 'undefined' && api_response !== null && api_response != '' ) {
										$( '#apaczka_error' ).html( '<pre>' + api_response.replace( /\n/g, '<br>' ) + '</pre>' );
									} else {
										let formatted_JSON = formatJSON( response );
										$( '#apaczka_error' ).html( '<pre>' + formatted_JSON + '</pre>' );
									}

									$( "#apaczka-calculate-wrapper" ).html( '' );
									$( "#apaczka_send" ).prop( "disabled", true );
								}

								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								$( '.apaczka_calculate_price' ).attr( 'disabled', false );

								let selected_tile = $( '.apaczka-calculate-item.selected' );
								if (typeof selected_tile != 'undefined' && selected_tile !== null) {
									let selected_service = $( selected_tile ).find( '.apaczka_calculate_radio' );

									if (typeof selected_service != 'undefined' && selected_service !== null && selected_service.length > 0 ) {
										let selected_carrier = $( selected_service ).attr( 'data-supplier' );
										console.log( 'selected_carrier' );
										console.log( selected_carrier );
										let checkout_delivery_point = $( 'input[name="_apaczka[delivery_point]"]' ).val();
										/*if (typeof checkout_delivery_point != 'undefined' && checkout_delivery_point !== null ) {
											let data = JSON.parse( checkout_delivery_point );
											console.log( 'zaslat checkout_delivery_point' );
											console.log( data );
											if ('apm_supplier' in data && selected_carrier.toUpperCase() === data.apm_supplier) {
												$( '#apaczka_delivery_point_id_wrapper' ).removeClass( 'apaczka-hidden' );

											}
											console.log( data.apm_supplier );
											if ('apm_supplier' in data && 'PACKETA' === data.apm_supplier ) {
												$( '#apaczka_delivery_point_id_wrapper' ).removeClass( 'apaczka-hidden' );
											}
										}*/

										if (typeof checkout_delivery_point != 'undefined' && checkout_delivery_point !== null) {
											try {
												let data = typeof checkout_delivery_point === 'string'
													? JSON.parse(checkout_delivery_point)
													: checkout_delivery_point;

												console.log('zaslat checkout_delivery_point');
												console.log(data);

												if (data?.apm_supplier && typeof data === 'object') {
													console.log(data.apm_supplier);

													if (selected_carrier?.toUpperCase?.() === data.apm_supplier) {
														$('#apaczka_delivery_point_id_wrapper').removeClass('apaczka-hidden');
													}

													if (data.apm_supplier === 'PACKETA') {
														$('#apaczka_delivery_point_id_wrapper').removeClass('apaczka-hidden');
													}
												}
											} catch (error) {
												console.error('Ошибка обработки checkout_delivery_point:', error, checkout_delivery_point);
											}
										}
									}
								}

								return false;

							} else {
								$( '#apaczka_error' ).html( 'Invalid response.' );
							}

						}
					);

					return false;
				}
			);

			$( document ).on(
				"click",
				'.apaczka_calculate_radio',
				function (event) {
					apaczka_calculate_selected_service = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
					handleCalculateDynamicFields( parseInt( apaczka_calculate_selected_service ) )
				}
			);

			$( "#apaczka_send" ).click(
				function (e) {

					let selected_tile = $( '.apaczka-calculate-item.selected' );
					if ( ! selected_tile || typeof selected_tile == 'undefined' || selected_tile === null) {
						e.preventDefault();
						alert( alsendo_order_metabox.text_no_selected );
						return false;
					}

					if ( selected_tile.length === 0 ) {
						e.preventDefault();
						alert( alsendo_order_metabox.text_no_selected );
						return false;
					}

					let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();
					console.log( 'shipping_method' );
					console.log( shipping_method );
					if ('' === shipping_method) {
						alert( alsendo_order_metabox.shipping_method_alert );
						return false;
					}

					if (false !== apaczka_dispath_point_handler_to_validate) {
						if ('' === apaczka_dispath_point_handler_to_validate.val()) {
							alert( "Punkt nadania nie może być pusty." );
							return false;
						}
					}

					let delivery_point_id;

					if ($( '#apaczka_delivery_point_id_wrapper' ).hasClass( 'apaczka-hidden' )) {
						delivery_point_id = ''
					} else {
						delivery_point_id = $( '#_apaczka\\[delivery_point_id\\]' ).val();
						if ( '' === delivery_point_id ) {
							alert( "Delivery point is empty." );
							return false;
						}
					}

					if ( ! $( this ).closest( "form" )[0].checkValidity()) {
						$( this ).closest( "form" )[0].reportValidity();
						return false;
					}

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'create_package',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						alsendo_connect_create: {
							sender: {},
							receiver: {},
							package_properties: {},
							additional_options: {},
							delivery_point: {},
							delivery_point_id: delivery_point_id,
							selected_service: apaczka_calculate_selected_service,
							selected_supplier: '',

						}
					};

					let package_properties = $( 'input[id^="_apaczka[package_properties]"], select[id^="_apaczka[package_properties]"]' );
					let sender             = $( 'input[id^="_apaczka[sender]"]' );

					let additional_options      = $( 'input[id^="_apaczka[additional_options]"]' );
					let receiver                = $( 'input[id^="_apaczka[receiver]"]' );
					let delivery_point          = $( 'input[name^="_apaczka[delivery_point]"]' );
					let is_residential_sender   = $( 'select[id="_apaczka[sender][is_residential]"]' ).val();
					let is_residential_receiver = $( 'select[id="_apaczka[receiver][is_residential]"]' ).val();

					receiver.each(
						function () {
							data.alsendo_connect_create.receiver[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_create.receiver['is_residential'] = is_residential_receiver;

					sender.each(
						function () {
							data.alsendo_connect_create.sender[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_create.sender['is_residential'] = is_residential_sender;

					let zaslat_supplier = $( '.apaczka-calculate-item.selected' ).attr( 'data-supplier' );
					console.log( 'zaslat_supplier:' );
					console.log( zaslat_supplier );
					if (typeof zaslat_supplier != 'undefined' && zaslat_supplier !== null) {
						data.alsendo_connect_create.selected_service = zaslat_supplier;
					}
					data.alsendo_connect_create.sender['from_id'] = $( '#_apaczka\\[sender_template\\]' ).val();
					let pickup_request_checkbox                   = $( 'input[name="_apaczka\\[package_properties\\]\\[is_pickup_request\\]"]' );
					if (typeof pickup_request_checkbox != 'undefined' && pickup_request_checkbox !== null) {
						if ( $( pickup_request_checkbox ).is( ':checked' ) ) {
							data.alsendo_connect_create.package_properties['pickup_request'] = 1;
						}
					}

					data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = $( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val();

					package_properties.each(
						function () {
							data.alsendo_connect_create.package_properties[$( this ).data( 'key' )] = $( this ).val();
						}
					);

					additional_options.each(
						function () {
							data.alsendo_connect_create.additional_options[$( this ).data( 'key' )] = $( this ).val();
						}
					);

					$( '#alsendo_pre_js_debug' ).remove();
					$( '#apaczka_error' ).html( '' );
					$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
					$( this ).attr( 'disabled', true );

					console.log( 'Alsendo connect: create_order_ajax_data' );
					console.log( data );

					$.post(
						ajaxurl,
						data,
						function (response) {
							if (response != 0) {
								response = JSON.parse( response );
								if (response.status === 'ok') {
									console.log( response );

									if ( 'zaslat_order' in response ) {
										if ( 'zaslat_ok' in response ) {
											console.log( 'Order created in Zaslat.cz' );
											window.location.reload();
											console.log( 'window.location.reload' );
										}
									}

								} else {

									console.log( 'Alsendo: send_order_error' );
									console.log( response.status );
									console.log( response );

									$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
									let order_id = $( '#alsendo_connect_wc_order_id' ).val();

									let api_response = '';

									if ( 'api_error' in response ) {
										api_response += 'API error: ' + response.api_error + '\n\n';
									}

									if ( 'status_code' in response  ) {
										api_response += '<br>' + 'API response code: ' + response.status_code + '\n\n';
									}
									if ( 'error_messages' in response  ) {
										console.log( response.error_messages );
										api_response += alsendo_process_api_response( response.error_messages );
									}
									if ( 'error' in response  ) {
										console.log( response.error );
										api_response += alsendo_process_api_response( response.error );
									}
									if ( 'errors' in response  ) {
										console.log( response.errors );
										if ( 'errors' in response.errors  ) {
											console.log( 'eeeeeeeeeee' );
											console.log( response.errors.errors );
											api_response += alsendo_process_api_response( response.errors.errors );
										} else {
											api_response += alsendo_process_api_response( response.errors );
										}

									}

									if ( 'status_text' in response  ) {
										api_response += 'Details: ' + response.status_text + '\n\n';
									}
									if ( 'raw_json' in response  ) {
										api_response += response.raw_json + '\n\n';
									}

									if ( 'apaczka_response' in response ) {
										if ( 'status_code' in response.apaczka_response  ) {
											api_response += 'API response code: ' + response.apaczka_response.status_code + '\n\n';
										}
										if ( 'message' in response.apaczka_response || 'errors' in response.apaczka_response ) {
											if (  'message' in response.apaczka_response ) {
												api_response += '<br>' + alsendo_process_api_response( response.apaczka_response.message );
											}
											if ( 'errors' in response.apaczka_response ) {
												console.log( 'additional_api_errors:' );
												console.log( response.apaczka_response.errors );
												api_response += '<br>' + alsendo_process_api_response( response.apaczka_response.errors );
											}
										}
									}

									console.log( 'api_response_errors:' );
									console.log( api_response );

									let woo_logs_section_url = ' <a target="blank_" href="' + alsendo_order_metabox.log_path + '">' + alsendo_order_metabox.text_here + '</a>';
									api_response            += "<br>Check log file 'alsendo-connect-apaczka-get-waybill-order-" + order_id + "'" + woo_logs_section_url + "</span>";

									$( '#apaczka_error' ).html( '<pre>' + api_response.replace( /\n/g, '<br>' ) + '</pre>' );

									$( '.apaczka_send' ).attr( 'disabled', false );
									// $( this ).parent().find( ".spinner" ).removeClass( 'is-active' );
									$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								}

								return false;
							} else {
								// console.log('Invalid response.');
								$( '#apaczka_error' ).html( 'Invalid response.' );
								$( '.apaczka_send' ).attr( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
							}

						}
					);

					return false;
				}
			);

			$( '#zaslat_cancel' ).click(
				function (e) {
					e.preventDefault();
					console.log( 'zaslat_order_cancel' );
					let order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );
					$( '#json-display-alsendo' ).text( '' );
					$( '#json-display-alsendo' ).css( 'display', 'none' );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'zaslat_cancel_order',
								security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
								zaslat_id: $( this ).attr( 'data-zaslat-id' ),
								order_id: order_id
							},
							beforeSend: function () {
								$( '#alsendo_cancellation_message' ).remove();
								$( '#zaslat_cancel' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
								$( '#alsendo_connect_preloader' ).after( '<span id="zaslat_cancellation_message" style="display:block;color:#26be22;margin-top:20px;"><b>' + alsendo_order_metabox.zaslat_reload_message + '</b></span>' );
							},
							success: function (response) {
								console.log( "Zaslat order_cancel response:" );
								console.log( response );
								if ( 0 !== response ) {
									if ('success' in response && response.success) {
										if ('data' in response ) {
											if ('message' in  response.data ) {
												if (typeof response.data.message != 'undefined' && response.data.message !== null) {
													let message = response.data.message;
													console.log( message );
													console.log( response.data );
													let status_color = '';
													if ('status_code' in  response.data && 200 === response.data.status_code ) {
														window.location.reload();
													} else {
														status_color = '#e03636';
														if ('errors' in  response.data ) {
															message += '<br>pre>' + alsendo_process_api_response( response.data.errors ) + '</pre>';
														}
														$( '#ecolet_wc_order_id' ).after( '<span id="alsendo_cancellation_message" style="display:block;margin-top:20px;font-weight:bold;color:' + status_color + '">' + message + '</span>' );
													}
												}
											}

										}
									} else {
										if ('data' in response && 'error' in response.data) {

											console.log( response.data.error );
											let status_color = '#e03636';
											let message      = '<br><pre>' + alsendo_process_api_response( response.data.error ) + '</pre>';
											$( '#ecolet_wc_order_id' ).after( '<span id="alsendo_zaslat_cancel_order_message" style="display:block;margin-top:20px;font-weight:bold;color:' + status_color + '">' + message + '</span>' );
										}
									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Zaslat cancel order" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( '#zaslat_cancel' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								$( '#zaslat_cancellation_message' ).remove();

							}
						}
					);

				}
			);

			$( '#zaslat_get_waybill' ).click(
				function (e) {
					e.preventDefault();
					console.log( 'zaslat_get_waybill' );
					let order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'zaslat_get_waybill',
								security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
								zaslat_id: $( this ).attr( 'data-zaslat-id' ),
								order_id: order_id
							},
							beforeSend: function () {
								$( '#alsendo_cancellation_message' ).remove();
								$( '#zaslat_get_waybill' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
							},
							success: function (response) {
								console.log( "Zaslat waybill response:" );
								console.log( response );

								if ('data' in response && 'error' in response.data ) {
									let message = '';
									if ( 'message' in response.data ) {
										message = response.data.message;
									}
									message += '<br>' + alsendo_process_api_response( response.data.error );

									$( '#ecolet_wc_order_id' ).after( '<span id="alsendo_cancellation_message" style="display:block;margin-top:20px;font-weight:bold;color:#e03636">' + message + '</span>' );

								} else if ('data' in response && 'data' in response.data ) {
									let filename   = 'zaslat_order_' + order_id + '.pdf';
									let pdf_string = response.data.data;
									console.log( "Zaslat waybill pdf_string:" );
									console.log( pdf_string );

									// Extract the base64 part by removing the prefix.
									let base64String = pdf_string.split( ',' )[1];

									// Decode the base64 string.
									let binaryString = window.atob( base64String );
									let binaryLen    = binaryString.length;
									let bytes        = new Uint8Array( binaryLen );
									for (let i = 0; i < binaryLen; i++) {
										bytes[i] = binaryString.charCodeAt( i );
									}

									// download file.
									let blob      = new Blob( [bytes], {type: 'application/pdf'} );
									let link      = document.createElement( 'a' );
									link.href     = window.URL.createObjectURL( blob );
									link.download = filename;
									document.body.appendChild( link );
									link.click();
									document.body.removeChild( link );
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Zaslat waybill" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
								$( '#zaslat_get_waybill' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
							},
							complete: function (response) {
								$( '#zaslat_get_waybill' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);

				}
			);

			$( '#zaslat_get_manifest' ).click(
				function (e) {
					e.preventDefault();
					console.log( 'zaslat_get_manifest' );
					let order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'zaslat_get_manifest',
								security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
								zaslat_id: $( this ).attr( 'data-zaslat-id' ),
								order_id: order_id
							},
							beforeSend: function () {
								$( '#zaslat_get_manifest' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
							},
							success: function (response) {
								console.log( "Zaslat manifest response:" );
								console.log( response );

								if ('data' in response && 'data' in response.data ) {
									let filename   = 'zaslat_order_' + order_id + '.pdf';
									let pdf_string = response.data.data;
									console.log( "Zaslat manifest pdf_string:" );
									console.log( pdf_string );

									// Extract the base64 part by removing the prefix.
									let base64String = pdf_string.split( ',' )[1];

									// Decode the base64 string.
									let binaryString = window.atob( base64String );
									let binaryLen    = binaryString.length;
									let bytes        = new Uint8Array( binaryLen );
									for (let i = 0; i < binaryLen; i++) {
										bytes[i] = binaryString.charCodeAt( i );
									}

									// download file.
									let blob      = new Blob( [bytes], {type: 'application/pdf'} );
									let link      = document.createElement( 'a' );
									link.href     = window.URL.createObjectURL( blob );
									link.download = filename;
									document.body.appendChild( link );
									link.click();
									document.body.removeChild( link );
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Zaslat manifest" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
								$( '#zaslat_get_manifest' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
							},
							complete: function (response) {
								$( '#zaslat_get_manifest' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);

				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_inpost\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_inpost_opeartor = ['INPOST'];

					let operators = dispath_point_inpost_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_inpost_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_fancourier\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_fancourier_opeartor = ['FAN_COURIER'];

					let operators = dispath_point_fancourier_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_fancourier_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_sameday\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_sameday_opeartor = ['SAMEDAY'];

					let operators = dispath_point_sameday_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_sameday_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_gls\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					console.log( 'alsendo_order_metabox: dispath_point_gls_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: [{ operator: 'GLS' }],
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_cargus\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					console.log( 'alsendo_order_metabox: dispath_point_gls_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: dispatch_point_map_country_param,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: [{ operator: 'CARGUS' }],
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_kurier48\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_kurier48_opeartor = ['POCZTA'];

					let operators = dispath_point_kurier48_opeartor.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_kurier48_click' );
					console.log( dispath_point_kurier48_opeartor );
					console.log( operators );
					console.log( map_country_code );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								console.log( point );
								console.log( point.code );
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: 'PL',
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_ups\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_ups = ['UPS'];

					let operators = dispath_point_ups.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_ups_click' );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: 'PL',
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_dpd\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_dpd = ['DPD'];

					let operators = dispath_point_dpd.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'alsendo_order_metabox: dispath_point_dpd_click' );
					console.log( 'map_country_code: ' + map_country_code );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: map_country_code,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				}
			);

			$( '#_apaczka\\[delivery_point_id\\]' ).click(
				function (e) {
					let field = $( this );
					e.preventDefault();
					let cod_amount_defined = is_cod_amount_defined();
					let is_cod_only        = false;
					if ( cod_amount_defined ) {
						is_cod_only = true;
					}

					console.log( 'alsendo_order_metabox: delivery_point_id_click' );
					console.log( 'alsendo_order_metabox__selected_service ID: ' + apaczka_calculate_selected_service );
					console.log( [serviceIdToApmSupplierId( parseInt( apaczka_calculate_selected_service ) )] );

					let operatorsArray = []

					let zaslat_supplier = $( '.apaczka-calculate-item[data-service_id="' + apaczka_calculate_selected_service + '"]' ).attr( 'data-supplier' );
					console.log( 'zaslat_supplier' );
					console.log( zaslat_supplier );
					if ( ! zaslat_supplier ) {
						let selected_tile = $( '.apaczka-calculate-item.selected' );
						if (typeof selected_tile != 'undefined' && selected_tile !== null) {
							let selected_service = $( selected_tile ).find( '.apaczka_calculate_radio' );
							if (typeof selected_service != 'undefined' && selected_service !== null && selected_service.length > 0) {
								zaslat_supplier = $( selected_service ).attr( 'data-supplier' );
								console.log( 'zaslat_supplier' );
								console.log( zaslat_supplier );
							}
						}
					}
					operatorsArray = [zaslat_supplier];

					console.log( 'operatorsArray' );
					console.log( operatorsArray );

					let operators = operatorsArray.map(
						function (operator) {
							return createOperator( 'operators - ' + operator, operator );
						}
					).filter( Boolean );
					operators     = operators.length ? operators : null;

					console.log( 'operators' );
					console.log( operators );

					let shipping_country = document.getElementById( "_apaczka[receiver][country_code]" ).value;
					if (typeof shipping_country != 'undefined' && shipping_country !== null) {
						shipping_country = shipping_country.toUpperCase();
					}

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								console.log( point.code );
								field.val( point.code );
								// $('#_apaczka_apm_access_point_id').val(record.foreign_access_point_id);
								$( 'input[id=_apaczka_apm_access_point_id]' ).each(
									function (ind, elem) {
										$( elem ).val( point.code );
									}
								);

								// $('#_apaczka_apm_supplier').val(record.supplier);
								$( 'input[id=_apaczka_apm_supplier]' ).each(
									function (ind, elem) {
										$( elem ).val( point.operator );
									}
								);

								// $('#_apaczka_apm_name').val(record.name);
								$( 'input[id=_apaczka_apm_name]' ).each(
									function (ind, elem) {
										$( elem ).val( point.description );
									}
								);

								// $('#_apaczka_apm_foreign_access_point_id').val(record.foreign_access_point_id);
								$( 'input[id=_apaczka_apm_foreign_access_point_id]' ).each(
									function (ind, elem) {
										$( elem ).val( point.code );
									}
								);

								// $('#_apaczka_apm_street').val(record.street);
								$( 'input[id=_apaczka_apm_street]' ).each(
									function (ind, elem) {
										$( elem ).val( point.street );
									}
								);

								// $('#_apaczka_apm_city').val(record.city);
								$( 'input[id=_apaczka_apm_city]' ).each(
									function (ind, elem) {
										$( elem ).val( point.city );
									}
								);

								// $('#_apaczka_apm_postal_code').val(record.postal_code);
								$( 'input[id=_apaczka_apm_postal_code]' ).each(
									function (ind, elem) {
										$( elem ).val( point.postalCode );
									}
								);

								// $('#_apaczka_apm_country_code').val(record.country_code);
								$( 'input[id=_apaczka_apm_country_code]' ).each(
									function (ind, elem) {
										$( elem ).val( shipping_country );
									}
								);

								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: is_cod_only,
							operatorMarkers: true,
							countryCodes: shipping_country,
							initialAddress: $( '#_apaczka\\[receiver\\]\\[city\\]' ).val(),
							operators: operators,
							codeSearch: true
						}
					);

					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}

				}
			);

		}
	);

	document.addEventListener(
		'click',
		function (e) {
			e          = e || window.event;
			let target = e.target || e.srcElement;

			let api_type = alsendo_order_metabox.api_type;

			if (target.hasAttribute( 'id' ) && 'alsendo_connect_alert_modal_close_button' === target.getAttribute( 'id' ) ) {
				// hide cancel package alert modal.
				$( "#apaczka_alert_modal" ).removeClass( "active" );
			}

			if (target.closest( '#apaczka_calculate_radio' ) ) {
				// orange borders.
				console.log( 'CLOSEST: apaczka_calculate_radio' );
				alsendo_connect_add_border_to_selected_service();
			}

			if ( target.hasAttribute( 'id' ) ) {

				if (target.getAttribute( 'id' ) === 'zaslat_get_order_details') {
					e.preventDefault();
					console.log( 'zaslat_get_order_details' );

					$( '#json-display-alsendo' ).text( '' );
					$( '#json-display-alsendo' ).css( 'display', 'none' );

					let data = {
						action: 'alsendo_connect',
						alsendo_connect_action: 'zaslat_get_order',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						zaslat_id: target.getAttribute( 'data-zaslat-id' )
					};

					console.log( data );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: data,
							beforeSend: function () {
								$( '#zaslat_get_order_details' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
							},
							success: function (response) {
								console.log( "Zaslat get_order_details response:" );
								console.log( response );
								if ( 0 !== response ) {
									if ( 'success' in response && response.success) {
										if ('data' in response && 'data' in response.data) {
											// let order_data = JSON.parse( response.data.data );.

											let formatted_JSON = formatJSON( response.data.data );
											$( '#json-display-alsendo' ).text( formatted_JSON );
											$( '#json-display-alsendo' ).css( 'display', 'block' );

										} else {
											if ('data' in response ) {
												// let order_data = JSON.parse( response.data.data );.

												let formatted_JSON = formatJSON( response.data );
												$( '#json-display-alsendo' ).text( formatted_JSON );
												$( '#json-display-alsendo' ).css( 'display', 'block' );

											}
										}

									} else {
										if ('data' in response && 'error' in response.data) {

											console.log( response.data.error );
											let status_color = '#e03636';
											let message      = '<br>' + alsendo_process_api_response( response.data.error );
											$( '#ecolet_wc_order_id' ).after( '<span id="alsendo_zaslat_get_details_message" style="display:block;margin-top:20px;font-weight:bold;color:' + status_color + '">' + message + '</span>' );
										}

									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Zaslat get details" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( '#zaslat_get_order_details' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);
				}

				if (target.getAttribute( 'id' ) === 'apaczka_geowidget_modal_cross') {
					e.preventDefault();
					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'none';
					}
				}
			}
		},
		false
	);

})( jQuery );