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

<div class="space-y-4">
	<div class="rounded-2xl border border-border bg-card shadow-sm">
		<div class="border-b border-border px-5 py-4">
			<div class="flex items-center gap-2 text-sm font-semibold text-foreground">
				<i data-lucide="bar-chart-3" class="h-5 w-5"></i>
				<span><?= lang('payroll_summary') ?></span>
			</div>
		</div>
		<div class="p-5 grid grid-cols-12 gap-4">
			<div class="sm:col-span-3"></div>
			<form id="form" role="form" enctype="multipart/form-data"
				action="<?php echo base_url() ?>admin/payroll/payroll_summary" method="post"
				class="space-y-2 sm:col-span-6">
			<?= form_select_group(
				'search_type',
				lang('search_type'),
				array(
						'' => lang('select') . ' ' . lang('search_type'),
						'employee' => lang('by') . ' ' . lang('employee'),
						'month' => lang('by') . ' ' . lang('month'),
						'period' => lang('by') . ' ' . lang('period'),
						'activities' => lang('all') . ' ' . lang('activities'),
					),
				!empty($search_type) ? $search_type : '',
				true,
				array('id' => 'search_type')
			); ?>

			<div class="by_employee" style="display: <?= !empty($search_type) && $search_type == 'employee' ? 'block' : 'none' ?>">
				<?= form_grouped_lookup_group(
					'user_id',
					lang('employee'),
					grouped_staff_lookup_groups(),
					!empty($user_id) ? $user_id : '',
					!empty($selected_user_label) ? $selected_user_label : '',
					true,
					array('id' => 'payroll_summary_employee'),
					'',
					array(
						'placeholder' => lang('search') . ' ' . lang('employee'),
						'helper' => 'Quick employee search.',
					)
				); ?>
			</div>

			<div class="by_month" style="display: <?= !empty($search_type) && $search_type == 'month' ? 'block' : 'none' ?>">
				<?= form_datepicker('by_month', lang('select') . ' ' . lang('month'), !empty($by_month) ? $by_month : '', true, array('class' => 'monthyear by_month', 'data-type' => 'month', 'data-format' => 'Y-m', 'data-auto-close' => 'true')); ?>
			</div>

			<div class="by_period" style="display: <?= !empty($search_type) && $search_type == 'period' ? 'block' : 'none' ?>">
				<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
					<?= form_datepicker('start_month', lang('start') . ' ' . lang('month'), !empty($start_month) ? $start_month : '', true, array('class' => 'by_period monthyear', 'data-type' => 'month', 'data-format' => 'Y-m', 'data-auto-close' => 'true')); ?>
					<?= form_datepicker('end_month', lang('end') . ' ' . lang('month'), !empty($end_month) ? $end_month : '', true, array('class' => 'by_period monthyear', 'data-type' => 'month', 'data-format' => 'Y-m', 'data-auto-close' => 'true')); ?>
				</div>
				<p id="periodMonthError" class="mt-2 hidden text-sm text-rose-500"></p>
			</div>

				<div class="flex justify-start">
					<button id="submit" type="submit" name="flag" value="1"
						class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-xs font-semibold text-white shadow-sm hover:bg-indigo-500">
						<i data-lucide="arrow-right" class="h-4 w-4"></i>
						<?= lang('go') ?>
					</button>
				</div>
			</form>
		</div>
	</div>
