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

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

$return_stock_info = isset($return_stock_info) ? $return_stock_info : null;
$return_stock_id = (!empty($return_stock_info) && isset($return_stock_info->return_stock_id)) ? $return_stock_info->return_stock_id : null;

$reference_no = '';
if (!empty($return_stock_info) && !empty($return_stock_info->reference_no)) {
	$reference_no = $return_stock_info->reference_no;
} else {
	if (empty(config_item('return_stock_number_format'))) {
		$reference_no .= config_item('return_stock_prefix');
	}
	if (config_item('increment_return_stock_number') == 'FALSE') {
		$this->load->helper('string');
		$reference_no .= random_string('nozero', 6);
	} else {
		$reference_no .= $this->return_stock_model->generate_return_stock_number();
	}
}

$return_stock_date = !empty($return_stock_info) && !empty($return_stock_info->return_stock_date) ? $return_stock_info->return_stock_date : date('Y-m-d');
$due_date = !empty($return_stock_info) && !empty($return_stock_info->due_date) ? $return_stock_info->due_date : date('Y-m-d');

$module_value = '';
$module_id_value = '';
$related_doc_id = '';
if (!empty($return_stock_info)) {
	$module_value = $return_stock_info->module;
	$module_id_value = $return_stock_info->module_id;
	$related_doc_id = $return_stock_info->invoices_id;
} elseif (!empty($module)) {
	$module_value = $module;
	$module_id_value = !empty($module_id) ? $module_id : '';
}
$module_label_value = '';
if ($module_value === 'supplier' && !empty($module_id_value) && !empty($all_supplier)) {
	foreach ($all_supplier as $supplier_row) {
		if ((string) $supplier_row->supplier_id === (string) $module_id_value) {
			$module_label_value = $supplier_row->name;
			break;
		}
	}
}

$permissionL = !empty($return_stock_info) && !empty($return_stock_info->permission) ? $return_stock_info->permission : null;

$all_user = get_staff_details();
$selected_agent = !empty($return_stock_info->user_id) ? $return_stock_info->user_id : $this->session->userdata('user_id');
$selected_agent_label = '';
if (!empty($selected_agent)) {
	$agent_profile = $this->db->where('user_id', $selected_agent)->get('tbl_account_details')->row();
	if (!empty($agent_profile)) {
		$selected_agent_label = $agent_profile->fullname;
	}
}

$discount_options = array(
	'' => lang('no') . ' ' . lang('discount'),
	'before_tax' => lang('before_tax'),
	'after_tax' => lang('after_tax'),
);
$discount_type = !empty($return_stock_info->discount_type) ? $return_stock_info->discount_type : '';

$notes = '';
if (!empty($return_stock_info) && !empty($return_stock_info->notes)) {
	$notes = $return_stock_info->notes;
} else {
	$notes = $this->config->item('return_stock_terms');
}

$warehouse_options = array('' => lang('select') . ' ' . lang('warehouse'));
$warehouse_selected = !empty($return_stock_info->warehouse_id) ? $return_stock_info->warehouse_id : '';
$usertype = profile();
if (!empty($usertype) && $usertype->role_id == 3) {
	$warehouse_list = $this->admin_model->select_data('tbl_warehouse', 'warehouse_id', 'warehouse_name', array('status' => 'published', 'warehouse_id' => $this->session->userdata['warehouse_id']));
	$warehouse_selected = $this->session->userdata['warehouse_id'];
} else {
	$warehouse_list = $this->admin_model->select_data('tbl_warehouse', 'warehouse_id', 'warehouse_name', array('status' => 'published'));
}
if (!empty($warehouse_list)) {
	foreach ($warehouse_list as $key => $label) {
		$warehouse_options[$key] = $label;
	}
}

$new_warehouse_link = '';
if (!empty($usertype) && $usertype->role_id == 1) {
	$new_warehouse_link = form_lookup_add_link('warehouse_id', base_url('admin/warehouse/create/0/from_warehouse_id'), lang('new') . ' ' . lang('warehouse'), 'xl');
}
		
