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

$new_warehouse_html = form_lookup_add_link(
	'warehouse_id',
	base_url('admin/warehouse/create'),
	lang('create') . ' ' . lang('warehouse')
);
$new_designation_html = form_select_add_link(
	'designations_id',
	base_url('admin/departments/details'),
	lang('create') . ' ' . lang('designation')
	,
	'xl',
	array(
		'data-modal-value-key' => 'designation_id',
		'data-modal-label-key' => 'designation_name',
	)
);

$get_field = static function ($source, $key, $default = '') {
	if (is_array($source) && array_key_exists($key, $source)) {
		return $source[$key];
	}
	if (is_object($source) && property_exists($source, $key)) {
		return $source->$key;
	}
	return $default;
};

$login_info = isset($login_info) ? $login_info : null;
$profile_info = null;
$user_id = null;
$login_user_id = (int) $get_field($login_info, 'user_id', 0);
if (!empty($login_user_id)) {
	$profile_info = $this->user_model->check_by(array('user_id' => $login_user_id), 'tbl_account_details');
	$user_id = $login_user_id;
}

$profile_account_details_id = (int) $get_field($profile_info, 'account_details_id', 0);
$profile_fullname = (string) $get_field($profile_info, 'fullname', '');
$profile_employment_id = (string) $get_field($profile_info, 'employment_id', '');
$profile_phone = (string) $get_field($profile_info, 'phone', '');
$profile_mobile = (string) $get_field($profile_info, 'mobile', '');
$profile_skype = (string) $get_field($profile_info, 'skype', '');
$profile_locale = (string) $get_field($profile_info, 'locale', $this->config->item('locale'));
$profile_language = (string) $get_field($profile_info, 'language', $this->config->item('language'));
$selected_warehouse = $get_field($profile_info, 'warehouse_id', '');
$selected_designation = $get_field($profile_info, 'designations_id', '');
$selected_company = $get_field($profile_info, 'company', '');

$login_username = (string) $get_field($login_info, 'username', '');
$login_email = (string) $get_field($login_info, 'email', '');
$user_type_val = (int) $get_field($login_info, 'role_id', 3);
$direction_val = (string) $get_field($login_info, 'direction', 'ltr');
$permissionL = $get_field($login_info, 'permission', null);
$is_modal_create = $this->input->is_ajax_request() && empty($user_id);

$selected_warehouse_label = null;
if (!empty($selected_warehouse)) {
	$warehouse = $this->db->where('warehouse_id', $selected_warehouse)->get('tbl_warehouse')->row();
	if (!empty($warehouse)) {
		$selected_warehouse_label = (string) $get_field($warehouse, 'warehouse_name', $get_field($warehouse, 'name', ''));
	}
}

$designation_opts = array('' => lang('select') . ' ' . lang('designation'));
if (!empty($all_designation_info)) {
	foreach ($all_designation_info as $department_name => $designation_group) {
		if (is_array($designation_group)) {
			$group_items = array();
			foreach ($designation_group as $designation) {
				$designation_id = (int) $get_field($designation, 'designations_id', 0);
				$designation_name = trim((string) $get_field($designation, 'designations', ''));
				if (empty($designation_id) || $designation_name === '') {
					continue;
				}
				$group_items[$designation_id] = $designation_name;
			}
			if (!empty($group_items)) {
				$group_label = is_string($department_name) && $department_name !== '' ? $department_name : lang('designation');
				$designation_opts[] = array(
					'label' => $group_label,
					'items' => $group_items,
				);
			}
			continue;
		}

		$designation_id = (int) $get_field($designation_group, 'designations_id', 0);
		$designation_name = trim((string) $get_field($designation_group, 'designations', ''));
		if (empty($designation_id) || $designation_name === '') {
			continue;
		}
		$designation_opts[$designation_id] = $designation_name;
	}
}

$is_department_head = false;
if (!empty($selected_designation) && !empty($user_id)) {
	$desig = $this->db->where('designations_id', $selected_designation)->get('tbl_designations')->row();
	$desig_department_id = (int) $get_field($desig, 'departments_id', 0);
	if (!empty($desig_department_id)) {
		$department = $this->db->where('departments_id', $desig_department_id)->get('tbl_departments')->row();
		$department_head_id = (int) $get_field($department, 'department_head_id', 0);
		$is_department_head = !empty($department_head_id) && $department_head_id === (int) $user_id;
	}
}

