<?= message_box('success'); ?>
<?= message_box('error'); ?>

<?php
$created = can_action('187', 'created');
$edited = can_action('187', 'edited');
$deleted = can_action('187', 'deleted');

$items_info = isset($items_info) ? $items_info : null;
$transfer_id = !empty($items_info) ? $items_info->transfer_item_id : null;

$reference_no = '';
if (!empty($items_info) && !empty($items_info->reference_no)) {
	$reference_no = $items_info->reference_no;
} else {
	if (empty(config_item('transfer_number_format'))) {
		$reference_no .= config_item('transfer_prefix');
	}
	if (config_item('increment_transfer_number') == 'FALSE') {
		$this->load->helper('string');
		$reference_no .= random_string('nozero', 6);
	} else {
		$reference_no .= $this->items_model->generateTransferItemNumber();
	}
}

$transfer_date = !empty($items_info) && !empty($items_info->date) ? date('Y-m-d', safe_strtotime($items_info->date)) : date('Y-m-d');
$from_selected = !empty($items_info) ? $items_info->from_warehouse_id : '';
$to_selected = !empty($items_info) ? $items_info->to_warehouse_id : '';
$permissionL = !empty($items_info) && !empty($items_info->permission) ? $items_info->permission : null;

$status_options = array(
	'pending' => lang('pending'),
	'complete' => lang('completed'),
	'approved' => lang('approved'),
	'rejected' => lang('rejected'),
);
$status_selected = !empty($items_info->status) ? ($items_info->status === 'completed' ? 'complete' : $items_info->status) : 'pending';

$notes = !empty($items_info) && !empty($items_info->notes) ? $items_info->notes : $this->config->item('transfer_notes');
$transfer_adjustment = !empty($items_info) && isset($items_info->shipping_cost) ? (float) $items_info->shipping_cost : 0;
$show_quantity_as = !empty($items_info) && !empty($items_info->show_quantity_as) ? $items_info->show_quantity_as : 'qty';

$warehouse_options = array('' => lang('select') . ' ' . lang('warehouse'));
if (!empty($warehouseList)) {
	foreach ($warehouseList as $key => $label) {
		$warehouse_options[$key] = $label;
	}
}

$new_warehouse_link_from = '';
$new_warehouse_link_to = '';
$from_label = '';
$to_label = '';
$usertype = profile();
if (!empty($usertype) && $usertype->role_id == 1) {
	$new_warehouse_link_from = form_lookup_add_link('from_warehouse_id', base_url('admin/warehouse/create/0/from_warehouse_id'), lang('new') . ' ' . lang('warehouse'), 'xl');
	$new_warehouse_link_to = form_lookup_add_link('to_warehouse_id', base_url('admin/warehouse/create/0/to_warehouse_id'), lang('new') . ' ' . lang('warehouse'), 'xl');
}
if (!empty($from_selected)) {
	$from_label = get_row('tbl_warehouse', array('warehouse_id' => $from_selected), 'warehouse_name');
}
if (!empty($to_selected)) {
	$to_label = get_row('tbl_warehouse', array('warehouse_id' => $to_selected), 'warehouse_name');
}

$existing_transfer_items = array();
if (!empty($items_info) && !empty($items_info->transfer_item_id)) {
	$loaded_items = $this->items_model->ordered_items_by_id($items_info->transfer_item_id, true);
	if (is_string($loaded_items) && $loaded_items !== '') {
		$decoded_items = json_decode($loaded_items);
		if (is_array($decoded_items)) {
			$loaded_items = $decoded_items;
		}
	}
	if (!empty($loaded_items) && is_array($loaded_items)) {
		$existing_transfer_items = $loaded_items;
	}
}

$custom_fields_section = custom_form_Fields(18, $transfer_id);
?>

