<?php defined('BASEPATH') or exit('No direct script access allowed');

$invoice_view = config_item('invoice_view');
$default_currency = $this->admin_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$currency_symbol = !empty($default_currency->symbol) ? $default_currency->symbol : '';
$tax_rates = $this->db->order_by('tax_rate_name', 'ASC')->get('tbl_tax_rates')->result();

$initial_items = array();
if (!empty($add_items)) {
	if (is_string($add_items)) {
		$decoded_items = json_decode($add_items);
		if (json_last_error() === JSON_ERROR_NONE && is_array($decoded_items)) {
			$initial_items = $decoded_items;
		}
	} elseif (is_array($add_items)) {
		$initial_items = $add_items;
	}
}

$show_quantity_value = 'qty';
if (!empty($info) && !empty($info->show_quantity_as)) {
	$show_quantity_value = strtolower((string) $info->show_quantity_as);
} elseif (!empty($hours_quantity)) {
	$show_quantity_value = 'hours';
} elseif (!empty($qty_hrs_quantity)) {
	$show_quantity_value = 'qty_hours';
}
if (!in_array($show_quantity_value, array('qty', 'hours', 'qty_hours'), true)) {
	$show_quantity_value = 'qty';
}

$discount_percent = !empty($info) && isset($info->discount_percent) ? $info->discount_percent : 0;
$adjustment_value = !empty($info) && isset($info->adjustment) ? $info->adjustment : 0;
$tax_lookup = array();
if (!empty($tax_rates)) {
	foreach ($tax_rates as $tax_rate) {
		$tax_lookup[$tax_rate->tax_rates_id] = $tax_rate->tax_rate_name . '|' . $tax_rate->tax_rate_percent;
	}
}
$is_transfer = !empty($itemType) && $itemType === 'transfer';
$hide_bottom_toolbar = !empty($hide_bottom_toolbar);
$line_title = $is_transfer ? 'Line Items' : 'Line Items';
$line_subtitle = $is_transfer ? 'Add and review transferred products' : lang('manage') . ' ' . strtolower(lang('items'));
?>

