<?php
$office_hours = config_item('office_hours');
$user_options = array('' => lang('select') . ' ' . lang('users'));
$all_users = $this->db->where('role_id !=', 2)->get('tbl_users')->result();
if (!empty($all_users)) {
	foreach ($all_users as $v_users) {
		$profile = $this->db->where('user_id', $v_users->user_id)->get('tbl_account_details')->row();
		if (!empty($profile)) {
			$user_options[$profile->user_id] = $profile->fullname;
		}
	}
}

$leave_category_options = array('' => lang('select') . ' ' . lang('leave_category'));
$all_leave_category = $this->db->get('tbl_leave_category')->result();
if (!empty($all_leave_category)) {
	foreach ($all_leave_category as $v_category) {
		$leave_category_options[$v_category->leave_category_id] = $v_category->leave_category;
	}
}

$hours_options = array();
for ($i = 1; $i <= $office_hours; $i++) {
	$label = ($office_hours <= 9 ? '0' : '') . $i;
	$hours_options[$i] = $label;
}
?>
<link rel="stylesheet" type="text/css" href="<?= base_url() ?>assets/plugins/dropzone/dropzone.min.css">
<script type="text/javascript" src="<?= base_url() ?>assets/plugins/dropzone/dropzone.min.js"></script>
<script type="text/javascript" src="<?= base_url() ?>assets/plugins/dropzone/dropzone.custom.js"></script>

<style type="text/css">
	.apply-leave-modal .leave-summary-panel .panel.panel-custom {
		margin-bottom: 0;
		border: 1px solid #dbe4ee;
		border-radius: 16px;
		overflow: hidden;
		background: #fff;
		box-shadow: 0 18px 40px -30px rgba(15, 23, 42, 0.45);
	}

	.apply-leave-modal .leave-summary-panel .panel-heading {
		padding: 18px 20px;
		background: #fff;
		border-bottom: 1px solid #e5e7eb;
	}

	.apply-leave-modal .leave-summary-panel .panel-title {
		font-size: 18px;
		color: #0f172a;
	}

	.apply-leave-modal .leave-summary-panel .table {
		margin-bottom: 0;
	}

	.apply-leave-modal .leave-summary-panel .table>tbody>tr>td {
		padding: 14px 18px;
		border-top: 1px solid #e5e7eb;
		color: #0f172a;
	}

	.apply-leave-modal .leave-summary-panel .table>tbody>tr:first-child>td {
		border-top: 0;
	}

	.apply-leave-modal .leave-summary-panel .table>tbody>tr:last-child>td {
		background: #f8fafc;
		font-weight: 700;
	}

	.apply-leave-modal .leave-form-row {
		display: flex;
		align-items: flex-start;
		gap: 0.75rem;
		padding: 0.5rem 0;
	}

	.apply-leave-modal .leave-form-label {
		width: 12rem;
		flex-shrink: 0;
		padding-top: 0.5rem;
		text-align: right;
		font-size: 0.875rem;
		font-weight: 500;
		color: #0f172a;
	}

	.apply-leave-modal .leave-form-spacer {
		width: 12rem;
		flex-shrink: 0;
	}

	.apply-leave-modal .leave-hours-grid {
		display: grid;
		grid-template-columns: minmax(0, 1fr) 140px;
		gap: 0.75rem;
	}

	.apply-leave-modal .leave-attachment-card .dropzone {
		min-height: 120px;
		border: 1px dashed #cbd5e1;
		border-radius: 1rem;
		background: #fff;
	}

	@media (max-width: 767.98px) {
		.apply-leave-modal .leave-form-row,
		.apply-leave-modal .leave-details-card .flex.items-start.gap-3.py-2,
		.apply-leave-modal .leave-attachment-card .flex.items-start.gap-3.py-2 {
			flex-direction: column;
			gap: 0.5rem;
		}

		.apply-leave-modal .leave-form-label,
		.apply-leave-modal .leave-details-card .flex.items-start.gap-3.py-2>label,
		.apply-leave-modal .leave-attachment-card .flex.items-start.gap-3.py-2>label {
			width: 100%;
			padding-top: 0;
			text-align: left;
		}

		.apply-leave-modal .leave-form-spacer {
			display: none;
		}

		.apply-leave-modal .leave-hours-grid {
			grid-template-columns: 1fr;
		}
	}
