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

	let is_ajax_running = false;

	$( document ).ready(
		function () {

			console.log('order-bulk-actions-ecolet.js');

			$( '.alsendo-connect-bulk-template' ).on(
				'click',
				function (e) {
					e.preventDefault();
					e.stopPropagation();
				}
			);

			$( '.alsendo-connect-bulk-template' ).on(
				'change',
				function (e) {
					e.preventDefault();
					//console.log($(this).val());
				}
			);

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

					// only shipments.
					if (action === 'alsendo_cnt_bulk_create_shipments') {
						e.preventDefault();
						let selected_data = alsendo_connect_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;
								let total_validated = 0;
								$.each(
									validate_orders,
									function (i, elem) {
										let carrier_id = false;
										let row_id                    = '#post-' + elem;
										let custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
										if ( ! custom_column_cell.length > 0) {
											row_id                    = '#order-' + elem;
											custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
										}
										if (typeof custom_column_cell != 'undefined' &&custom_column_cell !== null) {
											let is_alsendo_package = $( custom_column_cell ).find( '.alsendo-connect-inside-td' );

											if ( ! is_alsendo_package.length > 0 ) {
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).css( 'display', 'block' );
												$( custom_column_cell ).find( '.alsendo_connect_order_list_preloader' ).css( 'display', 'none' );
												$( custom_column_cell ).removeClass( 'order-preview' );
												$( custom_column_cell ).removeClass( 'disabled' );
												//$( custom_column_cell ).html( 'Not Alsendo Connect shipping method' );
												return;

											} else {

												carrier_id = $( is_alsendo_package ).attr('data-carrier-id');
												if (typeof carrier_id == 'undefined' || carrier_id === null || ! carrier_id.length > 0) {
													$( custom_column_cell ).removeClass( 'order-preview' );
													$( custom_column_cell ).removeClass( 'disabled' );
													$( custom_column_cell ).html( 'No selected carrier_id for shipping method' );
													return;
												}
											}

											let maybe_already_created_package = $( custom_column_cell ).find( '.alsendo_connect_order_list_tracking_number' );

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

												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).css( 'display', 'block' );
												$( custom_column_cell ).removeClass( 'order-preview' );
												$( custom_column_cell ).removeClass( 'disabled' );
											} else {
												validated_orders[index] = { 'order_id': elem, 'carrier_id': carrier_id };
												index++;
												total_validated++;
											}
										}

									}
								);

								$( '.alsendo_connect_order_list_status_error' ).each(
									function (i) {
										$( this ).html('');
									}
								);

								alsendo_connect_process_selected_item( validated_orders, 1, total_validated, form, 0, 0 );

							}
						}
					}

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

						let selected_data = alsendo_connect_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 custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
										if ( ! custom_column_cell.length > 0) {
											row_id                    = '#order-' + elem;
											custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
										}
										if (typeof custom_column_cell != 'undefined' && custom_column_cell !== null) {
											let is_alsendo_package = $( custom_column_cell ).find( '.alsendo-connect-status-inside-td' );
											if ( ! is_alsendo_package.length > 0 ) {
												$( custom_column_cell ).removeClass( 'order-preview' );
												$( custom_column_cell ).removeClass( 'disabled' );
												//$( custom_column_cell ).html( 'No package created for this item' );
												return;
											}

											let maybe_already_created_package = $( custom_column_cell ).find( '.alsendo_connect_order_list_tracking_number' );

											if (typeof maybe_already_created_package != 'undefined' && maybe_already_created_package !== null && maybe_already_created_package.length > 0) {
												let uuid = $( custom_column_cell ).find( '.alsendo_connect_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 {
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).css( 'display', 'block' );
												$( custom_column_cell ).removeClass( 'order-preview' );
												$( custom_column_cell ).removeClass( 'disabled' );
											}
										}

									}
								);

								let count = index - 1;

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


					// cancel shipments.
					if (action === 'alsendo_cnt_bulk_cancel_shipments') {
						console.log('cancel_shipments');

						e.preventDefault();
						let selected_data = alsendo_connect_table_processing();

						$( '.alsendo_connect_error_response' ).each(
							function (i) {
								$( this ).html('');
							}
						);

						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;
								let total_validated = 0;
								$.each(
									validate_orders,
									function (i, elem) {
										let carrier_id = false;
										let row_id                    = '#post-' + elem;
										let custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
										if ( ! custom_column_cell.length > 0) {
											row_id                    = '#order-' + elem;
											custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
										}

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

											let maybe_already_created_package = $( custom_column_cell ).find( '.alsendo_connect_order_list_tracking_number' );

											if (typeof maybe_already_created_package != 'undefined' && maybe_already_created_package !== null && maybe_already_created_package.length > 0) {
												let uuid = $( custom_column_cell ).find( '.alsendo_connect_order_list_tracking_number' ).attr('data-uuid');
												validated_orders[index] = { 'order_id': elem, 'uuid': uuid };
												index++;
												total_validated++;

											} else {
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
												$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).css( 'display', 'block' );
												$( custom_column_cell ).removeClass( 'order-preview' );
												$( custom_column_cell ).removeClass( 'disabled' );
											}
										}

									}
								);

								$( '.alsendo_connect_order_list_status_error' ).each(
									function (i) {
										$( this ).html('');
									}
								);

								alsendo_connect_cancel_selected_item( validated_orders, 1, total_validated, form, 0 );
								console.log('Ecolet: order to cancel:');
								console.log(validated_orders);

							}
						}

					}


				}
			);
		}
	);




	function alsendo_process_unknown_variable(variable) {
		if (typeof variable === 'object' && variable !== null && !Array.isArray(variable)) {
			return objectToString(variable);
		}
		if (typeof variable === 'string') {
			try {
				const parsedJSON = JSON.parse(variable);
				if (typeof parsedJSON === 'object' && parsedJSON !== null) {
					return objectToString(parsedJSON);
				}
			} catch (e) {

			}
		}

		return variable;
	}

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

			if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'alsendo_connect_status_modal_goto') {
				e.preventDefault();
				let order_id        = +target.getAttribute( 'data-id' );
				let order_link = '';
				if( alsendo_connect_orders_bulk.hpos ) {
					order_link = alsendo_connect_orders_bulk.admin_url + 'admin.php?page=wc-orders&action=edit&id=' + order_id;
				} else {
					order_link = alsendo_connect_orders_bulk.admin_url + 'post.php?post=' + order_id + '&action=edit';
				}

				document.location.href = order_link;
			}
			if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'alsendo_connect_status_modal_cancel') {
				e.preventDefault();
				$( '#alsendo_connect_status_modal' ).removeClass( 'active' );
			}
			if (target.classList.contains( 'alsendo_connect_status_modal_close_button' ) || target.classList.contains( 'alsendo_connect_status_modal_close') ) {
				e.preventDefault();
				$( '#alsendo_connect_status_modal' ).removeClass( 'active' );
			}



			if (target.classList.contains( 'alsendo_connect_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 action = 'alsendo_connect';
				let alsendo_connect_action = 'ecolet_get_waybill';
				let security = alsendo_connect_orders_bulk.nonce;

				$( '.alsendo_connect_order_list_status_error' ).find( 'span' ).each(
					function (i) {
						$( this ).remove();
					}
				);
				is_ajax_running = true;
				$( '.alsendo_connect_order_list_preloader' ).each(
					function (i, elem) {
						let attr = +$( elem ).attr( 'data-id' );
						if( order_id === attr ) {
							$(elem).css('display', 'inline-block');
						}
					}
				);
				$( 'tr[id="' + row_selector + '"]' ).css( {'opacity': '0.6', 'cursor': 'wait'} );

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

				let request = new XMLHttpRequest();
				request.open('POST', ajaxurl, true);
				request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
				request.responseType = 'blob';

				request.onload = function () {

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


					// Only handle status code 200
					if (request.status === 200 && request.response.size > 0) {
						let content_type = request.getResponseHeader("content-type");

						if (content_type === 'application/pdf') {
							//console.log( "success response PDF Label Ecolet" );
							let filename  = 'ecolet_woo_order_' + order_id + '.pdf';
							// download file
							var blob = new Blob([request.response], {type: 'application/pdf'});
							var link = document.createElement('a');
							link.href = window.URL.createObjectURL(blob);
							link.download = filename;
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);


						} else {
							// some error occured
							let text_from_blob = new Blob([request.response], {type: 'text/html'});
							let reader = new FileReader();
							let error_message = '';
							reader.onload = function () {

								let textResponse = JSON.parse(reader.result);
								console.log(textResponse);
								if ('data' in textResponse) {
									if( 'error_details' in textResponse.data ) {
										error_message = textResponse.data.error_details;
									} else if( 'message' in textResponse.data )  {
										error_message = textResponse.data.message;
									} else {
										error_message = textResponse.data;
									}

									let error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
										"Error:<br> " + error_message + "</span>";
									$( '.alsendo_connect_order_list_status_error' ).each(
										function (i, elem) {
											let attr = +$( elem ).attr( 'data-id' );
											if( order_id === attr ) {
												$(elem).append( error );
											}
										}
									);

									return;


								} else {
									error_message = textResponse;
								}
							};
							reader.readAsText(text_from_blob);

							return;
						}

					} else {

						$('.alsendo_connect_order_list_status_error').each(
							function (i, elem) {
								let attr = +$(elem).attr('data-id');
								if (order_id === attr) {
									$(elem).append('Some error is occured');
								}
							}
						);
					}
				};
				request.send('action=' + action + '&alsendo_connect_action=' + alsendo_connect_action + '&security=' + security + '&order_id=' + order_id + '&ecolet_id=' + uuid);

			}

			if (target.classList.contains( 'alsendo_connect_order_list_tracking_number' )) {
				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 data = {
					action: 'alsendo_connect',
					alsendo_connect_action: 'ecolet_get_order',
					security: alsendo_connect_orders_bulk.nonce,
					ecolet_id: uuid,
					order_id: order_id,
				};

				if ( is_ajax_running ) {
					return;
				}

				let row_selector = 'order-' + order_id;

				let is_error_exists = false;

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

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

							$( '.alsendo_connect_order_list_preloader' ).each(
								function (i, elem) {
									let attr = +$( elem ).attr( 'data-id' );
									if( order_id === attr ) {
										$(elem).css('display', 'inline-block');
									}
								}
							);

							is_ajax_running = true;

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

							$('.alsendo_connect_status_modal_text').html('');
							$('.alsendo_connect_status_modal_sub_title').html('');
							$('.alsendo_connect_status_modal_tracking').html('');
							$('.alsendo_connect_status_modal_action').html('');

							$( '.alsendo_connect_temp_data' ).each(
								function (i) {
									$( this ).remove();
								}
							);
						},
						success: function (response) {
							//console.log( response );

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


							if ( 0 !== response && '0' !== response ) {
								if ( 'success' in response && response.success) {
									if ('data' in response ) {
										console.log( response.data );

										let modal_header = '';
										let modal_subheader = '';
										let tracking_number = response.data.awb || false;
										let some_useful_info = '';
										let tracking_info = '';

										if( tracking_number ) {
											let tracking_link = alsendo_connect_orders_bulk.tracking_url + tracking_number;
											tracking_info = '<a target="blank_" href="' + tracking_link + '">'+ tracking_number + '</a>';
										}

										// Get courier infoю
										if ('service' in response.data) {
											if ('courierName' in response.data.service) {
												modal_header = response.data.service.courierName;
												if ('fullName' in response.data.service) {
													modal_subheader = response.data.service.fullName;
												}
											}
										}

										if( 'data' in response.data ) {
											let temp = response.data.data;
											for (let key in temp) {
												//some_useful_info = some_useful_info + ' ' +
												if (temp.hasOwnProperty( key ) && temp[key].message) {
													some_useful_info = some_useful_info + ' ' + temp[key].message;
													$('.alsendo_connect_status_modal_sub_title').text('');
												}
											}
										} else {

											// Create shipment details HTML
											some_useful_info = '<div class="shipment-details">' +
												'<div class="info-grid">' +
												'<div class="section sender-receiver">' +
												'<div class="sender-info">' +
												'<h4>Sender</h4>' +
												'<p>' + response.data.sender.name + '<br>' +
												response.data.sender.streetName + ' ' + response.data.sender.streetNumber + '<br>' +
												response.data.sender.city + ', ' + response.data.sender.stateCode + '<br>' +
												response.data.sender.phone + '</p>' +
												'</div>' +
												'<div class="receiver-info">' +
												'<h4>Receiver</h4>' +
												'<p>' + response.data.receiver.name + '<br>' +
												response.data.receiver.streetName + ' ' + response.data.receiver.streetNumber + '<br>' +
												response.data.receiver.city + ', ' + response.data.receiver.stateCode + '<br>' +
												response.data.receiver.phone + '</p>' +
												'</div>' +
												'</div>' +
												'<div class="section package-info">' +
												'<div class="details-grid">' +
												'<div class="detail-item">' +
												'<label>Content:</label>' +
												'<span>' + response.data.shipments[0].content + '</span>' +
												'</div>' +
												'<div class="detail-item">' +
												'<label>Dimensions:</label>' +
												'<span>' + response.data.shipments[0].dimension1 + 'x' + response.data.shipments[0].dimension2 + 'x' + response.data.shipments[0].dimension3 + ' cm</span>' +
												'</div>' +
												'<div class="detail-item">' +
												'<label>Weight:</label>' +
												'<span>' + response.data.shipments[0].weight + ' kg</span>' +
												'</div>' +
												'<div class="detail-item">' +
												'<label>Status:</label>' +
												'<span>' + response.data.status + '</span>' +
												'</div>' +
												'<div class="detail-item">' +
												'<label>Price:</label>' +
												'<span>' + response.data.price + ' ' + (response.data.vat ? '(VAT: ' + response.data.vat + '%)' : '') + '</span>' +
												'</div>' +
												'<div class="detail-item">' +
												'<label>Pickup:</label>' +
												'<span>' + new Date(response.data.pickup.date.date).toLocaleDateString() + ' ' + (response.data.pickup.hoursFrom || 'N/A') + '</span>' +
												'</div>' +
												'</div>' +
												'</div>' +
												'</div>' +
												'</div>';

											$('.alsendo_connect_status_modal_sub_title').text('Tracking number:');
										}

										// Update modal content
										$('.alsendo_connect_status_modal_title').append('<h3 class="alsendo_connect_temp_data">' + modal_header + '</h3>');
										$('.alsendo_connect_status_modal_title').append('<h4 class="alsendo_connect_temp_data">' + modal_subheader + '</h4>');
										$('.alsendo_connect_status_modal_tracking').html(tracking_info);
										$('.alsendo_connect_status_modal_text').html(some_useful_info);
										$('#alsendo_connect_status_modal').addClass('active');


									} else {
										is_error_exists = true;
									}
								} else {
									is_error_exists = true;
								}
							} else {
								is_error_exists = true;
							}

							if( is_error_exists ) {
								let error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
									"Error:<br> " + response.error_connection + "</span>";
							}


						},
						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="' + alsendo_connect_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='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
										"Error:<br> " + jsonResponse.error_connection + "</span>";
									} else if (jsonResponse.error_details) {
										// Handle error.
										error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
										"Error:<br> " + jsonResponse.error_details + "<br>" +
										"Verificați jurnalul pentru #" + order_id + woo_logs_section_url + "</span>";
									} else {
										// Unexpected JSON response.
										error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
										"Error:<br> Unexpected response from server.<br>Verificați jurnalul pentru #" + order_id + woo_logs_section_url + "</span>";
									}

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

									let error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
										"Error:<br> Some error is occured.<br>Verificați jurnalul pentru #" + order_id + woo_logs_section_url + "</span>";
								}

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

								let color = "#e03636";
								let error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color: " + color + "'>Error:<br> " + errorThrown + ', ' + e + ' ' + jqXHR.responseText + "</span>";
								$( '.alsendo_connect_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'} );
							$( '.alsendo_connect_order_list_preloader' ).each(
								function (i) {
									$( this ).css( 'display', 'none' );
								}
							);
							is_ajax_running = false;
						}
					}
				);
			}




		}
	);

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

		// if total reached.
		if (index > total) {

			document.querySelector('body').style.opacity = "1";
			document.querySelector('body').style.cursor = "unset";

			$( '.alsendo_connect_order_list_preloader' ).each(
				function (i) {
					$( this ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_shipping_statuses' ).each(
				function (i) {
					$( this ).removeClass( 'order-preview' );
					$( this ).removeClass( 'disabled' );
				}
			);

			return false;
		}

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

		if (typeof order_data == 'undefined' ) {
			return false;
		}

		let order_id = null;
		if( 'order_id' in order_data ) {
			order_id = +order_data.order_id;
		}

		let carrier_id = null;
		if( 'carrier_id' in order_data ) {
			carrier_id = order_data.carrier_id;
		}

		ajaxdata_process_item['order_id']           = order_id;
		ajaxdata_process_item['carrier_id']           = carrier_id;
		ajaxdata_process_item['action']             = 'alsendo_connect';
		ajaxdata_process_item['alsendo_connect_action'] = 'ecolet_bulk_create_shipments';

		ajaxdata_process_item['security']           = alsendo_connect_orders_bulk.nonce;

		if ( ! order_id ) {
			return false;
		}

		let row_id                    = '#post-' + order_id;
		let custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );

		if ( ! custom_column_cell.length > 0) {
			row_id                    = '#order-' + order_id;
			custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
		}

		ajaxdata_process_item['use_template'] = $( custom_column_cell ).find( '.alsendo-connect-bulk-template' ).val();

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


					$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
					$( custom_column_cell ).find( '.alsendo_connect_order_list_preloader' ).css( 'display', 'none' );
					$( custom_column_cell ).removeClass( 'order-preview' );
					$( custom_column_cell ).removeClass( 'disabled' );

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

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

							let method_name = $( custom_column_cell ).find('.alsendo-method-name').text();

							status_message = method_name + '<br><a style="padding:2px"' +
								' class="alsendo_connect_order_list_label btn-clone button-secondary btn-shipment-action"' +
								' data-order-id="' + order_id + '" ' +
								'data-uuid="' + uuid + '" ' +
								'title="Get Alsendo Connect label">' +
								'<span class="alsendo_connect_order_list_label dashicons dashicons-admin-page" ' +
								'data-order-id="' + order_id + '" ' +
								'data-uuid="' + uuid + '"></span></a>' +
								'<br><a data-tracking-id="' + awb_id + '" ' +
								'data-order-id="' + order_id + '" ' +
								'data-uuid="' + uuid + '" ' +
								'class="alsendo_connect_order_list_tracking_number" ' +
								'href="' + alsendo_connect_orders_bulk.tracking_url + awb_id + '">' + awb_id + '</a>' +
								'<span data-id="' + order_id + '" ' +
								'class="alsendo_connect_order_list_preloader">' +
								'<img class="alsendo_connect_preloader" ' +
								'src="' + alsendo_connect_orders_bulk.animation + '" ' +
								'alt="preloader"></span>' +
								'<span data-id="' + order_id + '" class="alsendo_connect_order_list_status_error"></span>';
						}
						$( custom_column_cell ).html( '<div class="alsendo-connect-status-inside-td">' + status_message + '</div>' );

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

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

					} else {
						failed++;

						console.log('alsendo_connect_process_selected_item failed');
						console.log(response);

						let error = '';
						if (typeof response.data.status != 'undefined' && response.data.status !== null && 'error' === response.data.status) {
							if (response.data.error_connection) {
								error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
									"Error:<br> " + data.error_connection + "</span>";
							} else if (response.data.message) {
								// Handle error.
								error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
									"Error:<br> " + response.data.message + "<br>" +
									"Verificați jurnalul complet pentru #" + order_id + woo_logs_section_url + "</span>";
							} else {
								// Unexpected JSON response.
								error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
									"Error:<br> Răspuns neașteptat de la server.<br>Verificați jurnalul pentru #" + order_id + woo_logs_section_url + "</span>";
							}

							let error_cell = $( '.alsendo_connect_order_list_status_error[data-id="' + order_id + '"]' );
							if (typeof error_cell != 'undefined' && error_cell !== null) {
								alsendo_process_error(order_id, error);
								error = '';
							}
						}

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

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

						$( '.alsendo_connect_order_list_preloader' ).each(
							function (i) {
								$( this ).css( 'display', 'none' );
							}
						);
						$( '.alsendo_connect_shipping_statuses' ).each(
							function (i) {
								$( this ).removeClass( 'order-preview' );
								$( this ).removeClass( 'disabled' );
							}
						);

						if (need_labels) {
							print_labels_bulk( alsendo_connect_successful_ids );
						}
					}

				}, complete: function () {
					//console.log('alsendo_connect_process_selected_item complete');
					if (index === total) {
						//console.log('process_last item complete');
					}
				}
			}
		);

	}


	function alsendo_process_error(order_id, error) {
		let error_cell = $('.alsendo_connect_order_list_status_error[data-id="' + order_id + '"]');
		if (error_cell.length > 0) {
			error_cell.append(error);
			error_cell.closest('.alsendo-connect-status-inside-td').show();
		}
	}

	function alsendo_connect_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 custom_column_cell = $( order_row ).find( '.alsendo_connect_shipping_statuses' );
						if (typeof custom_column_cell != 'undefined' && custom_column_cell !== null) {

							$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).hide();
							$( custom_column_cell ).addClass( 'order-preview' );
							$( custom_column_cell ).addClass( 'disabled' );
							selected_row_count++;
							orders[index] = order_id;
							index++;
						}
					}
				}
			}
		);

		if (selected_row_count === 0) {
			alert( 'No orders selected' );
			return;
		} else {
			result['selected_row_count'] = selected_row_count;
			result['orders']             = orders;
			return result;
		}
	}

	function alsendo_connect_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 alsendo_connect_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']             = 'alsendo_connect';
		ajaxdata_process_item['alsendo_connect_action'] = 'ecolet_bulk_create_labels';
		ajaxdata_process_item['security']           = alsendo_connect_orders_bulk.nonce;

		let hpos = alsendo_connect_orders_bulk.hpos;
		let selector = '#post-' + order_id;
		if( hpos ) {
			selector = '#order-' + order_id;
		}
		let custom_column_cell = $( selector + ' > .alsendo_connect_shipping_statuses' );

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

					if ( response.error) {
						failed++;

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

						if (typeof response.error_connection != 'undefined' && response.error_connection !== null) {
							let error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
								"Error:<br> " + response.error_connection + "</span>";
							$( custom_column_cell ).html( error );
						}
						if (typeof response.error_details != 'undefined' && response.error_details !== null) {

							console.log( response.error_details );
							let error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
								"Error:<br> " + response.error_details + "</span>";
							$( '.alsendo_connect_order_list_status_error[data-id="' + order_id + '"]' ).append( error );
						}
						if (index < total) {
							alsendo_connect_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) {
								alsendo_connect_process_labels_bulk( orders, (index + 1), total, failed, pdf_data );
							}
						}
					}

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

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

						alsendo_connect_load_zip(
							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 = 'alsendo_connect_order_' + order_id + '.pdf';

											let row_id                    = '#post-' + order_id;
											let custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );

											if ( ! custom_column_cell.length > 0) {
												row_id                    = '#order-' + order_id;
												custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
											}
											$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
											$( custom_column_cell ).removeClass( 'order-preview' );
											$( custom_column_cell ).removeClass( 'disabled' );
											$( custom_column_cell ).find( '.alsendo-connect-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 = "alsendo_connect_labels.zip";
											document.body.appendChild( link );
											link.click();
											document.body.removeChild( link );
										}
									);

								}
							}
						);

					}

				}, complete: function () {

				}
			}
		);

	}



	function alsendo_connect_cancel_selected_item( orders, index, total, form, failed ) {

		// if total reached.
		if (index > total) {

			document.querySelector('body').style.opacity = "1";
			document.querySelector('body').style.cursor = "unset";

			$( '.alsendo_connect_order_list_preloader' ).each(
				function (i) {
					$( this ).css( 'display', 'none' );
				}
			);
			$( '.alsendo_connect_shipping_statuses' ).each(
				function (i) {
					$( this ).removeClass( 'order-preview' );
					$( this ).removeClass( 'disabled' );
				}
			);

			return false;
		}

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

		if (typeof order_data == 'undefined' ) {
			return false;
		}

		let order_id = null;
		if( 'order_id' in order_data ) {
			order_id = +order_data.order_id;
		}

		let uuid_id = null;
		if( 'uuid' in order_data ) {
			uuid_id = order_data.uuid;
		}

		ajaxdata_process_item['order_id']           = order_id;
		ajaxdata_process_item['ecolet_id']           = uuid_id;
		ajaxdata_process_item['action']             = 'alsendo_connect';
		ajaxdata_process_item['alsendo_connect_action'] = 'ecolet_bulk_cancel_shipments';

		ajaxdata_process_item['security']           = alsendo_connect_orders_bulk.nonce;

		if ( ! order_id ) {
			return false;
		}

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

					console.log('Ecolet bulk cancel response');
					console.log(response);
					console.log(order_id);

					// Find the correct row - try both selectors
					let row_id = '#post-' + order_id;
					let custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );

					if ( ! custom_column_cell.length > 0) {
						row_id = '#order-' + order_id;
						custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
					}

					// Clean up the cell
					$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).removeClass( 'alsendo-connect-alert-status' );
					$( custom_column_cell ).find( '.alsendo_connect_order_list_preloader' ).css( 'display', 'none' );
					$( custom_column_cell ).removeClass( 'order-preview' );
					$( custom_column_cell ).removeClass( 'disabled' );

					if ( 'data' in response && 'status_code' in response.data && response.data.status_code == 200 ) {
						// Success - show "Anulowano"
						let cancelled_text = alsendo_connect_orders_bulk.cancelled_text;
						if ( 'data' in response && 'message' in response.data  ) {
							cancelled_text = response.data.message;
						}
						let status_message = '<span class="alsendo_connect_order_cancelled_status" style="color:green;"><b>' + cancelled_text + '</b></span>';
						//$( custom_column_cell ).html(status_message);
						$( custom_column_cell ).find( '.alsendo-connect-status-inside-td' ).after( status_message );

						console.log('Successfully cancelled order: ' + order_id);

					} else {
						// Error case
						failed++;

						console.log('alsendo_connect_cancel_selected_item failed for order: ' + order_id);

						let error = '';
						if( 'error_messages' in response ) {
							error = "<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>" +
								"Error:<br> " + response.error_messages + "</span>";
						}

						if ( 'data' in response && 'message' in response.data  ) {
							error = response.data.message;
						}

						// Display error in the cell
						let error_cell = $( '.alsendo_connect_order_list_status_error[data-id="' + order_id + '"]' );
						if (typeof error_cell != 'undefined' && error_cell !== null && error_cell.length > 0) {
							alsendo_process_error(order_id, error);
						} else {
							// If no specific error cell, show in the status cell
							if (error) {
								$( custom_column_cell ).html(error);
							}
						}
					}

					// Continue with next item
					if (index < total) {
						alsendo_connect_cancel_selected_item( orders, (index + 1), total, form, failed );
					}

					// Last item - reset UI state
					if (index === total) {
						document.querySelector('body').style.opacity = "1";
						document.querySelector('body').style.cursor = "unset";

						$( '.alsendo_connect_order_list_preloader' ).each(
							function (i) {
								$( this ).css( 'display', 'none' );
							}
						);
						$( '.alsendo_connect_shipping_statuses' ).each(
							function (i) {
								$( this ).removeClass( 'order-preview' );
								$( this ).removeClass( 'disabled' );
							}
						);
					}

				},
				error: function(xhr, status, error) {
					// Handle AJAX errors
					console.log('AJAX error for order: ' + order_id, error);

					let row_id = '#post-' + order_id;
					let custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );

					if ( ! custom_column_cell.length > 0) {
						row_id = '#order-' + order_id;
						custom_column_cell = $( row_id + ' > .alsendo_connect_shipping_statuses' );
					}

					$( custom_column_cell ).html("<span class='alsendo_connect_error_response' style='font-weight:bold; color:#ff0000'>AJAX Error</span>");

					// Continue with next item
					if (index < total) {
						alsendo_connect_cancel_selected_item( orders, (index + 1), total, form, failed );
					}
				},
				complete: function () {
					//console.log('alsendo_connect_process_selected_item complete');
				}
			}
		);

	}


	function alsendo_create_order_modal_content(data) {
		// Helper function to format address
		const formatAddress = (addr) => {
			let parts = [];
			if (addr.street_name) parts.push(addr.street_name + ' ' + addr.street_number);
			if (addr.block && addr.block !== '-') parts.push('bl. ' + addr.block);
			if (addr.entrance && addr.entrance !== '-') parts.push('entr. ' + addr.entrance);
			if (addr.floor && addr.floor !== '-') parts.push('fl. ' + addr.floor);
			if (addr.flat && addr.flat !== '-') parts.push('ap. ' + addr.flat);
			if (addr.postal_code) parts.push(addr.postal_code);
			if (addr.locality) parts.push(addr.locality);
			if (addr.county) parts.push(addr.county);
			if (addr.country) parts.push(addr.country);
			return parts.join(', ');
		};

		// Get active additional services
		const activeServices = Object.entries(data.additional_services)
			.filter(([_, service]) => service.status === true)
			.map(([name]) => name.toUpperCase())
			.join(', ');

		let some_useful_info = '<div class="shipment-details-order">' +
			'<div class="section-order receiver-section">' +
			'<div class="receiver-info">' +
			'<h4>Receiver Details</h4>' +
			'<div class="address-comparison">' +
			'<div class="current-address">' +
			'<p><strong>Address for API:</strong><br>' +
			formatAddress(data.receiver) + '</p>' +
			'<p><strong>Contact:</strong> ' + data.receiver.contact_person + '<br>' +
			'Phone: ' + data.receiver.phone + '<br>' +
			'Email: ' + data.receiver.email + '</p>' +
			'</div>' +
			'<div class="woo-alsendo-address">' +
			'<p><span class="alsendo-strong">WooCommerce Address:</span><br>' +
			'<strong>Line 1:</strong><br>' + data.receiver_woo_address.line_1 + '<br>' +
			'<strong>Line 2:</strong><br>' + (data.receiver_woo_address.line_2 || '') + '</p>' +
			'</div>' +
			'</div>' +
			'</div>' +
			'</div>' +

			'<div class="section-order details-grid">' +
			'<div class="sender-info">' +
			'<h4>Sender</h4>' +
			'<p>' + data.sender.name + '<br>' +
			formatAddress(data.sender) + '<br>' +
			'Contact: ' + data.sender.contact_person + '<br>' +
			'Phone: ' + data.sender.phone + '</p>' +
			'</div>' +

			'<div class="parcel-info">' +
			'<h4>Parcel Details</h4>' +
			'<p>Type: ' + data.parcel.type + ' (' + data.parcel.shape + ')<br>' +
			'Weight: ' + data.parcels.weight + ' kg<br>' +
			'Dimensions: ' + data.parcels.dimensions.length + 'x' +
			data.parcels.dimensions.width + 'x' +
			data.parcels.dimensions.height + ' cm<br>' +
			'Declared Value: ' + data.parcels.declared_value + '<br>' +
			'Content: ' + data.parcels.content + '</p>' +
			'</div>' +
			'</div>';

		// Only add services section if there are active services.
		if (activeServices) {
			some_useful_info +=
				'<div class="section-order services-info">' +
				'<h4>Active Services</h4>' +
				'<p>' + activeServices + '</p>' +
				'</div>';
		}

		some_useful_info += '</div>';

		return some_useful_info;
	}

})( jQuery );