<div class="bt">
	<div class="prodcutTable rounded-2xl border border-border bg-card shadow-sm"
		data-terget="<?= html_escape($itemType) ?>"
		data-currency-symbol="<?= html_escape($currency_symbol) ?>">
		<div class="flex flex-col gap-4 border-b border-border px-5 py-4 xl:flex-row xl:items-center xl:justify-between">
			<div class="flex flex-col gap-3 md:flex-row md:flex-wrap md:items-center">
				<div class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-muted text-muted-foreground">
					<i data-lucide="layers" class="h-5 w-5"></i>
				</div>
				<div>
					<h3 class="text-base font-semibold text-foreground"><?= $line_title ?></h3>
					<p class="text-sm text-muted-foreground"><?= $line_subtitle ?></p>
				</div>
				<?php if (!$is_transfer) { ?>
					<div class="inline-flex flex-wrap items-center rounded-full border border-border bg-muted/40 p-1">
						<label class="inline-flex cursor-pointer items-center">
							<input type="radio" value="qty" name="show_quantity_as" class="peer sr-only" <?= $show_quantity_value === 'qty' ? 'checked' : '' ?>>
							<span class="rounded-full px-3.5 py-2 text-xs font-semibold text-muted-foreground transition peer-checked:bg-primary peer-checked:text-white"><?= lang('qty'); ?></span>
						</label>
						<label class="inline-flex cursor-pointer items-center">
							<input type="radio" value="hours" name="show_quantity_as" class="peer sr-only" <?= $show_quantity_value === 'hours' ? 'checked' : '' ?>>
							<span class="rounded-full px-3.5 py-2 text-xs font-semibold text-muted-foreground transition peer-checked:bg-primary peer-checked:text-white"><?= lang('hours'); ?></span>
						</label>
						<label class="inline-flex cursor-pointer items-center">
							<input type="radio" value="qty_hours" name="show_quantity_as" class="peer sr-only" <?= $show_quantity_value === 'qty_hours' ? 'checked' : '' ?>>
							<span class="rounded-full px-3.5 py-2 text-xs font-semibold text-muted-foreground transition peer-checked:bg-primary peer-checked:text-white"><?= lang('qty') . '/' . lang('hours'); ?></span>
						</label>
					</div>
				<?php } else { ?>
					<input type="hidden" name="show_quantity_as" value="<?= html_escape($show_quantity_value) ?>">
				<?php } ?>
			</div>

			<div class="grid w-full gap-2 md:grid-cols-[minmax(0,1fr)_auto] xl:w-auto xl:min-w-[520px]">
				<div class="relative min-w-0 w-full">
					<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"
						placeholder="<?= lang('search_product_barcode') ?>"
						id="<?= html_escape($itemType) ?>_item"
						class="h-10 w-full rounded-xl border border-border bg-background pl-10 pr-3 text-[13px] text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 md:h-11 md:text-sm md:pl-11">
					<div class="absolute left-0 right-0 top-[calc(100%+0.35rem)] z-30 hidden max-h-72 overflow-y-auto rounded-xl border border-border bg-card shadow-lg" data-legacy-item-search-results></div>
				</div>
				<div class="flex items-center justify-stretch gap-2 md:justify-end">
					<?php if (!$is_transfer) { ?>
						<?= btn_modal(
							'admin/items/manuallyItems',
							'',
							'',
							'lg',
							'plus',
							array(
								'class' => 'inline-flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-muted text-muted-foreground hover:bg-muted/70 md:h-11 md:w-11',
								'title' => lang('add') . ' ' . lang('manual'),
							)
						) ?>
					<?php } ?>
					<button type="button"
						class="inline-flex h-10 flex-1 items-center justify-center gap-1.5 rounded-xl bg-primary px-3 text-[13px] font-semibold text-white shadow-sm hover:bg-primary/90 md:h-11 md:flex-none md:px-3.5 md:text-sm"
						data-legacy-add-row>
						<i data-lucide="plus" class="h-3.5 w-3.5 md:h-4 md:w-4"></i>
						<?= $is_transfer ? lang('add_item') : lang('add') . ' ' . lang('row') ?>
					</button>
				</div>
			</div>
		</div>

		<div class="s_table overflow-x-auto">
			<table class="invoice-items-table items mb-0 min-w-[1280px] border-collapse">
				<thead class="bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground">
					<tr>
						<th class="w-12 px-4 py-2 text-left">#</th>
						<th class="min-w-[340px] px-4 py-2 text-left"><?= lang('item_details') ?></th>
						<th class="w-[120px] px-3 py-2 text-left"><?= lang('unit') ?></th>
						<th class="qty w-[110px] px-3 py-2 text-left"><?= $show_quantity_value === 'hours' ? lang('hours') : ($show_quantity_value === 'qty_hours' ? lang('qty') . '/' . lang('hours') : lang('qty')) ?></th>
						<?php if (!$is_transfer) { ?>
							<th class="w-[120px] px-3 py-2 text-left"><?= lang('price') ?></th>
							<th class="w-[220px] px-3 py-2 text-left"><?= lang('tax_rate') ?></th>
							<th class="w-[140px] px-3 py-2 text-right"><?= lang('total') ?></th>
						<?php } ?>
						<th class="hidden-print w-[70px] px-3 py-2 text-right"><?= lang('action') ?></th>
					</tr>
				</thead>
				<tbody id="<?= html_escape($itemType) ?>Table" class="divide-y divide-slate-200 dark:divide-slate-800" data-legacy-items-body></tbody>
			</table>
		</div>

		<?php if (!$is_transfer) { ?>
			<div class="border-t border-border px-5 py-6">
				<div class="grid gap-4 2xl:grid-cols-[minmax(0,1fr)_380px]">
					<div class="grid gap-4 sm:grid-cols-2">
						<?php
						$adjustmentText = $itemType != 'transfer' ? 'adjustment' : 'shipping_cost';
						if ($itemType != 'transfer') {
						?>
							<label class="block rounded-2xl border border-border bg-card p-4 shadow-sm">
								<span class="mb-2.5 block text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground"><?= lang('discount'); ?> (%)</span>
								<input type="number" name="discount_percent" value="<?= html_escape($discount_percent) ?>" data-parsley-type="number" min="0" max="100" class="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm font-medium text-foreground shadow-inner focus:border-primary focus:bg-background focus:outline-none focus:ring-2 focus:ring-primary/20">
							</label>
						<?php } ?>

						<label class="block rounded-2xl border border-border bg-card p-4 shadow-sm">
							<span class="mb-2.5 block text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground"><?= lang($adjustmentText); ?></span>
							<input type="number" name="adjustment" value="<?= html_escape($adjustment_value) ?>" data-parsley-type="number" class="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm font-medium text-foreground shadow-inner focus:border-primary focus:bg-background focus:outline-none focus:ring-2 focus:ring-primary/20">
						</label>

						<?php
						if ($itemType == 'invoice') {
							do_action('add_more_field_after_discount_field', !empty($info) ? $info : '');
						}
						?>
					</div>

					<div class="rounded-2xl border border-border bg-muted/30 p-4">
						<div class="space-y-3 text-sm">
							<div class="flex items-center justify-between gap-4 text-muted-foreground">
								<span><?= lang('sub_total'); ?></span>
								<span class="subtotal text-lg font-semibold text-foreground">0.00</span>
							</div>
							<div class="space-y-2" data-legacy-tax-breakdown></div>
							<div class="flex items-center justify-between gap-4 text-muted-foreground">
								<span><?= lang('tax'); ?></span>
								<span class="tax_total text-lg font-semibold text-foreground">0.00</span>
							</div>
							<?php if ($itemType != 'transfer') { ?>
								<div class="flex items-center justify-between gap-4 text-muted-foreground">
									<span><?= lang('discount'); ?></span>
									<span class="discount_percent text-lg font-semibold text-rose-500">0.00</span>
								</div>
							<?php } ?>
							<div class="flex items-center justify-between gap-4 text-muted-foreground">
								<span><?= lang($adjustmentText); ?></span>
								<span class="adjustment text-lg font-semibold text-foreground"><?= display_money($adjustment_value, $currency_symbol) ?></span>
							</div>
							<div class="border-t border-border pt-3">
								<div class="flex items-end justify-between gap-4">
									<div>
										<p class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">Total Amount</p>
										<p class="mt-1 text-[11px] text-muted-foreground">Ready to save this document</p>
									</div>
									<span class="total text-[2rem] font-semibold text-primary">0.00</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		<?php } else { ?>
			<input type="hidden" name="adjustment" value="<?= html_escape($adjustment_value) ?>">
		<?php } ?>
	</div>
</div>

<div data-legacy-tax-hidden></div>
<div id="removed-items" data-legacy-removed-items></div>
<input type="hidden" name="discount_total" value="0.00" data-legacy-discount-total>

