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

<?php
$taxes = $this->db->order_by('tax_rate_percent', 'ASC')->get('tbl_tax_rates')->result();
$tax_rates_id = null;
$tax_lookup_map = array();
if (!empty($items_info->tax_rates_id) && !is_numeric($items_info->tax_rates_id)) {
	$tax_rates_id = json_decode($items_info->tax_rates_id);
}
$selected_tax_items = array();
if (!empty($taxes)) {
	foreach ($taxes as $tax) {
		$tax_lookup_map[$tax->tax_rates_id] = $tax->tax_rate_name . '|' . $tax->tax_rate_percent;
		if (!empty($tax_rates_id) && is_array($tax_rates_id) && in_array($tax->tax_rates_id, $tax_rates_id)) {
			$selected_tax_items[] = array(
				'id' => $tax->tax_rates_id,
				'text' => $tax->tax_rate_name . ' (' . $tax->tax_rate_percent . '%)',
			);
		}
	}
}
?>

<div class="rounded-2xl border border-border bg-card shadow-sm">
	<form role="form" id="manuallyItemForm" data-manual-item-form="1" data-tax-lookup-map="<?= html_escape(json_encode($tax_lookup_map, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) ?>" data-parsley-validate="" novalidate="" enctype="multipart/form-data" method="post" class="p-5 space-y-4">
		<div class="grid gap-4 md:grid-cols-2">
			<?= form_input_group('item_name', lang('item_name'), '', 'text', true); ?>
			<?= form_input_group('qty', lang('qty'), '1', 'text', true, array('data-parsley-type' => 'number')); ?>
			<?= form_input_group('rate', lang('price'), '', 'text', true, array('data-parsley-type' => 'number')); ?>
			<?= form_input_group('unit', lang('unit') . ' ' . lang('type'), '', 'text', false, array('placeholder' => lang('unit_type_example'))); ?>
		</div>

		<?= form_textarea_group('item_desc', lang('description'), '', 3, false); ?>

		<?= form_multi_lookup_group('tax_rates_id', lang('tax'), $selected_tax_items, false, array(), '', array('type' => 'tax_rate', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('tax'))); ?>

		<div class="flex justify-end gap-2">
			<button type="submit" class="btn btn-sm btn-primary itemManualy"><?= lang('added') . ' ' . lang('manually'); ?></button>
			<button type="button" class="btn btn-default btn-sm" data-dismiss="modal"><?= lang('close'); ?></button>
		</div>
	</form>
</div>

<script>
	(function() {
		const form = document.getElementById('manuallyItemForm');
		if (!form || form.dataset.manualReady === '1') {
			return;
		}
		form.dataset.manualReady = '1';

		const taxLookup = <?= json_encode($tax_lookup_map, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;

		const getFieldValue = (name) => {
			const input = form.querySelector(`[name="${name}"]`);
			return input ? input.value : '';
		};

		const getSelectedTaxValues = () => {
			const hiddenInputs = form.querySelectorAll('[data-lookup-hidden-list] input[name="tax_rates_id[]"]');
			return Array.from(hiddenInputs)
				.map((input) => taxLookup[input.value] || '')
				.filter(Boolean);
		};

		const closeModal = () => {
			const modal = form.closest('.modal');
			if (window.jQuery && modal) {
				window.jQuery(modal).modal('hide');
			}
		};

		form.addEventListener('submit', function(event) {
			event.preventDefault();
			event.stopPropagation();
			if (typeof event.stopImmediatePropagation === 'function') {
				event.stopImmediatePropagation();
			}

			const itemName = getFieldValue('item_name').trim();
			if (!itemName) {
				const input = form.querySelector('[name="item_name"]');
				if (input) {
					input.focus();
				}
				return;
			}

			const payload = {
				item_name: itemName,
				item_desc: getFieldValue('item_desc').trim(),
				quantity: getFieldValue('qty') || '1',
				unit_cost: getFieldValue('rate') || '0',
				unit: getFieldValue('unit').trim(),
				taxname: getSelectedTaxValues(),
				saved_items_id: 0,
				items_id: '',
			};

			const activeTable = document.querySelector('.prodcutTable[data-terget]');
			const targetType = activeTable ? activeTable.getAttribute('data-terget') : 'purchase';

			if (typeof window.addManualSalesItem === 'function') {
				const inserted = window.addManualSalesItem(payload, targetType);
				if (inserted) {
					closeModal();
				}
			}
		}, true);
	})();
</script>