</style>

<form data-parsley-validate="" novalidate="" action="<?php echo base_url() ?>admin/leave_management/save_leave_application" method="post" enctype="multipart/form-data" class="apply-leave-modal space-y-6">
	<div class="grid grid-cols-12 gap-6">
		<div class="col-span-12 xl:col-span-8 space-y-6">
			<div class="leave-details-card rounded-xl border border-border bg-card p-5 shadow-sm">
				<?php if (!empty(admin_head())) { ?>
					<div>
						<?= form_select_group(
							'user_id',
							lang('select') . ' ' . lang('users'),
							$user_options,
							$this->session->userdata('user_id'),
							true,
							array(
								'id' => 'users_id',
								'class' => 'select_box',
								'style' => 'width: 100%',
								'onchange' => 'get_leave_details(this.value)'
							),
							'',
							'',
							'horizontal'
						); ?>
					</div>
				<?php } else { ?>
					<input type="hidden" id="user_id" name="user_id" value="<?php echo $this->session->userdata('user_id') ?>">
				<?php } ?>

				<div>
					<?= form_select_group(
						'leave_category_id',
						lang('leave_category'),
						$leave_category_options,
						'',
						true,
						array(
							'id' => 'leave_category',
							'class' => 'select_box',
							'style' => 'width: 100%'
						),
						'',
						form_lookup_add_link(
							'leave_category_id',
							base_url('admin/leave_management/leave_category'),
							lang('leave_category'),
							'sm'
						),
						'horizontal'
					); ?>
				</div>

				<div>
					<?= form_radio_group(
						'leave_type',
						lang('duration'),
						array(
							'single_day' => lang('single_day'),
							'multiple_days' => lang('multiple_days'),
							'hours' => lang('hours')
						),
						'single_day',
						true,
						array(
							'group_class' => 'sm:grid-cols-3 gap-5 pt-2'
						),
						'horizontal'
					); ?>
				</div>

				<div id="single_day_section" data-leave-section="single_day">
					<?= form_datepicker(
						'single_day_start_date',
						lang('start_date'),
						'',
						true,
						array(
							'id' => 'single_day_start_date',
							'class' => 'datepicker',
							'onchange' => 'check_available_leave(this.value)'
						),
						'',
						'',
						'horizontal'
					); ?>
				</div>

				<div id="multiple_days_section" data-leave-section="multiple_days" class="space-y-0" style="display: none;" hidden aria-hidden="true">
					<?= form_datepicker(
						'multiple_days_start_date',
						lang('start_date'),
						'',
						true,
						array(
							'id' => 'multiple_days_start_date',
							'class' => 'start_date',
							'disabled' => 'disabled',
						),
						'',
						'',
						'horizontal'
					); ?>
					<?= form_datepicker(
						'multiple_days_end_date',
						lang('end_date'),
						'',
						true,
						array(
							'id' => 'multiple_days_end_date',
							'class' => 'end_date',
							'disabled' => 'disabled',
							'onchange' => 'check_available_leave(this.value)'
						),
						'',
						'',
						'horizontal'
					); ?>
				</div>

				<div id="hours_section" data-leave-section="hours" style="display: none;" hidden aria-hidden="true">
					<div class="leave-form-row">
						<label for="hours_start_date" class="leave-form-label"><?= lang('start_date') ?> <span class="text-red-500">*</span></label>
						<div class="flex-1">
							<div class="leave-hours-grid">
								<?= form_datepicker(
									'hours_start_date',
									'',
									'',
									true,
									array(
										'id' => 'hours_start_date',
										'class' => 'datepicker',
										'disabled' => 'disabled',
										'onchange' => 'check_available_leave(this.value)'
									),
									'',
									'',
									'stacked'
								); ?>
								<label class="space-y-1 text-sm font-medium text-foreground block">
									<span><?= lang('hours') ?> <span class="text-red-500">*</span></span>
									<select id="hours_value" name="hours" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm dark:focus:border-secondary dark:focus:ring-3 dark:focus:ring-secondary/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30 select_box" required disabled="disabled">
										<?php foreach ($hours_options as $hour_value => $hour_label) { ?>
											<option value="<?= html_escape($hour_value) ?>"><?= html_escape($hour_label) ?></option>
										<?php } ?>
									</select>
								</label>
							</div>
						</div>
					</div>
				</div>

				<div class="leave-form-row pt-0">
					<div class="leave-form-spacer"></div>
					<div class="flex-1 text-xs text-danger" id="leave_validation_message"></div>
				</div>

				<div>
					<?= form_textarea_group(
						'reason',
						lang('reason'),
						'',
						6,
						false,
						array('id' => 'present', 'style' => 'min-height: 140px;'),
						'horizontal'
					); ?>
				</div>

				<?= custom_form_Fields(17, null); ?>
			</div>

			<div class="leave-attachment-card rounded-xl border border-border bg-card p-5 shadow-sm">
				<div class="flex items-start gap-3 py-2">
					<label class="w-48 text-sm font-medium text-foreground pt-2 text-right"><?= lang('attachment') ?></label>
					<div class="flex-1">
						<div id="comments_file-dropzone" class="dropzone mb-4"></div>
						<div id="comments_file-dropzone-scrollbar">
							<div id="comments_file-previews">
								<div id="file-upload-row" class="mt pull-left">
									<div class="preview box-content pr-lg" style="width:100px;">
										<span data-dz-remove class="pull-right" style="cursor: pointer">
											<i data-lucide="x"></i>
										</span>
										<img data-dz-thumbnail class="upload-thumbnail-sm" />
										<input class="file-count-field" type="hidden" name="files[]" value="" />
										<div class="mb progress progress-striped upload-progress-sm active mt-sm" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
											<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
										</div>
									</div>
								</div>
							</div>
						</div>

						<script type="text/javascript">
							$(document).ready(function() {
								$(".existing_image").click(function() {
									$(this).parent().remove();
								});
								var fileSerial = 0;
								// Get the template HTML and remove it from the doumenthe template HTML and remove it from the doument
								var previewNode = document.querySelector("#file-upload-row");
								previewNode.id = "";
								var previewTemplate = previewNode.parentNode.innerHTML;
								previewNode.parentNode.removeChild(previewNode);
								Dropzone.autoDiscover = false;
								var projectFilesDropzone = new Dropzone("#comments_file-dropzone", {
									url: "<?= base_url() ?>admin/common/upload_file",
									thumbnailWidth: 80,
									thumbnailHeight: 80,
									parallelUploads: 20,
									previewTemplate: previewTemplate,
									dictDefaultMessage: '<?php echo lang("file_upload_instruction"); ?>',
									autoQueue: true,
									previewsContainer: "#comments_file-previews",
									clickable: true,
									accept: function(file, done) {
										if (file.name.length > 200) {
											done("Filename is too long.");
											$(file.previewTemplate).find(".description-field").remove();
										}
										$.ajax({
											url: "<?= base_url() ?>admin/common/validate_project_file",
											data: {
												file_name: file.name,
												file_size: file.size
											},
											cache: false,
											type: 'POST',
											dataType: "json",
											success: function(response) {
												if (response.success) {
													fileSerial++;
													$(file.previewTemplate).find(".description-field").attr("name", "comment_" + fileSerial);
													$(file.previewTemplate).append("<input type='hidden' name='file_name_" + fileSerial + "' value='" + file.name + "' />\n\
																			<input type='hidden' name='file_size_" + fileSerial + "' value='" + file.size + "' />");
													$(file.previewTemplate).find(".file-count-field").val(fileSerial);
													done();
												} else {
													$(file.previewTemplate).find("input").remove();
													done(response.message);
												}
											}
										});
									},
									processing: function() {
										$("#file-save-button").prop("disabled", true);
									},
									queuecomplete: function() {
										$("#file-save-button").prop("disabled", false);
									},
									fallback: function() {
										$("body").addClass("dropzone-disabled");
										$('.modal-dialog').find('[type="submit"]').removeAttr('disabled');

										$("#comments_file-dropzone").hide();

										$("#file-modal-footer").prepend("<button id='add-more-file-button' type='button' class='btn  btn-default pull-left'><i data-lucide='plus-circle'></i> " + "<?php echo lang("add_more"); ?>" + "</button>");

										$("#file-modal-footer").on("click", "#add-more-file-button", function() {
											var newFileRow = "<div class='file-row pb pt10 b-b mb10'>" +
												"<div class='pb clearfix '><button type='button' class='btn btn-xs btn-danger pull-left mr remove-file'><i data-lucide='x'></i></button> <input class='pull-left' type='file' name='manualFiles[]' /></div>" +
												"<div class='mb5 pb5'><input class='form-control description-field'  name='comment[]'  type='text' style='cursor: auto;' placeholder='<?php echo lang("comment") ?>' /></div>" +
												"</div>";
											$("#comments_file-previews").prepend(newFileRow);
										});
										$("#add-more-file-button").trigger("click");
										$("#comments_file-previews").on("click", ".remove-file", function() {
											$(this).closest(".file-row").remove();
										});
									},
									success: function(file) {
										setTimeout(function() {
											$(file.previewElement).find(".progress-striped").removeClass("progress-striped").addClass("progress-bar-success");
										}, 1000);
									}
								});
							});
						</script>
					</div>
				</div>
			</div>

			<div class="leave-form-row pt-0">
				<div class="leave-form-spacer"></div>
				<div class="flex items-center gap-2">
					<button type="button" class="inline-flex items-center rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted" data-dismiss="modal"><?= lang('close') ?></button>
					<button type="submit" id="file-save-button" class="inline-flex items-center rounded-lg bg-indigo-600 px-4 py-2 text-xs font-semibold text-white shadow-sm hover:bg-indigo-500"><?= lang('submit') ?></button>
				</div>
			</div>
		</div>

		<div class="col-span-12 xl:col-span-4">
			<div class="leave-summary-panel xl:sticky xl:top-4">
				<div id="leave_user_details"></div>
			</div>
		</div>
	</div>