<?php if (!$hide_bottom_toolbar) { ?>
	<div class="btn-bottom-toolbar mt-4 flex flex-wrap items-center justify-between gap-2 text-right">
		<div class="flex items-center gap-2">
			<input type="button" id="Preset" value="<?= $is_transfer ? 'Reset Form' : lang('reset') ?>" name="update" class="inline-flex h-9 items-center cursor-pointer rounded-lg border border-rose-200 bg-rose-50 px-4 text-sm font-semibold text-rose-700 hover:bg-rose-100">
		</div>
		<div class="flex flex-wrap items-center gap-2">
		<?php if (!empty($add_items)) { ?>
			<input type="hidden" name="isedit" value="1">
			<input type="submit" value="<?= $is_transfer ? 'Save Changes' : lang('update') ?>" name="create" class="inline-flex h-9 items-center rounded-lg border border-sky-200 cursor-pointer bg-sky-50 px-4 text-sm font-semibold text-sky-700 hover:bg-sky-100">
			<button type="button" onclick="goBack()" 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"><?= lang('cancel') ?></button>
		<?php } else { ?>
			<input type="submit" value="<?= $is_transfer ? 'Save Draft' : lang('save_as_draft') ?>" name="save_as_draft" class="inline-flex h-9 items-center rounded-lg cursor-pointer border border-sky-200 bg-sky-50 px-4 text-sm font-semibold text-sky-700 hover:bg-sky-100">
			<input type="submit" value="<?= $is_transfer ? 'Create Transfer' : lang('update') ?>" name="update" class="inline-flex h-9 items-center rounded-lg border border-emerald-200 cursor-pointer bg-emerald-50 px-4 text-sm font-semibold text-emerald-700 hover:bg-emerald-100">
		<?php } ?>
		</div>
	</div>
<?php } ?>

