<div class="invoice-modern bg-slate-50 dark:bg-slate-950">
	<?= message_box('success') ?>
	<?= message_box('error') ?>
	<script src="<?= base_url() ?>assets/plugins/jquery-ui/jquery-u.min.js"></script>
	<link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/awesomplete/awesomplete.css">
	<script src="<?= base_url() ?>assets/plugins/awesomplete/awesomplete.min.js"></script>
	<?php
	$edited = can_action('154', 'edited');
	$deleted = can_action('154', 'deleted');
	if (!empty($invoice_info)) {
		$invoices_id = $invoice_info->invoices_id;
	} else {
		$invoices_id = null;
	}
	$selected_client = !empty($invoice_info->client_id) ? $invoice_info->client_id : '';
	$client_label = '';
	if (!empty($selected_client)) {
		$client_label = get_row('tbl_client', array('client_id' => $selected_client), 'name');
	}
	$warehouse_selected = !empty($invoice_info->warehouse_id) ? $invoice_info->warehouse_id : (!empty($this->session->userdata['warehouse_id']) ? $this->session->userdata['warehouse_id'] : '');
	$warehouse_options = array('' => lang('select') . ' ' . lang('warehouse'));
	if (!empty($warehouseList) && is_array($warehouseList)) {
		foreach ($warehouseList as $warehouse_id => $warehouse_name) {
			$warehouse_options[$warehouse_id] = $warehouse_name;
		}
	}
	$selected_agent = !empty($invoice_info->user_id) ? $invoice_info->user_id : $this->session->userdata('user_id');
	$agent_label = '';
	if (!empty($selected_agent)) {
		$agent_label = get_row('tbl_account_details', array('user_id' => $selected_agent), 'fullname');
	}
	echo form_open(base_url('admin/invoice/save_invoice/' . $invoices_id), array('id' => 'pos-sales-form', 'class' => 'space-y-4', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => '', 'role' => 'form')); ?>
	<input type="hidden" name="show_quantity_as" value="qty">

	<section class="space-y-6 pb-10">
		<div class="relative z-30 overflow-visible rounded-3xl border border-slate-200/70 bg-white/90 px-6 py-5 shadow-sm backdrop-blur focus-within:z-40 dark:border-slate-800/70 dark:bg-slate-900/80">
			<div class="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
				<div class="flex flex-col gap-4 lg:flex-row lg:items-end lg:gap-6 ">
					<div class="relative z-40 grid w-full gap-3 overflow-visible md:grid-cols-2 xl:grid-cols-5">
						<?php
						$reference_no = '';
						if (!empty($invoice_info)) {
							$reference_no = $invoice_info->reference_no;
						} else {
							if (config_item('increment_invoice_number') == 'FALSE') {
								$this->load->helper('string');
								$reference_no = random_string('nozero', 6);
							} else {
								$reference_no = $this->invoice_model->generate_invoice_number();
							}
						}
						?>
						<div class="pos-topfield relative z-[60] min-w-[190px]">
							<?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true, array(), '', '', 'stacked'); ?>
						</div>
						<div id="posWarehouseFieldWrap" class="pos-topfield relative z-[60] min-w-[200px] rounded-xl transition-all duration-300">
							<?= form_select_group(
								'warehouse_id',
								lang('warehouse'),
								$warehouse_options,
								$warehouse_selected,
								true,
								array('id' => 'warehouse_id', 'onchange' => 'setPosWarehouse(this.value)')
							); ?>
						</div>
						<input type="hidden" name="warehouseId" class="WarehouseValue" value="<?= html_escape($warehouse_selected) ?>">
						<div class="pos-topfield relative z-[80] min-w-[200px]">
							<?= form_lookup_group(
								'client_id',
								lang('client'),
								$selected_client,
								$client_label,
								true,
								array(),
								'',
								array('type' => 'client', 'placeholder' => lang('search') . ' ' . lang('client')),
								'stacked'
							); ?>
						</div>
						<div class="pos-topfield relative z-[60] min-w-[170px]">
							<?= form_datepicker(
								'due_date',
								lang('due_date'),
								!empty($invoice_info->due_date) ? $invoice_info->due_date : date('Y-m-d', strtotime("+" . config_item('invoices_due_after') . " days")),
								false,
								array('data-format' => config_item('date_picker_format')),
								'',
								'',
								'stacked'
							); ?>
						</div>
						<div class="pos-topfield relative z-[60] min-w-[190px]">
							<?= form_lookup_group(
								'user_id',
								lang('sales') . ' ' . lang('agent'),
								$selected_agent,
								$agent_label,
								true,
								array(),
								'',
								array('type' => 'staff', 'placeholder' => lang('search') . ' ' . lang('sales') . ' ' . lang('agent')),
								'stacked'
							); ?>
						</div>
					</div>
					<input type="hidden" value="1" name="pos">
				</div>
			</div>
		</div>

		<div class="grid gap-6 lg:grid-cols-[minmax(0,7fr)_minmax(0,5fr)]">
			<div class="space-y-4">
				<div class="rounded-3xl border border-slate-200/70 bg-white/90 p-5 shadow-sm backdrop-blur dark:border-slate-800/70 dark:bg-slate-900/80">
					<div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
						<div>
							<div class="text-sm font-semibold text-slate-900 dark:text-slate-100"><?= lang('items') ?></div>
							<p class="text-xs text-slate-500 dark:text-slate-400"><?= lang('search') ?> <?= lang('product') ?> <?= lang('by') ?> <?= lang('name') ?> <?= lang('or') ?> <?= lang('code') ?></p>
						</div>
						<div class="relative w-full lg:w-80">
							<i data-lucide="search" class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"></i>
							<input type="text" id="search_text" name="term" placeholder="<?= lang('enter_product_name_and_code') ?>" class="h-10 w-full rounded-xl border border-slate-200 bg-white pl-10 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:border-slate-300 focus:outline-none focus:ring-2 focus:ring-slate-100 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100 dark:placeholder:text-slate-500 dark:focus:border-slate-500 dark:focus:ring-slate-800">
						</div>
					</div>
					<div id="posWarehouseAlert" class="mt-3 hidden rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-semibold text-rose-700 dark:border-rose-900/60 dark:bg-rose-900/20 dark:text-rose-300"></div>
					<div class="mt-4 flex flex-wrap gap-2">
						<button type="button" class="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-slate-100 px-3.5 py-1.5 text-xs font-semibold text-slate-700 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200">
							<?= lang('all') ?> <?= lang('items') ?>
						</button>
						<button type="button" class="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-3.5 py-1.5 text-xs font-semibold text-slate-500 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:bg-slate-800">
							<?= lang('popular') ?>
						</button>
						<button type="button" class="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-3.5 py-1.5 text-xs font-semibold text-slate-500 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:hover:bg-slate-800">
							<?= lang('new') ?>
						</button>
					</div>
				</div>

				<div class="rounded-3xl border border-slate-200/70 bg-white/90 p-4 shadow-sm backdrop-blur dark:border-slate-800/70 dark:bg-slate-900/80">
					<div id="product_result" class="grid min-h-[330px] gap-4 sm:grid-cols-2 xl:grid-cols-3">
						<div class="col-span-full rounded-xl border border-dashed border-slate-200 p-6 text-center text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">
							<?= lang('select') ?> <?= lang('warehouse') ?> <?= lang('to') ?> <?= lang('load') ?> <?= lang('items') ?>.
						</div>
					</div>
				</div>
			</div>

			<div class="space-y-4">
				<div class="rounded-3xl border border-slate-200/70 bg-white/90 p-3 shadow-sm backdrop-blur dark:border-slate-800/70 dark:bg-slate-900/80">
					<div class="mb-4 flex items-center justify-between">
						<div class="flex items-center gap-2 text-sm font-semibold text-slate-900 dark:text-slate-100">
							<i data-lucide="shopping-basket" class="h-4 w-4"></i>
							Cart
						</div>
						<span class="rounded-full bg-indigo-50 px-3 py-1 text-xs font-semibold text-indigo-600 dark:bg-indigo-900/40 dark:text-indigo-300"><?= lang('pos_sales') ?></span>
					</div>
					<?php
					$items = array();
					$tax_rates = $this->db->order_by('tax_rate_name', 'ASC')->get('tbl_tax_rates')->result();
					$currency_symbol = default_currency();
					$discount_percent = 0;
					$discount_type = 'percent';
					$adjustment = 0;
					$show_quantity_as = 'qty';
					$this->load->view('admin/common/sales_items_editor', array(
						'items' => $items,
						'tax_rates' => $tax_rates,
						'show_quantity_as' => $show_quantity_as,
						'discount_percent' => $discount_percent,
						'discount_type' => $discount_type,
						'adjustment' => $adjustment,
						'currency_symbol' => $currency_symbol,
						'itemType' => 'pos',
						'editor_variant' => 'pos',
					));
					?>
				</div>

			</div>
		</div>
	</section>

	<?php echo form_close(); ?>