<?php if (!empty($created) || !empty($edited)) { ?>


	<div class="space-y-6">
		<?= form_open(base_url('admin/items/saveTransferItem/' . $transfer_id), array('class' => 'space-y-6', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => '', 'role' => 'form')); ?>

		<div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
			<div class="xl:col-span-7 space-y-6">
				<div class="rounded-xl border border-border bg-card p-6 space-y-5">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-3">
						<i data-lucide="move-right" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground">Transfer Information</h2>
					</div>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
						<?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true, array('placeholder' => lang('reference_no'))); ?>
						<?= form_datepicker('date', lang('date'), $transfer_date, true, array('data-auto-close' => 'true')); ?>
						<?= form_lookup_group(
							'from_warehouse_id',
							lang('FROM') . ' ' . lang('warehouse'),
							$from_selected,
							$from_label,
							true,
							array(),
							'',
							array('type' => 'warehouse', 'append' => $new_warehouse_link_from, 'onchange' => 'getItemByWarehouse', 'placeholder' => lang('search') . ' ' . lang('warehouse'))
						); ?>
						<?= form_lookup_group(
							'to_warehouse_id',
							lang('TO') . ' ' . lang('warehouse'),
							$to_selected,
							$to_label,
							true,
							array(),
							'',
							array('type' => 'warehouse', 'append' => $new_warehouse_link_to, 'placeholder' => lang('search') . ' ' . lang('warehouse'))
						); ?>
						<?= form_select_group('status', lang('status'), $status_options, $status_selected, true, array('class' => 'select_box')); ?>
					</div>
					<input type="hidden" name="warehouse_id" class="WarehouseValue" value="<?= html_escape($from_selected) ?>">
				</div>

				<div class="rounded-xl border border-border bg-card p-6 space-y-5">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-3">
						<i data-lucide="package-search" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground">Line Items</h2>
					</div>
					<input type="hidden" name="show_quantity_as" value="<?= html_escape($show_quantity_as) ?>">
					<input type="hidden" name="adjustment" value="<?= html_escape($transfer_adjustment) ?>">
					<div class="space-y-3">
						<div class="grid gap-2 md:grid-cols-[minmax(0,1fr)_auto]">
							<div class="relative">
								<i data-lucide="search" class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"></i>
								<input type="text" id="transfer-item-search" placeholder="<?= lang('search_product_barcode') ?>" class="h-10 w-full rounded-lg border border-border bg-background pl-10 pr-3 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
								<div id="transfer-item-results" class="transfer-item-results hidden"></div>
							</div>
							<button type="button" id="transfer-add-item" class="inline-flex h-10 items-center justify-center gap-1.5 rounded-lg bg-primary px-4 text-sm font-semibold text-white hover:bg-primary/90">
								<i data-lucide="plus" class="h-4 w-4"></i>
								<?= lang('add_item') ?>
							</button>
						</div>
						<div id="transfer-item-alert" class="hidden transfer-item-alert"></div>

						<div class="overflow-x-auto rounded-lg border border-border">
							<table class="min-w-full transfer-items-table">
								<thead>
									<tr>
										<th class="w-12">#</th>
										<th><?= lang('item_details') ?></th>
										<th class="w-28"><?= lang('unit') ?></th>
										<th class="w-28"><?= lang('qty') ?></th>
										<th class="w-20 text-right"><?= lang('action') ?></th>
									</tr>
								</thead>
								<tbody id="transfer-items-body"></tbody>
								<tfoot>
									<tr>
										<td colspan="3" class="text-right text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground"><?= lang('total_quantity') ?></td>
										<td id="transfer-total-qty" class="text-sm font-semibold text-foreground">0</td>
										<td></td>
									</tr>
								</tfoot>
							</table>
						</div>
						<div id="removed-transfer-items"></div>
					</div>
				</div>

			</div>

			<aside class="xl:col-span-5 space-y-6">
				<div class="rounded-xl border border-border bg-card p-6 space-y-4">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-2">
						<i data-lucide="shield-check" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground">Access Control</h2>
					</div>
					<?= form_permission_modern($permission_user, $permissionL, lang('assigned_to')); ?>
				</div>

				<?php if (!empty($custom_fields_section)) { ?>
					<?= $custom_fields_section; ?>
				<?php } ?>

				<div class="rounded-xl border border-border bg-card p-6 space-y-4">
					<div class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-2">
						<i data-lucide="paperclip" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('attachment') ?></h2>
					</div>
					<div class="space-y-4">
						<?= form_attachment_group('files[]', null, 'dropzone', array(
							'dropzone_id' => 'transfer-attachments-dropzone',
							'list_id' => 'transfer-attachments-list',
							'click_label' => '<span class="font-semibold text-slate-900 dark:text-slate-100">' . html_escape(lang('click_to_upload')) . '</span><br><span class="text-xs text-slate-500 dark:text-slate-400">' . html_escape(lang('drag_and_drop_file_here')) . '</span>',
							'hint' => lang('file_upload_instruction_js'),
						)); ?>
						<?php
						$uploaded_file = array();
						if (!empty($items_info) && !empty($items_info->attachment)) {
							$uploaded_file = json_decode($items_info->attachment);
						}
						if (!empty($uploaded_file)) { ?>
							<div class="space-y-2">
								<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('uploaded_file'); ?></p>
								<div class="flex flex-wrap gap-3">
									<?php foreach ($uploaded_file as $v_files_image) { ?>
										<div class="relative w-[112px] rounded-xl border border-border bg-background p-2 shadow-sm">
											<button type="button" class="existing_image absolute right-1 top-1 inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-950/40 dark:hover:text-rose-300" aria-label="<?= lang('delete'); ?>">
												<i data-lucide="x" class="h-4 w-4"></i>
											</button>
											<?php if ($v_files_image->is_image == 1) { ?>
												<img data-dz-thumbnail src="<?php echo base_url() . $v_files_image->path ?>" class="upload-thumbnail-sm h-24 w-full rounded-lg object-cover" />
											<?php } else { ?>
												<div class="mailbox-attachment-icon flex h-24 w-full items-center justify-center rounded-lg border border-border bg-slate-50 text-slate-500 dark:bg-slate-900 dark:text-slate-300">
													<i data-lucide="file-text" class="h-5 w-5"></i>
												</div>
											<?php } ?>

											<input type="hidden" name="path[]" value="<?php echo $v_files_image->path ?>">
											<input type="hidden" name="fileName[]" value="<?php echo $v_files_image->fileName ?>">
											<input type="hidden" name="fullPath[]" value="<?php echo $v_files_image->fullPath ?>">
											<input type="hidden" name="size[]" value="<?php echo $v_files_image->size ?>">
											<input type="hidden" name="is_image[]" value="<?php echo $v_files_image->is_image ?>">
										</div>
									<?php } ?>
								</div>
							</div>
						<?php } ?>
					</div>
				</div>


				<?= form_editor('notes', lang('notes'), $notes, false, array('rows' => 5)); ?>

			</aside>
		</div>

		<div class="transfer-footer-actions mt-4 flex flex-wrap items-center justify-between gap-2">
			<button type="button" id="transfer-reset" class="inline-flex h-9 items-center rounded-lg border border-rose-200 bg-rose-50 px-4 text-sm font-semibold text-rose-700 hover:bg-rose-100">Reset Form</button>
			<div class="flex flex-wrap items-center gap-2">
				<input type="submit" value="Save Draft" name="save_as_draft" class="inline-flex h-9 items-center rounded-lg cursor-pointer border border-slate-300 bg-white px-4 text-sm font-semibold text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800">
				<input type="submit" value="<?= !empty($transfer_id) ? 'Save Changes' : 'Create Transfer' ?>" name="update" class="inline-flex h-9 items-center rounded-lg border border-slate-900 cursor-pointer bg-slate-900 px-4 text-sm font-semibold text-white hover:bg-slate-800 dark:border-slate-100 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white">
			</div>
		</div>

		<?= form_close(); ?>
	</div>

	<script type="text/javascript">
		$(document).ready(function() {
			$(".existing_image").on("click", function() {
				$(this).parent().remove();
			});
		})

		function getItemByWarehouse(warehouseId) {
			var input = document.querySelector('[name="warehouse_id"]');
			if (input) {
				input.value = warehouseId || '';
			}
			var searchInput = document.getElementById('transfer-item-search');
			var results = document.getElementById('transfer-item-results');
			var alertBox = document.getElementById('transfer-item-alert');
			if (searchInput) {
				searchInput.value = '';
			}
			if (results) {
				results.innerHTML = '';
				results.classList.add('hidden');
			}
			if (alertBox) {
				alertBox.classList.add('hidden');
			}
		}

		(function() {
			var body = document.getElementById('transfer-items-body');
			var totalQty = document.getElementById('transfer-total-qty');
			var addBtn = document.getElementById('transfer-add-item');
			var searchInput = document.getElementById('transfer-item-search');
			var resultsPanel = document.getElementById('transfer-item-results');
			var alertBox = document.getElementById('transfer-item-alert');
			var resetBtn = document.getElementById('transfer-reset');
			var removedWrap = document.getElementById('removed-transfer-items');
			var transferForm = body ? body.closest('form') : null;
			if (!body || !addBtn || !searchInput) {
				return;
			}

			var initialItems = <?= json_encode($existing_transfer_items, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
			var selectedSuggestion = null;
			var fetchedSuggestions = [];
			var searchDebounce = null;

			function getFromWarehouseId() {
				var fromInput = document.querySelector('[name="from_warehouse_id"]');
				if (fromInput && fromInput.value) {
					return String(fromInput.value).trim();
				}
				var fallback = document.querySelector('.WarehouseValue');
				if (fallback && fallback.value) {
					return String(fallback.value).trim();
				}
				return '';
			}

			function showAlert(message) {
				if (!alertBox) {
					if (typeof window.alert === 'function') {
						window.alert(message);
					}
					return;
				}
				alertBox.textContent = message;
				alertBox.classList.remove('hidden');
				window.clearTimeout(alertBox._hideTimer);
				alertBox._hideTimer = window.setTimeout(function() {
					alertBox.classList.add('hidden');
				}, 2800);
			}

			function clearSuggestions() {
				fetchedSuggestions = [];
				selectedSuggestion = null;
				if (resultsPanel) {
					resultsPanel.innerHTML = '';
					resultsPanel.classList.add('hidden');
				}
			}

			function renderSuggestions(items) {
				if (!resultsPanel) {
					return;
				}
				if (!Array.isArray(items) || !items.length) {
					resultsPanel.innerHTML = '<div class="transfer-item-result-empty">No matching products</div>';
					resultsPanel.classList.remove('hidden');
					return;
				}
				resultsPanel.innerHTML = items.map(function(item, index) {
					var row = item.row || {};
					var code = row.code ? ' (' + esc(row.code) + ')' : '';
					return '' +
						'<button type="button" class="transfer-item-result" data-suggestion-index="' + index + '">' +
						'<span class="transfer-item-result-name">' + esc(row.item_name || item.label || 'Item') + code + '</span>' +
						'<span class="transfer-item-result-meta">' + esc(row.unit || row.unit_type || 'Pieces') + '</span>' +
						'</button>';
				}).join('');
				resultsPanel.classList.remove('hidden');
			}

			function requestSuggestions(term) {
				var warehouseId = getFromWarehouseId();
				if (!warehouseId) {
					clearSuggestions();
					showAlert('Please select a warehouse before searching products.');
					return;
				}
				var url = '<?= base_url('admin/common/suggestions') ?>';
				$.ajax({
					url: url,
					type: 'GET',
					dataType: 'json',
					data: {
						term: term || '',
						warehouse_id: warehouseId,
						limit: 10
					},
					success: function(response) {
						fetchedSuggestions = Array.isArray(response) ? response : [];
						renderSuggestions(fetchedSuggestions);
					},
					error: function() {
						clearSuggestions();
						showAlert('Could not load products. Please try again.');
					}
				});
			}

			function esc(value) {
				return String(value == null ? '' : value)
					.replace(/&/g, '&amp;')
					.replace(/</g, '&lt;')
					.replace(/>/g, '&gt;')
					.replace(/"/g, '&quot;')
					.replace(/'/g, '&#039;');
			}

			function normalize(item) {
				return {
					items_id: item && (item.items_id || item.transfer_itemList_id) ? (item.items_id || item.transfer_itemList_id) : '',
					saved_items_id: item && item.saved_items_id ? item.saved_items_id : 0,
					item_name: item && item.item_name ? item.item_name : '',
					item_desc: item && item.item_desc ? item.item_desc : '',
					unit: item && (item.unit || item.unit_type) ? (item.unit || item.unit_type) : 'Pieces',
					quantity: item && item.quantity ? item.quantity : 1,
					unit_cost: item && (item.unit_cost || item.rate) ? (item.unit_cost || item.rate) : 0,
				};
			}

			function renderRow(item) {
				var row = document.createElement('tr');
				row.className = 'transfer-row';
				row.innerHTML = '' +
					'<td class="transfer-col-index text-muted-foreground font-semibold"></td>' +
					'<td>' +
					'<input type="hidden" data-field="items_id" value="' + esc(item.items_id) + '">' +
					'<input type="hidden" data-field="saved_items_id" value="' + esc(item.saved_items_id) + '">' +
					'<input type="hidden" data-field="unit_cost" value="' + esc(item.unit_cost) + '">' +
					'<div class="space-y-1">' +
					'<input type="text" data-field="item_name" value="' + esc(item.item_name) + '" class="h-9 w-full rounded-md border border-border bg-background px-3 text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" placeholder="<?= lang('item_name_placeholder') ?>">' +
					'<input type="text" data-field="item_desc" value="' + esc(item.item_desc) + '" class="h-8 w-full rounded-md border border-border bg-background px-3 text-xs text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" placeholder="<?= lang('item_detail_placeholder') ?>">' +
					'</div>' +
					'</td>' +
					'<td><input type="text" data-field="unit" value="' + esc(item.unit) + '" class="h-9 w-full rounded-md border border-border bg-background px-2 text-center text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"></td>' +
					'<td><input type="number" min="0" step="0.01" data-field="quantity" value="' + esc(item.quantity) + '" class="h-9 w-full rounded-md border border-border bg-background px-2 text-center text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"></td>' +
					'<td class="text-right"><button type="button" class="inline-flex h-9 w-9 items-center justify-center rounded-md border border-rose-200 bg-rose-50 text-rose-600 hover:bg-rose-100" data-remove-row><i data-lucide="trash-2" class="h-4 w-4"></i></button></td>';
				body.appendChild(row);
				if (window.lucide && typeof window.lucide.createIcons === 'function') {
					window.lucide.createIcons({
						attrs: {
							'stroke-width': 1.75
						}
					});
				}
			}

			function updateNamesAndTotals() {
				var rows = body.querySelectorAll('tr.transfer-row');
				var sum = 0;
				rows.forEach(function(row, index) {
					var idxCell = row.querySelector('.transfer-col-index');
					if (idxCell) {
						idxCell.textContent = String(index + 1);
					}
					row.querySelectorAll('[data-field]').forEach(function(field) {
						var key = field.getAttribute('data-field');
						if (key) {
							field.name = 'items[' + index + '][' + key + ']';
						}
					});
					var qty = parseFloat(row.querySelector('[data-field="quantity"]')?.value || '0') || 0;
					sum += qty;
				});
				if (totalQty) {
					totalQty.textContent = Number(sum % 1 === 0 ? sum.toFixed(0) : sum.toFixed(2)).toString();
				}
			}

			function countValidRows() {
				var valid = 0;
				body.querySelectorAll('tr.transfer-row').forEach(function(row) {
					var saved = row.querySelector('[data-field="saved_items_id"]');
					var nameInput = row.querySelector('[data-field="item_name"]');
					var qtyInput = row.querySelector('[data-field="quantity"]');
					var hasSaved = saved && saved.value && saved.value !== '0' && saved.value !== 'undefined';
					var hasManualName = nameInput && nameInput.value && String(nameInput.value).trim() !== '';
					var hasQty = qtyInput && (parseFloat(qtyInput.value || '0') > 0);
					if (hasQty && (hasSaved || hasManualName)) {
						valid++;
					}
				});
				return valid;
			}

			function appendSelectedSuggestion(selected) {
				var warehouseId = getFromWarehouseId();
				if (!warehouseId) {
					showAlert('Please select a warehouse before adding products.');
					return false;
				}
				if (!selected) {
					showAlert('Search and select a product from the list first.');
					return false;
				}

				var rowData = normalize(selected.row || selected);
				if (!rowData.saved_items_id) {
					showAlert('Selected product is invalid. Please choose another.');
					return false;
				}

				renderRow(rowData);
				searchInput.value = '';
				clearSuggestions();
				updateNamesAndTotals();
				return true;
			}

			addBtn.addEventListener('click', function() {
				var selected = selectedSuggestion;
				if (!selected && fetchedSuggestions.length === 1) {
					selected = fetchedSuggestions[0];
				}
				if (selected) {
					appendSelectedSuggestion(selected);
					return;
				}

				renderRow(normalize({
					item_name: '',
					item_desc: '',
					unit: 'Pieces',
					quantity: 1,
					saved_items_id: 0,
					unit_cost: 0
				}));
				updateNamesAndTotals();
				var rows = body.querySelectorAll('tr.transfer-row');
				if (rows.length) {
					var lastName = rows[rows.length - 1].querySelector('[data-field="item_name"]');
					if (lastName) {
						lastName.focus();
					}
				}
			});

			searchInput.addEventListener('keydown', function(event) {
				if (event.key === 'Enter') {
					event.preventDefault();
					if (!resultsPanel || resultsPanel.classList.contains('hidden')) {
						addBtn.click();
					}
				}
			});

			searchInput.addEventListener('input', function() {
				var term = (searchInput.value || '').trim();
				selectedSuggestion = null;
				window.clearTimeout(searchDebounce);
				searchDebounce = window.setTimeout(function() {
					if (!term) {
						clearSuggestions();
						return;
					}
					requestSuggestions(term);
				}, 220);
			});

			searchInput.addEventListener('focus', function() {
				if (!getFromWarehouseId()) {
					showAlert('Please select a warehouse before searching products.');
					return;
				}
				var term = (searchInput.value || '').trim();
				if (term) {
					requestSuggestions(term);
				}
			});

			if (resultsPanel) {
				resultsPanel.addEventListener('click', function(event) {
					var option = event.target.closest('[data-suggestion-index]');
					if (!option) {
						return;
					}
					var idx = parseInt(option.getAttribute('data-suggestion-index'), 10);
					if (isNaN(idx) || !fetchedSuggestions[idx]) {
						return;
					}
					selectedSuggestion = fetchedSuggestions[idx];
					appendSelectedSuggestion(selectedSuggestion);
				});
			}

			document.addEventListener('click', function(event) {
				if (event.target.closest('#transfer-item-results') || event.target.closest('#transfer-item-search')) {
					return;
				}
				if (resultsPanel) {
					resultsPanel.classList.add('hidden');
				}
			});

			body.addEventListener('input', function(event) {
				if (event.target && event.target.closest('tr.transfer-row')) {
					updateNamesAndTotals();
				}
			});

			body.addEventListener('click', function(event) {
				var removeBtn = event.target.closest('[data-remove-row]');
				if (!removeBtn) {
					return;
				}
				var row = removeBtn.closest('tr.transfer-row');
				if (!row) {
					return;
				}
				var existingId = row.querySelector('[data-field="items_id"]');
				if (existingId && existingId.value && removedWrap) {
					var removedInput = document.createElement('input');
					removedInput.type = 'hidden';
					removedInput.name = 'removed_items[]';
					removedInput.value = existingId.value;
					removedWrap.appendChild(removedInput);
				}
				row.remove();
				updateNamesAndTotals();
			});

			if (resetBtn) {
				resetBtn.addEventListener('click', function() {
					body.innerHTML = '';
					if (removedWrap) {
						removedWrap.innerHTML = '';
					}
					clearSuggestions();
					searchInput.value = '';
					if (Array.isArray(initialItems) && initialItems.length) {
						initialItems.forEach(function(item) {
							renderRow(normalize(item));
						});
					}
					updateNamesAndTotals();
				});
			}

			if (Array.isArray(initialItems) && initialItems.length) {
				initialItems.forEach(function(item) {
					renderRow(normalize(item));
				});
			}
			updateNamesAndTotals();

			if (transferForm) {
				transferForm.addEventListener('submit', function(event) {
					if (countValidRows() < 1) {
						event.preventDefault();
						showAlert('Please add at least one item with name and quantity before creating transfer.');
						searchInput.focus();
					}
				});
			}
		})();
	</script>
	<style>
		#transfer-attachments-dropzone {
			min-height: 160px;
			border-color: hsl(var(--border));
			background: hsl(var(--background));
		}

		#transfer-attachments-dropzone:hover {
			background: hsl(var(--muted) / 0.35);
		}

		#transfer-attachments-dropzone .dz-message {
			margin: 0;
		}
	</style>

	<style>
		.transfer-item-results {
			position: absolute;
			left: 0;
			right: 0;
			top: calc(100% + 6px);
			z-index: 30;
			max-height: 280px;
			overflow-y: auto;
			border: 1px solid #d4d4d8;
			border-radius: 8px;
			background: #ffffff;
			box-shadow: 0 10px 24px rgba(2, 6, 23, 0.08);
		}

		.dark .transfer-item-results {
			border-color: #3f3f46;
			background: #111827;
			box-shadow: 0 10px 24px rgba(0, 0, 0, 0.4);
		}

		.transfer-item-result {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 12px;
			padding: 9px 10px;
			text-align: left;
			border: 0;
			background: transparent;
		}

		.transfer-item-result:hover {
			background: #f4f4f5;
		}

		.dark .transfer-item-result:hover {
			background: #1f2937;
		}

		.transfer-item-result-name {
			font-size: 12px;
			font-weight: 600;
			color: #111827;
		}

		.dark .transfer-item-result-name {
			color: #f3f4f6;
		}

		.transfer-item-result-meta {
			font-size: 11px;
			color: #71717a;
		}

		.dark .transfer-item-result-meta {
			color: #a1a1aa;
		}

		.transfer-item-result-empty {
			padding: 10px;
			font-size: 12px;
			color: #71717a;
		}

		.dark .transfer-item-result-empty {
			color: #a1a1aa;
		}

		.transfer-item-alert {
			border: 1px solid #fda4af;
			background: #fff1f2;
			color: #be123c;
			font-size: 12px;
			font-weight: 600;
			border-radius: 8px;
			padding: 8px 10px;
		}

		.dark .transfer-item-alert {
			border-color: #9f1239;
			background: rgba(159, 18, 57, 0.18);
			color: #fda4af;
		}

		.transfer-items-table {
			border-collapse: collapse;
		}

		.transfer-items-table thead th {
			font-size: 10px;
			font-weight: 700;
			letter-spacing: 0.14em;
			text-transform: uppercase;
			color: #71717a;
			background: #f4f4f5;
			padding: 10px 12px;
			border-bottom: 1px solid #e4e4e7;
		}

		.transfer-items-table tbody td,
		.transfer-items-table tfoot td {
			padding: 10px 12px;
			border-bottom: 1px solid #e4e4e7;
			vertical-align: middle;
		}

		.transfer-items-table tfoot td {
			background: #fafafa;
			border-bottom: 0;
		}

		.dark .transfer-items-table thead th {
			color: #a1a1aa;
			background: #18181b;
			border-bottom-color: #3f3f46;
		}

		.dark .transfer-items-table tbody td,
		.dark .transfer-items-table tfoot td {
			border-bottom-color: #3f3f46;
		}

		.dark .transfer-items-table tfoot td {
			background: #18181b;
		}

		.transfer-footer-actions {
			border: 1px solid #d4d4d8;
			border-radius: 10px;
			background: #fafafa;
			padding: 10px 12px;
		}

		.dark .transfer-footer-actions {
			border-color: #3f3f46;
			background: #18181b;
		}

		.transfer-footer-actions input,
		.transfer-footer-actions button {
			height: 36px !important;
			border-radius: 8px !important;
			font-size: 12px !important;
			font-weight: 600;
		}

		.transfer-footer-actions #transfer-reset {
			border-color: #fecdd3 !important;
			background: #fff1f2 !important;
			color: #e11d48 !important;
		}

		.dark .transfer-footer-actions #transfer-reset {
			border-color: #9f1239 !important;
			background: rgba(159, 18, 57, 0.18) !important;
			color: #fda4af !important;
		}
	</style>
<?php } else { ?>
	<div class="rounded-2xl border border-border bg-card p-6 text-sm text-muted-foreground">
		<?= lang('you_dont_have_permission') ?>
	</div>
<?php } ?>