<script>
	(function() {
		const itemType = <?= json_encode($itemType) ?>;
		const isTransfer = itemType === 'transfer';
		const initialItems = <?= json_encode($initial_items, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
		const invoiceView = <?= json_encode((string) $invoice_view) ?>;
		const container = document.querySelector('.prodcutTable[data-terget="<?= html_escape($itemType) ?>"]');
		if (!container || container.dataset.legacyReady === '1') {
			return;
		}
		container.dataset.legacyReady = '1';

		const tbody = container.querySelector('[data-legacy-items-body]');
		const removedWrap = document.querySelector('[data-legacy-removed-items]');
		const taxHiddenWrap = document.querySelector('[data-legacy-tax-hidden]');
		const subtotalCell = container.querySelector('.subtotal');
		const discountCell = container.querySelector('.discount_percent');
		const taxTotalCell = container.querySelector('.tax_total');
		const taxBreakdownWrap = container.querySelector('[data-legacy-tax-breakdown]');
		const adjustmentCell = container.querySelector('.adjustment');
		const totalCell = container.querySelector('.total');
		const discountInput = container.querySelector('input[name="discount_percent"]');
		const adjustmentInput = container.querySelector('input[name="adjustment"]');
		const discountTotalInput = document.querySelector('[data-legacy-discount-total]');
		const qtyLabel = container.querySelector('th.qty');
		const addRowButton = container.querySelector('[data-legacy-add-row]');
		const resetButton = document.getElementById('Preset');
		const searchInput = container.querySelector('#<?= html_escape($itemType) ?>_item');
		const searchResults = container.querySelector('[data-legacy-item-search-results]');
		const currencySymbol = container.getAttribute('data-currency-symbol') || '';
		const taxLookupMap = <?= json_encode($tax_lookup, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
		const appBaseUrl = (typeof window.base_url === 'string' && window.base_url)
			|| (window.appConfig && typeof window.appConfig.base_url === 'string' && window.appConfig.base_url)
			|| <?= json_encode(base_url()) ?>;
		const taxOptions = Object.values(taxLookupMap || {}).map((value) => {
			const parts = String(value).split('|');
			const name = (parts[0] || '').trim();
			const percent = (parts[1] || '').trim();
			return {
				value,
				label: percent ? `${name} (${percent}%)` : name,
			};
		}).filter((opt) => opt.value && opt.label);

		if (!tbody) {
			return;
		}

		let itemSearchToken = 0;

		const getWarehouseField = () => {
			const form = container.closest('form');
			const scope = form || document;
			return scope.querySelector('[name="warehouse_id"]') || scope.querySelector('[name="warehouseId"]') || null;
		};

		const clearWarehouseHighlight = () => {
			const field = getWarehouseField();
			if (!field) return;
			const wrap = field.closest('.form-group, [data-lookup], .relative, .col-sm-6, .col-sm-4') || field.parentElement;
			if (wrap) {
				wrap.classList.remove('ring-2', 'ring-rose-300', 'dark:ring-rose-700', 'rounded-lg');
			}
		};

		const requireWarehouseSelection = () => {
			const field = getWarehouseField();
			if (!field) {
				return true;
			}
			const selected = String(field.value || '').trim();
			if (selected) {
				clearWarehouseHighlight();
				return true;
			}

			const wrap = field.closest('.form-group, [data-lookup], .relative, .col-sm-6, .col-sm-4') || field.parentElement;
			if (wrap) {
				wrap.classList.add('ring-2', 'ring-rose-300', 'dark:ring-rose-700', 'rounded-lg');
			}
			if (searchResults) {
					searchResults.innerHTML = '<div class="px-3 py-2 text-sm font-medium text-rose-600 dark:text-rose-400">' + <?= json_encode(lang('please_select_warehouse_first')) ?> + '</div>';
				searchResults.classList.remove('hidden');
			}
			if (window.toastr && typeof window.toastr.warning === 'function') {
					window.toastr.warning(<?= json_encode(lang('please_select_warehouse_first')) ?>);
			}
			return false;
		};

		const closeItemResults = () => {
			if (!searchResults) return;
			searchResults.classList.add('hidden');
			searchResults.innerHTML = '';
		};

		const getWarehouseId = () => {
			const field = getWarehouseField();
			return field ? String(field.value || '').trim() : '';
		};

		const renderItemResults = (items) => {
			if (!searchResults) return;
			if (!items.length) {
				searchResults.innerHTML = '<div class="px-3 py-2 text-sm text-muted-foreground">No items found</div>';
				searchResults.classList.remove('hidden');
				return;
			}

			searchResults.innerHTML = items.map((entry) => {
				const row = entry && entry.row ? entry.row : {};
				const label = entry && entry.label ? entry.label : (row.item_name || '');
				const desc = row && row.item_desc ? String(row.item_desc).replace(/<[^>]*>/g, '').trim() : '';
				const price = parseFloat(row.unit_cost || row.rate || 0) || 0;
				return `<button type="button" class="flex w-full items-start justify-between gap-3 px-3 py-2 text-left hover:bg-muted" data-legacy-item-payload='${escapeHtml(JSON.stringify(entry))}'>
					<span class="min-w-0">
						<span class="block truncate text-sm font-medium text-foreground">${escapeHtml(label)}</span>
						<span class="block truncate text-xs text-muted-foreground">${escapeHtml(desc || 'Saved item')}</span>
					</span>
					<span class="shrink-0 text-xs font-semibold text-muted-foreground">${escapeHtml(formatAmount(price))}</span>
				</button>`;
			}).join('');
			searchResults.classList.remove('hidden');
		};

		const fetchItemSuggestions = (term) => {
			if (!searchInput || !searchResults) return;
			const query = String(term || '').trim();
			if (query.length < 2) {
				closeItemResults();
				return;
			}
			if (!requireWarehouseSelection()) {
				return;
			}

			itemSearchToken += 1;
			const token = itemSearchToken;
			searchResults.innerHTML = '<div class="px-3 py-2 text-sm text-muted-foreground">Searching...</div>';
			searchResults.classList.remove('hidden');

			const url = `${appBaseUrl}admin/common/suggestions?term=${encodeURIComponent(query)}&warehouse_id=${encodeURIComponent(getWarehouseId())}`;
			fetch(url, {
				headers: {
					'X-Requested-With': 'XMLHttpRequest'
				},
			})
				.then((response) => response.json())
				.then((data) => {
					if (token !== itemSearchToken) return;
					const items = Array.isArray(data)
						? data.filter((entry) => entry && entry.saved_items_id && String(entry.saved_items_id) !== '0' && entry.row)
						: [];
					renderItemResults(items);
				})
				.catch((error) => {
					if (token !== itemSearchToken) return;
					searchResults.innerHTML = '<div class="px-3 py-2 text-sm text-rose-500">Unable to load items</div>';
					searchResults.classList.remove('hidden');
				});
		};

		const debounce = (fn, wait) => {
			let timer = null;
			return function() {
				const args = arguments;
				clearTimeout(timer);
				timer = setTimeout(() => fn.apply(null, args), wait);
			};
		};

		const debouncedItemSearch = debounce(fetchItemSuggestions, 220);

		const formatAmount = (value) => {
			const amount = Number(value || 0);
			const formatted = amount.toFixed(2);
			return currencySymbol ? `${currencySymbol} ${formatted}` : formatted;
		};

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

		const normalizeTaxes = (taxes) => {
			if (!Array.isArray(taxes)) {
				return [];
			}
			return taxes.filter(Boolean).map((tax) => String(tax));
		};

		const rowMarkup = (data) => {
			if (isTransfer) {
				return `
					<td class="px-4 py-3 text-sm font-semibold text-muted-foreground" data-legacy-index></td>
					<td class="px-4 py-3">
						<input type="hidden" data-legacy-field="items_id" value="${escapeHtml(data.items_id || '')}">
						<input type="hidden" data-legacy-field="saved_items_id" value="${escapeHtml(data.saved_items_id || 0)}">
						<input type="hidden" data-legacy-field="item_desc" value="${escapeHtml(data.item_desc || '')}">
						<input type="hidden" data-legacy-field="unit_cost" value="${escapeHtml(data.unit_cost || 0)}">
						<div class="space-y-1.5">
							<input type="text" data-legacy-field="item_name" value="${escapeHtml(data.item_name || '')}" placeholder="<?= lang('select') . ' ' . lang('item') ?>" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-sm font-medium text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20" readonly>
							${data.item_desc ? `<p class="text-xs text-muted-foreground">${escapeHtml(data.item_desc)}</p>` : ''}
						</div>
					</td>
					<td class="px-3 py-3">
						<input type="text" data-legacy-field="unit" value="${escapeHtml(data.unit || '1')}" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-center text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
					</td>
					<td class="px-3 py-3">
						<input type="number" step="0.01" min="0" data-legacy-field="quantity" value="${escapeHtml(data.quantity || 1)}" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-center text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
					</td>
					<td class="px-3 py-3 text-right">
						<button type="button" class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-rose-200 bg-rose-50 text-rose-600 hover:bg-rose-100" data-legacy-remove-item>
							<i data-lucide="trash-2" class="h-4 w-4"></i>
						</button>
					</td>
				`;
			}
			const taxes = normalizeTaxes(data.taxname);
			const taxBadges = taxes.length
				? taxes.map((tax) => {
					const parts = tax.split('|');
					const label = `${escapeHtml(parts[0] || tax)}${parts[1] ? ` (${escapeHtml(parts[1])}%)` : ''}`;
					return `<span class="inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-[11px] font-medium text-muted-foreground" data-legacy-tax-chip="${escapeHtml(tax)}">
						<span>${label}</span>
						<button type="button" class="rounded-full p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground" data-legacy-tax-remove="${escapeHtml(tax)}">
							<i data-lucide="x" class="h-3 w-3"></i>
						</button>
					</span>`;
				}).join('')
				: '';
			const taxHidden = taxes.map((tax) => `<input type="hidden" data-legacy-tax-hidden value="${escapeHtml(tax)}">`).join('');
			return `
				<td class="px-4 py-3 text-sm font-semibold text-muted-foreground" data-legacy-index></td>
				<td class="px-4 py-3">
					<input type="hidden" data-legacy-field="items_id" value="${escapeHtml(data.items_id || '')}">
					<input type="hidden" data-legacy-field="saved_items_id" value="${escapeHtml(data.saved_items_id || 0)}">
					<div class="space-y-2">
						<input type="text" data-legacy-field="item_name" value="${escapeHtml(data.item_name || '')}" placeholder="<?= lang('item_name') ?>" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-sm font-medium text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
						<textarea data-legacy-field="item_desc" rows="2" placeholder="<?= lang('description') ?>" class="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">${escapeHtml(data.item_desc || '')}</textarea>
						${invoiceView === '2' ? `
							<input type="text" data-legacy-field="hsn_code" value="${escapeHtml(data.hsn_code || '')}" placeholder="<?= lang('hsn_code') ?>" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-xs text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
						` : ''}
					</div>
				</td>
				<td class="px-3 py-3">
					<input type="text" data-legacy-field="unit" value="${escapeHtml(data.unit || '1')}" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-center text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
				</td>
				<td class="px-3 py-3">
					<input type="number" step="0.01" min="0" data-legacy-field="quantity" value="${escapeHtml(data.quantity || 1)}" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-center text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
				</td>
				<td class="px-3 py-3">
					<input type="number" step="0.01" min="0" data-legacy-field="unit_cost" value="${escapeHtml(data.unit_cost || 0)}" class="h-9 w-full rounded-lg border border-border bg-background px-3 text-sm text-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20">
				</td>
				<td class="px-3 py-3">
					<div class="relative">
						<div class="flex min-h-[42px] w-full flex-wrap items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 py-1.5 focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20" data-legacy-tax-control>
							<div class="${taxes.length ? '' : 'hidden '}contents" data-legacy-tax-badges>${taxBadges}</div>
							<input type="text" placeholder="<?= lang('search') . ' ' . lang('tax') ?>" class="min-w-[96px] flex-1 border-0 bg-transparent px-1 py-1 text-xs text-muted-foreground outline-none placeholder:text-muted-foreground focus:border-transparent focus:outline-none focus:ring-0" data-legacy-tax-input>
						</div>
						<div class="absolute z-30 mt-1 hidden max-h-48 w-full overflow-y-auto rounded-lg border border-border bg-card shadow-lg" data-legacy-tax-results></div>
						${taxHidden}
					</div>
				</td>
				<td class="px-3 py-3 text-right text-base font-semibold text-foreground" data-legacy-line-total>${formatAmount(0)}</td>
				<td class="px-3 py-3 text-right">
					<button type="button" class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-rose-200 bg-rose-50 text-rose-600 hover:bg-rose-100" data-legacy-remove-item>
						<i data-lucide="trash-2" class="h-4 w-4"></i>
					</button>
				</td>
			`;
		};

		const getRows = () => Array.from(tbody.querySelectorAll('tr[data-legacy-item-row]'));

		const updateNames = () => {
			getRows().forEach((row, index) => {
				const indexCell = row.querySelector('[data-legacy-index]');
				if (indexCell) {
					indexCell.textContent = String(index + 1);
				}

				row.querySelectorAll('[data-legacy-field]').forEach((field) => {
					const key = field.getAttribute('data-legacy-field');
					if (!key) {
						return;
					}
					field.name = `items[${index}][${key}]`;
				});

				row.querySelectorAll('[data-legacy-tax-hidden]').forEach((field) => {
					field.name = `items[${index}][taxname][]`;
				});
			});
		};

		const updateQtyHeader = () => {
			const checked = container.querySelector('input[name="show_quantity_as"]:checked');
			if (!qtyLabel || !checked) {
				return;
			}
			if (checked.value === 'hours') {
				qtyLabel.textContent = <?= json_encode(lang('hours')) ?>;
			} else if (checked.value === 'qty_hours') {
				qtyLabel.textContent = <?= json_encode(lang('qty') . '/' . lang('hours')) ?>;
			} else {
				qtyLabel.textContent = <?= json_encode(lang('qty')) ?>;
			}
		};

		const getRowInfo = (row) => {
			const quantity = parseFloat(row.querySelector('[data-legacy-field="quantity"]')?.value || '0') || 0;
			const rate = parseFloat(row.querySelector('[data-legacy-field="unit_cost"]')?.value || '0') || 0;
			const taxes = Array.from(row.querySelectorAll('[data-legacy-tax-hidden]')).map((input) => input.value).filter(Boolean);
			return {
				quantity,
				rate,
				lineTotal: quantity * rate,
				taxes,
			};
		};

		const updateRowTotal = (row) => {
			const lineTotalCell = row.querySelector('[data-legacy-line-total]');
			if (!lineTotalCell) {
				return;
			}
			const info = getRowInfo(row);
			lineTotalCell.textContent = formatAmount(info.lineTotal);
		};

		const updateTaxBadges = (row) => {
			const badgeWrap = row.querySelector('[data-legacy-tax-badges]');
			if (!badgeWrap) return;
			const taxes = Array.from(row.querySelectorAll('[data-legacy-tax-hidden]')).map((input) => input.value).filter(Boolean);
			if (!taxes.length) {
				badgeWrap.innerHTML = '';
				badgeWrap.classList.add('hidden');
				return;
			}
			badgeWrap.classList.remove('hidden');
			badgeWrap.innerHTML = taxes.map((tax) => {
				const parts = String(tax).split('|');
				const label = `${escapeHtml(parts[0] || tax)}${parts[1] ? ` (${escapeHtml(parts[1])}%)` : ''}`;
				return `<span class="inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-[11px] font-medium text-muted-foreground" data-legacy-tax-chip="${escapeHtml(tax)}">
					<span>${label}</span>
					<button type="button" class="rounded-full p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground" data-legacy-tax-remove="${escapeHtml(tax)}">
						<i data-lucide="x" class="h-3 w-3"></i>
					</button>
				</span>`;
			}).join('');
			if (window.lucide && typeof window.lucide.createIcons === 'function') {
				window.lucide.createIcons({
					attrs: {
						'stroke-width': 1.75
					}
				});
			}
		};

		const addTaxToRow = (row, taxValue) => {
			if (!taxValue) return;
			const exists = Array.from(row.querySelectorAll('[data-legacy-tax-hidden]')).some((input) => input.value === taxValue);
			if (exists) return;
			const hidden = document.createElement('input');
			hidden.type = 'hidden';
			hidden.setAttribute('data-legacy-tax-hidden', '1');
			hidden.value = taxValue;
			const control = row.querySelector('[data-legacy-tax-control]');
			if (control) {
				control.after(hidden);
			} else {
				row.querySelector('[data-legacy-tax-badges]')?.after(hidden);
			}
			updateNames();
			updateTaxBadges(row);
			updateTotals();
		};

		const updateTotals = () => {
			let subtotal = 0;
			const taxTotals = new Map();

			getRows().forEach((row) => {
				const info = getRowInfo(row);
				subtotal += info.lineTotal;
				info.taxes.forEach((taxValue) => {
					const taxParts = String(taxValue).split('|');
					const taxRate = parseFloat(taxParts[1] || '0') || 0;
					const taxAmount = (info.lineTotal * taxRate) / 100;
					taxTotals.set(taxValue, (taxTotals.get(taxValue) || 0) + taxAmount);
				});
			});

			let totalTax = 0;
			if (taxHiddenWrap) {
				taxHiddenWrap.innerHTML = '';
			}

			taxTotals.forEach((amount, taxValue) => {
				totalTax += amount;
				if (!taxHiddenWrap) {
					return;
				}
				const taxNameInput = document.createElement('input');
				taxNameInput.type = 'hidden';
				taxNameInput.name = 'total_tax_name[]';
				taxNameInput.value = taxValue;
				const taxValueInput = document.createElement('input');
				taxValueInput.type = 'hidden';
				taxValueInput.name = 'total_tax[]';
				taxValueInput.value = amount.toFixed(2);
				taxHiddenWrap.appendChild(taxNameInput);
				taxHiddenWrap.appendChild(taxValueInput);
			});

			if (taxBreakdownWrap) {
				if (!taxTotals.size) {
					taxBreakdownWrap.innerHTML = '';
				} else {
					taxBreakdownWrap.innerHTML = Array.from(taxTotals.entries()).map(([taxValue, amount]) => {
						const taxParts = String(taxValue).split('|');
						const taxName = taxParts[0] || taxValue;
						const taxRate = taxParts[1] ? `(${taxParts[1]}%)` : '';
						return `<div class="flex items-center justify-between gap-4 rounded-xl border border-border bg-background px-3 py-2 text-muted-foreground">
							<span class="min-w-0 truncate">
								<span class="font-semibold text-foreground">${escapeHtml(taxName)}</span>
								<span class="text-muted-foreground">${escapeHtml(taxRate)}</span>
							</span>
							<span class="shrink-0 font-semibold text-foreground">${escapeHtml(formatAmount(amount))}</span>
						</div>`;
					}).join('');
				}
			}

			const discountPercent = parseFloat(discountInput?.value || '0') || 0;
			const adjustment = parseFloat(adjustmentInput?.value || '0') || 0;
			const discountTotal = (subtotal * discountPercent) / 100;
			const total = subtotal - discountTotal + totalTax + adjustment;

			if (subtotalCell) {
				subtotalCell.textContent = formatAmount(subtotal);
			}
			if (discountCell) {
				discountCell.textContent = formatAmount(discountTotal);
			}
			if (taxTotalCell) {
				taxTotalCell.textContent = formatAmount(totalTax);
			}
			if (adjustmentCell) {
				adjustmentCell.textContent = formatAmount(adjustment);
			}
			if (totalCell) {
				totalCell.textContent = formatAmount(total);
			}
			if (discountTotalInput) {
				discountTotalInput.value = discountTotal.toFixed(2);
			}
		};

		const appendRow = (data) => {
			const row = document.createElement('tr');
			row.setAttribute('data-legacy-item-row', '1');
			row.className = 'align-top';
			row.innerHTML = rowMarkup(data || {});
			tbody.appendChild(row);
			updateNames();
			updateRowTotal(row);
			updateTotals();
			if (window.lucide && typeof window.lucide.createIcons === 'function') {
				window.lucide.createIcons({
					attrs: {
						'stroke-width': 1.75
					}
				});
			}
			return row;
		};

		const renderTaxResults = (resultsWrap, items) => {
			if (!resultsWrap) return;
			if (!items.length) {
				resultsWrap.innerHTML = '<div class="px-3 py-2 text-xs text-muted-foreground"><?= lang('nothing_to_display') ?></div>';
				resultsWrap.classList.remove('hidden');
				positionTaxResults(resultsWrap);
				return;
			}
			resultsWrap.innerHTML = items.map((item) => {
				return `<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-xs text-foreground hover:bg-muted" data-tax-value="${escapeHtml(item.value)}">
					<span>${escapeHtml(item.label)}</span>
				</button>`;
			}).join('');
			resultsWrap.classList.remove('hidden');
			positionTaxResults(resultsWrap);
		};

		const positionTaxResults = (resultsWrap) => {
			if (!resultsWrap || resultsWrap.classList.contains('hidden')) return;
			const row = resultsWrap.closest('tr[data-legacy-item-row]');
			const input = row ? row.querySelector('[data-legacy-tax-input]') : null;
			const control = row ? row.querySelector('[data-legacy-tax-control]') : null;
			if (!input && !control) return;
			const rect = (control || input).getBoundingClientRect();
			resultsWrap.style.position = 'fixed';
			resultsWrap.style.left = `${rect.left}px`;
			resultsWrap.style.top = `${rect.bottom + 6}px`;
			resultsWrap.style.width = `${rect.width}px`;
			resultsWrap.style.zIndex = '99999';
		};

		tbody.addEventListener('input', (event) => {
			const input = event.target.closest('[data-legacy-tax-input]');
			if (!input) return;
			const row = input.closest('tr[data-legacy-item-row]');
			const resultsWrap = row ? row.querySelector('[data-legacy-tax-results]') : null;
			if (!resultsWrap) return;
			const query = input.value.trim().toLowerCase();
			const items = query
				? taxOptions.filter((opt) => opt.label.toLowerCase().includes(query)).slice(0, 8)
				: taxOptions.slice(0, 8);
			renderTaxResults(resultsWrap, items);
		});

		tbody.addEventListener('focusin', (event) => {
			const input = event.target.closest('[data-legacy-tax-input]');
			if (!input) return;
			const row = input.closest('tr[data-legacy-item-row]');
			const resultsWrap = row ? row.querySelector('[data-legacy-tax-results]') : null;
			if (!resultsWrap) return;
			renderTaxResults(resultsWrap, taxOptions.slice(0, 8));
		});

		window.addEventListener('resize', () => {
			tbody.querySelectorAll('[data-legacy-tax-results]:not(.hidden)').forEach(positionTaxResults);
		});

		window.addEventListener('scroll', () => {
			tbody.querySelectorAll('[data-legacy-tax-results]:not(.hidden)').forEach(positionTaxResults);
		}, true);

		tbody.addEventListener('click', (event) => {
			const option = event.target.closest('[data-tax-value]');
			if (!option) return;
			const row = option.closest('tr[data-legacy-item-row]');
			const resultsWrap = option.closest('[data-legacy-tax-results]');
			const input = row ? row.querySelector('[data-legacy-tax-input]') : null;
			const taxValue = option.getAttribute('data-tax-value');
			if (!row || !taxValue) return;
			addTaxToRow(row, taxValue);
			if (input) {
				input.value = '';
			}
			if (resultsWrap) {
				resultsWrap.classList.add('hidden');
			}
		});

		document.addEventListener('click', (event) => {
			if (event.target.closest('[data-legacy-tax-input]') || event.target.closest('[data-legacy-tax-results]')) {
				return;
			}
			tbody.querySelectorAll('[data-legacy-tax-results]').forEach((panel) => {
				panel.classList.add('hidden');
			});
		});

		tbody.addEventListener('click', (event) => {
			const removeBtn = event.target.closest('[data-legacy-tax-remove]');
			if (!removeBtn) return;
			const row = removeBtn.closest('tr[data-legacy-item-row]');
			const taxValue = removeBtn.getAttribute('data-legacy-tax-remove');
			if (!row || !taxValue) return;
			row.querySelectorAll('[data-legacy-tax-hidden]').forEach((input) => {
				if (input.value === taxValue) {
					input.remove();
				}
			});
			updateTaxBadges(row);
			updateTotals();
		});

		const removeRow = (row) => {
			const itemIdField = row.querySelector('[data-legacy-field="items_id"]');
			const itemId = itemIdField ? itemIdField.value : '';
			if (itemId && removedWrap) {
				const removedInput = document.createElement('input');
				removedInput.type = 'hidden';
				removedInput.name = 'removed_items[]';
				removedInput.value = itemId;
				removedWrap.appendChild(removedInput);
			}
			row.remove();
			updateNames();
			updateTotals();
		};

		const normalizeInitialItem = (item) => {
			let taxes = Array.isArray(item.taxname) ? item.taxname : [];
			if (!taxes.length && item.item_tax_name) {
				const legacyTaxTotal = parseFloat(item.item_tax_total || '0') || 0;
				const legacyLineTotal = parseFloat(item.total_cost || item.unit_cost || item.rate || 0) * (parseFloat(item.quantity || item.qty || 1) || 1);
				if (legacyTaxTotal > 0 && legacyLineTotal > 0) {
					const legacyRate = ((legacyTaxTotal / legacyLineTotal) * 100).toFixed(2).replace(/\.?0+$/, '');
					taxes = [`${item.item_tax_name}|${legacyRate}`];
				} else {
					taxes = [String(item.item_tax_name)];
				}
			}
			return {
				items_id: item.items_id || item.proposals_items_id || item.credit_note_items_id || '',
				saved_items_id: item.saved_items_id || 0,
				item_name: item.item_name || '',
				item_desc: item.item_desc || '',
				hsn_code: item.hsn_code || '',
				unit: item.unit || '',
				quantity: item.quantity || item.qty || 1,
				unit_cost: item.unit_cost || item.rate || item.cost_price || 0,
				taxname: taxes,
			};
		};

		if (Array.isArray(initialItems) && initialItems.length) {
			initialItems.forEach((item) => appendRow(normalizeInitialItem(item)));
		} else {
			updateTotals();
		}

		tbody.addEventListener('input', (event) => {
			const row = event.target.closest('tr[data-legacy-item-row]');
			if (!row) {
				return;
			}
			updateRowTotal(row);
			updateTotals();
		});

		tbody.addEventListener('click', (event) => {
			const removeButton = event.target.closest('[data-legacy-remove-item]');
			if (!removeButton) {
				return;
			}
			const row = removeButton.closest('tr[data-legacy-item-row]');
			if (!row) {
				return;
			}
			removeRow(row);
		});

		container.querySelectorAll('input[name="show_quantity_as"]').forEach((radio) => {
			radio.addEventListener('change', updateQtyHeader);
		});
		updateQtyHeader();

		if (discountInput) {
			discountInput.addEventListener('input', updateTotals);
		}
		if (adjustmentInput) {
			adjustmentInput.addEventListener('input', updateTotals);
		}
		if (addRowButton) {
			addRowButton.addEventListener('click', () => {
				appendRow({
					item_name: '',
					item_desc: '',
					quantity: 1,
					unit_cost: 0,
					unit: '',
					taxname: [],
					saved_items_id: 0,
				});
			});
		}

		if (searchInput && searchResults) {
			searchInput.addEventListener('input', () => {
				debouncedItemSearch(searchInput.value);
			});

			searchInput.addEventListener('focus', () => {
				if (!requireWarehouseSelection()) {
					return;
				}
				if (searchInput.value.trim().length >= 2) {
					debouncedItemSearch(searchInput.value);
				}
			});

			searchResults.addEventListener('click', (event) => {
				const option = event.target.closest('[data-legacy-item-payload]');
				if (!option) return;
				try {
					const payload = JSON.parse(option.getAttribute('data-legacy-item-payload'));
					const row = payload && payload.row ? payload.row : {};
					appendRow({
						item_name: row.item_name || '',
						item_desc: row.item_desc || '',
						hsn_code: row.hsn_code || '',
						unit: row.unit || row.unit_type || '1',
						quantity: row.qty || row.quantity || 1,
						unit_cost: row.rate || row.unit_cost || 0,
						taxname: Array.isArray(row.taxname) ? row.taxname : [],
						saved_items_id: row.saved_items_id || payload.saved_items_id || 0,
						items_id: '',
					});
					searchInput.value = '';
					closeItemResults();
				} catch (e) {
					closeItemResults();
				}
			});

			document.addEventListener('click', (event) => {
				if (!container.contains(event.target)) {
					closeItemResults();
				}
			});

			const warehouseField = getWarehouseField();
			if (warehouseField) {
				warehouseField.addEventListener('change', clearWarehouseHighlight);
			}
		}
		if (resetButton) {
			resetButton.addEventListener('click', () => {
				tbody.innerHTML = '';
				if (removedWrap) {
					removedWrap.innerHTML = '';
				}
				if (taxHiddenWrap) {
					taxHiddenWrap.innerHTML = '';
				}
				if (Array.isArray(initialItems) && initialItems.length) {
					initialItems.forEach((item) => appendRow(normalizeInitialItem(item)));
				} else {
					updateTotals();
				}
			});
		}

		window.__legacySalesEditors = window.__legacySalesEditors || {};
		window.__legacySalesEditors[itemType] = {
			addItem(data) {
				appendRow(data);
			}
		};

		window.addManualSalesItem = function(data, targetType) {
			const target = targetType || itemType;
			const editor = window.__legacySalesEditors && window.__legacySalesEditors[target]
				? window.__legacySalesEditors[target]
				: window.__legacySalesEditors && window.__legacySalesEditors[itemType];
			if (!editor || !data) {
				return false;
			}
			editor.addItem({
				item_name: data.item_name || '',
				item_desc: data.item_desc || '',
				quantity: data.quantity || 1,
				unit_cost: data.unit_cost || 0,
				unit: data.unit || '',
				taxname: Array.isArray(data.taxname) ? data.taxname : [],
				saved_items_id: data.saved_items_id || 0,
				items_id: data.items_id || '',
			});
			return true;
		};
	})();
</script>