$client_opts = array('' => lang('select') . ' ' . lang('client'));
if (!empty($all_client_info)) {
	foreach ($all_client_info as $client) {
		$client_id = (int) $get_field($client, 'client_id', 0);
		if (empty($client_id)) {
			continue;
		}
		$client_name = (string) $get_field($client, 'name', '');
		$label = !empty($client_name) ? $client_name : ('#' . $client_id);
		$client_opts[$client_id] = $label;
	}
}

$all_client_menu = $this->db->where('parent', 0)->order_by('sort')->get('tbl_client_menu')->result();
if (!empty($login_info)) {
	$user_menu = $this->db->where('user_id', $login_info->user_id)->get('tbl_client_role')->result();
}
$selected_client_menus = array();
if (!empty($user_menu)) {
	foreach ($user_menu as $menu) {
		$menu_id = (int) $get_field($menu, 'menu_id', 0);
		if (!empty($menu_id)) {
			$selected_client_menus[$menu_id] = true;
		}
	}
}
if (!empty($created) || !empty($edited)) {
?>
	<div class="overflow-visible rounded-2xl border border-border bg-card shadow-[0_12px_34px_-22px_rgba(15,23,42,0.45)]">
		<div class="border-b border-border bg-gradient-to-r from-slate-50/90 via-white to-slate-50/60 px-6 py-5 dark:from-slate-900/50 dark:via-card dark:to-slate-900/40">
			<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
				<div>
					<p class="text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground"><?= lang('user') ?></p>
					<h2 class="text-xl font-semibold text-foreground md:text-2xl"><?= !empty($user_id) ? lang('update') . ' ' . lang('user') : lang('create') . ' ' . lang('user') ?></h2>
					<p class="mt-1 text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('user') . ' ' . lang('details') ?></p>
				</div>
				<span class="inline-flex items-center rounded-full border border-indigo-200 bg-indigo-50 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-indigo-700 dark:border-indigo-500/30 dark:bg-indigo-500/15 dark:text-indigo-200">
					<?= !empty($user_id) ? lang('edit') : lang('new') ?>
				</span>
			</div>
		</div>

		<div class="p-6 md:p-7">
			<?= form_open(base_url('admin/user/save_user/' . (!empty($user_id) ? $user_id : '')), array('class' => 'space-y-6', 'enctype' => 'multipart/form-data', 'data-parsley-validate' => 'true', 'role' => 'form')); ?>

			<div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
				<div class="space-y-6 xl:col-span-2">
					<div class="rounded-xl border border-border bg-card p-5 shadow-sm transition-shadow duration-200 hover:shadow-md">
						<div class="mb-4 flex items-center gap-2 border-b border-border pb-3 text-sm font-semibold text-foreground">
							<i data-lucide="user-cog" class="h-4 w-4"></i>
							<span><?= lang('general') ?></span>
						</div>

						<input type="hidden" id="user_id" name="user_id" value="<?= !empty($login_user_id) ? (int) $login_user_id : '' ?>">
						<input type="hidden" name="account_details_id" value="<?= !empty($profile_account_details_id) ? (int) $profile_account_details_id : '' ?>">

						<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
							<?= form_input_group('fullname', lang('full_name'), $profile_fullname, 'text', true); ?>
							<?= form_input_group('employment_id', lang('employment_id'), $profile_employment_id, 'text', true); ?>
							<?= form_input_group('username', lang('username'), $login_username, 'text', true); ?>
							<?= form_input_group('email', lang('email'), $login_email, 'email', true); ?>
							<?= form_input_group('password', lang('password'), '', 'password', empty($user_id)); ?>
							<?= form_input_group('confirm_password', lang('confirm_password'), '', 'password', empty($user_id)); ?>
							<?= form_input_group('phone', lang('phone'), $profile_phone, 'text', true); ?>
							<?= form_input_group('mobile', lang('mobile'), $profile_mobile, 'text', false); ?>
							<?= form_input_group('skype', lang('skype'), $profile_skype, 'text', false); ?>

							<?php
							$local_opts = array();
							$locals = $this->db->get('tbl_locales')->result();
							if (!empty($locals)) {
								foreach ($locals as $loc) {
									$local_opts[$loc->locale] = ucfirst($loc->locale);
								}
							}
							?>
							<?= form_select_group('locale', lang('locale'), $local_opts, $profile_locale, false); ?>

							<?php
							$lang_opts = array();
							if (!empty($languages)) {
								foreach ($languages as $lang) {
									$lang_opts[$lang->name] = ucfirst($lang->name);
								}
							}
							?>
							<?= form_select_group('language', lang('language'), $lang_opts, $profile_language, false); ?>
							<?= form_lookup_group('warehouse_id', lang('warehouse'), $selected_warehouse, $selected_warehouse_label, true, array(), '', array('type' => 'warehouse', 'append' => $new_warehouse_html)); ?>

							<?= form_select_group(
								'role_id',
								lang('user_type'),
								array(
									1 => lang('admin'),
									3 => lang('staff'),
									2 => lang('client'),
								),
								$user_type_val,
								true,
								array('id' => 'user_type', 'data-search' => true)
							); ?>

							<?= form_select_group('direction', lang('direction'), array('ltr' => lang('LTR'), 'rtl' => lang('RTL')), $direction_val, true, array('data-search' => false)); ?>
						</div>
					</div>

					<div id="department_section" class="overflow-visible rounded-xl border border-border bg-card p-5 shadow-sm transition-shadow duration-200 hover:shadow-md">
						<div class="mb-4 flex items-center gap-2 border-b border-border pb-3 text-sm font-semibold text-foreground">
							<i data-lucide="building-2" class="h-4 w-4"></i>
							<span><?= lang('department') ?> &amp; <?= lang('designation') ?></span>
						</div>
						<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
							<?= form_select_group('designations_id', lang('designation'), $designation_opts, $selected_designation, false, array('class' => 'department', 'id' => 'designations_id', 'data-search' => true), '', $new_designation_html); ?>
							<div class="md:pt-7">
								<?= form_checkbox('department_head_id', 'Is he Department head?', $is_department_head, false, array('class' => 'department', 'value' => '1', 'id' => 'department_head_id')); ?>
							</div>
						</div>
					</div>

					<?php if (!$is_modal_create) { ?>
					<div id="client_permission_section" class="rounded-xl border border-border bg-card p-5 shadow-sm transition-shadow duration-200 hover:shadow-md">
						<div class="mb-4 flex items-center gap-2 border-b border-border pb-3 text-sm font-semibold text-foreground">
							<i data-lucide="shield-check" class="h-4 w-4"></i>
							<span><?= lang('select') . ' ' . lang('client') ?> &amp; <?= lang('permission') ?></span>
						</div>
						<div class="space-y-5">
							<?= form_select_group('company', lang('company'), $client_opts, $selected_company, false, array('id' => 'company', 'class' => 'client_permission', 'data-search' => true)); ?>
							<div class="rounded-xl border border-border bg-muted/10 p-4">
								<div class="mb-3 flex items-center justify-between gap-3">
									<h4 class="text-sm font-semibold text-foreground"><?= lang('client') . ' ' . lang('permission') ?></h4>
									<div class="flex items-center gap-2">
										<button type="button" data-client-switch="on" class="inline-flex items-center rounded-md border border-emerald-200 bg-emerald-50 px-2.5 py-1.5 text-xs font-semibold text-emerald-700 hover:bg-emerald-100 dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-300">
											<?= lang('enable') . ' ' . lang('all') ?>
										</button>
										<button type="button" data-client-switch="off" class="inline-flex items-center rounded-md border border-rose-200 bg-rose-50 px-2.5 py-1.5 text-xs font-semibold text-rose-700 hover:bg-rose-100 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-300">
											<?= lang('disable') . ' ' . lang('all') ?>
										</button>
									</div>
								</div>
								<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
									<?php if (!empty($all_client_menu)) : ?>
										<?php foreach ($all_client_menu as $menu_item) : ?>
											<?php
											$menu_id = (int) $get_field($menu_item, 'menu_id', 0);
											if (empty($menu_id)) {
												continue;
											}
											$menu_label = (string) $get_field($menu_item, 'label', '');
											$checked = !empty($selected_client_menus[$menu_id]);
											?>
											<label class="flex items-center justify-between rounded-lg border border-border bg-card px-3 py-2 text-sm transition-colors hover:bg-muted/30">
												<span class="font-medium text-foreground"><?= lang($menu_label) ?></span>
												<span class="relative inline-flex h-6 w-11 items-center">
													<input
														type="checkbox"
														name="client_menu[<?= $menu_id ?>]"
														value="<?= $menu_id ?>"
														class="client_permission peer sr-only"
														<?= $checked ? 'checked' : '' ?>>
													<span class="h-6 w-11 rounded-full bg-slate-300 transition-colors peer-checked:bg-indigo-600 dark:bg-slate-600"></span>
													<span class="pointer-events-none absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform peer-checked:translate-x-5"></span>
												</span>
											</label>
										<?php endforeach; ?>
									<?php else : ?>
										<p class="text-sm text-muted-foreground"><?= lang('no_data') ?></p>
									<?php endif; ?>
								</div>
							</div>
						</div>
					</div>
					<?php } ?>
				</div>

				<div class="space-y-6">
					<div class="rounded-xl border border-border bg-card p-5 shadow-sm transition-shadow duration-200 hover:shadow-md">
						<div class="mb-4 flex items-center gap-2 border-b border-border pb-3 text-sm font-semibold text-foreground">
							<i data-lucide="image" class="h-4 w-4"></i>
							<span><?= lang('profile_image') ?></span>
						</div>
						<?= form_attachment_group('avatar', lang('image'), 'photo', array(
							'preview_url' => !empty($user_id) ? base_url(staffImage($user_id)) : '',
						)); ?>
					</div>

					<?php if ($is_modal_create) { ?>
						<input type="hidden" name="permission" value="everyone">
					<?php } else { ?>
					<div class="rounded-xl border border-border bg-card p-5 shadow-sm transition-shadow duration-200 hover:shadow-md">
						<div class="mb-4 flex items-center gap-2 border-b border-border pb-3 text-sm font-semibold text-foreground">
							<i data-lucide="users" class="h-4 w-4"></i>
							<span><?= lang('access') ?> &amp; <?= lang('permission') ?></span>
						</div>
						<?= form_permission_modern($assign_user, $permissionL, lang('assined_to')); ?>
					</div>
					<?php } ?>
				</div>
			</div>

			<div class="flex items-center gap-2 border-t border-border pt-4">
				<?= btn_update(!empty($user_id) ? lang('update') : lang('save'), 'md') ?>
				<?= btn_cancel('admin/user/user_list', 'cancel', 'md', 'x', array('class' => 'mb-0 !h-9')); ?>
			</div>

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

<script>
	(function() {
		const roleSelect = document.getElementById('user_type');
		const departmentSection = document.getElementById('department_section');
		const clientSection = document.getElementById('client_permission_section');
		const clientSwitchButtons = document.querySelectorAll('[data-client-switch]');

		if (!roleSelect || !departmentSection) {
			return;
		}

		const toggleSectionFields = (section, selector, enabled, requiredNames = []) => {
			const fields = section.querySelectorAll(selector);
			fields.forEach((el) => {
				el.disabled = !enabled;
				if (requiredNames.includes(el.name)) {
					if (enabled) {
						el.setAttribute('required', 'required');
					} else {
						el.removeAttribute('required');
					}
				} else {
					el.removeAttribute('required');
				}
			});
		};

		const applyUserTypeRules = () => {
			const role = String(roleSelect.value || '');
			const isClient = role === '2';
			const isAdminOrStaff = role === '1' || role === '3';

			departmentSection.style.display = isAdminOrStaff ? '' : 'none';

			toggleSectionFields(departmentSection, '.department', isAdminOrStaff, ['designations_id']);
			if (clientSection) {
				clientSection.style.display = isClient ? '' : 'none';
				toggleSectionFields(clientSection, '.client_permission', isClient, ['company']);
			}
		};

		roleSelect.addEventListener('change', applyUserTypeRules);
		applyUserTypeRules();

		clientSwitchButtons.forEach((btn) => {
			btn.addEventListener('click', () => {
				const turnOn = btn.getAttribute('data-client-switch') === 'on';
				if (!clientSection) {
					return;
				}
				const switches = clientSection.querySelectorAll('input[type="checkbox"].client_permission');
				switches.forEach((input) => {
					if (!input.disabled) {
						input.checked = turnOn;
					}
				});
			});
		});
	})();

	function getItemByWarehouse(warehouseId) {
		$('[name="warehouse_id"]').val(warehouseId);
	}
</script>