</form>

<script type="text/javascript">
	(function() {
		var initialized = false;
		var currentScript = document.currentScript;
		var formNode = currentScript ? currentScript.previousElementSibling : document.querySelector('.apply-leave-modal');
		if (!formNode) {
			return;
		}
		var baseUrl = <?= json_encode(base_url()) ?>;
		var userDetailsNode = formNode.querySelector('#leave_user_details');
		var validationNode = formNode.querySelector('#leave_validation_message');

		function setSectionState(section, visible) {
			if (!section) {
				return;
			}
			section.hidden = !visible;
			section.setAttribute('aria-hidden', visible ? 'false' : 'true');
			section.style.display = visible ? '' : 'none';
			section.querySelectorAll('input, select, textarea').forEach(function(field) {
				if (field.type === 'hidden') {
					return;
				}
				if (field.dataset.requiredInit === undefined) {
					field.dataset.requiredInit = field.required ? '1' : '0';
				}
				field.disabled = !visible;
				field.required = visible && field.dataset.requiredInit === '1';
			});
		}

		function getSelectedLeaveType() {
			var selected = formNode.querySelector('input[name="leave_type"]:checked');
			return selected ? selected.value : 'single_day';
		}

		function syncLeaveTypeMode() {
			var mode = getSelectedLeaveType();
			setSectionState(formNode.querySelector('#single_day_section'), mode === 'single_day');
			setSectionState(formNode.querySelector('#multiple_days_section'), mode === 'multiple_days');
			setSectionState(formNode.querySelector('#hours_section'), mode === 'hours');
		}

		function getCurrentUserId() {
			var adminUserField = formNode.querySelector('#users_id');
			if (adminUserField && adminUserField.value) {
				return adminUserField.value;
			}
			var currentUserField = formNode.querySelector('#user_id');
			return currentUserField ? currentUserField.value : '';
		}

		function getCurrentLeaveCategoryId() {
			var categoryField = formNode.querySelector('#leave_category');
			return categoryField ? categoryField.value : '';
		}

		function getLeaveDates() {
			var mode = getSelectedLeaveType();
			if (mode === 'multiple_days') {
				return {
					start: formNode.querySelector('#multiple_days_start_date') ? formNode.querySelector('#multiple_days_start_date').value : '',
					end: formNode.querySelector('#multiple_days_end_date') ? formNode.querySelector('#multiple_days_end_date').value : ''
				};
			}
			if (mode === 'hours') {
				return {
					start: formNode.querySelector('#hours_start_date') ? formNode.querySelector('#hours_start_date').value : '',
					end: ''
				};
			}
			return {
				start: formNode.querySelector('#single_day_start_date') ? formNode.querySelector('#single_day_start_date').value : '',
				end: ''
			};
		}

		window.get_leave_details = function(userId) {
			var selectedUserId = userId || getCurrentUserId();
			if (!userDetailsNode) {
				return;
			}
			if (!selectedUserId) {
				userDetailsNode.innerHTML = '';
				return;
			}
			$.ajax({
				url: baseUrl + 'admin/common/get_leave_details/' + encodeURIComponent(selectedUserId),
				type: 'GET',
				success: function(response) {
					userDetailsNode.innerHTML = response;
				},
				error: function() {
					userDetailsNode.innerHTML = '';
				}
			});
		};

		window.check_available_leave = function() {
			var userId = getCurrentUserId();
			var leaveCategoryId = getCurrentLeaveCategoryId();
			var dates = getLeaveDates();
			var endDate = dates.end ? dates.end : 'null';

			if (!validationNode) {
				return;
			}
			if (!userId || !leaveCategoryId || !dates.start) {
				validationNode.textContent = '';
				return;
			}

			$.ajax({
				url: baseUrl + 'admin/common/check_available_leave/' + encodeURIComponent(userId) + '/' + encodeURIComponent(dates.start) + '/' + encodeURIComponent(endDate) + '/' + encodeURIComponent(leaveCategoryId),
				type: 'GET',
				success: function(response) {
					validationNode.textContent = response ? String(response).trim() : '';
				},
				error: function() {
					validationNode.textContent = '';
				}
			});
		};

		function bindValidationEvents() {
			var watchedFieldIds = [
				'users_id',
				'leave_category',
				'single_day_start_date',
				'multiple_days_start_date',
				'multiple_days_end_date',
				'hours_start_date',
				'hours_value'
			];

			watchedFieldIds.forEach(function(fieldId) {
				var field = formNode.querySelector('#' + fieldId);
				if (!field) {
					return;
				}
				field.addEventListener('change', function() {
					if (fieldId === 'users_id') {
						window.get_leave_details(field.value);
					}
					window.check_available_leave();
				});
			});
		}

		function initLeaveTypeToggle() {
			if (initialized) {
				return;
			}
			var radios = formNode.querySelectorAll('input[name="leave_type"]');
			if (!radios.length) {
				return;
			}

			var hasChecked = false;
			radios.forEach(function(radio) {
				if (radio.checked) {
					hasChecked = true;
				}
				var syncSections = function() {
					syncLeaveTypeMode();
					window.check_available_leave();
				};
				radio.addEventListener('change', syncSections);
				radio.addEventListener('click', syncSections);
			});

			if (!hasChecked) {
				var singleDayRadio = formNode.querySelector('input[name="leave_type"][value="single_day"]');
				if (singleDayRadio) {
					singleDayRadio.checked = true;
				}
			}

			syncLeaveTypeMode();
			bindValidationEvents();
			window.get_leave_details();
			window.check_available_leave();
			initialized = true;
		}

		document.addEventListener('DOMContentLoaded', initLeaveTypeToggle);
		initLeaveTypeToggle();
	})();
</script>