</div>
	<?php if (!empty($show_summary)) {
		if ($search_type == 'period') {
			$by = ' - ' . ' ' . date('F-Y', safe_strtotime($start_month)) . ' ' . lang('TO') . ' ' . date('F-Y', safe_strtotime($end_month));
			$pdf = $start_month . 'n' . $end_month;
	}
	if ($search_type == 'month') {
		$by = ' - ' . ' ' . date('F-Y', safe_strtotime($by_month));
		$pdf = $by_month;
	}
	if ($search_type == 'employee') {
		$user_info = $this->db->where('user_id', $user_id)->get('tbl_account_details')->row();
		$by = ' - ' . ' ' . ' ' . (!empty($user_info->fullname) ? $user_info->fullname : lang('unknown'));
		$pdf = $user_id;
	}
?>
		<div id="payment_history" class="all_payment_history space-y-4 mt-4">
		<div class="show_print border-b dark:border-gray-600" style="width: 100%; margin-bottom: 30px">
			<!-- show when print start-->
			<table style="width: 100%; vertical-align: middle;">
				<tr>
					<td style="width: 50px; border: 0px;">
						<img style="width: 50px;height: 50px;margin-bottom: 5px;"
							src="<?= base_url() . config_item('company_logo') ?>" alt="" class="rounded-full" />
					</td>

					<td style="border: 0px;">
						<p style="margin-left: 10px; font: 14px lighter;"><?= config_item('company_name') ?></p>
					</td>
				</tr>
			</table>
		</div>
		<!--  **************** show when print End ********************* -->
		<div class="rounded-2xl border border-border bg-card shadow-sm">
			<div class="border-b border-border px-5 py-4">
				<div class="flex flex-wrap items-center justify-between gap-2 text-sm font-semibold text-foreground">
					<span><?= lang('payroll_summary') . ' ' . $by ?></span>
					<div class="hidden-print flex items-center gap-2">
						<button class="inline-flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs font-semibold text-red-600 hover:bg-red-100"
							data-toggle="tooltip" data-placement="top" title="<?= lang('print') ?>" type="button"
							onclick="payroll_summary_print()">
							<i data-lucide="printer" class="h-4 w-4"></i>
							<?= lang('print') ?>
						</button>
						<a href="<?= base_url('admin/payroll/payroll_summary_pdf/' . $search_type . '/' . $pdf); ?>"
							class="inline-flex items-center gap-2 rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-2 text-xs font-semibold text-indigo-600 hover:bg-indigo-100"
							data-toggle="tooltip" data-placement="top" title="<?= lang('generate_pdf') ?>">
							<i data-lucide="file-text" class="h-4 w-4"></i>
							PDF
						</a>
					</div>
				</div>
			</div>
			<div class="p-5">
				<table class="table table-striped" id="DataTables" cellspacing="0" width="100%">
					<thead>
						<tr>
							<th><?= lang('month') ?></th>
							<th><?= lang('date') ?></th>
							<th><?= lang('gross_salary') ?></th>
							<th><?= lang('total_deduction') ?></th>
							<th><?= lang('net_salary') ?></th>
							<th><?= lang('fine_deduction') ?></th>
							<th><?= lang('amount') ?></th>
							<th class="hidden-print"><?= lang('details') ?></th>
						</tr>
					</thead>
					<tbody>
						<script type="text/javascript">
							$(document).ready(function() {
								<?php if ($search_type == 'employee') { ?>
									list = base_url + "admin/payroll/payment_historyList/<?= $pdf ?>";
								<?php } ?>

								<?php if ($search_type == 'month') { ?>
									list = base_url + "admin/payroll/payment_historyMonth/<?= $pdf ?>";
								<?php } ?>

								<?php if ($search_type == 'period') { ?>
									list = base_url + "admin/payroll/payment_historyPeriod/<?= $pdf ?>";
								<?php } ?>
							});
						</script>

						<?php
						$currency = $this->payroll_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
						if (!empty($employee_payroll)) {
							foreach ($employee_payroll as $index => $v_payroll) {
								$salary_payment_history = $this->db->where('salary_payment_id', $v_payroll->salary_payment_id)->get('tbl_salary_payment_details')->result();
								$total_salary_amount = 0;
								if (!empty($salary_payment_history)) {
									foreach ($salary_payment_history as $v_payment_history) {
										if (is_numeric($v_payment_history->salary_payment_details_value)) {
											if ($v_payment_history->salary_payment_details_label == 'overtime_salary') {
												$rate = $v_payment_history->salary_payment_details_value;
											} elseif ($v_payment_history->salary_payment_details_label == 'hourly_rates') {
												$rate = $v_payment_history->salary_payment_details_value;
											}
											$total_salary_amount += $v_payment_history->salary_payment_details_value;
										}
									}
								}
								$salary_allowance_info = $this->db->where('salary_payment_id', $v_payroll->salary_payment_id)->get('tbl_salary_payment_allowance')->result();
								$total_allowance = 0;
								if (!empty($salary_allowance_info)) {
									foreach ($salary_allowance_info as $v_salary_allowance_info) {
										$total_allowance += $v_salary_allowance_info->salary_payment_allowance_value;
									}
								}
								if (empty($rate)) {
									$rate = 0;
								}
								$salary_deduction_info = $this->db->where('salary_payment_id', $v_payroll->salary_payment_id)->get('tbl_salary_payment_deduction')->result();
								$total_deduction = 0;
								if (!empty($salary_deduction_info)) {
									foreach ($salary_deduction_info as $v_salary_deduction_info) {
										$total_deduction += $v_salary_deduction_info->salary_payment_deduction_value;
									}
								}

								$total_paid_amount = $total_salary_amount + $total_allowance - $rate;
								$gross = 0;
								$deduction = 0;
						?>
								<tr>
									<td><?php echo date('F-Y', safe_strtotime($v_payroll->payment_month)); ?></td>
									<td><?php echo display_date($v_payroll->paid_date); ?></td>
									<td><?php echo display_money($total_paid_amount, $currency->symbol); ?></td>
									<td><?php echo display_money($total_deduction, $currency->symbol); ?></td>
									<td><?php echo display_money($net_salary = $total_paid_amount - $total_deduction, $currency->symbol); ?></td>
									<td><?php
										if (!empty($v_payroll->fine_deduction)) {
											echo display_money($fine_deduction = $v_payroll->fine_deduction, $currency->symbol);
										} else {
											$fine_deduction = 0;
										}
										?></td>
									<td><?php echo display_money($net_salary - $fine_deduction, $currency->symbol); ?></td>
									<td class="hidden-print">
										<?= btn_modal(
											'admin/payroll/salary_payment_details/' . $v_payroll->salary_payment_id,
											'',
											lang('view'),
											'lg',
											'eye',
											array('class' => 'inline-flex items-center justify-center rounded-lg border border-slate-200 bg-slate-50 p-2 text-slate-600 hover:bg-slate-100 h-7 mb-0')
										) ?>
									</td>
								</tr>
							<?php }; ?>
						<?php } else { ?>
							<tr>
								<td colspan="8"><?= lang('nothing_to_display') ?></td>
							</tr>
						<?php }; ?>
					</tbody>
				</table>
			</div>
		</div><!--************ Payment History End***********-->
		<?php
		$print_currency = !empty($currency) ? $currency : $this->payroll_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
		$print_rows = array();
		$print_gross_total = 0;
		$print_deduction_total = 0;
		$print_net_total = 0;
		$print_paid_total = 0;
		if (!empty($employee_payroll)) {
			foreach ($employee_payroll as $v_payroll) {
				$salary_payment_history = $this->db->where('salary_payment_id', $v_payroll->salary_payment_id)->get('tbl_salary_payment_details')->result();
				$total_salary_amount = 0;
				$rate = 0;
				if (!empty($salary_payment_history)) {
					foreach ($salary_payment_history as $v_payment_history) {
						if (is_numeric($v_payment_history->salary_payment_details_value)) {
							if ($v_payment_history->salary_payment_details_label == 'overtime_salary' || $v_payment_history->salary_payment_details_label == 'hourly_rates') {
								$rate = $v_payment_history->salary_payment_details_value;
							}
							$total_salary_amount += $v_payment_history->salary_payment_details_value;
						}
					}
				}
				$salary_allowance_info = $this->db->where('salary_payment_id', $v_payroll->salary_payment_id)->get('tbl_salary_payment_allowance')->result();
				$total_allowance = 0;
				if (!empty($salary_allowance_info)) {
					foreach ($salary_allowance_info as $v_salary_allowance_info) {
						$total_allowance += $v_salary_allowance_info->salary_payment_allowance_value;
					}
				}
				$salary_deduction_info = $this->db->where('salary_payment_id', $v_payroll->salary_payment_id)->get('tbl_salary_payment_deduction')->result();
				$total_deduction = 0;
				if (!empty($salary_deduction_info)) {
					foreach ($salary_deduction_info as $v_salary_deduction_info) {
						$total_deduction += $v_salary_deduction_info->salary_payment_deduction_value;
					}
				}
				$gross_salary = $total_salary_amount + $total_allowance - $rate;
				$fine_deduction = !empty($v_payroll->fine_deduction) ? $v_payroll->fine_deduction : 0;
				$net_salary = $gross_salary - $total_deduction;
				$paid_amount = $net_salary - $fine_deduction;
				$print_gross_total += $gross_salary;
				$print_deduction_total += $total_deduction + $fine_deduction;
				$print_net_total += $net_salary;
				$print_paid_total += $paid_amount;
				$print_rows[] = array(
					'month' => date('F-Y', safe_strtotime($v_payroll->payment_month)),
					'date' => display_date($v_payroll->paid_date),
					'gross' => $gross_salary,
					'deduction' => $total_deduction,
					'net' => $net_salary,
					'fine' => $fine_deduction,
					'amount' => $paid_amount,
				);
			}
		}
		?>
		<div id="payroll-summary-print-design" style="display:none">
			<style>
				.payroll-summary-pdf-print { color:#172033; background:#fff; font:12px/1.55 DejaVu Sans, Arial, Helvetica, sans-serif; padding:18px 22px 24px; }
				.payroll-summary-pdf-print table { width:100%; border-collapse:collapse; border-spacing:0; }
				.payroll-summary-pdf-print .brand-shell { border:1px solid #d7deea; padding:18px 20px; background:#f8fafc; margin-bottom:18px; }
				.payroll-summary-pdf-print .brand-logo { width:60px; height:60px; background:#fff; border:1px solid #d7deea; padding:6px; }
				.payroll-summary-pdf-print .brand-title { font-size:24px; font-weight:500; color:#0f172a; margin:0 0 4px; }
				.payroll-summary-pdf-print .brand-text { font-size:12px; color:#64748b; margin:0; }
				.payroll-summary-pdf-print .report-meta { width:300px; text-align:right; }
				.payroll-summary-pdf-print .header-title { font-size:20px; font-weight:700; color:#0f172a; margin:0 0 4px; line-height:1.15; }
				.payroll-summary-pdf-print .header-subtitle { font-size:10px; color:#64748b; margin:0; line-height:1.35; }
				.payroll-summary-pdf-print .range-chip { display:inline-block; padding-top:4px; color:#475569; font-size:9px; font-weight:700; letter-spacing:.08em; text-transform:uppercase; }
				.payroll-summary-pdf-print .metrics { margin:0 0 18px; }
				.payroll-summary-pdf-print .metric-card { width:23.5%; border:1px solid #d7deea; background:#fff; padding:14px 16px; vertical-align:top; }
				.payroll-summary-pdf-print .metric-gap { width:2%; }
				.payroll-summary-pdf-print .metric-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.12em; color:#64748b; margin-bottom:6px; }
				.payroll-summary-pdf-print .metric-value { font-size:21px; font-weight:700; color:#0f172a; margin:0; }
				.payroll-summary-pdf-print .metric-note { font-size:11px; color:#94a3b8; margin-top:4px; }
				.payroll-summary-pdf-print .table-shell { border:1px solid #d7deea; overflow:hidden; background:#fff; }
				.payroll-summary-pdf-print .table-head td { background:#1e293b; color:#f8fafc; font-size:11px; font-weight:700; letter-spacing:.06em; text-transform:uppercase; padding:12px 14px; border-bottom:1px solid #1e293b; }
				.payroll-summary-pdf-print .row td { padding:12px 14px; border-bottom:1px solid #e2e8f0; color:#1e293b; vertical-align:top; }
				.payroll-summary-pdf-print .row-alt td { background:#f8fafc; }
				.payroll-summary-pdf-print .number { text-align:right; }
				.payroll-summary-pdf-print .muted { color:#64748b; }
				.payroll-summary-pdf-print .total-row td { padding:14px; background:#eef2ff; border-top:1px solid #c7d2fe; font-weight:700; color:#1e1b4b; }
			</style>
			<div class="payroll-summary-pdf-print">
				<div class="brand-shell">
					<table><tr>
						<td style="width:84px;border:0"><img class="brand-logo" src="<?= base_url() . config_item('company_logo') ?>" alt="<?= html_escape(config_item('company_name')) ?>"></td>
						<td style="border:0"><p class="brand-title"><?= html_escape(config_item('company_name')) ?></p><p class="brand-text"><?= lang('payroll_summary') ?></p></td>
						<td class="report-meta" style="border:0"><p class="header-title"><?= lang('payroll_summary') ?></p><p class="header-subtitle">Payroll disbursement, deductions, and final paid amount<?= !empty($by) ? ' for ' . html_escape(trim($by, ' -')) : '' ?>.</p><span class="range-chip"><?= lang('generated_on') ?> <?= display_date(date('Y-m-d')) ?></span></td>
					</tr></table>
				</div>
				<table class="metrics"><tr>
					<td class="metric-card"><div class="metric-label"><?= lang('records') ?></div><p class="metric-value"><?= count($print_rows) ?></p><div class="metric-note"><?= lang('salary_details') ?></div></td>
					<td class="metric-gap"></td>
					<td class="metric-card"><div class="metric-label"><?= lang('gross_salary') ?></div><p class="metric-value"><?= display_money($print_gross_total, $print_currency->symbol) ?></p><div class="metric-note"><?= lang('before') ?> <?= lang('deductions') ?></div></td>
					<td class="metric-gap"></td>
					<td class="metric-card"><div class="metric-label"><?= lang('total_deduction') ?></div><p class="metric-value"><?= display_money($print_deduction_total, $print_currency->symbol) ?></p><div class="metric-note"><?= lang('including') ?> <?= lang('fine_deduction') ?></div></td>
					<td class="metric-gap"></td>
					<td class="metric-card"><div class="metric-label"><?= lang('paid_amount') ?></div><p class="metric-value"><?= display_money($print_paid_total, $print_currency->symbol) ?></p><div class="metric-note"><?= lang('net_salary') ?>: <?= display_money($print_net_total, $print_currency->symbol) ?></div></td>
				</tr></table>
				<div class="table-shell">
					<table>
						<thead><tr class="table-head"><td><?= lang('month') ?></td><td><?= lang('date') ?></td><td class="number"><?= lang('gross_salary') ?></td><td class="number"><?= lang('total_deduction') ?></td><td class="number"><?= lang('net_salary') ?></td><td class="number"><?= lang('fine_deduction') ?></td><td class="number"><?= lang('amount') ?></td></tr></thead>
						<tbody>
						<?php if (!empty($print_rows)): foreach ($print_rows as $index => $row): ?>
							<tr class="row<?= ($index % 2 !== 0) ? ' row-alt' : '' ?>"><td><?= $row['month'] ?></td><td><?= $row['date'] ?></td><td class="number"><?= display_money($row['gross'], $print_currency->symbol) ?></td><td class="number"><?= display_money($row['deduction'], $print_currency->symbol) ?></td><td class="number"><?= display_money($row['net'], $print_currency->symbol) ?></td><td class="number"><?= display_money($row['fine'], $print_currency->symbol) ?></td><td class="number"><?= display_money($row['amount'], $print_currency->symbol) ?></td></tr>
						<?php endforeach; ?>
							<tr class="total-row"><td colspan="2"><?= lang('total') ?></td><td class="number"><?= display_money($print_gross_total, $print_currency->symbol) ?></td><td class="number"><?= display_money($print_deduction_total, $print_currency->symbol) ?></td><td class="number"><?= display_money($print_net_total, $print_currency->symbol) ?></td><td class="number">-</td><td class="number"><?= display_money($print_paid_total, $print_currency->symbol) ?></td></tr>
						<?php else: ?>
							<tr class="row"><td colspan="7" class="muted"><?= lang('nothing_to_display') ?></td></tr>
						<?php endif; ?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		<script type="text/javascript">
			function payroll_summary_print() {
				var source = document.getElementById('payroll-summary-print-design');
				if (!source) return;
				var root = document.getElementById('payroll-summary-print-root');
				if (root) root.remove();
				var style = document.getElementById('payroll-summary-print-style');
				if (!style) {
					style = document.createElement('style');
					style.id = 'payroll-summary-print-style';
					style.textContent = '@media print{@page{margin:18px}body> :not(#payroll-summary-print-root){display:none!important}#payroll-summary-print-root{display:block!important;background:#fff!important;color:#172033!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}}';
					document.head.appendChild(style);
				}
				root = document.createElement('div');
				root.id = 'payroll-summary-print-root';
				root.style.display = 'none';
				root.innerHTML = source.innerHTML;
				document.body.appendChild(root);
				var cleanup = function() {
					var printRoot = document.getElementById('payroll-summary-print-root');
					if (printRoot) printRoot.remove();
					window.removeEventListener('afterprint', cleanup);
				};
				window.addEventListener('afterprint', cleanup);
				setTimeout(function() {
					window.print();
					setTimeout(cleanup, 15000);
				}, 100);
			}
		</script>
	<?php } ?>
	<div class="by_activities mt-4"
		style="display: <?= !empty($search_type) && $search_type == 'activities' ? 'block' : 'none' ?>">
		<div class="rounded-2xl border border-border bg-card shadow-sm">
			<div class="border-b border-border px-5 py-4">
				<div class="flex flex-wrap items-center justify-between gap-2 text-sm font-semibold text-foreground">
					<span><?= lang('payroll_summary'); ?></span>
					<a onclick="return confirm('<?= lang('delete_alert') ?>')"
						href="<?= base_url() ?>admin/payroll/clear_activities"
						class="inline-flex items-center gap-2 rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-2 text-xs font-semibold text-indigo-600 hover:bg-indigo-100">
						<i data-lucide="trash-2" class="h-4 w-4"></i>
						<?= lang('clear') ?>
					</a>
				</div>
			</div>
			<div class="p-5">
				<div class="overflow-x-auto rounded-xl border border-border">
				<table class="min-w-full text-sm" id="Transation_DataTables">
					<thead class="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
						<tr>
							<th class="px-4 py-3 text-left"><?= lang('activity_date') ?></th>
							<th class="px-4 py-3 text-left"><?= lang('user') ?></th>
							<th class="px-4 py-3 text-left"><?= lang('module') ?></th>
							<th class="px-4 py-3 text-left"><?= lang('activity') ?></th>
						</tr>
					</thead>
					<tbody class="divide-y divide-border [&>tr>td]:px-4 [&>tr>td]:py-3">
						<?php
						$activities_info = $this->db->where('module', 'payroll')->get('tbl_activities')->result();
						if (!empty($activities_info)) {
							foreach ($activities_info as $v_activity) {

						?>
								<tr>
									<td><?= display_datetime($v_activity->activity_date); ?></td>
									<?php $activity_user = $this->db->where('user_id', $v_activity->user)->get('tbl_account_details')->row(); ?>
									<td><?= !empty($activity_user->fullname) ? $activity_user->fullname : lang('unknown'); ?></td>
									<td><?= $v_activity->module ?></td>
									<td>
										<?= lang($v_activity->activity) ?>
										<strong> <?= $v_activity->value1 . ' ' . $v_activity->value2 ?></strong>
									</td>
								</tr>
						<?php
							}
						}
						?>
					</tbody>
				</table>
				</div>
			</div>
		</div>
		<script type="text/javascript">
			$(document).ready(function() {
				$('#Transation_DataTables').dataTable({
					paging: false,
					"bSort": false
				});
			});
		</script>
	</div>
</div>


	<script type="text/javascript">
		(function() {
			function toMonthValue(value) {
				if (!value) {
					return '';
				}
				return value.length >= 7 ? value.slice(0, 7) : value;
			}

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

			function syncSearchTypeFields() {
				var select = document.getElementById('search_type');
				var form = document.getElementById('form');
				if (!select || !form) return;

				var employeeWrap = form.querySelector(':scope > .by_employee');
				var monthWrap = form.querySelector(':scope > .by_month');
				var periodWrap = form.querySelector(':scope > .by_period');
				var periodError = document.getElementById('periodMonthError');

				var mode = select.value || '';
				setSectionState(employeeWrap, mode === 'employee');
				setSectionState(monthWrap, mode === 'month');
				setSectionState(periodWrap, mode === 'period');
				if (periodError && mode !== 'period') {
					periodError.classList.add('hidden');
					periodError.textContent = '';
				}
			}

			function validateMonthsBeforeSubmit(event) {
				var select = document.getElementById('search_type');
				var periodError = document.getElementById('periodMonthError');
				if (!select) {
					return true;
				}

				var mode = select.value || '';
				if (mode === 'period') {
					var startInput = document.querySelector('input[name="start_month"]');
					var endInput = document.querySelector('input[name="end_month"]');
					var startMonth = toMonthValue(startInput ? startInput.value : '');
					var endMonth = toMonthValue(endInput ? endInput.value : '');
					if (!startMonth || !endMonth) {
						if (periodError) {
							periodError.textContent = 'Please select both start and end month.';
							periodError.classList.remove('hidden');
						}
						event.preventDefault();
						return false;
					}
					if (startMonth > endMonth) {
						if (periodError) {
							periodError.textContent = 'Start month cannot be greater than end month.';
							periodError.classList.remove('hidden');
						}
						event.preventDefault();
						return false;
					}
					if (periodError) {
						periodError.classList.add('hidden');
						periodError.textContent = '';
					}
				}
				return true;
			}

			document.addEventListener('DOMContentLoaded', function() {
				var select = document.getElementById('search_type');
				if (!select) return;
				syncSearchTypeFields();
				select.addEventListener('change', syncSearchTypeFields);
				var form = document.getElementById('form');
				if (form) {
					form.addEventListener('submit', validateMonthsBeforeSubmit);
				}
			});
		})();
	</script>
