(function ($) {
	let inpost_intl_successful_ids = {};

	let is_ajax_running = false;

	$( document ).ready(
		function () {

			$( '#doaction' ).on(
				'click',
				function (e) {
					var form   = $( '#posts-filter' );
					let action = $( '#bulk-action-selector-top' ).val();

					// only shipments.
					if (action === 'inpost_intl_bulk_create_shipments') {
						e.preventDefault();
						let selected_data = inpost_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, elem) {

										let row_id                    = '#post-' + elem;
										let inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
										if ( ! inpost_custom_column_cell.length > 0) {
											row_id                    = '#order-' + elem;
											inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
										}
										if (typeof inpost_custom_column_cell != 'undefined' && inpost_custom_column_cell !== null) {

											let is_inpost_package = $( inpost_custom_column_cell ).find( '.inpost-status-inside-td' );
											if ( ! is_inpost_package.length > 0 ) {
												$( inpost_custom_column_cell ).removeClass( 'order-preview' );
												$( inpost_custom_column_cell ).removeClass( 'disabled' );
												$( inpost_custom_column_cell ).html( 'Not Inpost International shipping method' );
												return;
											}

											let maybe_already_created_package = $( inpost_custom_column_cell ).find( '.inpost_intl_order_list_tracking_number' );

											if (typeof maybe_already_created_package != 'undefined' && maybe_already_created_package !== null && maybe_already_created_package.length > 0) {

												$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).removeClass( 'easypack-alert-status' );
												$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).css( 'display', 'block' );
												$( inpost_custom_column_cell ).removeClass( 'order-preview' );
												$( inpost_custom_column_cell ).removeClass( 'disabled' );
											} else {
												validated_orders[index] = elem;
												index++;
											}
										}

									}
								);

								inpost_process_selected_item( validated_orders, 1, selected_data.selected_row_count, form, 0, 0 );

							}
						}
					}

					// only labels.
					if (action === 'inpost_intl_bulk_create_labels') {
						e.preventDefault();

						let selected_data = inpost_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, elem) {

										let row_id                    = '#post-' + elem;
										let inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
										if ( ! inpost_custom_column_cell.length > 0) {
											row_id                    = '#order-' + elem;
											inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
										}
										if (typeof inpost_custom_column_cell != 'undefined' && inpost_custom_column_cell !== null) {
											let is_inpost_package = $( inpost_custom_column_cell ).find( '.inpost-status-inside-td' );
											if ( ! is_inpost_package.length > 0 ) {
												$( inpost_custom_column_cell ).removeClass( 'order-preview' );
												$( inpost_custom_column_cell ).removeClass( 'disabled' );
												$( inpost_custom_column_cell ).html( 'Not Inpost International shipping method' );
												return;
											}

											let maybe_already_created_package = $( inpost_custom_column_cell ).find( '.inpost_intl_order_list_tracking_number' );

											if (typeof maybe_already_created_package != 'undefined' && maybe_already_created_package !== null && maybe_already_created_package.length > 0) {
												let uuid = $( inpost_custom_column_cell ).find( '.inpost_intl_order_list_label' ).attr( 'data-uuid' );

												if (typeof uuid != 'undefined' && uuid !== null) {
													let data                = {};
													data['order_id']        = elem;
													data['uuid']            = uuid;
													validated_orders[index] = data;
													index++;
												}
											} else {
												$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).removeClass( 'easypack-alert-status' );
												$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).css( 'display', 'block' );
												$( inpost_custom_column_cell ).removeClass( 'order-preview' );
												$( inpost_custom_column_cell ).removeClass( 'disabled' );
											}
										}

									}
								);

								let count = index - 1;

								inpost_process_labels_bulk( validated_orders, 1, count );
							}
						}
					}
				}
			);
		}
	);

	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( 'inpost_intl_order_list_label' )) {

				e.preventDefault();
				let order_id        = target.getAttribute( 'data-order-id' );
				let tracking_number = target.getAttribute( 'data-tracking-id' );

				let uuid         = target.getAttribute( 'data-uuid' );
				let row_selector = 'order-' + order_id;

				let data = {
					action: 'inpost_international',
					inpost_intl_action: 'inpost_international_get_label',
					security: inpost_intl_orders_bulk.nonce,
					order_id: order_id,
					uuid: uuid,
				};

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

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

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

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

							$( 'tr[id="' + row_selector + '"]' ).css( {'opacity': '0.6', 'cursor': 'wait'} );
						},
						success: function ( response ) {
							console.log( "success response Label" );
							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_order_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' );

									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_order_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_order_list_preloader' ).each(
								function (i) {
									$( this ).css( 'display', 'none' );
								}
							);
							is_ajax_running = false;
						}
					}
				);

			}

			if (target.classList.contains( 'inpost_intl_order_list_tracking_number' )) {
				e.preventDefault();
				let order_id        = target.getAttribute( 'data-order-id' );
				let tracking_number = target.getAttribute( 'data-tracking-id' );

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

				if ( is_ajax_running ) {
					return;
				}

				let row_selector = 'order-' + order_id;

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

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

							is_ajax_running = true;
							$( 'span.inpost_intl_order_list_preloader[data-id="' + order_id + '"]' ).css( 'display', 'inline-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_orders_bulk.log_path + '">here</a>';

							const tracking_data = response[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' );

								}

							} 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_order_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_orders_bulk.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) {
							console.log( "complete response" );

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

			if (target.classList.contains( 'dashicons-media-spreadsheet' )) {
				e.preventDefault();

				let order_id = target.getAttribute( 'data-id' );

				let row_id                    = '#post-' + order_id;
				let inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
				if ( ! inpost_custom_column_cell.length > 0) {
					row_id                    = '#order-' + order_id;
					inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
				}

				$( inpost_custom_column_cell ).addClass( 'order-preview' );
				$( inpost_custom_column_cell ).addClass( 'disabled' );
				$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).hide();
				print_labels_bulk( [order_id] );

			}
		}
	);

	function inpost_process_selected_item(orders, index, total, form, failed, need_labels = false, locker_size = false) {

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

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

		ajaxdata_process_item['order_id']           = order_id;
		ajaxdata_process_item['action']             = 'inpost_international';
		ajaxdata_process_item['inpost_intl_action'] = 'inpost_intl_bulk_create_shipments';
		ajaxdata_process_item['locker_size']        = '';
		ajaxdata_process_item['security']           = inpost_intl_orders_bulk.nonce;
		if (locker_size) {
			ajaxdata_process_item['locker_size'] = locker_size;
		}

		$.ajax(
			{
				beforeSend: function () {
					document.querySelector( 'body' ).style.opacity = "0.6";
					document.querySelector( 'body' ).style.cursor  = "wait";
					$( '.inpost_intl_order_list_status_error' ).find( 'span' ).each(
						function (i) {
							$( this ).remove();
						}
					);
				},
				type: 'POST',
				url: inpost_intl_orders_bulk.ajaxurl,
				data: ajaxdata_process_item,
				dataType: 'json',
				success: function (data) {

					let row_id                    = '#post-' + order_id;
					let inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );

					if ( ! inpost_custom_column_cell.length > 0) {
						row_id                    = '#order-' + order_id;
						inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
					}
					$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).removeClass( 'easypack-alert-status' );
					$( inpost_custom_column_cell ).removeClass( 'order-preview' );
					$( inpost_custom_column_cell ).removeClass( 'disabled' );

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

					if (data.status === 'ok') {
						let status_message = '';
						if (typeof data.tracking_number != 'undefined' && data.tracking_number !== null) {
							let uuid = '';
							if (typeof data.uuid != 'undefined' && data.uuid !== null) {
								uuid = data.uuid;
							}

							status_message = '<a style="padding:2px"' +
								' class="inpost_intl_order_list_label btn-clone button-secondary btn-shipment-action"' +
								' data-order-id="' + order_id + '" ' +
								'data-uuid="' + uuid + '" ' +
								'title="Get Inpost label">' +
								'<span class="inpost_intl_order_list_label dashicons dashicons-admin-page" ' +
								'data-order-id="' + order_id + '" ' +
								'data-uuid="' + uuid + '"></span></a>' +
								'<br><a data-tracking-id="' + data.tracking_number + '" ' +
								'data-order-id="' + order_id + '" ' +
								'data-uuid="' + uuid + '" ' +
								'class="inpost_intl_order_list_tracking_number" ' +
								'href="https://inpost.pl/sledzenie-przesylek?number=' + data.tracking_number + '">' + data.tracking_number + '</a>' +
								'<span data-id="' + order_id + '" ' +
								'class="inpost_intl_order_list_preloader">' +
								'<img class="inpost_intl_preloader" ' +
								'src="' + inpost_intl_orders_bulk.animation + '" ' +
								'alt="inpost international preloader"></span>' +
								'<span data-id="' + order_id + '" class="inpost_intl_order_list_status_error"></span>';
						}
						$( inpost_custom_column_cell ).html( '<div class="inpost-status-inside-td">' + status_message + '</div>' );

						// collect succesful created orders for further print labels.
						inpost_intl_successful_ids[index] = order_id;

						if (index <= total) {
							inpost_process_selected_item( orders, (index + 1), total, form, failed, need_labels, locker_size );
						}

					} else {
						failed++;

						if (typeof data.error != 'undefined' && data.error !== null) {
							let error = '';
							if (data.error_connection) {
								error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
									"Error:<br> " + data.error_connection + "</span>";
							} else if (data.error_details) {
								// Handle error.
								error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
									"Error:<br> " + data.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>";
							}
							console.log( error );
							$( '.inpost_intl_order_list_status_error[data-id="' + order_id + '"]' ).append( error );
							$( '.inpost_intl_order_list_status_error[data-id="' + order_id + '"]' ).closest( '.inpost-status-inside-td' ).css( 'display', 'block' )
						}

						if (data.status === 'already_created') {
							inpost_intl_successful_ids[index] = order_id;
						}

						// continue with next.
						if (index < total) {
							inpost_process_selected_item( orders, (index + 1), total, form, failed, need_labels, locker_size );
						}
					}

					// last item.
					if (index == total) {
						if (need_labels) {
							print_labels_bulk( inpost_intl_successful_ids );
						}
					}

				}, complete: function () {
					document.querySelector( 'body' ).style.opacity = "1";
					document.querySelector( 'body' ).style.cursor  = "unset";
				}
			}
		);

	}

	function inpost_table_processing() {
		var form  = $( '#posts-filter' ),
			table = form.find( 'table' );

		if (form.length === 0) {
			form  = $( '#wc-orders-filter' );
			table = form.find( 'table' );
		}

		let all_rows = 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 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( 'Nie wybrano żadnych zamówień' );
			return;
		} else {
			result['selected_row_count'] = selected_row_count;
			result['orders']             = orders;
			return result;
		}
	}

	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;
	}

	function inpost_process_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_orders_bulk.nonce;

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

		let hpos = inpost_intl_orders_bulk.hpos;
		let selector = '#post-' + order_id;
		if( hpos ) {
			selector = '#order-' + order_id;
		}
		let inpost_custom_column_cell = $( selector + ' > .easypack_shipping_statuses' );

		$.ajax(
			{
				beforeSend: function () {
					document.querySelector( 'body' ).style.opacity = "0.6";
					document.querySelector( 'body' ).style.cursor  = "wait";
				},
				type: 'POST',
				url: inpost_intl_orders_bulk.ajaxurl,
				data: ajaxdata_process_item,
				dataType: 'json',
				success: function (response) {

					if ( response.error) {
						failed++;

						$( inpost_custom_column_cell ).removeClass( 'order-preview' );
						$( inpost_custom_column_cell ).removeClass( 'disabled' );

						if (typeof response.error_connection != 'undefined' && response.error_connection !== null) {
							let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
								"Error:<br> " + response.error_connection + "</span>";
							$( inpost_custom_column_cell ).html( error );
						}
						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_order_list_status_error[data-id="' + order_id + '"]' ).append( error );
						}
						if (index < total) {
							inpost_process_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_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', inpost_intl_orders_bulk.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 row_id                    = '#post-' + order_id;
											let inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );

											if ( ! inpost_custom_column_cell.length > 0) {
												row_id                    = '#order-' + order_id;
												inpost_custom_column_cell = $( row_id + ' > .easypack_shipping_statuses' );
											}
											$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).removeClass( 'easypack-alert-status' );
											$( inpost_custom_column_cell ).removeClass( 'order-preview' );
											$( inpost_custom_column_cell ).removeClass( 'disabled' );
											$( inpost_custom_column_cell ).find( '.inpost-status-inside-td' ).show();

											// 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 () {

				}
			}
		);

	}

})( jQuery );
