<?= message_box('success'); ?>
<?= message_box('error'); ?>
<?php
$created = can_action('94', 'created');
$edited = can_action('94', 'edited');
$currency_symbol = default_currency();
$is_edit_mode = !empty($salary_template_info->salary_template_id);

if (!empty($created) || !empty($edited)) {
	$basic_salary_value = isset($salary_template_info->basic_salary) ? (float) $salary_template_info->basic_salary : 0;
	$overtime_salary_value = isset($salary_template_info->overtime_salary) ? (float) $salary_template_info->overtime_salary : 0;
	$salary_grade_value = isset($salary_template_info->salary_grade) ? $salary_template_info->salary_grade : '';

	$allowance_rows = array();
	if (!empty($salary_allowance_info)) {
		foreach ($salary_allowance_info as $allowance) {
			$allowance_rows[] = array(
				'id' => !empty($allowance->salary_allowance_id) ? $allowance->salary_allowance_id : '',
				'label' => !empty($allowance->allowance_label) ? $allowance->allowance_label : '',
				'value' => isset($allowance->allowance_percent) ? (float) $allowance->allowance_percent : 0,
				'amount' => isset($allowance->allowance_value) ? (float) $allowance->allowance_value : 0,
				'type' => !empty($allowance->allowance_type) ? $allowance->allowance_type : 'percent',
			);
		}
	} else {
		$allowance_rows = array(
			array('id' => '', 'label' => lang('house_rent_allowance'), 'value' => 0, 'amount' => 0, 'type' => 'percent'),
			array('id' => '', 'label' => lang('medical_allowance'), 'value' => 0, 'amount' => 0, 'type' => 'fixed'),
		);
	}

	$deduction_rows = array();
	if (!empty($salary_deduction_info)) {
		foreach ($salary_deduction_info as $deduction) {
			$deduction_type = !empty($deduction->deduction_type) ? $deduction->deduction_type : 'fixed';
			$deduction_input_value = isset($deduction->deduction_percent) ? (float) $deduction->deduction_percent : (isset($deduction->deduction_value) ? (float) $deduction->deduction_value : 0);
			$deduction_rows[] = array(
				'id' => !empty($deduction->salary_deduction_id) ? $deduction->salary_deduction_id : '',
				'label' => !empty($deduction->deduction_label) ? $deduction->deduction_label : '',
				'value' => $deduction_input_value,
				'amount' => isset($deduction->deduction_value) ? (float) $deduction->deduction_value : 0,
				'type' => $deduction_type,
			);
		}
	} else {
		$deduction_rows = array(
			array('id' => '', 'label' => lang('provident_fund'), 'value' => 0, 'amount' => 0, 'type' => 'percent'),
			array('id' => '', 'label' => lang('tax_deduction'), 'value' => 0, 'amount' => 0, 'type' => 'percent'),
		);
	}

	$total_allowance = 0;
	foreach ($allowance_rows as $row) {
		$total_allowance += (float) $row['amount'];
	}

	$total_deduction = 0;
	foreach ($deduction_rows as $row) {
		$total_deduction += (float) $row['amount'];
	}

	$gross_salary = $basic_salary_value + $total_allowance;
	$net_salary = $gross_salary - $total_deduction;
	$panel_classes = 'overflow-hidden rounded-2xl border border-border bg-card shadow-sm';
	$field_label_classes = 'mb-2 flex items-center gap-1 text-[0.9rem] font-semibold uppercase tracking-[0.08em] text-muted-foreground';
	$text_input_classes = 'h-10 w-full rounded-xl border border-border bg-input px-3  font-medium text-foreground shadow-sm transition focus:border-primary/50 focus:outline-none focus:ring-4 focus:ring-primary/10';
	$text_input_plain_classes = 'h-10 w-full rounded-none border-0 bg-transparent px-3 font-medium text-foreground shadow-none transition placeholder:text-muted-foreground focus:outline-none focus:ring-0';
	$select_embedded_classes = 'h-10 w-full appearance-none rounded-none border-0 border-l border-l-border bg-muted/30 bg-[linear-gradient(45deg,transparent_50%,hsl(var(--muted-foreground))_50%),linear-gradient(135deg,hsl(var(--muted-foreground))_50%,transparent_50%)] bg-[position:calc(100%-16px)_calc(50%-3px),calc(100%-11px)_calc(50%-3px)] bg-[size:5px_5px,5px_5px] bg-no-repeat px-3 pr-8 text-center font-medium text-foreground shadow-none transition focus:outline-none focus:ring-0 sm:text-center';
	$icon_button_classes = 'inline-flex h-8 w-8 items-center justify-center self-end rounded-lg bg-transparent text-muted-foreground transition hover:bg-muted hover:text-destructive sm:self-center';
	$component_row_classes = 'grid grid-cols-1 items-start gap-2 sm:grid-cols-[minmax(0,1fr)_26px] sm:items-center sm:gap-[10px]';
	$component_main_classes = 'grid min-h-10 grid-cols-1 overflow-hidden rounded-xl border border-border bg-background/50 sm:grid-cols-[minmax(0,1fr)_96px_132px]';
	$component_value_wrap_classes = 'flex min-w-0 items-center gap-2 border-t border-t-border px-3 text-foreground sm:border-l sm:border-t-0 sm:border-l-border';
	$card_header_classes = 'border-b border-border px-4 py-4 sm:px-5';
	$card_body_classes = 'px-4 py-4 sm:px-5 sm:py-5';
	$card_footer_classes = 'flex items-center justify-between border-t border-border bg-muted/20 px-4 py-4 sm:px-5';
	$summary_panel_classes = $panel_classes . ' mt-5 grid grid-cols-1 items-center gap-5 px-4 py-5 sm:px-6 xl:grid-cols-[minmax(0,1fr)_220px]';
	$button_secondary_classes = 'inline-flex h-10 min-w-[96px] items-center justify-center gap-2 rounded-xl border border-border bg-card px-4 font-semibold text-foreground transition hover:bg-muted';
	$button_primary_classes = 'inline-flex h-10 min-w-[96px] items-center justify-center gap-2 rounded-xl border border-primary bg-primary px-4 font-semibold text-primary-foreground shadow-sm transition hover:bg-primary/90';
	?>

	<div class="text-foreground">
		<div>
			<form data-parsley-validate="" novalidate="" role="form" enctype="multipart/form-data"
				action="<?= base_url() ?>admin/payroll/set_salary_details/<?php if ($is_edit_mode) {
																								echo $salary_template_info->salary_template_id;
																							} ?>"
				method="post">

				<div class="<?= $panel_classes ?>">
					<div class="grid grid-cols-1 gap-5 px-4 py-4 sm:px-5 xl:grid-cols-3">
						<div>
							<label for="salary_grade" class="<?= $field_label_classes ?>">
								<span><?= lang('salary_grade') ?></span>
								<span class="text-destructive">*</span>
							</label>
							<input id="salary_grade" type="text" name="salary_grade" required
								value="<?= html_escape($salary_grade_value) ?>"
								placeholder="<?= html_escape(lang('salary_grade')) ?>"
								class="<?= $text_input_classes ?>">
						</div>

						<div>
							<label for="basic_salary" class="<?= $field_label_classes ?>">
								<span><?= lang('basic_salary') ?></span>
								<span class="text-destructive">*</span>
							</label>
							<div class="relative">
								<span class="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 font-medium text-muted-foreground"><?= html_escape($currency_symbol) ?></span>
								<input id="basic_salary" type="number" step="0.01" min="0" name="basic_salary" required
									value="<?= html_escape((string) $basic_salary_value) ?>"
									placeholder="<?= html_escape(lang('basic_salary')) ?>"
									class="<?= $text_input_classes ?> pl-[34px]">
							</div>
						</div>

						<div>
							<label for="overtime_salary" class="<?= $field_label_classes ?>"><?= lang('overtime_rate') ?></label>
							<div class="relative">
								<span class="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 font-medium text-muted-foreground"><?= html_escape($currency_symbol) ?></span>
								<input id="overtime_salary" type="number" step="0.01" min="0" name="overtime_salary"
									value="<?= html_escape((string) $overtime_salary_value) ?>"
									placeholder="<?= html_escape(lang('overtime_rate')) ?>"
									class="<?= $text_input_classes ?> pl-[34px]">
							</div>
						</div>
					</div>
				</div>

				<div class="mt-5 grid grid-cols-1 gap-5 xl:grid-cols-2">
					<div class="<?= $panel_classes ?>">
						<div class="<?= $card_header_classes ?>">
							<h2 class="font-semibold leading-snug text-foreground/85"><?= lang('allowances') ?></h2>
							<p class="mt-1 text-[0.95rem] leading-relaxed text-muted-foreground"><?= lang('the_percentage_value_will_be_calculated_based_on_basic_salary') ?></p>
						</div>
						<div class="<?= $card_body_classes ?>">
							<div id="allowance_list" class="grid gap-3">
								<?php foreach ($allowance_rows as $row) : ?>
									<div class="salary-component-row <?= $component_row_classes ?>" data-component-row="allowance">
										<div class="<?= $component_main_classes ?>">
											<input type="text" name="allowance_label[]"
												value="<?= html_escape($row['label']) ?>"
												placeholder="<?= html_escape(lang('enter') . ' ' . lang('allowances') . ' ' . lang('label')) ?>"
												class="<?= $text_input_plain_classes ?>">

											<select name="allowance_type[]" class="salary-component-type <?= $select_embedded_classes ?> allowance_type">
												<option value="percent" <?= $row['type'] === 'percent' ? 'selected' : '' ?>><?= lang('percent') ?></option>
												<option value="fixed" <?= $row['type'] === 'fixed' ? 'selected' : '' ?>><?= lang('fixed') ?></option>
											</select>

											<div class="<?= $component_value_wrap_classes ?>">
												<span class="component-prefix text-[1rem] font-medium text-muted-foreground"><?= $row['type'] === 'fixed' ? html_escape($currency_symbol) : '%' ?></span>
												<input type="number" step="0.01" min="0" name="allowance_percent[]"
													value="<?= html_escape((string) $row['value']) ?>"
													placeholder="0"
													class="component-input salary h-9 min-w-0 flex-1 border-0 bg-transparent p-0  font-medium text-foreground shadow-none focus:outline-none focus:ring-0">
											</div>
										</div>

										<input type="hidden" name="allowance_value[]"
											value="<?= html_escape((string) $row['amount']) ?>"
											class="component-amount allowance_amount">
										<input type="hidden" name="salary_allowance_id[]"
											value="<?= html_escape((string) $row['id']) ?>">

										<button type="button" class="<?= $icon_button_classes ?> component-remove" aria-label="<?= html_escape(lang('delete')) ?>">
											<i data-lucide="trash-2" class="h-4 w-4"></i>
										</button>
									</div>
								<?php endforeach; ?>
							</div>

							<button type="button" id="add_more" class="mt-4 inline-flex h-9 w-full items-center justify-center gap-2 rounded-xl border border-dashed border-primary/20 bg-primary/5 text-[1.05rem] font-medium text-primary/80 transition hover:border-primary/35 hover:bg-primary/10">
								<i data-lucide="plus" class="h-4 w-4"></i>
								<span>Add Allowance</span>
							</button>
						</div>
						<div class="<?= $card_footer_classes ?>">
							<span class="text-[1.05rem] font-medium text-muted-foreground">Total Allowances</span>
							<span id="total_allowance" class="font-semibold tracking-[0.01em] text-emerald-500/90"><?= display_money($total_allowance, $currency_symbol) ?></span>
						</div>
					</div>

					<div class="<?= $panel_classes ?>">
						<div class="<?= $card_header_classes ?>">
							<h2 class="font-semibold leading-snug text-foreground/85"><?= lang('deductions') ?></h2>
							<p class="mt-1 text-[0.95rem] leading-relaxed text-muted-foreground"><?= lang('the_percentage_value_will_be_calculated_based_on_basic_salary') ?></p>
						</div>
						<div class="<?= $card_body_classes ?>">
							<div id="deduction_list" class="grid gap-3">
								<?php foreach ($deduction_rows as $row) : ?>
									<div class="salary-component-row <?= $component_row_classes ?>" data-component-row="deduction">
										<div class="<?= $component_main_classes ?>">
											<input type="text" name="deduction_label[]"
												value="<?= html_escape($row['label']) ?>"
												placeholder="<?= html_escape(lang('enter') . ' ' . lang('deductions') . ' ' . lang('label')) ?>"
												class="<?= $text_input_plain_classes ?>">

											<select name="deduction_type[]" class="salary-component-type <?= $select_embedded_classes ?> deduction_type">
												<option value="percent" <?= $row['type'] === 'percent' ? 'selected' : '' ?>><?= lang('percent') ?></option>
												<option value="fixed" <?= $row['type'] === 'fixed' ? 'selected' : '' ?>><?= lang('fixed') ?></option>
											</select>

											<div class="<?= $component_value_wrap_classes ?>">
												<span class="component-prefix text-[1rem] font-medium text-muted-foreground"><?= $row['type'] === 'fixed' ? html_escape($currency_symbol) : '%' ?></span>
												<input type="number" step="0.01" min="0" name="deduction_percent[]"
													value="<?= html_escape((string) $row['value']) ?>"
													placeholder="0"
													class="component-input deduction h-9 min-w-0 flex-1 border-0 bg-transparent p-0  font-medium text-foreground shadow-none focus:outline-none focus:ring-0">
											</div>
										</div>

										<input type="hidden" name="deduction_value[]"
											value="<?= html_escape((string) $row['amount']) ?>"
											class="component-amount deduction_amount">
										<input type="hidden" name="salary_deduction_id[]"
											value="<?= html_escape((string) $row['id']) ?>">

										<button type="button" class="<?= $icon_button_classes ?> component-remove" aria-label="<?= html_escape(lang('delete')) ?>">
											<i data-lucide="trash-2" class="h-4 w-4"></i>
										</button>
									</div>
								<?php endforeach; ?>
							</div>

							<button type="button" id="add_more_deduc" class="mt-4 inline-flex h-9 w-full items-center justify-center gap-2 rounded-xl border border-dashed border-primary/20 bg-primary/5 text-[1.05rem] font-medium text-primary/80 transition hover:border-primary/35 hover:bg-primary/10">
								<i data-lucide="plus" class="h-4 w-4"></i>
								<span>Add Deduction</span>
							</button>
						</div>
						<div class="<?= $card_footer_classes ?>">
							<span class="text-[1.05rem] font-medium text-muted-foreground">Total Deductions</span>
							<span id="total_deductions" class="font-semibold tracking-[0.01em] text-rose-500/90">- <?= display_money($total_deduction, $currency_symbol) ?></span>
						</div>
					</div>
				</div>

				<div class="<?= $summary_panel_classes ?>">
					<div>
						<h2 class="mb-3 flex items-center gap-2 text-[1.15rem] font-semibold text-foreground/85">
							<i data-lucide="badge-dollar-sign" class="h-4 w-4 text-primary"></i>
							<span><?= lang('total_salary_details') ?></span>
						</h2>

						<div class="grid max-w-[280px] gap-3">
							<div class="flex items-center justify-between gap-4 text-[1.05rem]">
								<span class="font-medium text-muted-foreground"><?= lang('gross_salary') ?></span>
								<span id="gross_salary_value" class="font-medium text-foreground/90"><?= display_money($gross_salary, $currency_symbol) ?></span>
							</div>
							<div class="flex items-center justify-between gap-4 text-[1.05rem]">
								<span class="font-medium text-muted-foreground"><?= lang('total_deduction') ?></span>
								<span id="summary_total_deduction" class="font-medium text-rose-500/90">- <?= display_money($total_deduction, $currency_symbol) ?></span>
							</div>
						</div>
					</div>

					<div class="w-full max-w-none justify-self-stretch rounded-2xl border border-primary/10 bg-primary/[0.04] px-5 py-4 text-right xl:max-w-[220px] xl:justify-self-end">
						<div class="text-[0.85rem] font-medium uppercase tracking-[0.1em] text-primary/75"><?= lang('net_salary') ?></div>
						<div id="net_salary_display" class="mt-2 text-[1.5rem] font-semibold leading-none tracking-[-0.02em] text-foreground/90"><?= display_money($net_salary, $currency_symbol) ?></div>
					</div>
				</div>

				<div class="mt-5 flex flex-col-reverse justify-end gap-2.5 border-t border-border pt-5 sm:flex-row">
					<a href="<?= base_url('admin/payroll/salary_template') ?>" class="<?= $button_secondary_classes ?>">
						<i data-lucide="x" class="h-4 w-4"></i>
						<span><?= lang('cancel') ?></span>
					</a>
					<button type="submit" class="<?= $button_primary_classes ?>">
						<i data-lucide="save" class="h-4 w-4"></i>
						<span><?= $is_edit_mode ? lang('updates') : lang('save') ?></span>
					</button>
				</div>
			</form>
		</div>
	</div>

	<script type="text/javascript">
		(function($) {
			const currencySymbol = <?= json_encode($currency_symbol) ?>;
			const currencyPosition = <?= json_encode((int) config_item('currency_position')) ?>;
			const allowanceList = $('#allowance_list');
			const deductionList = $('#deduction_list');
			const maxRows = 100;
			const componentRowClass = <?= json_encode($component_row_classes) ?>;
			const componentMainClass = <?= json_encode($component_main_classes) ?>;
			const textInputPlainClass = <?= json_encode($text_input_plain_classes) ?>;
			const selectEmbeddedClass = <?= json_encode($select_embedded_classes) ?>;
			const componentValueWrapClass = <?= json_encode($component_value_wrap_classes) ?>;
			const iconButtonClass = <?= json_encode($icon_button_classes) ?>;

			function formatMoney(value) {
				const amount = Number(value || 0);
				const formatted = amount.toLocaleString(undefined, {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				});
				return currencyPosition === 2 ? formatted + ' ' + currencySymbol : currencySymbol + ' ' + formatted;
			}

			function getPrefix(type) {
				return type === 'fixed' ? currencySymbol : '%';
			}

			function buildRow(kind, label) {
				const typeClass = kind === 'allowance' ? 'allowance_type' : 'deduction_type';
				const valueClass = kind === 'allowance' ? 'salary' : 'deduction';
				const hiddenClass = kind === 'allowance' ? 'allowance_amount' : 'deduction_amount';
				const labelName = kind + '_label[]';
				const percentName = kind + '_percent[]';
				const valueName = kind + '_value[]';
				const idName = kind === 'allowance' ? 'salary_allowance_id[]' : 'salary_deduction_id[]';
				const labelPlaceholder = kind === 'allowance'
					? <?= json_encode(lang('enter') . ' ' . lang('allowances') . ' ' . lang('label')) ?>
					: <?= json_encode(lang('enter') . ' ' . lang('deductions') . ' ' . lang('label')) ?>;

				return $(
					'<div class="salary-component-row ' + componentRowClass + '" data-component-row="' + kind + '">' +
					'<div class="' + componentMainClass + '">' +
					'<input type="text" name="' + labelName + '" value="' + (label || '') + '" placeholder="' + labelPlaceholder + '" class="' + textInputPlainClass + '">' +
					'<select name="' + kind + '_type[]" class="salary-component-type ' + selectEmbeddedClass + ' ' + typeClass + '">' +
					'<option value="percent"><?= html_escape(lang('percent')) ?></option>' +
					'<option value="fixed"><?= html_escape(lang('fixed')) ?></option>' +
					'</select>' +
					'<div class="' + componentValueWrapClass + '">' +
					'<span class="component-prefix text-[1rem] font-medium text-muted-foreground">%</span>' +
					'<input type="number" step="0.01" min="0" name="' + percentName + '" value="0" placeholder="0" class="component-input ' + valueClass + ' h-9 min-w-0 flex-1 border-0 bg-transparent p-0  font-medium text-foreground shadow-none focus:outline-none focus:ring-0">' +
					'</div>' +
					'</div>' +
					'<input type="hidden" name="' + valueName + '" value="0" class="component-amount ' + hiddenClass + '">' +
					'<input type="hidden" name="' + idName + '" value="">' +
					'<button type="button" class="' + iconButtonClass + ' component-remove" aria-label="<?= html_escape(lang('delete')) ?>">' +
					'<i data-lucide="trash-2" class="h-4 w-4"></i>' +
					'</button>' +
					'</div>'
				);
			}

			function updateRow(row) {
				const input = row.find('.component-input');
				const select = row.find('.salary-component-type');
				const prefix = row.find('.component-prefix');
				const amountField = row.find('.component-amount');
				const rawValue = parseFloat(input.val());
				const baseSalary = parseFloat($('#basic_salary').val()) || 0;
				const type = select.val();
				let amount = 0;

				if (!isNaN(rawValue)) {
					amount = type === 'fixed' ? rawValue : (rawValue * baseSalary / 100);
				}

				amount = isNaN(amount) ? 0 : amount;
				prefix.text(getPrefix(type));
				amountField.val(amount.toFixed(2));
				row.attr('data-computed-amount', amount.toFixed(2));
			}

			function calculatePayroll() {
				let totalAllowance = 0;
				let totalDeduction = 0;
				const basicSalary = parseFloat($('#basic_salary').val()) || 0;

				allowanceList.find('.salary-component-row').each(function() {
					updateRow($(this));
					totalAllowance += parseFloat($(this).attr('data-computed-amount')) || 0;
				});

				deductionList.find('.salary-component-row').each(function() {
					updateRow($(this));
					totalDeduction += parseFloat($(this).attr('data-computed-amount')) || 0;
				});

				const grossSalary = basicSalary + totalAllowance;
				const netSalary = grossSalary - totalDeduction;

				$('#total_allowance').text(formatMoney(totalAllowance));
				$('#total_deductions').text('- ' + formatMoney(totalDeduction));
				$('#gross_salary_value').text(formatMoney(grossSalary));
				$('#summary_total_deduction').text('- ' + formatMoney(totalDeduction));
				$('#net_salary_display').text(formatMoney(netSalary));
			}

			function refreshIcons() {
				if (window.lucide && typeof window.lucide.createIcons === 'function') {
					window.lucide.createIcons();
				}
			}

			$('#add_more').on('click', function() {
				if (allowanceList.children().length >= maxRows) {
					alert(<?= json_encode(lang('max_100_file_allowed')) ?>);
					return;
				}

				allowanceList.append(buildRow('allowance', ''));
				refreshIcons();
				calculatePayroll();
			});

			$('#add_more_deduc').on('click', function() {
				if (deductionList.children().length >= maxRows) {
					alert(<?= json_encode(lang('max_100_file_allowed')) ?>);
					return;
				}

				deductionList.append(buildRow('deduction', ''));
				refreshIcons();
				calculatePayroll();
			});

			$(document).on('input change', '#basic_salary, .component-input, .salary-component-type', function() {
				calculatePayroll();
			});

			$(document).on('click', '.component-remove', function() {
				$(this).closest('.salary-component-row').remove();
				calculatePayroll();
			});

			refreshIcons();
			calculatePayroll();
		})(jQuery);
	</script>
<?php } ?>