</div>

<script>
	var POS_WAREHOUSE_STORAGE_KEY = 'zisco_pos_selected_warehouse_id';
	var POS_WAREHOUSE_LABEL_STORAGE_KEY = 'zisco_pos_selected_warehouse_label';

	function readPosWarehouseState() {
		try {
			return {
				id: localStorage.getItem(POS_WAREHOUSE_STORAGE_KEY) || '',
				label: localStorage.getItem(POS_WAREHOUSE_LABEL_STORAGE_KEY) || ''
			};
		} catch (e) {
			return {
				id: '',
				label: ''
			};
		}
	}

	function persistPosWarehouseState(id, label) {
		try {
			if (id) {
				localStorage.setItem(POS_WAREHOUSE_STORAGE_KEY, String(id));
				localStorage.setItem(POS_WAREHOUSE_LABEL_STORAGE_KEY, String(label || ''));
			} else {
				localStorage.removeItem(POS_WAREHOUSE_STORAGE_KEY);
				localStorage.removeItem(POS_WAREHOUSE_LABEL_STORAGE_KEY);
			}
		} catch (e) {
			// Ignore storage errors in private mode or restricted environments.
		}
	}

	function applyPosWarehouseToInputs(id, label) {
		var hiddenWarehouse = document.querySelector('[name="warehouseId"]');
		var postedWarehouse = document.querySelector('[name="warehouse_id"]');
		var wrap = document.getElementById('posWarehouseFieldWrap');
		var lookupInput = wrap ? wrap.querySelector('input[type="text"], select') : null;

		if (hiddenWarehouse) {
			hiddenWarehouse.value = id || '';
		}
		if (postedWarehouse) {
			postedWarehouse.value = id || '';
		}
		if (lookupInput) {
			if (lookupInput.tagName === 'SELECT') {
				lookupInput.value = id || '';
			} else {
				lookupInput.value = label || lookupInput.value || '';
			}
		}
	}

	function setPosWarehouse(id) {
		var hidden = document.querySelector('[name="warehouseId"]');
		var postedWarehouse = document.querySelector('[name="warehouse_id"]');
		var wrap = document.getElementById('posWarehouseFieldWrap');
		var alertBox = document.getElementById('posWarehouseAlert');
		var warehouseAttentionClasses = ['ring-4', 'ring-rose-200', 'dark:ring-rose-900/40', 'border-rose-400', 'dark:border-rose-500', 'animate-pulse'];
		var labelInput = wrap ? wrap.querySelector('input[type="text"], select') : null;
		var labelText = '';
		if (labelInput) {
			if (labelInput.tagName === 'SELECT') {
				var selectedOption = labelInput.options[labelInput.selectedIndex];
				labelText = selectedOption ? selectedOption.text.trim() : '';
			} else {
				labelText = labelInput.value.trim();
			}
		}
		if (hidden) {
			hidden.value = id || '';
		}
		if (postedWarehouse) {
			postedWarehouse.value = id || '';
		}
		persistPosWarehouseState(id || '', labelText);
		if (id && wrap) {
			wrap.classList.remove.apply(wrap.classList, warehouseAttentionClasses);
		}
		if (id && alertBox) {
			alertBox.classList.add('hidden');
			alertBox.textContent = '';
		}
		if (window.refreshPosProducts) {
			window.refreshPosProducts();
		}
	}

	(function() {
		var topFields = Array.prototype.slice.call(document.querySelectorAll('.pos-topfield'));
		var setActiveTopField = function(activeField) {
			topFields.forEach(function(field) {
				field.style.zIndex = field === activeField ? '120' : '60';
			});
		};
		if (topFields.length) {
			topFields.forEach(function(field) {
				field.addEventListener('focusin', function() {
					setActiveTopField(field);
				});
				field.addEventListener('click', function() {
					setActiveTopField(field);
				});
			});
			document.addEventListener('click', function(e) {
				if (!e.target.closest('.pos-topfield')) {
					setActiveTopField(null);
				}
			});
		}

		var grid = document.getElementById('product_result');
		var searchInput = document.getElementById('search_text');
		var warehouseInput = document.querySelector('[name="warehouseId"]');
		var postedWarehouseInput = document.querySelector('[name="warehouse_id"]');
		var warehouseFieldWrap = document.getElementById('posWarehouseFieldWrap');
		var warehouseAlert = document.getElementById('posWarehouseAlert');
		var warehouseAttentionClasses = ['ring-4', 'ring-rose-200', 'dark:ring-rose-900/40', 'border-rose-400', 'dark:border-rose-500', 'animate-pulse'];
		var appBaseUrl =
			(typeof window.base_url === 'string' && window.base_url) ||
			(window.appConfig && typeof window.appConfig.base_url === 'string' && window.appConfig.base_url) ||
			(typeof window.baseUrl === 'string' && window.baseUrl) ||
			(typeof base_url === 'string' && base_url) ||
			<?= json_encode(base_url()); ?>;
		if (appBaseUrl.slice(-1) !== '/') {
			appBaseUrl += '/';
		}
		var currencySymbol = <?= json_encode(default_currency()); ?>;
		if (!grid) return;

		var storedWarehouseState = readPosWarehouseState();
		if (warehouseInput && !warehouseInput.value && postedWarehouseInput && postedWarehouseInput.value) {
			applyPosWarehouseToInputs(postedWarehouseInput.value, storedWarehouseState.label);
		}
		if (warehouseInput && !warehouseInput.value && storedWarehouseState.id) {
			applyPosWarehouseToInputs(storedWarehouseState.id, storedWarehouseState.label);
		}
		if (warehouseInput && warehouseInput.value) {
			var lookupInput = warehouseFieldWrap ? warehouseFieldWrap.querySelector('input[type="text"]') : null;
			persistPosWarehouseState(warehouseInput.value, lookupInput ? lookupInput.value.trim() : '');
		}
		if (postedWarehouseInput && !postedWarehouseInput.value && warehouseInput && warehouseInput.value) {
			postedWarehouseInput.value = warehouseInput.value;
		}

		var activeController = null;
		var lastQuery = '';

		var escapeHtml = function(value) {
			if (value === null || value === undefined) return '';
			return String(value)
				.replace(/&/g, '&amp;')
				.replace(/</g, '&lt;')
				.replace(/>/g, '&gt;')
				.replace(/\"/g, '&quot;')
				.replace(/'/g, '&#39;');
		};

		var resolveImage = function(row) {
			var fallback = appBaseUrl + 'assets/img/product.png';
			if (!row || !row.upload_file) return fallback;
			try {
				var files = JSON.parse(row.upload_file);
				if (!Array.isArray(files) || !files.length) return fallback;
				var image = files.find(function(file) {
					return file && file.is_image === 1;
				});
				if (!image || !image.path) return fallback;
				return appBaseUrl + image.path;
			} catch (e) {
				return fallback;
			}
		};

		var renderEmpty = function(message) {
			grid.innerHTML =
				'<div class="col-span-full rounded-xl border border-dashed border-slate-200 p-6 text-center text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">' +
				escapeHtml(message) +
				'</div>';
		};

		var renderItems = function(items) {
			if (!items.length) {
				renderEmpty('No items found');
				return;
			}
			grid.innerHTML = items
				.map(function(entry) {
					var row = entry.row || {};
					var price = parseFloat(row.unit_cost || row.rate || 0);
					return (
						'<button type="button" data-pos-item-id="' +
						escapeHtml(entry.saved_items_id) +
						'" class="group flex flex-col overflow-hidden rounded-3xl border border-slate-200/80 bg-white text-left shadow-sm transition hover:-translate-y-0.5 hover:border-indigo-200 hover:shadow-md dark:border-slate-800/80 dark:bg-slate-900 dark:hover:border-indigo-500/50">' +
						'<div class="relative h-32 w-full overflow-hidden bg-slate-100 dark:bg-slate-800">' +
						'<img src="' +
						escapeHtml(resolveImage(row)) +
						'" alt="' +
						escapeHtml(row.item_name || entry.label || '') +
						'" class="h-full w-full object-cover transition duration-300 group-hover:scale-105" />' +
						'</div>' +
						'<div class="flex flex-1 flex-col gap-1 px-3 py-3">' +
						'<div class="text-sm font-semibold text-slate-900 dark:text-slate-100">' +
						escapeHtml(row.item_name || entry.label || '') +
						'</div>' +
						'<div class="text-xs text-slate-500 dark:text-slate-400">' +
						escapeHtml(row.code || '') +
						'</div>' +
						'<div class="mt-3 inline-flex items-center justify-between">' +
						'<span class="text-sm font-semibold text-slate-900 dark:text-slate-100">' +
						escapeHtml(currencySymbol + (price ? price.toFixed(2) : '0.00')) +
						'</span>' +
						'<span class="rounded-full bg-slate-100 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-slate-500 dark:bg-slate-800 dark:text-slate-300">' +
						escapeHtml(row.unit || row.unit_type || '') +
						'</span>' +
						'</div>' +
						'</div>' +
						'</button>'
					);
				})
				.join('');
		};

		var flashWarehouseRequired = function() {
			if (warehouseAlert) {
					warehouseAlert.textContent = <?= json_encode(lang('please_select_warehouse_before_searching')) ?>;
				warehouseAlert.classList.remove('hidden');
			}
			if (warehouseFieldWrap) {
				warehouseFieldWrap.classList.remove.apply(warehouseFieldWrap.classList, warehouseAttentionClasses);
				window.requestAnimationFrame(function() {
					warehouseFieldWrap.classList.add.apply(warehouseFieldWrap.classList, warehouseAttentionClasses);
				});
			}
		};

		var fetchItems = function(term) {
			var warehouseId = warehouseInput ? warehouseInput.value : '';
			if (!warehouseId) {
				flashWarehouseRequired();
				renderEmpty('Select a warehouse to load items.');
				return;
			}
			if (activeController) {
				activeController.abort();
			}
			activeController = new AbortController();
			grid.innerHTML =
				'<div class="col-span-full rounded-xl border border-dashed border-slate-200 p-6 text-center text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">Loading items...</div>';
			var url =
				appBaseUrl +
				'admin/common/suggestions?term=' +
				encodeURIComponent(term || '') +
				'&warehouse_id=' +
				encodeURIComponent(warehouseId) +
				'&limit=48';
			fetch(url, {
					headers: {
						'X-Requested-With': 'XMLHttpRequest'
					},
					signal: activeController.signal,
				})
				.then(function(response) {
					return response.json();
				})
				.then(function(data) {
					var items = Array.isArray(data) ?
						data.filter(function(entry) {
							return entry && entry.saved_items_id && String(entry.saved_items_id) !== '0';
						}) :
						[];
					renderItems(items);
				})
				.catch(function(error) {
					if (error.name === 'AbortError') return;
					renderEmpty('Unable to load items');
				});
		};

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

		var handleSearch = debounce(function() {
			var query = searchInput ? searchInput.value.trim() : '';
			lastQuery = query;
			fetchItems(query);
		}, 220);

		if (searchInput) {
			searchInput.addEventListener('input', handleSearch);
			searchInput.addEventListener('focus', function() {
				var warehouseId = warehouseInput ? warehouseInput.value : '';
				if (!warehouseId) {
					flashWarehouseRequired();
				}
			});
		}

		if (warehouseFieldWrap) {
			warehouseFieldWrap.addEventListener('blur', function() {
				var selectedWarehouse = warehouseInput ? warehouseInput.value : '';
				if (!selectedWarehouse) return;
				var lookupInput = warehouseFieldWrap.querySelector('input[type="text"]');
				persistPosWarehouseState(selectedWarehouse, lookupInput ? lookupInput.value.trim() : '');
			}, true);
		}

		grid.addEventListener('click', function(event) {
			var target = event.target.closest('[data-pos-item-id]');
			if (!target) return;
			var itemId = target.getAttribute('data-pos-item-id');
			if (!itemId) return;
			var url = appBaseUrl + 'admin/common/suggestions/' + encodeURIComponent(itemId);
			fetch(url, {
					headers: {
						'X-Requested-With': 'XMLHttpRequest'
					}
				})
				.then(function(response) {
					return response.json();
				})
				.then(function(data) {
					var row = data && data.row ? data.row : null;
					if (!row || !window.__salesItemsEditors || !window.__salesItemsEditors.pos) {
						return;
					}
					var posCode = row.code || row.item_code || row.sku || '';
					var posDesc = posCode ? ('SKU: ' + posCode) : (row.item_desc || '');
					window.__salesItemsEditors.pos.addItem({
						item_name: row.item_name || '',
						item_desc: posDesc,
						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 || itemId,
						items_id: '',
					});
				})
				.catch(function() {});
		});

		window.refreshPosProducts = function() {
			fetchItems(lastQuery);
		};

		var totalHeader = document.querySelector('.sales-items-modern[data-terget="pos"] .sales-items-modern__summary .border-t p');
		var totalSubText = document.querySelector('.sales-items-modern[data-terget="pos"] .sales-items-modern__summary .border-t p.mt-1');
		if (totalHeader) {
			totalHeader.textContent = 'TOTAL VALUE';
		}
		if (totalSubText) {
			totalSubText.classList.add('hidden');
		}

		fetchItems('');
	})();
</script>
