let inpost_intl_current_tab = false;

(function ($) {

	$( document ).ready(
		function ($) {

			const PLUGIN_SLUG = window.inpost_intl.plugin_slug;

			const { __, _x, _n, sprintf } = window.wp.i18n;
			let is_ajax_running           = false;
			const create_order_pickup_log = __( 'You can find additional info in log file:', 'inpost-international' );

			let color_picker_input = $( '#inpost_international_settings_geowidget\\[map_button_color\\]' );
			if ( typeof color_picker_input != 'undefined' && color_picker_input !== null ) {
				$( color_picker_input ).wpColorPicker(
					{
						defaultColor: '#ffc107',
						change: function (event, ui) {
						},
						clear: function () {
						},
						hide: true,
						palettes: true
					}
				);
				// Initiate alternative Color Picker.
				// $( color_picker_input ).iris();
			}

			// add logo on settings page.
			let logo = '<img class="inpost_icon" src="' + inpost_intl.logo_src + '" alt="inpost icon" style="height: 40px;float:left">';
			$( '.nav-tab-wrapper' ).before( logo );

			// work with tabs.
			var activetab = '';
			if ('undefined' != typeof localStorage) {
				activetab = localStorage.getItem( 'activetab' );
			}
			if ('' !== activetab && $( activetab ).length) {
				$( activetab ).fadeIn();
			} else {
				$( '.group:first' ).fadeIn();
			}

			$( '.group .collapsed' ).each(
				function () {
					$( this )
					.find( 'input:checked' )
					.parent()
					.parent()
					.parent()
					.nextAll()
					.each(
						function () {
							if ($( this ).hasClass( 'last' )) {
								$( this ).removeClass( 'hidden' );
								return false;
							}
							$( this )
							.filter( '.hidden' )
							.removeClass( 'hidden' );
						}
					);
				}
			);

			if ('' !== activetab && $( activetab + '-tab' ).length) {
				$( activetab + '-tab' ).addClass( 'nav-tab-active' );
			} else {
				$( '.nav-tab-wrapper a:first' ).addClass( 'nav-tab-active' );
			}
			$( '.nav-tab-wrapper a' ).click(
				function (evt) {
					$( '.nav-tab-wrapper a' ).removeClass( 'nav-tab-active' );
					$( this )
					.addClass( 'nav-tab-active' )
					.blur();
					var clicked_group = $( this ).attr( 'href' );
					if ('undefined' != typeof localStorage) {
						localStorage.setItem( 'activetab', $( this ).attr( 'href' ) );
					}
					$( '.group' ).hide();
					$( clicked_group ).fadeIn();

					let tab_index    = +$( this ).attr( 'data-tab' );
					let tab_slug     = $( this ).attr( 'data-tab-slug' );
					let settings_url = inpost_intl.settings_url;

					let url = new URL( settings_url );

					if ( 1 === tab_index) {
						window.history.pushState( {}, '', url );
					} else {
						url.searchParams.set( 'tab', tab_slug );
						if ( 'products' === tab_slug || 'shipments' === tab_slug ) {
							let nonce = inpost_intl.nonce;
							url.searchParams.set( 'nonce', nonce );
						}
						window.history.pushState( {}, '', url );
					}
					evt.preventDefault();
				}
			);

			// products manage table: search.
			$( '#search-submit' ).on(
				'click',
				function (e) {
					e.preventDefault();
					let search = $( '#search_id-search-input' ).val();
					if ( ! search.length > 0 ) {
						alert( 'No text in search field' );
					}
					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=products';
					var url          = new URL( settings_url );
					let category     = $( '#product_cat' ).val();
					if (category ) {
						params += '&product_cat=' + category;
						url.searchParams.set( 'product_cat', category );
					}

					let product_type = $( '#dropdown_product_type' ).val();

					if ( product_type ) {
						params += '&product_type=' + product_type;
						url.searchParams.set( 'product_type', product_type );
					}

					let product_qty = $( '#dropdown_product_qty' ).val();
					if ( product_qty ) {
						params += '&per_page=' + product_qty;
						url.searchParams.set( 'per_page', product_qty );
					}

					let shipping_class = $( '#dropdown_shipping_classes' ).val();
					if ( shipping_class ) {
						params += '&product_shipping_class=' + shipping_class;
						url.searchParams.set( 'product_shipping_class', shipping_class );
					}

					if ( search.length > 0 ) {
						params += '&s=' + search;
						url.searchParams.set( 's', search );
					}

					let nonce = inpost_intl.nonce;
					params   += '&nonce=' + nonce;
					url.searchParams.set( 'nonce', nonce );

					// Update the URL and reload the page.
					window.history.pushState( {}, '', url );
					window.location.reload();

				}
			);

			// products manage table: filter.
			$( '#filter_action' ).on(
				'click',
				function (e) {
					e.preventDefault();
					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=products';
					var url          = new URL( settings_url );
					let category     = $( '#product_cat' ).val();
					if ( category ) {
						params += '&product_cat=' + category;
						url.searchParams.set( 'product_cat', category );
					}

					let product_type = $( '#dropdown_product_type' ).val();
					if ( product_type ) {
						params += '&product_type=' + product_type;
						url.searchParams.set( 'product_type', product_type );
					}

					let product_qty = $( '#dropdown_product_qty' ).val();

					if ( product_qty ) {
						params += '&per_page=' + product_qty;
						url.searchParams.set( 'per_page', product_qty );
					}

					let shipping_class = $( '#dropdown_shipping_classes' ).val();
					if ( shipping_class ) {
						params += '&product_shipping_class=' + shipping_class;
						url.searchParams.set( 'product_shipping_class', shipping_class );
					}

					let search = $( '#search_id-search-input' ).val();

					if ( search.length > 0 ) {
						params += '&s=' + search;
						url.searchParams.set( 's', search );
					}

					let nonce = inpost_intl.nonce;
					params   += '&nonce=' + nonce;
					url.searchParams.set( 'nonce', nonce );

					window.history.pushState( {}, '', url );
					window.location.reload();

				}
			);

			// initial connection to API.
			$( '#inpost-intl-connection' ).on(
				'click',
				function (e) {
					e.preventDefault();

					if ( 'disabled' === $( '#inpost-intl-connection' ).attr( 'disabled' ) ) {
						return false;
					}

					let client_id     = $( 'input[id="inpost_international_settings_auth[client_id]"]' ).val();
					let client_secret = $( 'input[id="inpost_international_settings_auth[client_secret]"]' ).val();
					let api_type      = $( 'select[id="inpost_international_settings_auth[api_type]"]' ).val();

					if ( ! $.trim( client_id ) || ! $.trim( client_secret ) ) {
						alert( 'Add credentials' );
						return false;
					}

					$.ajax(
						{
							type: 'POST',
							url: inpost_intl.ajaxurl,
							dataType: 'json',
							data: {
								action: 'inpost_intl_start_connection',
								nonce: $( '#inpost-intl-connection-nonce' ).attr( 'data-id' ),
								client_id: $.trim( client_id ),
								client_secret: $.trim( client_secret ),
								api_type: api_type
							},
							beforeSend: function () {
								$( '#inpost-intl-connection' ).attr( 'disabled', 'disabled' );
								$( '#inpost-intl-connection-preloader' ).addClass( 'show' );
							},
							success: function (response) {
								console.log( "Success response" );
								console.log( response );

								if (response.login_link) {
									// console.log( response.login_link );
									document.location.href = response.login_link;
								}
							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

								let response      = jqXHR.responseText;
								let cleanResponse = inpost_intl_clear_json_response( response );
								try {
									let jsonResponse = JSON.parse( cleanResponse );
									if (jsonResponse.login_link) {
										document.location.href = jsonResponse.login_link;
									}
								} catch (e) {
									console.error( "Error during JSON parse:", e );
								}

							},
							complete: function (response) {
								$( '#inpost-intl-connection' ).prop( 'disabled', false );
								$( '#inpost-intl-connection' ).removeAttr( 'disabled' );

							}
						}
					);

				}
			);

			// Dimensions templates - add, delete.
			$( '#' + PLUGIN_SLUG + '_dmtemplate_add' ).click(
				function (e) {
					e.preventDefault();
					let cloned       = $( '.' + PLUGIN_SLUG + '_dmtemplate-cell-wraper:last' ).clone();
					let cloned_index = $( '.' + PLUGIN_SLUG + '_dmtemplate-cell-wraper:last' ).attr( 'data-index' );

					if ( '0' === cloned_index ) {

					}

					$( '#' + PLUGIN_SLUG + '_dmtemplate-cell' ).append( cloned );

					let last_row_index = +$( '.' + PLUGIN_SLUG + '_dmtemplate-cell-wraper:last' ).attr( 'data-index' );
					last_row_index++;

					let selected_radio_name = 'inpost_international_settings_sending[templates][' + last_row_index + '][selected]';

					$( cloned ).find( 'input' ).each(
						function (index, input) {
							if ( '0' === cloned_index ) {
								$( input ).prop( 'disabled', false );
							}
							let cell = $( input ).attr( 'data-id' );
							if ( typeof cell != 'undefined' && cell !== null ) {
								if ('selected' === cell) {
									$( input ).val( last_row_index );
									let selected_radio_name = 'inpost_international_settings_sending[templates][' + last_row_index + '][selected]';
									$( input ).attr( 'name', selected_radio_name );
								} else {
									let new_name_attr = 'inpost_international_settings_sending[templates][' + last_row_index + '][' + cell + ']'
									$( input ).attr( 'name', new_name_attr );
								}

							}
						}
					);

					$( '.' + PLUGIN_SLUG + '_dmtemplate_selected' ).each(
						function (index, radio) {
							$( this ).val( index );
							$( this ).attr( 'name', selected_radio_name );
							if ( index === last_row_index ) {
								$( radio ).prop( 'checked', true );
							} else {
								$( radio ).prop( 'checked', false );
							}
						}
					);

					$( '.' + PLUGIN_SLUG + '_dmtemplate-cell-wraper' ).each(
						function (index, obj) {
							$( this ).attr( 'data-index', index );
						}
					);

					/*$( '.' + PLUGIN_SLUG + '_dmtemplate_selected' ).each(
						function (index, obj) {
							$( this ).val( index );
							$( this ).attr( 'name', selected_radio_name );
						}
					);*/

				}
			);

			// dispatch points - add, delete.
			$( '#' + PLUGIN_SLUG + '_dpoint_add' ).click(
				function (e) {
					e.preventDefault();
					let cloned = $( '.' + PLUGIN_SLUG + '_dpoint-cell-wraper:last' ).clone();
					$( '#' + PLUGIN_SLUG + '_dpoint-cell' ).append( cloned );
					/*$( '.inpost_international_settings_dispatch_points_dpoint_selected' ).each(
						function (index, radio) {
							$( radio ).attr( 'name', '' );
						}
					);*/
					let last_row_index = +$( '.' + PLUGIN_SLUG + '_dpoint-cell-wraper:last' ).attr( 'data-index' );
					last_row_index++;

					let selected_radio_name = 'inpost_international_settings_dispatch_points[points][' + last_row_index + '][selected]';

					$( cloned ).find( 'input' ).each(
						function (index, input) {
							let cell = $( input ).attr( 'data-id' );
							if ( typeof cell != 'undefined' && cell !== null ) {
								if ('selected' === cell) {
									$( input ).val( last_row_index );
									let selected_radio_name = 'inpost_international_settings_dispatch_points[points][' + last_row_index + '][selected]';
									$( input ).attr( 'name', selected_radio_name );
								} else {
									let new_name_attr = 'inpost_international_settings_dispatch_points[points][' + last_row_index + '][' + cell + ']'
									$( input ).attr( 'name', new_name_attr );
								}

							}
						}
					);

					$( '.' + PLUGIN_SLUG + '_dpoint_selected' ).each(
						function (index, radio) {
							$( this ).val( index );
							$( this ).attr( 'name', selected_radio_name );
							if ( index === last_row_index ) {
								$( radio ).prop( 'checked', true );
							} else {
								$( radio ).prop( 'checked', false );
							}
						}
					);

					$( '.' + PLUGIN_SLUG + '_dpoint-cell-wraper' ).each(
						function (index, obj) {
							$( this ).attr( 'data-index', index );
						}
					);

					/*$( '.' + PLUGIN_SLUG + '_dpoint_selected' ).each(
						function (index, obj) {
							$( this ).val( index );
							$( this ).attr( 'name', selected_radio_name );
						}
					);*/

				}
			);

			$( document ).on(
				'click',
				'.inpost-intl-update-reload',
				function (e) {
					e.preventDefault();
					location.reload();
				}
			);

			$( document ).on(
				'click',
				'.inpost-intl-update-single-product',
				function (e) {
					e.preventDefault();
					let product_id    = $( this ).attr( 'data-product-id' );
					let preloader     = $( 'img[data-id="' + product_id + '"]' );
					let action_result = $( 'span[data-action-id="' + product_id + '"]' );
					$( action_result ).hide();
					$( action_result ).addClass( 'status_hidden' );
					$( action_result ).css( 'display', 'none' );

					let collect_data = {};

					let rows = $( 'ul[class="inpost_intl_allowed_methods_' + product_id + '"]' );
					rows.each(
						function (i, elem) {
							let product_template = $( 'select[name^="inpost_intl_templates_' + product_id + '"]' ).val();
							collect_data[i]      = { allowed_methods: [], product_id: product_id, template: product_template };
							$( preloader ).show();
							$( preloader ).removeClass( 'preloader_hidden' );
							$( preloader ).css( 'display', 'block' );
							let checkboxes = $( elem ).find( 'input[id^="inpost_intl_allowed_methods"]' );
							checkboxes.each(
								function (i2, checkbox) {
									if ($( checkbox ).is( ':checked' )) {
										collect_data[i].allowed_methods.push( $( checkbox ).attr( 'data-method' ) );
									}
								}
							);
						}
					);

					if (Object.keys( collect_data ).length === 0) {
						alert( 'Some error with procsessing products' );
					}

					$( this ).prop( 'disabled', 'disabled' );

					$.ajax(
						{
							type: 'POST',
							dataType: 'json',
							url: inpost_intl.ajaxurl,
							data: {
								action: 'inpost_international',
								inpost_intl_action: 'product_table_update_product',
								security: inpost_intl.nonce,
								product_id: product_id,
								product_data: collect_data[0],
								data_key: 0,
								all_data: collect_data
							},
							success: function (response) {
							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( preloader ).hide();
								$( preloader ).addClass( 'preloader_hidden' );
								$( preloader ).css( 'display', 'none' );
								$( action_result ).show();
								$( action_result ).removeClass( 'status_hidden' );
								$( action_result ).css( 'display', 'block' );
								$( 'input[data-product-id="' + product_id + '"]' ).prop( 'disabled', false );
							}
						}
					);
				}
			);

			$( document ).on(
				'click',
				'.inpost-intl-update-product-bulk',
				function (e) {
					e.preventDefault();

					let collect_data = {};

					let rows       = $( 'ul[class^="inpost_intl_allowed_methods_"]' );
					let rows_total = 0;
					rows.each(
						function (i, elem) {
							let product_id           = $( elem ).attr( 'data-product-id' );
							let product_template     = $( 'select[name^="inpost_intl_templates_' + product_id + '"]' ).val();
							collect_data[i]          = { allowed_methods: [], product_id: product_id, template: product_template };
							let preloader            = $( 'img[data-id="' + product_id + '"]' );
							let action_result        = $( 'span[data-action-id="' + product_id + '"]' );
							let single_update_button = $( '.inpost-intl-update-single-product' );
							$( single_update_button ).prop( 'disabled', 'disabled' );
							$( action_result ).css( 'display', 'none' );
							$( action_result ).hide();
							$( action_result ).addClass( 'status_hidden' );
							$( preloader ).show();
							$( preloader ).removeClass( 'preloader_hidden' );
							$( preloader ).css( 'display', 'block' );
							let checkboxes = $( elem ).find( 'input[id^="inpost_intl_allowed_methods"]' );
							checkboxes.each(
								function (i2, checkbox) {
									if ($( checkbox ).is( ':checked' )) {
										collect_data[i].allowed_methods.push( $( checkbox ).attr( 'data-method' ) );
									}
								}
							);
							rows_total++;
						}
					);

					if (Object.keys( collect_data ).length === 0) {
						alert( 'Some error with procsessing products' );
					}

					$( '.inpost-pl-action-status' ).each(
						function (i, elem) {
							$( elem ).hide();
						}
					);

					let bulk_actions_current   = 0;
					let bulk_actions_remainded = 0;
					let bulk_actions_fail      = 0;
					let bulk_actions_success   = 0;

					bulk_actions_remainded = rows_total;
					bulk_process( collect_data );

					function bulk_process(all_rows_data, status = false) {
						let product_to_proccess = all_rows_data[bulk_actions_current];
						bulk_actions_remainded  = bulk_actions_remainded - 1;

						if (bulk_actions_remainded < 0) {
							return bulk_finish();
						}

						$.ajax(
							{
								type: 'POST',
								dataType: 'json',
								url: inpost_intl.ajaxurl,
								data: {
									action: 'inpost_international',
									inpost_intl_action: 'product_table_update_product',
									security: inpost_intl.nonce,
									product_id: product_to_proccess.product_id,
									product_data: product_to_proccess,
									data_key: bulk_actions_current,
									all_data: all_rows_data
								},
								success: function (response) {
									bulk_update( response, true );
									bulk_actions_current = bulk_actions_current + 1;
									bulk_process( response );
								},
								error: function (response) {

									bulk_update( response, false );
									bulk_actions_current = bulk_actions_current + 1;
									bulk_process( response );
								},
								complete: function (response) {

								}
							}
						);
					}

					function bulk_finish() {
						console.log( 'FINISH' );
					}

					function bulk_update(response, success = false) {

						bulk_actions_fail = bulk_actions_fail + 1;

						if (success) {
							bulk_actions_success = bulk_actions_success + 1;
						} else {
							bulk_actions_fail = bulk_actions_fail + 1;
						}

						let product_id = response[bulk_actions_current].product_id;

						let preloader     = $( 'img[data-id="' + product_id + '"]' );
						let action_result = $( 'span[data-action-id="' + product_id + '"]' );
						$( preloader ).hide();
						$( preloader ).addClass( 'preloader_hidden' );
						$( preloader ).css( 'display', 'none' );
						$( action_result ).show();
						$( action_result ).removeClass( 'status_hidden' );
						$( action_result ).css( 'display', 'block' );
						$( 'input[data-product-id="' + product_id + '"]' ).prop( 'disabled', false );

					}

					return false;

				}
			);

			$( document ).on(
				'input',
				'#inpost_international_settings_shipments .pagination-links .current-page',
				function (e) {
					e.preventDefault();

					// Clear any existing timeout.
					if (window.paginationTimeout) {
						clearTimeout( window.paginationTimeout );
					}

					// Get the input value.
					let paged_value = $( this ).val();

					// Set a timeout to wait for user to complete typing.
					window.paginationTimeout = setTimeout(
						function () {
							// Basic validation.
							if (paged_value && ! isNaN( paged_value ) && paged_value > 0) {
								let settings_url = inpost_intl.settings_url + '&tab=shipments';
								var url          = new URL( settings_url );
								url.searchParams.set( 'shipments_paged', paged_value );

								// Update the URL and reload the page.
								window.history.pushState( {}, '', url );

								// Add another small delay before reload.
								setTimeout(
									function () {
										window.location.reload();
									},
									200
								); // 200ms delay before reload.
							}
						},
						1000
					); // delay to wait for user input completion.
				}
			);

			$( '#filter_action_shipments' ).on(
				'click',
				function (e) {
					e.preventDefault();

					let shipmets_qty = $( 'select[id="dropdown_shipment_qty"]' ).val();

					if (isNaN( shipmets_qty )) {
						return;
					}

					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=shipments';
					var url          = new URL( settings_url );

					let send_method = $( 'select[id="shipment_send_type"]' ).val();
					if (send_method) {
						params += '&shipment_send_type=' + send_method;
						url.searchParams.set( 'shipment_send_type', send_method );
					}

					params += '&shipment_qty=' + shipmets_qty;
					url.searchParams.set( 'shipment_qty', shipmets_qty );

					let nonce = inpost_intl.nonce;
					url.searchParams.set( 'nonce', nonce );

					// Update the URL and reload the page.
					window.history.pushState( {}, '', url );
					window.location.reload();

				}
			);

			$( '#inpost_intl_shipment_dispatch_point' ).on(
				'change',
				function (e) {
					e.preventDefault();
					console.log( 'inpost_intl_shipment_dispatch_point CHANGE' );
					let selectedOption     = $( this ).find( 'option:selected' );
					let cutoff_postal_code = selectedOption.attr( 'data-postal-code' );
					console.log( 'cutoff_postal_code' );
					console.log( cutoff_postal_code );
					if (cutoff_postal_code) {
						console.log( 'cutoff_postal_code set new' );
						$( '#inpost_intl_cutoff_postal_code' ).val( cutoff_postal_code );
					}
				}
			);

			function inpost_intl_create_pickup_time_object(day, time_from, time_to) {
				const fromDateTime = day + 'T' + time_from + ':00';
				const toDateTime   = day + 'T' + time_to;

				const fromDate      = new Date( fromDateTime );
				const toDate        = new Date( toDateTime );
				const fromFormatted = fromDate.toISOString();
				const toFormatted   = toDate.toISOString();

				return {
					pickup_time: {
						from: fromFormatted,
						to: toFormatted
					}
				};
			}

			function inpost_intl_debug_print_r(obj) {

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

				function inpost_intl_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 inpost_intl_format_object( obj );
			}

			$( '#inpost_intl_create_pickup_order' ).on(
				'click',
				function (e) {
					e.preventDefault();

					$( '.create_pickup_order_prepre' ).hide();

					let fields = [
						{elem: $( '.inpost_intl_cutoff_date' )},
						{elem: $( '#inpost_intl_cutoff_time_from' )},
						{elem: $( '#inpost_intl_cutoff_time_api' )}
					];

					if (fields.some(
						function (field) {
							return ! field.elem.val().length;
						}
					)) {
						fields.forEach(
							function (field) {
								if ( ! field.elem.val().length) {
									field.elem.css( 'border', '2px solid red' );
									setTimeout(
										function () {
											field.elem.css( 'border', '' );
										},
										2000
									);
								}
							}
						);
						return;
					}

					let day         = $( '.inpost_intl_cutoff_date' ).val();
					let time_from   = $( '#inpost_intl_cutoff_time_from' ).val();
					let time_to     = $( '#inpost_intl_cutoff_time_api' ).val();
					let pickup_time = inpost_intl_create_pickup_time_object( day, time_from, time_to );

					let shipments_table = $( '.inpost-intl-shipments-table' );
					if (shipments_table.length === 0) {
						return;
					}

					let all_rows = shipments_table.find( "th[class='check-column']" ).children( "input[type='checkbox']" );

					let total_shipments = $( '#inpost_intl_pickup_order_parcel_qty' ).val();;
					let total_weight = $( '#inpost_intl_pickup_order_parcel_weight' ).val();
					let index        = 1;

					/*all_rows.each(
						function (i, elem) {
							if ($( elem ).is( ':checked' )) {
								total_shipments++;
								let order_id           = $( elem ).val();
								let order_weight_input = $( 'input.shipment_weight[data-order-id=' + order_id + ']' );

								if ( order_weight_input.length > 0 ) {
									let shipment_weight = +$( order_weight_input ).val();
									total_weight += shipment_weight;
								}
							}
						}
					);*/

					if (total_shipments === 0) {
						alert( 'Nie wybrano żadnych zamówień' );
						return;
					}

					let selected_dpoint = $( '#inpost_intl_shipment_dispatch_point' ).find( 'option:selected' ).val();

					let data = {
						action: 'inpost_international',
						inpost_intl_action: 'create_pickup_order',
						security: inpost_intl.nonce,
						pickup_time: pickup_time,
						total_weight: total_weight,
						total_shipments: total_shipments,
						selected_dpoint: selected_dpoint
					};

					console.log( 'create order_pickup_data' );
					console.log( data );

					$.ajax(
						{
							type: 'POST',
							dataType: 'json',
							url: inpost_intl.ajaxurl,
							data: data,
							beforeSend: function () {
								$( '#inpost_intl_create_pickup_order' ).prop( 'disabled', 'disabled' );
								$( '.inpost_intl_pickup_order_preloader' ).show();
								$( '.maybe_pickup_order_error' ).remove();
								$( '#create_pickup_order_result' ).html( '' );
								$( '#create_pickup_order_result' ).css( 'display', 'none' );
							},
							success: function (response) {
								console.log( response );
								let possible_error = response.data.error;
								if ( typeof possible_error != 'undefined' && possible_error !== null ) {
									let create_pickup_order_result = "<span class='create_pickup_order_result_error' style='font-weight:bold; color:#ff002c'>Error:<br></span>";
									let error_details              = response.data.error_details;
									if ( typeof error_details != 'undefined' && error_details !== null ) {
										create_pickup_order_result += "<span class='create_pickup_order_result_error' style='font-weight:bold; color:#ff002c'>" + error_details + "</span>";
									}
									create_pickup_order_result += "<span class='create_pickup_order_result_error' style='font-weight:bold; color:#000'>" +
										"<br>" + create_order_pickup_log + " inpost-international-create-pickup-order " +
										"</span>";
									$( '#create_pickup_order_result' ).html( create_pickup_order_result );
									$( '#create_pickup_order_result' ).css( 'display', 'inline-block' );
								} else {
									let pickup_order_ref = response.data.carrierReference;
									if ( typeof pickup_order_ref != 'undefined' && pickup_order_ref !== null ) {
										let create_pickup_order_result       = "<span class='create_pickup_order_result_ok' style='font-weight:bold; color:#26be22'>Result:<br></span>";
										let pickup_order_ref_carrier         = pickup_order_ref.carrier;
										let pickup_order_ref_tracking_number = pickup_order_ref.trackingNumber;
										let id                               = response.data.id;
										let time_created                     = response.data.createdTime;
										if ( typeof pickup_order_ref_carrier != 'undefined' && pickup_order_ref_carrier !== null ) {
											create_pickup_order_result += "<span class='create_pickup_order_result_ok' style='font-weight:bold; color:#000'>Przewoźnik: " + pickup_order_ref_carrier + "</span><br>";
										}
										if ( typeof pickup_order_ref_tracking_number != 'undefined' && pickup_order_ref_tracking_number !== null ) {
											create_pickup_order_result += "<span class='create_pickup_order_result_ok' style='font-weight:bold; color:#000'>Numer śledzenia: " + pickup_order_ref_tracking_number + "</span><br>";
										}
										if ( typeof id != 'undefined' && id !== null ) {
											create_pickup_order_result += "<span class='create_pickup_order_result_ok' style='font-weight:bold; color:#000'>ID: " + id + "</span><br>";
										}
										if ( typeof time_created != 'undefined' && time_created !== null ) {
											create_pickup_order_result += "<span class='create_pickup_order_result_ok' style='font-weight:bold; color:#000'>Stworzone: " + inpost_intl_formate_iso_date( time_created ) + "</span><br>";
										}
										create_pickup_order_result += "<span class='create_pickup_order_result_error' style='font-weight:bold; color:#000'>" +
											"<br>" + create_order_pickup_log + " inpost-international-create-pickup-order " +
											"</span>";
										$( '#create_pickup_order_result' ).html( create_pickup_order_result );
										$( '#create_pickup_order_result' ).css( 'display', 'inline-block' );
									}
								}
							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

								let response      = jqXHR.responseText;
								let cleanResponse = inpost_intl_clear_json_response( response );
								try {
									let jsonResponse = JSON.parse( cleanResponse );
									console.error( jsonResponse );
									let data = jsonResponse.data;
									if ( typeof data != 'undefined' && data !== null ) {
										$( '#create_pickup_order_result' ).html( '<pre>' + inpost_intl_debug_print_r( data ) + '</pre>' );
									}
								} catch (e) {
									console.error( "Error during JSON parse:", e );
								}
							},
							complete: function (response) {
								$( '.create_pickup_order_prepre' ).show();
								$( '#inpost_intl_create_pickup_order' ).prop( 'disabled', false );
								$( '.inpost_intl_pickup_order_preloader' ).hide();
							}
						}
					);

				}
			);

			$( '#inpost_intl_cutoff_action' ).on(
				'click',
				function (e) {
					e.preventDefault();

					let cutoff_postal_code = $( '#inpost_intl_cutoff_postal_code' ).val();

					if( ! cutoff_postal_code || 'undefined' == typeof cutoff_postal_code ) {
						alert('No selected postal code');
						return;
					}

					$.ajax(
						{
							type: 'POST',
							dataType: 'json',
							url: inpost_intl.ajaxurl,
							data: {
								action: 'inpost_international',
								inpost_intl_action: 'get_cutoff_pickup_time',
								security: inpost_intl.nonce,
								postal_code: cutoff_postal_code
							},
							beforeSend: function () {
								$( '#inpost_intl_cutoff_action' ).prop( 'disabled', 'disabled' );
								$( '#inpost_intl_cutoff_time_api' ).removeClass( 'deadline' );
								$( '.inpost_intl_cut_off_preloader' ).show();
								$( '.maybe_cutt_off_time_error' ).remove();
							},
							success: function (response) {

								console.log( response );

								let maybe_error = response.error;
								if (  maybe_error ) {
									let error_connection = response.error_connection;
									let error_unknown    = response.error_unknown;
									if ( typeof error_connection != 'undefined' && error_connection !== null ) {
										$( ".inpost-intl-filter-box-shipments-pickup" ).append( '<span class="maybe_cutt_off_time_error" style="color:#f00;"><br><br><br><br>' + error_connection + '</span>' );
									}
								} else {
									let api_cutoff_time = response.data.cutoffTime;
									if ( typeof api_cutoff_time != 'undefined' && api_cutoff_time !== null ) {
										$( '#inpost_intl_cutoff_time_api' ).val( api_cutoff_time );
										$( '#inpost_intl_cutoff_action' ).prop( 'disabled', false );
										$( '#inpost_intl_create_pickup_order' ).prop( 'disabled', false );
										$( '#inpost_intl_cutoff_time_api' ).removeClass( 'empty' );
										$( '#inpost_intl_cutoff_time_api' ).addClass( 'deadline' );
									}
								}
							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

								let response      = jqXHR.responseText;
								let cleanResponse = inpost_intl_clear_json_response( response );
								try {
									let jsonResponse = JSON.parse( cleanResponse );
									console.error( jsonResponse );

									let maybe_error = jsonResponse.error;
									if (  maybe_error ) {
										let error_connection = jsonResponse.error_connection;
										let error_unknown    = jsonResponse.error_unknown;
										if ( typeof error_connection != 'undefined' && error_connection !== null ) {
											$( ".inpost-intl-filter-box-shipments-pickup" ).append( '<span class="maybe_cutt_off_time_error" style="color:#f00;"><br><br><br><br>' + error_connection + '</span>' );
										}
									} else {
										let api_cutoff_time = jsonResponse.data.cutoffTime;
										if ( typeof api_cutoff_time != 'undefined' && api_cutoff_time !== null ) {
											$( '#inpost_intl_cutoff_time_api' ).val( api_cutoff_time );
											$( '#inpost_intl_create_pickup_order' ).prop( 'disabled', false );
											$( '#inpost_intl_cutoff_time_api' ).removeClass( 'empty' );
											$( '#inpost_intl_cutoff_time_api' ).addClass( 'deadline' );
										}
									}

								} catch (e) {
									console.error( "Error during JSON parse:", e );
								}

							},
							complete: function (response) {
								$( '.inpost_intl_cut_off_preloader' ).hide();
								$( '#inpost_intl_cutoff_action' ).prop( 'disabled', false );
							}
						}
					);
				}
			);

			$( '#filter_action_shipments_send_method' ).on(
				'click',
				function (e) {
					e.preventDefault();

					let send_method = $( 'select[id="shipment_send_type"]' ).val();

					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=shipments';
					var url          = new URL( settings_url );

					if (send_method) {
						params += '&shipment_send_type=' + send_method;
						url.searchParams.set( 'shipment_send_type', send_method );
					}

					let shipmets_qty = $( 'select[id="dropdown_shipment_qty"]' ).val();

					if (shipmets_qty && ! isNaN( shipmets_qty )) {
						params += '&shipment_qty=' + shipmets_qty;
						url.searchParams.set( 'shipment_qty', shipmets_qty );
					}

					let nonce = inpost_intl.nonce;
					url.searchParams.set( 'nonce', nonce );

					// Update the URL and reload the page.
					window.history.pushState( {}, '', url );
					window.location.reload();

				}
			);

			$( document ).on(
				'click',
				'#inpost_international_settings_shipments .pagination-links a',
				function (e) {
					e.preventDefault();

					const href      = $( this ).attr( 'href' );
					let paged_value = null;
					let first_page  = null;

					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=shipments';
					var url          = new URL( settings_url );

					let send_method = $( 'select[id="shipment_send_type"]' ).val();

					if (send_method) {
						params += '&shipment_send_type=' + send_method;
						url.searchParams.set( 'shipment_send_type', send_method );
					}

					if (href) {
						const url   = new URL( href );
						paged_value = url.searchParams.get( 'paged' );
						first_page  = $( this ).hasClass( 'first-page' );
					}

					if (first_page) {
						params += '&shipments_paged=' + 1;
						url.searchParams.set( 'shipments_paged', 1 );

					} else if (paged_value) {
						params += '&shipments_paged=' + paged_value;
						url.searchParams.set( 'shipments_paged', paged_value );

					}

					let shipmets_qty = $( 'select[id="dropdown_shipment_qty"]' ).val();

					if (shipmets_qty && ! isNaN( shipmets_qty )) {
						params += '&shipment_qty=' + shipmets_qty;
						url.searchParams.set( 'shipment_qty', shipmets_qty );
					}

					let nonce = inpost_intl.nonce;
					url.searchParams.set( 'nonce', nonce );

					if ( paged_value || first_page ) {
						// Update the URL and reload the page.
						window.history.pushState( {}, '', url );
						window.location.reload();
					}
				}
			);

			const $searchInputs = $( '.inpost-intl-shipm-search-input' );

			// Check on document ready.
			$searchInputs.each(
				function () {
					if ($( this ).val()) {
						inpost_intl_disable_other_inputs( $( this ) );
						return false; // Exit loop if we found an input with value.
					}
				}
			);

			// Handle input events.
			$searchInputs.on(
				'input',
				function () {
					const $currentInput = $( this );

					if ($currentInput.val()) {
						inpost_intl_disable_other_inputs( $currentInput );
					} else {
						inpost_intl_enable_all_inputs();
					}
				}
			);

			function inpost_intl_disable_other_inputs($activeInput) {
				$searchInputs.not( $activeInput ).prop( 'disabled', true );
			}

			function inpost_intl_enable_all_inputs() {
				$searchInputs.prop( 'disabled', false );
			}

			$( document ).on(
				'click',
				'#inpost-intl-search-shipments-reset',
				function (e) {
					e.preventDefault();
					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=shipments';
					var url          = new URL( settings_url );
					let shipmets_qty = $( 'select[id="dropdown_shipment_qty"]' ).val();
					if (shipmets_qty && ! isNaN( shipmets_qty )) {
						params += '&shipment_qty=' + shipmets_qty;
						url.searchParams.set( 'shipment_qty', shipmets_qty );
					}

					let nonce = inpost_intl.nonce;
					params   += '&nonce=' + nonce;
					url.searchParams.set( 'nonce', nonce );

					window.history.pushState( {}, '', url );
					window.location.reload();
				}
			);

			$( document ).on(
				'click',
				'#inpost-intl-search-shipments-submit',
				function (e) {
					e.preventDefault();

					let tracking  = $( '#inpost-intl-search-tracking' ).val();
					let order     = $( '#inpost-intl-search-order' ).val();
					let phone     = $( '#inpost-intl-search-phone' ).val();
					let email     = $( '#inpost-intl-search-email' ).val();
					let reference = $( '#inpost-intl-search-email' ).val();

					console.log( 'tracking: ' + tracking );
					console.log( 'order: ' + order );
					console.log( 'phone: ' + phone );
					console.log( 'email: ' + email );
					console.log( 'reference: ' + reference );

					let params       = '';
					let settings_url = inpost_intl.settings_url + '&tab=shipments';
					var url          = new URL( settings_url );

					if (tracking) {
						params += '&search_tracking=' + tracking;
						url.searchParams.set( 'search_tracking', tracking );
					} else if (order) {
						params += '&search_order=' + order;
						url.searchParams.set( 'search_order', order );
					} else if (phone) {
						params += '&search_phone=' + phone;
						url.searchParams.set( 'search_phone', phone );
					} else if (email) {
						params += '&search_email=' + email;
						url.searchParams.set( 'search_email', email );
					}

					let nonce = inpost_intl.nonce;
					params   += '&nonce=' + nonce;
					url.searchParams.set( 'nonce', nonce );

					if ( tracking || order || phone || email || reference ) {
						// Update the URL and reload the page.
						window.history.pushState( {}, '', url );
						window.location.reload();
					}

				}
			);

			document.addEventListener(
				'change',
				function (e) {
					e          = e || window.event;
					var target = e.target || e.srcElement;
					if ( target.classList.contains( PLUGIN_SLUG + '_dpoint_selected' ) ) {
						if ( target.checked ) {

							$( '.' + PLUGIN_SLUG + '_dpoint_selected' ).each(
								function (index, radio) {
									let i = index.toString();
									if ( i === target.value ) {
										$( radio ).prop( 'checked', true );
									}
									$( radio ).attr( 'name', 'inpost_international_settings_dispatch_points[points][' + target.value + '][selected]' );
								}
							);
						}
					}

					if ( target.classList.contains( PLUGIN_SLUG + '_dmtemplate_selected' ) ) {
						if ( target.checked ) {
							$( '.' + PLUGIN_SLUG + '_dmtemplate_selected' ).each(
								function (index, radio) {
									let i = index.toString();
									if ( i === target.value ) {
										$( radio ).prop( 'checked', true );
									}
									$( radio ).attr( 'name', 'inpost_international_settings_sending[templates][' + target.value + '][selected]' );
								}
							);
						}
					}

					// toggle switch checkboxes.
					if ( target.classList.contains( 'inpost-intl-switch-checkbox' ) ) {

						let switch_id    = target.getAttribute( 'data-id' );
						let hidden_input = $( 'input[id=' + switch_id + ']' );
						if ( typeof hidden_input != 'undefined' && hidden_input !== null ) {
							if (target.checked) {
								$( hidden_input ).val( 1 );
							} else {
								$( hidden_input ).val( '' );
							}
						}
					}

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_allow_all') {

						let allow_all = 0;
						if (target.checked) {
							allow_all = 1;
						}
						$.ajax(
							{
								type: 'POST',
								url: inpost_intl.ajaxurl,
								dataType: 'json',
								data: {
									action: 'inpost_international',
									inpost_intl_action: 'inpost_intl_allow_all',
									security: inpost_intl.nonce,
									allow_all: allow_all
								},
								beforeSend: function () {
									$( '#inpost_intl_allow_all' ).attr( 'disabled', 'disabled' );
									$( '#inpost-intl-allow-all-preloader' ).css( 'display', 'inline-block' );
									$( '.allow-all' ).css( 'display', 'none' );
								},
								success: function (response) {
									console.log( response );

								},
								error: function (jqXHR, textStatus, errorThrown) {
									console.log( "Error response" );
									console.log( textStatus );
									console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

									let response      = jqXHR.responseText;
									let cleanResponse = inpost_intl_clear_json_response( response );
									try {
										let jsonResponse = JSON.parse( cleanResponse );
										console.error( jsonResponse );
									} catch (e) {
										console.error( "Error during JSON parse:", e );
									}

								},
								complete: function (response) {
									$( '#inpost_intl_allow_all' ).prop( 'disabled', false );
									$( '#inpost-intl-allow-all-preloader' ).css( 'display', 'none' );
									$( '.allow-all' ).css( 'display', 'inline-block' );

								}
							}
						);
					}

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'enabled_only_for_admins') {
						let enabled = 0;
						if (target.checked) {
							enabled = 1;
						}

						$.ajax(
							{
								type: 'POST',
								url: inpost_intl.ajaxurl,
								dataType: 'json',
								data: {
									action: 'inpost_international',
									inpost_intl_action: 'inpost_intl_enabled_only_for_admins',
									security: inpost_intl.nonce,
									enabled: enabled
								},
								beforeSend: function () {
									$( '#enabled_only_for_admins' ).attr( 'disabled', 'disabled' );
									$( '#inpost-intl-enabled-only-for-admins-preloader' ).css( 'display', 'inline-block' );
									$( '.enabled-only-for-admins' ).css( 'display', 'none' );
								},
								success: function (response) {

								},
								error: function (jqXHR, textStatus, errorThrown) {
									console.log( "Error response" );
									console.log( textStatus );
									console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

									let response      = jqXHR.responseText;
									let cleanResponse = inpost_intl_clear_json_response( response );
									try {
										let jsonResponse = JSON.parse( cleanResponse );
										console.error( jsonResponse );
									} catch (e) {
										console.error( "Error during JSON parse:", e );
									}

								},
								complete: function (response) {
									$( '#enabled_only_for_admins' ).prop( 'disabled', false );
									$( '#inpost-intl-enabled-only-for-admins-preloader' ).css( 'display', 'none' );
									$( '.enabled-only-for-admins' ).css( 'display', 'inline-block' );

								}
							}
						);
					}

					if (target.hasAttribute( 'name' ) && target.getAttribute( 'name' ) === 'inpost_intl_templates') {
						let select_value      = target.value;
						let all_templ_selects = $( 'select[name^="inpost_intl_templates_"]' );
						all_templ_selects.each(
							function (i, elem) {
								$( elem ).val( select_value );
							}
						);
					}

					if ( target.classList.contains( 'inpost_intl_rule_checkbox' ) ) {
						let id = target.getAttribute( 'id' );

						let rows       = $( 'ul[class^="inpost_intl_allowed_methods_"]' );
						let rows_total = 0;
						rows.each(
							function (i, elem) {
								let same_checkboxes = $( elem ).find( 'input[data-method="' + id + '"]' );
								same_checkboxes.each(
									function (i2, checkbox) {
										if (target.checked) {
											$( checkbox ).prop( 'checked', true );
										} else {
											$( checkbox ).prop( 'checked', false );
										}
									}
								);
								rows_total++;
							}
						);

					}

					if ( target.classList.contains( 'inpost_intl_check_row' ) ) {
						let product_id     = target.value;
						let row_checkboxes = $( 'input[id^="inpost_intl_allowed_methods[' + product_id + ']"]' );
						if ( target.checked ) {
							if ( row_checkboxes ) {
								$( row_checkboxes ).each(
									function (i, elem) {
										$( elem ).prop( 'checked', true );
									}
								);
							}
						} else {
							if ( row_checkboxes ) {
								$( row_checkboxes ).each(
									function (i, elem) {
										$( elem ).prop( 'checked', false );
									}
								);
							}
						}
					}

				},
				false
			);

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

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_status_modal_close_button') {
						e.preventDefault();
						$( '#inpost_intl_status_modal' ).removeClass( 'active' );
					}

					if ( target.classList.contains( PLUGIN_SLUG + '_dpoint-remove' ) ) {
						let points = $( '.' + PLUGIN_SLUG + '_dpoint_selected' );
						console.log( points );
						console.log( points.length );
						if ( points.length > 1 ) {
							target.parentNode.parentNode.parentNode.removeChild( target.parentNode.parentNode );
							$( '.' + PLUGIN_SLUG + '_dpoint_selected' ).each(
								function (index, obj) {
									$( this ).val( index );
								}
							);
							$( '.' + PLUGIN_SLUG + '_dpoint-cell-wraper' ).each(
								function (index, obj) {
									$( this ).attr( 'data-index', index );
								}
							);
						}

					}

					if ( target.classList.contains( PLUGIN_SLUG + '_dmtemplate-remove' ) ) {
						let points = $( '.' + PLUGIN_SLUG + '_dmtemplate_selected' );
						//console.log( points );
						console.log( points.length );

						if ( points.length > 1 ) {
							target.parentNode.parentNode.parentNode.removeChild( target.parentNode.parentNode );
							let selected_template = 0;
							$( '.' + PLUGIN_SLUG + '_dmtemplate_selected' ).each(
								function (index, obj) {
									$( this ).val( index );
									// $( this ).attr( 'name', selected_radio_name );
									if ($( obj ).is( ':checked' )) {
										console.log( 'index of checked: ' +  index );
										selected_template = index;
									}
								}
							);

							$( '.' + PLUGIN_SLUG + '_dmtemplate-cell-wraper' ).each(
								function (index, obj) {
									$( this ).attr( 'data-index', index );
								}
							);
						}

					}

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost-intl-disconnect') {
						e.preventDefault();
						console.log( 'inpost-intl-disconnect' );

						$.ajax(
							{
								type: 'POST',
								url: inpost_intl.ajaxurl,
								dataType: 'json',
								data: {
									action: 'inpost_international',
									inpost_intl_action: 'inpost_intl_disconnect',
									security: inpost_intl.nonce
								},
								beforeSend: function () {
									$( '#inpost-intl-disconnect' ).attr( 'disabled', 'disabled' );
									$( '#inpost-intl-disconnection-preloader' ).addClass( 'show' );
								},
								success: function (response) {
								},
								error: function (jqXHR, textStatus, errorThrown) {
									console.log( "Error response" );
									console.log( textStatus );
									console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
								},
								complete: function (response) {
									window.location.reload();
								}
							}
						);
					}

					if ( target.classList.contains( 'inpost-intl-btn-shipment-action' ) ) {
						e.preventDefault();
						let order_id = target.getAttribute( 'data-id' );
						let uuid     = target.getAttribute( 'data-uuid' );
						if (typeof uuid != 'undefined' && uuid !== null) {
							let row_selector = 'inpost-int-shipment-' + order_id;

							let data                 = {
								action: 'inpost_international',
								inpost_intl_action: 'inpost_international_get_label',
								security: inpost_intl.nonce,
								order_id: order_id,
								uuid: uuid,
							};
							let woo_logs_section_url = ' <a target="blank_" href="' + inpost_intl.log_path + '">here</a>';
							if ( is_ajax_running ) {
								return;
							}

							$.ajax(
								{
									type: 'POST',
									dataType: 'json',
									url: inpost_intl.ajaxurl,
									data: data,
									beforeSend: function (jqXHR) {
										jqXHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' );

										$( '.inpost_intl_shipment_list_status_error' ).find( 'span' ).each(
											function (i) {
												$( this ).remove();
											}
										);

										is_ajax_running = true;
										$( 'span.inpost_intl_shipment_list_preloader[data-id="' + order_id + '"]' ).css( 'display', 'block' );

										$( 'tr[id="' + row_selector + '"]' ).css(
											{
												'opacity': '0.6',
												'cursor': 'wait'
											}
										);
									},
									success: function (response) {
										console.log( response );

										if (response.pdf) {

											let filename = 'inpost_int_zamowenie_' + order_id + '.pdf';

											// Decode the base64 string.
											let binaryString = window.atob( response.pdf );
											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 );

										} else if (response.error) {
											let error = '';
											if (response.error_connection) {
												error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
													"Error:<br> " + response.error_connection + "</span>";
											} else if (response.error_details) {
												// Handle error.
												error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
													"Error:<br> " + response.error_details + "<br>" +
													"Or check log file for order #" + order_id + woo_logs_section_url + "</span>";
											} else {
												// Unexpected JSON response.
												error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
													"Error:<br> Unexpected response from server.<br>Check log file for order #" + order_id + woo_logs_section_url + "</span>";
											}

											$( '.inpost_intl_shipment_list_status_error[data-id="' + order_id + '"]' ).append( error );
										} else {
											let unknown_response = process_unknown_variable( response );
											error                = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
												"Error:<br> " + unknown_response + ".<br>Check log file for order #" + order_id + woo_logs_section_url + "</span>";
											$( '.inpost_intl_order_list_status_error[data-id="' + order_id + '"]' ).append( error );
										}

									},
									error: function (jqXHR, textStatus, errorThrown) {

										let response = jqXHR.responseText;
										console.log( 'ERR response:' );
										console.log( response );
										let cleanResponse = response.replace( /<!--[\s\S]*?-->/g, '' );
										try {
											let jsonResponse = JSON.parse( cleanResponse );
											if (jsonResponse.pdf) {
												console.log( 'Error, but - yes, PDF' );
												// console.log(jsonResponse.pdf);
												let filename = 'inpost_int_zamowenie_' + order_id + '.pdf';

												// Decode the base64 string.
												let binaryString = window.atob( jsonResponse.pdf );
												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 );
											}

										} catch (e) {
											console.error( "Error during JSON parse:", e );

											let color = "#e03636";
											let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color: " + color + "'>Error:<br> " + errorThrown + ', ' + e + ' ' + jqXHR.responseText + "</span>";
											$( '.inpost_intl_shipment_list_status_error[data-id="' + order_id + '"]' ).append( error );
											console.log( "error response" );
											console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

										}

									},
									complete: function (response) {
										console.log( "complete response" );
										$( 'tr[id="' + row_selector + '"]' ).css( {'opacity': '1', 'cursor': 'unset'} );
										$( '.inpost_intl_shipment_list_preloader' ).each(
											function (i) {
												$( this ).css( 'display', 'none' );
											}
										);
										is_ajax_running = false;
									}
								}
							);
						}
					}

					if ( target.classList.contains( 'inpost-intl-btn-status-action' ) ) {
						e.preventDefault();
						const warning = __( 'No tracking number found fot this shipment', 'inpost-international' );
						let order_id  = target.getAttribute( 'data-id' );

						let tracking_number = target.getAttribute( 'data-tracking' );

						let data = {
							action: 'inpost_international',
							inpost_intl_action: 'inpost_international_get_status',
							security: inpost_intl.nonce,
							tracking_number: tracking_number,
							order_id: order_id,
						};

						if ( ! tracking_number ) {
							alert( warning );
							return;
						}

						if ( is_ajax_running ) {
							return;
						}

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

							let row_selector = 'inpost-int-shipment-' + order_id;

							$.ajax(
								{
									type: 'POST',
									dataType: 'json',
									url: inpost_intl.ajaxurl,
									data: data,
									beforeSend: function (jqXHR) {
										is_ajax_running = true;
										jqXHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' );

										$( '.inpost_intl_shipment_list_status_error' ).find( 'span' ).each(
											function (i) {
												$( this ).remove();
											}
										);
										$( 'span.inpost_intl_shipment_list_preloader[data-id="' + order_id + '"]' ).css( 'display', 'block' );
										$( 'tr[id="' + row_selector + '"]' ).css(
											{
												'opacity': '0.6',
												'cursor': 'wait'
											}
										);
									},
									success: function (response) {
										console.log( response );

										let woo_logs_section_url = ' <a target="blank_" href="' + inpost_intl.log_path + '">here</a>';

										const tracking_data = response[0];
										if (typeof tracking_data != 'undefined' && tracking_data !== null) {
											let events = tracking_data.events;
											console.log( events );
											if (typeof events != 'undefined' && events !== null) {
												let modal_header    = '';
												let modal_subheader = '';

												const events_html = inpost_intl_process_events( events );

												const destination = tracking_data.destination;
												if (typeof destination != 'undefined' && destination !== null) {
													modal_header    = destination.locationType + ' ' + destination.name;
													modal_subheader = [
														destination.countryCode,
														destination.postalCode,
														destination.province,
														destination.city,
														destination.street,
														destination.building,
														destination.flat
													].filter( Boolean ).join( ', ' );
												}

												$( '.inpost_intl_temp_data' ).each(
													function (i) {
														$( this ).remove();
													}
												);
												$( '.inpost_intl_status_modal_text' ).html( events_html );
												$( '.inpost_intl_status_modal_tracking' ).text( tracking_number );
												$( '.inpost_intl_status_modal_title' ).append( '<h3 class="inpost_intl_temp_data">' + modal_header + '</h3>' );
												$( '.inpost_intl_status_modal_title' ).append( '<h4 class="inpost_intl_temp_data">' + modal_subheader + '</h4>' );
												$( '#inpost_intl_status_modal' ).addClass( 'active' );
												console.log( 'inpost_intl_status_modal' );

											}

										} else {
											if (response.error) {
												let error = '';
												if (response.error_connection) {
													error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
														"Error:<br> " + response.error_connection + "</span>";
												} else if (response.error_details) {
													// Handle error.
													error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
														"Error:<br> " + response.error_details + "<br>" +
														"Or check log file for order #" + order_id + woo_logs_section_url + "</span>";
												} else {
													// Unexpected JSON response.
													error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
														"Error:<br> Unexpected response from server.<br>Check log file for order #" + order_id + woo_logs_section_url + "</span>";
												}

												$( '.inpost_intl_shipment_list_status_error[data-id="' + order_id + '"]' ).append( error );
											}
										}

									},
									error: function (jqXHR, textStatus, errorThrown) {
										let response = jqXHR.responseText;
										console.error( "Error response:" );
										console.error( response );

										let woo_logs_section_url = ' <a target="blank_" href="' + inpost_intl.log_path + '">here</a>';

										let cleanResponse = response.replace( /<!--[\s\S]*?-->/g, '' );
										try {
											let jsonResponse = JSON.parse( cleanResponse );

											if (jsonResponse.error) {
												let error = '';
												if (jsonResponse.error_connection) {
													error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
														"Error:<br> " + jsonResponse.error_connection + "</span>";
												} else if (jsonResponse.error_details) {
													// Handle error.
													error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
														"Error:<br> " + jsonResponse.error_details + "<br>" +
														"Or check log file for order #" + order_id + woo_logs_section_url + "</span>";
												} else {
													// Unexpected JSON response.
													error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
														"Error:<br> Unexpected response from server.<br>Check log file for order #" + order_id + woo_logs_section_url + "</span>";
												}

												$( '.inpost_intl_order_list_status_error[data-id="' + order_id + '"]' ).append( error );
											} else {

												let tracking_data = jsonResponse[0];
												if (typeof tracking_data != 'undefined' && tracking_data !== null) {
													let events = tracking_data.events;
													if (typeof events != 'undefined' && events !== null) {
														let modal_header    = '';
														let modal_subheader = '';

														const events_html = inpost_intl_process_events( events );

														const destination = tracking_data.destination;
														if (typeof destination != 'undefined' && destination !== null) {
															modal_header    = destination.locationType + ' ' + destination.name;
															modal_subheader = [
																destination.countryCode,
																destination.postalCode,
																destination.province,
																destination.city,
																destination.street,
																destination.building,
																destination.flat
															].filter( Boolean ).join( ', ' );
														}

														$( '.inpost_intl_temp_data' ).each(
															function (i) {
																$( this ).remove();
															}
														)
														$( '.inpost_intl_status_modal_text' ).html( events_html );
														$( '.inpost_intl_status_modal_tracking' ).text( tracking_number );
														$( '.inpost_intl_status_modal_title' ).append( '<h3 class="inpost_intl_temp_data">' + modal_header + '</h3>' );
														$( '.inpost_intl_status_modal_title' ).append( '<h4 class="inpost_intl_temp_data">' + modal_subheader + '</h4>' );
														$( '#inpost_intl_status_modal' ).addClass( 'active' );

													}
												}
											}

										} catch (e) {
											console.error( "Error during JSON parse:", e );

											let color = "#e03636";
											let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color: " + color + "'>Error:<br> " + errorThrown + ', ' + e + ' ' + jqXHR.responseText + "</span>";
											$( '.inpost_intl_order_list_status_error[data-id="' + order_id + '"]' ).append( error );
											console.log( "error response" );
											console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

										}
									},
									complete: function (response) {
										$( 'tr[id="' + row_selector + '"]' ).css( {'opacity': '1', 'cursor': 'unset'} );
										$( '.inpost_intl_shipment_list_preloader' ).each(
											function (i) {
												$( this ).css( 'display', 'none' );
											}
										);
										is_ajax_running = false;
									}
								}
							);

						}
					}

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_shipments_labels_bulk') {
						e.preventDefault();
						let selected_data = inpost_intl_shipment_table_processing();
						if (typeof selected_data != 'undefined' && selected_data !== null) {
							if (Object.keys( selected_data.orders ).length) {
								let validate_orders  = selected_data.orders;
								let validated_orders = {};

								let index = 1;
								$.each(
									validate_orders,
									function (i, order_id) {

										let order_row_selector = '#inpost-int-shipment-' + order_id;
										let order_row          = $( order_row_selector );

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

											let action = $( order_row ).find( '#inpost_intl_uuid' );
											if (typeof action != 'undefined' && action !== null ) {

												let uuid = $( action ).attr( 'data-uuid' )
												if (typeof uuid != 'undefined' && uuid !== null && uuid.length > 0) {
													let data                = {};
													data['order_id']        = order_id;
													data['uuid']            = uuid;
													validated_orders[index] = data;
													index++;

												} else {
													$( 'tr[id="' + order_row_selector + '"]' ).css(
														{
															'opacity': '1',
															'cursor': 'unset'
														}
													);
												}
											}
										}
									}
								);

								let count = index - 1;

								inpost_process_shipment_table_labels_bulk( validated_orders, 1, count );
							}
						}
					}
				},
				false
			);

			const sender_phone_input      = document.getElementById( 'inpost_international_settings_merchant[phone]' );
			let prefix                    = '+48 ';
			let merchant_country          = 'PL';
			let merchant_country_selector = document.getElementById( 'inpost_international_settings_merchant[country]' );
			if ( typeof merchant_country_selector != 'undefined' && merchant_country_selector !== null ) {
				merchant_country = merchant_country_selector.value;
				if ('IT' === merchant_country) {
					prefix = '+39 ';
				}

				merchant_country_selector.addEventListener(
					'change',
					function () {
						if ( typeof sender_phone_input != 'undefined' && sender_phone_input !== null ) {
							sender_phone_input.value = '';
							if (this.value === 'IT') {
								prefix = '+39 ';
							}
							if (this.value === 'PL') {
								prefix = '+48 ';
							}
						}
					}
				);

			}

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

				sender_phone_input.addEventListener(
					'input',
					function (e) {
						let cursor_position           = this.selectionStart;
						let old_value                 = this.value;
						let new_value                 = '';
						let merchant_country_selector = document.getElementById( 'inpost_international_settings_merchant[country]' );
						if ( typeof merchant_country_selector != 'undefined' && merchant_country_selector !== null ) {
							merchant_country = merchant_country_selector.value;
						}
						if ('PL' === merchant_country) {
							prefix    = '+48 ';
							new_value = inpost_intl_format_phone_number_pl( old_value, prefix );
						}
						if ('IT' === merchant_country) {
							prefix    = '+39 ';
							new_value = inpost_intl_format_phone_number_it( old_value, prefix );
						}

						// Only update if the new value is different.
						if (new_value !== old_value) {
							this.value = new_value;
							if ( cursor_position ) {
								// Adjust cursor position.
								if (cursor_position < prefix.length) {
									cursor_position = prefix.length;
								} else if (new_value.charAt( cursor_position - 1 ) === '-') {
									cursor_position++;
								}
								this.setSelectionRange( cursor_position, cursor_position );
							}
						}
					}
				);

				function inpost_intl_format_phone_number_pl(value, prefix ) {
					if (value.length < prefix.length) {
						return prefix;
					}
					let number           = value.slice( prefix.length ).replace( /\D/g, '' );
					let formatted_number = '';
					for (let i = 0; i < number.length && i < 9; i++) {
						if (i === 3 || i === 6) {
							formatted_number += '-';
						}
						formatted_number += number[i];
					}
					return prefix + formatted_number;
				}

				function inpost_intl_format_phone_number_it(value, prefix) {
					if (value.length < prefix.length) {
						return prefix;
					}

					let number           = value.slice( prefix.length ).replace( /\D/g, '' );
					let formatted_number = '';

					// Allow up to 10 digits for Italy (changed from i < 9 to i < 10)
					for (let i = 0; i < number.length && i < 10; i++) {
						if (i === 3 || i === 6) {
							formatted_number += '-';
						}
						formatted_number += number[i];
					}

					return prefix + formatted_number;
				}

				sender_phone_input.addEventListener(
					'focus',
					function () {
						if ( ! this.value) {
							this.value = prefix;
						}
					}
				);

				sender_phone_input.addEventListener(
					'blur',
					function () {
						if (this.value === prefix) {
							this.value = '';
						}
					}
				);

				const inputs      = document.querySelectorAll( '.inpost_intl_validated_input' );
				const tooltip     = document.createElement( 'div' );
				tooltip.className = 'inpost-intl-tooltip';
				document.body.appendChild( tooltip );
				if (typeof inputs != 'undefined' && inputs !== null) {
					let validationTimeout;
					inputs.forEach(
						function (input) {
							input.addEventListener(
								'input',
								function (e) {
									clearTimeout( validationTimeout );  // Clear any existing timeout.

									validationTimeout = setTimeout(
										function () {
											const value = parseFloat( this.value );
											const min   = parseFloat( this.min );
											const max   = parseFloat( this.max );
											const step  = parseFloat( this.step ) || 1;

											if (isNaN( value )) {
												inpost_intl_hide_tooltip( this );
												return;
											}
											// Exit if the input is not a number.

											if (value < min) {
												inpost_intl_show_tooltip( this, 'Min value ' + min + ' is allowed only' );
												this.value = min;
											} else if (value > max) {
												inpost_intl_show_tooltip( this, 'Max value ' + max + ' is allowed only' );
												this.value = max;
											} else {
												inpost_intl_hide_tooltip( this );
												// Round to nearest step.
												const roundedValue = Math.round( value / step ) * step;
												if (roundedValue !== value) {
													this.value = roundedValue.toFixed( inpost_intl_get_decimal_places( step ) );
												}
											}
										},
										1500
									);
								}
							);
						}
					);
				}
			}

			function inpost_intl_get_decimal_places(num) {
				if (Math.floor( num ) === num) {
					return 0;
				}
				return num.toString().split( "." )[1].length || 0;
			}

			function inpost_intl_show_tooltip(input, message) {
				// Remove any existing tooltip.
				let parent = input.parentNode;
				if (typeof parent != 'undefined' && parent !== null) {
					const existingTooltip = parent.querySelector( '.inpost-intl-tooltip' );
					if (existingTooltip) {
						existingTooltip.remove();
					}
				}

				// Create new tooltip.
				const tooltip       = document.createElement( 'div' );
				tooltip.className   = 'inpost-intl-tooltip';
				tooltip.textContent = message;

				// Style the tooltip.
				tooltip.style.position        = 'absolute';
				tooltip.style.backgroundColor = '#FCC905';
				tooltip.style.color           = '#fff';
				tooltip.style.padding         = '5px 10px';
				tooltip.style.borderRadius    = '4px';
				tooltip.style.fontSize        = '14px';
				tooltip.style.zIndex          = '1000';
				tooltip.style.whiteSpace      = 'nowrap';

				// Position the tooltip.
				const inputRect         = input.getBoundingClientRect();
				tooltip.style.bottom    = inputRect.height + 'px';
				tooltip.style.left      = '0';
				tooltip.style.transform = 'translateY(-5px)';
				// Move it 5px up.

				// Ensure the input's parent has a relative position.
				if (getComputedStyle( input.parentNode ).position === 'static') {
					input.parentNode.style.position = 'relative';
				}

				// Append the tooltip to the input's parent.
				input.parentNode.appendChild( tooltip );

				// Remove the tooltip after 3 seconds.
				setTimeout(
					function () {
						tooltip.remove();
					},
					3000
				);
			}

			function inpost_intl_hide_tooltip(input) {
				let parent = input.parentNode;
				if (typeof parent != 'undefined' && parent !== null) {
					const existingTooltip = parent.querySelector( '.inpost-intl-tooltip' );
					if (existingTooltip) {
						existingTooltip.remove();
					}
				}
			}

			function inpost_intl_clear_json_response(resp) {
				return resp
					.replace( /<!--[\s\S]*?-->/g, '' )  // Remove HTML comments.
					.replace( /<[^>]*>[\s\S]*?<\/[^>]*>/g, '' )  // Remove all HTML tags and their content.
					.replace( /<[^>]*>/g, '' )  // Remove any remaining HTML tags.
					.trim();  // Remove leading/trailing whitespace.

			}

			function inpost_intl_shipment_table_processing() {
				let shipments_table = $( '#the-list-inpost-international-shipments' );

				let all_rows = shipments_table.find( "th[class='check-column']" ).children( "input[type='checkbox']" );

				let result             = {};
				let selected_row_count = 0;
				let orders             = {};
				let index              = 1;
				all_rows.each(
					function (i, elem) {
						if ($( elem ).is( ':checked' )) {
							let order_row          = null;
							let order_id           = $( elem ).val();
							let order_row_selector = 'inpost-int-shipment-' + order_id;
							if (typeof order_id != 'undefined' && order_id !== null) {
								selected_row_count++;
								orders[index] = order_id;
								index++;

								$( 'tr[id="' + order_row_selector + '"]' ).css(
									{
										'opacity': '0.6',
										'cursor': 'wait'
									}
								);

								/*let inpost_custom_column_cell = $( order_row ).find( '.easypack_shipping_statuses' );
								if (typeof inpost_custom_column_cell != 'undefined' && inpost_custom_column_cell !== null) {

									$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).hide();
									$( inpost_custom_column_cell ).addClass( 'order-preview' );
									$( inpost_custom_column_cell ).addClass( 'disabled' );
									selected_row_count++;
									orders[index] = order_id;
									index++;
								}*/
							}

							/*let old_table = document.getElementById( 'post-' + order_id );
							let new_table = document.getElementById( 'order-' + order_id );

							if (typeof old_table != 'undefined' && old_table !== null) {
								order_row = old_table;
							} else if (typeof new_table != 'undefined' && new_table !== null) {
								order_row = new_table;
							}

							if (order_row) {
								let inpost_custom_column_cell = $( order_row ).find( '.easypack_shipping_statuses' );
								if (typeof inpost_custom_column_cell != 'undefined' && inpost_custom_column_cell !== null) {

									$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).hide();
									$( inpost_custom_column_cell ).addClass( 'order-preview' );
									$( inpost_custom_column_cell ).addClass( 'disabled' );
									selected_row_count++;
									orders[index] = order_id;
									index++;
								}
							}*/
						}
					}
				);

				if (selected_row_count === 0) {
					alert( __( 'No rows selected', 'inpost-international' ) );
					return;
				} else {
					result['selected_row_count'] = selected_row_count;
					result['orders']             = orders;
					return result;
				}
			}

			function inpost_process_shipment_table_labels_bulk(orders, index, total, failed = 0, pdf_data = {} ) {

				// if total reached.
				if (index > total) {
					return false;
				}

				var ajaxdata_process_item = {},
					process_item          = orders[index],
					order_id              = process_item.order_id;

				ajaxdata_process_item['order_id']           = order_id;
				ajaxdata_process_item['uuid']               = process_item.uuid;
				ajaxdata_process_item['action']             = 'inpost_international';
				ajaxdata_process_item['inpost_intl_action'] = 'inpost_intl_bulk_create_labels';
				ajaxdata_process_item['security']           = inpost_intl.nonce;

				console.log( 'pdf_data' );
				console.log( pdf_data );

				$.ajax(
					{
						beforeSend: function () {
							$( '.inpost_intl_get_labels_preloader' ).css( 'display', 'inline-block' );
							$( '#inpost_intl_shipments_labels_bulk' ).prop( 'disabled', 'disabled' );
						},
						type: 'POST',
						url: inpost_intl.ajaxurl,
						data: ajaxdata_process_item,
						dataType: 'json',
						success: function (response) {
							if ( response.error) {
								failed++;
								if (typeof response.error_details != 'undefined' && response.error_details !== null) {
									console.log( response.error_details );
									let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
										"Error:<br> " + response.error_details + "</span>";
									$( '.inpost_intl_shipment_list_status_error[data-id="' + order_id + '"]' ).append( error );
								}
								if (index < total) {
									inpost_process_shipment_table_labels_bulk( orders, (index + 1), total, failed, pdf_data );
								}

							} else {

								if (typeof response.pdf != 'undefined' && response.pdf !== null) {
									let data         = {};
									data['order_id'] = order_id;
									data['pdf']      = response.pdf;
									pdf_data[index]  = data;
									if (index <= total) {
										inpost_process_shipment_table_labels_bulk( orders, (index + 1), total, failed, pdf_data );
									}
								}
							}

							// last item.
							if (index == total) {
								console.log( 'LAST' );
								document.querySelector( 'body' ).style.opacity = "1";
								document.querySelector( 'body' ).style.cursor  = "unset";
								console.log( 'pdf_data' );
								console.log( pdf_data );

								function loadJSZip(callback) {
									let js_zip = document.createElement( 'script' );
									js_zip.setAttribute( 'src', inpos_intl.jszip_path );
									js_zip.onload = callback;
									document.head.appendChild( js_zip );
								}

								loadJSZip(
									function () {
										if (Object.keys( pdf_data ).length > 0) {
											let zip      = new JSZip();
											let promises = [];

											// Process each PDF label.
											for (let key in pdf_data) {
												if (pdf_data.hasOwnProperty( key ) && pdf_data[key].pdf) {
													let order_id = pdf_data[key].order_id;
													let filename = 'inpost_int_zamowenie_' + order_id + '.pdf';

													console.log( filename );
													let order_row_selector = 'inpost-int-shipment-' + order_id;
													$( 'tr[id="' + order_row_selector + '"]' ).css(
														{
															'opacity': '1',
															'cursor': 'unset'
														}
													);

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

													// Add file to zip.
													zip.file( filename, bytes, {binary: true} );
												}
											}

											// Generate zip file
											zip.generateAsync( {type: "blob"} )
												.then(
													function (content) {
														// Download zip file
														let link      = document.createElement( 'a' );
														link.href     = window.URL.createObjectURL( content );
														link.download = "inpost_labels.zip";
														document.body.appendChild( link );
														link.click();
														document.body.removeChild( link );
													}
												);

										}
									}
								);

							}

						}, complete: function () {
							$( '.inpost_intl_get_labels_preloader' ).css( 'display', 'none' );
							$( '#inpost_intl_shipments_labels_bulk' ).prop( 'disabled', false );
						}
					}
				);

			}

			function inpost_intl_formate_iso_date(isoDateString) {
				const date = new Date( isoDateString );

				// Format options for Polish locale
				const options = {
					day: '2-digit',
					month: '2-digit',
					year: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					hour12: false
				};

				return date.toLocaleString( 'pl-PL', options );
			}

			function inpost_intl_process_events(events) {
				// Sort events by timestamp, newest first
				events.sort(
					function (a, b) {
						return new Date( b.timestamp ) - new Date( a.timestamp );
					}
				);

				// Create HTML table for events
				let table_html = "<div class=\"tracking-events-container\"><table class=\"tracking-events\"><thead><tr><th>Data i czas</th><th>Kod</th><th>Tytuł</th><th>Opis</th></tr></thead><tbody>";

				events.forEach(
					function (event) {
						const date           = new Date( event.timestamp );
						const formatted_date = date.getDate().toString().padStart( 2, '0' ) + '.' + (date.getMonth() + 1).toString().padStart( 2, '0' ) + '.' + date.getFullYear();
						const formatted_time = date.toTimeString().split( ' ' )[0];

						table_html += "<tr><td>" + formatted_date + " " + formatted_time + "</td><td>" + event.eventCode + "</td><td>" + event.eventTitle + "</td><td>" + event.eventDescription + "</td></tr>";
					}
				);

				table_html += "</tbody></table></div>";

				return table_html;
			}

			const copyBtn = document.getElementById( 'inpost-copy-cron-url-btn' );
			const input   = document.getElementById( 'inpost_international_server_cron' );
			const tooltip = document.getElementById( 'copy-tooltip' );

			if (copyBtn && input && tooltip) {
				copyBtn.addEventListener(
					'click',
					function () {
						// Create a temporary input to copy the value.
						const tempInput = document.createElement( 'input' );
						tempInput.value = input.value;
						document.body.appendChild( tempInput );
						tempInput.select();
						tempInput.setSelectionRange( 0, 99999 );

						try {
							document.execCommand( 'copy' );
							copyBtn.classList.add( 'copied' );
							tooltip.textContent = 'Copied!';

							// Reset after 2 seconds.
							setTimeout(
								function () {
									copyBtn.classList.remove( 'copied' );
									tooltip.textContent = 'Copy';
								},
								2000
							);

						} catch (err) {
							console.error( 'Failed to copy: ', err );
							tooltip.textContent = 'Failed to copy';

							setTimeout(
								function () {
									tooltip.textContent = 'Copy';
								},
								2000
							);
						}

						// Remove temporary input.
						document.body.removeChild( tempInput );
					}
				);
			}

			$( 'input.inpost_international_dmtemplate[data-id="name"]' ).each(
				function () {
					let slug_input = $( this ).siblings( 'input[data-id="slug"]' );
					if (typeof slug_input != 'undefined' && slug_input !== null) {
						if (slug_input.val() === '') {
							slug_input.val( inpost_intl_sanitize_title( $( this ).val() ) );
						}
					}
				}
			);

			$( document ).on(
				'change',
				'input.inpost_international_dmtemplate[data-id="name"]',
				function () {
					let name_value = $( this ).val();
					// Generate slug from name.
					let slug = inpost_intl_sanitize_title( name_value );
					// Find the corresponding slug input (sibling with data-id="slug").
					$( this ).closest( 'td' ).find( 'input[data-id="slug"]' ).val( slug );
				}
			);

			function inpost_intl_sanitize_title(str) {

				if ( ! str) {
					return '';
				}

				var char_map = {
					// Latin.
					'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE',
					'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I',
					'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O',
					'Õ': 'O', 'Ö': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U',
					'Ý': 'Y', 'Þ': 'TH', 'ß': 'ss', 'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a',
					'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e',
					'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 'ð': 'd', 'ñ': 'n',
					'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ø': 'o', 'ù': 'u',
					'ú': 'u', 'û': 'u', 'ü': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y',
					// Polish.
					'Ł': 'L', 'ł': 'l', 'Ń': 'N', 'ń': 'n', 'Ć': 'C', 'ć': 'c', 'Ź': 'Z',
					'ź': 'z', 'Ż': 'Z', 'ż': 'z', 'Ś': 'S', 'ś': 's', 'Ą': 'A', 'ą': 'a',
					'Ę': 'E', 'ę': 'e', 'Ó': 'O', 'ó': 'o'
				};

				// Replace special characters.
				for (var char in char_map) {
					str = str.replace( new RegExp( char, 'g' ), char_map[char] );
				}

				str = str.toLowerCase();

				str = str.replace( /[^a-z0-9]+/g, '-' );

				str = str.replace( /^-+|-+$/g, '' );

				return str;
			}

		}
	);

})( jQuery );