$warehouse_label = '';
if (!empty($warehouse_selected) && !empty($warehouse_options[$warehouse_selected])) {
	$warehouse_label = $warehouse_options[$warehouse_selected];
}

$module_options = array(
	'' => lang('none'),
	'supplier' => lang('supplier'),
	'client' => lang('client'),
);
?>

<?php if (!empty($created) || !empty($edited)) { ?>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
	

	<div class="space-y-6">
		<div class="rounded-2xl border border-border bg-card p-6 shadow-sm">
			<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
				<div>
					<p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('return_stock') ?></p>
					<h1 class="text-2xl font-semibold text-foreground"><?= !empty($return_stock_id) ? lang('edit') . ' ' . lang('return_stock') : lang('new') . ' ' . lang('return_stock') ?></h1>
					<p class="text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('return_stock') ?></p>
				</div>
				<div class="flex flex-wrap items-center gap-2">
					<a href="<?= base_url('admin/return_stock') ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
						<i data-lucide="list" class="h-4 w-4"></i>
						<?= lang('all') . ' ' . lang('return_stock') ?>
					</a>
					<?php if (!empty($return_stock_id)) { ?>
						<a href="<?= base_url('admin/return_stock/create_returnstock') ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
							<i data-lucide="plus" class="h-4 w-4"></i>
							<?= lang('new') . ' ' . lang('return_stock') ?>
						</a>
					<?php } ?>
				</div>
			</div>
		</div>

		<?= form_open(base_url('admin/return_stock/save_return_stock/' . $return_stock_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-8 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="file-text" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('return_stock') . ' ' . lang('details') ?></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_select_group('module', lang('related_to'), $module_options, $module_value, true, array('id' => 'check_related', 'class' => 'select_box', 'data-live-search' => 'true')); ?>
						<?= form_datepicker('return_stock_date', lang('return_stock') . ' ' . lang('date'), $return_stock_date, true, array('data-max' => '#due_date', 'data-auto-close' => 'true')); ?>
						<?= form_datepicker('due_date', lang('due_date'), $due_date, false, array('data-min' => '#return_stock_date', 'data-auto-close' => 'true')); ?>
						<?= form_lookup_group(
							'warehouse_id',
							lang('warehouse'),
							$warehouse_selected,
							$warehouse_label,
							true,
							array('placeholder' => lang('search') . ' ' . lang('warehouse')),
							'md:col-span-1',
							array(
								'type' => 'warehouse',
								'append' => $new_warehouse_link,
							)
						); ?>
						<?= form_lookup_group(
							'user_id',
							lang('sales') . ' ' . lang('agent'),
							$selected_agent,
							$selected_agent_label,
							true,
							array('placeholder' => lang('search') . ' ' . lang('agent')),
							'md:col-span-1',
							array('type' => 'staff')
						); ?>
					</div>
					<input type="hidden" name="warehouseId" class="WarehouseValue" value="<?= html_escape($warehouse_selected) ?>">

					<?php if (!empty($module_value) && !empty($module_id_value)) { ?>
						<input type="hidden" name="un_module" value="<?= html_escape($module_value) ?>">
						<input type="hidden" name="un_module_id" value="<?= html_escape($module_id_value) ?>">
					<?php } ?>

					<div class="grid grid-cols-1 md:grid-cols-2 gap-5" id="related_to"></div>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-5" id="related_result"></div>
				</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="settings" class="h-5 w-5"></i>
						<h2 class="text-base font-semibold text-foreground"><?= lang('settings') ?></h2>
					</div>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
						<?= form_switch_radio('update_stock', lang('update_stock'), (!empty($return_stock_info) && isset($return_stock_info->update_stock)) ? $return_stock_info->update_stock : 'Yes'); ?>
						<?= form_select_group('discount_type', lang('discount_type'), $discount_options, $discount_type, false, array('data-discount-type' => '1')); ?>
					</div>
					<?= form_editor('notes', lang('notes'), $notes, false, array('rows' => 5)); ?>
				</div>
			</div>

			<aside class="xl:col-span-4 space-y-6">
				<?= form_permission_modern($permission_user, $permissionL, lang('assigned_to')); ?>
			</aside>
		</div>

		<div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
			<?php
			$pdata['itemType'] = 'returnstock';
			if (!empty($return_stock_info) && !empty($return_stock_id)) {
				$pdata['add_items'] = $this->return_stock_model->ordered_items_by_id($return_stock_info->return_stock_id, true);
				$pdata['info'] = $return_stock_info;
			}
			$this->load->view('admin/items/selectItem', $pdata);
			?>
		</div>

		<?= form_close(); ?>
	</div>
<?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 } ?>

<script>
	document.addEventListener('DOMContentLoaded', function() {
		var moduleSelect = document.getElementById('check_related');
		var relatedContainer = document.getElementById('related_to');
		var relatedResult = document.getElementById('related_result');
		var presetModule = "<?= html_escape($module_value) ?>";
		var presetModuleId = "<?= html_escape($module_id_value) ?>";
		var presetModuleLabel = "<?= html_escape($module_label_value) ?>";
		var presetRelatedId = "<?= html_escape($related_doc_id) ?>";

		function loadRelatedData(name, value, selectedId) {
			if (!value) {
				relatedResult.innerHTML = '';
				return;
			}
			var url = base_url + "admin/return_stock/client_change_data/" + name + "/" + value;
			fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
				.then(function(res) { return res.json(); })
				.then(function(data) {
					relatedResult.innerHTML = data.related_info || '';
					var select = relatedResult.querySelector('.getItemsInfo');
					if (select && selectedId) {
						select.value = selectedId;
						if (window.refreshSelectpicker) window.refreshSelectpicker(select);
					}
				});
		}

		document.addEventListener('change', function(event) {
			if (!event.target) return;
			if (event.target === moduleSelect) {
				if (!event.target.value) {
					relatedContainer.innerHTML = '';
					relatedResult.innerHTML = '';
					return;
				}
				get_related_moduleName(event.target.value, true);
				relatedResult.innerHTML = '';
				return;
			}
			if (event.target.closest('#related_to') && (event.target.name === 'supplier_id' || event.target.name === 'client_id')) {
				loadRelatedData(event.target.name, event.target.value);
			}
		});

		document.addEventListener('lookup:change', function(event) {
			if (!event.detail || !event.detail.wrapper) return;
			if (!relatedContainer.contains(event.detail.wrapper)) return;
			var hidden = event.detail.wrapper.querySelector('[data-lookup-hidden]');
			if (!hidden || !hidden.name) return;
			if (hidden.name !== 'supplier_id' && hidden.name !== 'client_id') return;
			if (hidden.value) {
				loadRelatedData(hidden.name, hidden.value);
			} else {
				relatedResult.innerHTML = '';
			}
		});

		if (presetModule) {
			moduleSelect.value = presetModule;
			get_related_moduleName(presetModule, true);
			setTimeout(function() {
				var relatedSelect = relatedContainer.querySelector('select[name="supplier_id"], select[name="client_id"]');
				var relatedLookup = relatedContainer.querySelector('[data-lookup]');
				if (relatedSelect) {
					relatedSelect.value = presetModuleId;
					if (window.refreshSelectpicker) window.refreshSelectpicker(relatedSelect);
					if (presetModuleId) {
						loadRelatedData(relatedSelect.name, presetModuleId, presetRelatedId);
					}
				} else if (relatedLookup) {
					var hidden = relatedLookup.querySelector('[data-lookup-hidden]');
					var input = relatedLookup.querySelector('[data-lookup-input]');
					if (hidden) hidden.value = presetModuleId;
					if (input && presetModuleId) {
						input.value = presetModuleLabel || input.value || '';
					}
					if (presetModuleId) {
						loadRelatedData(hidden ? hidden.name : '', presetModuleId, presetRelatedId);
					}
				}
			}, 300);
		}
	});
</script>
