<?php echo message_box('success'); ?>
<?php echo message_box('error');

$edited = can_action('98', 'edited');
$created = can_action('98', 'created');
$deleted = can_action('98', 'deleted');

?>
<!-- ************ Expense Report List start ************-->
<?php if (empty($switch)) { ?>
	<?php
	$selected_year = !empty($year) ? $year : date('Y');
	$selected_month = !empty($selected_month) ? sprintf('%02d', (int) $selected_month) : date('m');
	$selected_month_name = date('F', safe_strtotime($year . '-' . $selected_month));
	$report_list_url = base_url('admin/payroll/advance_salary_reportList/' . $year . '/' . $selected_month);
	?>
	<style>
	.js-month-pill {
		cursor: pointer;
	}
	</style>
	<div class="space-y-4">
		<div id="advance_salary" class="rounded-2xl border border-border bg-card shadow-sm">
			<div class="p-5">
				<div class="space-y-4">
					<div class="flex flex-col gap-4 border-b border-border pb-4 lg:flex-row lg:items-start lg:justify-between">
						<div class="min-w-0 flex-1 hidden-print">
							<div class="flex flex-wrap gap-2" data-advance-months>
								<?php for ($i = 1; $i <= 12; $i++) :
									$month_value = sprintf('%02d', $i);
									$month_name = date('F', safe_strtotime($year . '-' . $month_value));
									$is_active = ($selected_month == $month_value);
									$month_rows = !empty($advance_salary_info[$i]) ? $advance_salary_info[$i] : array();
									$total_records = count($month_rows);
									$total_amount = 0;
									$approved_count = 0;
									$pending_count = 0;
									foreach ($month_rows as $advance_salary) {
										$total_amount += (float) $advance_salary->advance_amount;
										if ($advance_salary->status == '1' || $advance_salary->status == '3') {
											$approved_count++;
										} elseif ($advance_salary->status == '0') {
											$pending_count++;
										}
									}
								?>
									<a href="<?= base_url('admin/payroll/advance_salary_reportList/' . $year . '/' . $month_value) ?>"
										class="js-month-pill inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold transition <?= $is_active ? 'bg-indigo-600 text-white shadow-sm' : 'text-muted-foreground' ?>"
										data-advance-month="<?= $month_value ?>"
										data-month-name="<?= html_escape($month_name) ?>"
										data-pdf-url="<?= base_url('admin/payroll/advance_salary_pdf/' . $year . '/' . $month_value) ?>"
										data-total-records="<?= (int) $total_records ?>"
										data-approved-count="<?= (int) $approved_count ?>"
										data-pending-count="<?= (int) $pending_count ?>"
										data-total-amount="<?= html_escape(display_money($total_amount, default_currency())) ?>">
										<?= $month_name ?>
									</a>
								<?php endfor; ?>
							</div>
						</div>

						<div class="w-full lg:w-auto lg:min-w-[280px]">
							<form action="<?php echo base_url() ?>admin/payroll/advance_salary" method="post" class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-end">
								<label for="advance-salary-year" class="block w-full space-y-1 text-sm font-medium text-foreground sm:max-w-[180px]">
									<input id="advance-salary-year" name="year" type="text"
										value="<?= html_escape($selected_year) ?>"
										class="years w-full rounded-lg border border-border bg-input px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30 dark:focus:border-secondary dark:focus:ring-3 dark:focus:ring-secondary/30"
										data-format="Y">
								</label>
								<div class="sm:self-end">
									<button type="submit" data-toggle="tooltip" data-placement="top" title="<?= lang('search') ?>"
										class="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 sm:w-auto">
										<i data-lucide="search" class="h-4 w-4"></i>
										<?= lang('search') ?>
									</button>
								</div>
							</form>
						</div>
					</div>

					<div class="rounded-xl border border-border bg-card shadow-sm">
						<div class="border-b border-border px-4 py-3">
							<div class="flex flex-wrap items-center justify-between gap-3">
								<div class="space-y-2">
									<div class="inline-flex items-center gap-2 text-sm font-semibold text-foreground">
										<i data-lucide="calendar" class="h-4 w-4"></i>
										<span id="advanceSalaryMonthTitle"><?= $selected_month_name . ' ' . $year; ?></span>
									</div>
									<?php
									$current_rows = !empty($advance_salary_info[(int) $selected_month]) ? $advance_salary_info[(int) $selected_month] : array();
									$current_total_records = count($current_rows);
									$current_total_amount = 0;
									$current_approved_count = 0;
									$current_pending_count = 0;
									foreach ($current_rows as $advance_salary) {
										$current_total_amount += (float) $advance_salary->advance_amount;
										if ($advance_salary->status == '1' || $advance_salary->status == '3') {
											$current_approved_count++;
										} elseif ($advance_salary->status == '0') {
											$current_pending_count++;
										}
									}
									?>
									<div class="flex flex-wrap gap-2 text-xs">
										<span class="inline-flex items-center rounded-full bg-slate-100 px-3 py-1 font-semibold text-slate-700 dark:bg-slate-800 dark:text-slate-200">
											<?= lang('total') ?>: <span id="advanceSalaryTotalRecords" class="ml-1"><?= (int) $current_total_records ?></span>
										</span>
										<span class="inline-flex items-center rounded-full bg-emerald-100 px-3 py-1 font-semibold text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">
											<?= lang('accepted') ?>: <span id="advanceSalaryApprovedCount" class="ml-1"><?= (int) $current_approved_count ?></span>
										</span>
										<span class="inline-flex items-center rounded-full bg-amber-100 px-3 py-1 font-semibold text-amber-700 dark:bg-amber-950/40 dark:text-amber-300">
											<?= lang('pending') ?>: <span id="advanceSalaryPendingCount" class="ml-1"><?= (int) $current_pending_count ?></span>
										</span>
										<span class="inline-flex items-center rounded-full bg-sky-100 px-3 py-1 font-semibold text-sky-700 dark:bg-sky-950/40 dark:text-sky-300">
											<?= lang('amount') ?>: <span id="advanceSalaryTotalAmount" class="ml-1"><?= display_money($current_total_amount, default_currency()) ?></span>
										</span>
									</div>
								</div>

								<div class="hidden-print">
									<a id="advanceSalaryPdfLink" href="<?= base_url('admin/payroll/advance_salary_pdf/' . $year . '/' . $selected_month) ?>" 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" data-toggle="tooltip" title="<?= lang('pdf') ?>">
										<i data-lucide="file-text" class="h-4 w-4"></i>
									</a>
								</div>
							</div>
						</div>

						<div class="overflow-x-auto p-4">
							<table class="min-w-full text-sm DataTables" id="DataTables" cellspacing="0" width="100%">
								<thead class="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
									<tr>
										<th class="px-4 py-3 text-left"><?= lang('emp_id') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('name') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('amount') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('deduct_month') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('request_date') ?></th>
										<th class="px-4 py-3 text-left"><?= lang('status') ?></th>
										<?php if ($this->session->userdata('user_type') == 1) { ?>
											<th class="px-4 py-3 text-left"><?= lang('action') ?></th>
										<?php } ?>
									</tr>
								</thead>
								<tbody class="divide-y divide-border [&>tr>td]:px-4 [&>tr>td]:py-3"></tbody>
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<script type="text/javascript">
		$(document).ready(function() {
			list = <?= json_encode($report_list_url) ?>;
			fire_datatable(list, 'DataTables');

			$('[data-advance-month]').on('click', function(e) {
				e.preventDefault();
				var $link = $(this);
				var url = $link.attr('href');
				$('[data-advance-month]').removeClass('bg-indigo-600 text-white shadow-sm bg-gray-200 dark:bg-gray-700').addClass('text-muted-foreground');
				$link.removeClass('text-muted-foreground').addClass('bg-indigo-600 text-white shadow-sm');
				$('#advanceSalaryMonthTitle').text($link.data('month-name') + ' <?= html_escape($year) ?>');
				$('#advanceSalaryPdfLink').attr('href', $link.data('pdf-url'));
				$('#advanceSalaryTotalRecords').text($link.data('total-records'));
				$('#advanceSalaryApprovedCount').text($link.data('approved-count'));
				$('#advanceSalaryPendingCount').text($link.data('pending-count'));
				$('#advanceSalaryTotalAmount').text($link.data('total-amount'));
				table_url(url);
			});
		});
	</script>
<?php } ?>
<script>
	document.addEventListener('click', function(e) {
		const trigger = e.target.closest('[data-tab-target]');
		if (!trigger) return;
		e.preventDefault();

		const groupEl = trigger.closest('[data-tab-group]');
		if (!groupEl) return;
		const groupName = groupEl.getAttribute('data-tab-group');
		const target = trigger.getAttribute('data-tab-target');
		const contentRoot = document.querySelector('[data-tab-content="' + groupName + '"]');
		if (!contentRoot) return;

		groupEl.querySelectorAll('[data-tab-target]').forEach(function(el) {
			el.classList.remove('bg-slate-900', 'text-white', 'dark:bg-slate-100', 'dark:text-slate-900');
			el.classList.add('text-foreground', 'hover:bg-muted');
		});
		trigger.classList.remove('text-foreground', 'hover:bg-muted');
		trigger.classList.add('bg-slate-900', 'text-white', 'dark:bg-slate-100', 'dark:text-slate-900');

		contentRoot.querySelectorAll('[data-tab-pane]').forEach(function(pane) {
			pane.classList.add('hidden');
			pane.classList.remove('block');
		});
		const activePane = contentRoot.querySelector('[data-tab-pane="' + target + '"]');
		if (activePane) {
			activePane.classList.remove('hidden');
			activePane.classList.add('block');
		}
	});
</script>

<?php if (!empty($switch)) { ?>
	<div class="space-y-4">
		<div class="rounded-2xl border border-border bg-card shadow-sm">
			<div class="p-5">
				<div class="grid grid-cols-1 gap-6 lg:grid-cols-12">
					<div class="lg:col-span-3">
						<ul class="space-y-1 rounded-xl border border-border bg-muted/40 p-2" data-tab-group="switch-tabs">
							<li><a href="#leave_report" data-toggle="tab" data-tab-target="leave_report"
									class="inline-flex w-full items-center rounded-lg px-3 py-2 text-sm font-medium transition <?= $active == 1 ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900' : 'text-foreground hover:bg-muted' ?>"><?= lang('advance_salary_report') ?></a>
							</li>
							<li class="my_advance_salary"><a href="#my_leave" data-toggle="tab" data-tab-target="my_leave"
									class="inline-flex w-full items-center rounded-lg px-3 py-2 text-sm font-medium transition <?= $active == 2 ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900' : 'text-foreground hover:bg-muted' ?>"><?= lang('advance_salary') ?></a>
							</li>
							<?php if ($this->session->userdata('user_type') == 1) { ?>
								<li class="all_advance_salary"><a href="#all_leave" data-toggle="tab" data-tab-target="all_leave"
										class="inline-flex w-full items-center rounded-lg px-3 py-2 text-sm font-medium transition text-foreground hover:bg-muted"><?= lang('all_advance_salary') ?></a>
								</li>
							<?php } ?>

						</ul>
					</div>
					<div class="lg:col-span-9">
						<div  data-tab-content="switch-tabs">
							<div class="<?= $active == 2 ? 'block' : 'hidden' ?>" id="my_leave" data-tab-pane="my_leave" style="position: relative;">
								<div class="rounded-xl border border-border bg-card shadow-sm">
									<div class="border-b border-border px-4 py-3">
										<div class="text-sm font-semibold text-foreground"><?= lang('advance_salary') ?></div>
									</div>
									<div class="p-5">

										<!-- Table -->
											<table class="min-w-full text-sm" id="DataTables" cellspacing="0" width="100%">
												<thead class="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
													<tr>
														<th class="px-4 py-3 text-left"><?= lang('emp_id') ?></th>
														<th class="px-4 py-3 text-left"><?= lang('name') ?></th>
														<th class="px-4 py-3 text-left"><?= lang('amount') ?></th>
														<th class="px-4 py-3 text-left"><?= lang('request_date') ?></th>
														<th class="px-4 py-3 text-left"><?= lang('deduct_month') ?></th>
														<th class="px-4 py-3 text-left"><?= lang('status') ?></th>
														<?php if ($this->session->userdata('user_type') == 1) { ?>
															<th class="px-4 py-3 text-left"><?= lang('action') ?></th>
														<?php } ?>
													</tr>
												</thead>
												<tbody class="divide-y divide-border [&>tr>td]:px-4 [&>tr>td]:py-3">
													<?php
													$my_total = 0;
													$my_advance_salary = $this->payroll_model->my_advance_salary_info();
													if (!empty($my_advance_salary)) {
														foreach ($my_advance_salary as $my_salary) {
															$my_total += $my_salary->advance_amount;
														}
													} ?>
												</tbody>

											</table>

									</div>
									<div class="border-t border-border px-4 py-3 text-sm font-semibold text-foreground">
										<?= lang('total') . ' ' . lang('advance_salary') ?>:
										<span class="ml-2 rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-700">
											<?php echo display_money($my_total, default_currency()); ?>
										</span>
									</div>
								</div>
							</div>

							<script type="text/javascript">
								$(document).ready(function() {
									list = base_url + "admin/payroll/my_advance_salaryList";
									<?php if (admin_head()) { ?>
										$('.all_advance_salary').on('click', function() {
											table_url(base_url + "admin/payroll/all_advance_salaryList");
										});
									<?php } ?>
									$('.my_advance_salary').on('click', function() {
										table_url(base_url + "admin/payroll/my_advance_salaryList");
									});

								});
							</script>

							<div class="<?= $active == 1 ? 'block' : 'hidden' ?>" id="leave_report" data-tab-pane="leave_report" style="position: relative;">
								<div class="rounded-xl border border-border bg-card shadow-sm">
									<div class="border-b border-border px-4 py-3">
										<div class="flex flex-wrap items-center justify-between gap-2 text-sm font-semibold text-foreground">
											<span><?= lang('advance_salary_report') ?></span>
											<form class="flex items-center gap-2" action="<?php echo base_url() ?>admin/payroll/advance_salary"
												method="post">
												<?= form_datepicker('year', '', !empty($year) ? $year : '', false, array('class' => 'years w-24', 'data-format' => 'Y')) ?>
												<button type="submit" data-toggle="tooltip" data-placement="top"
													title="<?= lang('search') ?>" class="inline-flex h-[38px] items-center gap-2 rounded-lg bg-indigo-600 px-4 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">
													<i data-lucide="search" class="h-4 w-4"></i>
													<?= lang('search') ?>
												</button>
											</form>
										</div>
									</div>
									<div class="p-5">

										<?php if ($this->session->userdata('user_type') == 1) { ?>
											<div id="">
												<div class="border-b border-border pb-2 text-xs font-semibold uppercase text-muted-foreground">
													<?= lang('all') . ' ' . lang('advance_salary_report') ?>
												</div>
												<div id="morris_line_all"></div>
											</div>
										<?php } ?>
										<div class="mt-6">
											<div class="border-b border-border pb-2 text-xs font-semibold uppercase text-muted-foreground">
												<?= lang('my_report') ?>
											</div>
											<div id="morris_line_my"></div>
										</div>

									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<?php if ($this->session->userdata('user_type') == 1) { ?>
		<script type="text/javascript">
			$(function() {
				if (typeof Morris === 'undefined') return;

				var chartdata = [
					<?php foreach ($advance_salary_info as $key => $v_advance_salary) {
						$month_name = date('F', safe_strtotime($year . '-' . $key)); // get full name of month by date query
						$total_amount = 0;
						foreach ($v_advance_salary as $advance_salary) {
							$total_amount += $advance_salary->advance_amount;
						}
					?> {
							y: "<?= $month_name ?>",
							all_report: <?= $total_amount ?>,
						},
					<?php } ?>


				];
				// Line Chart
				// -----------------------------------

				new Morris.Line({
					element: 'morris_line_all',
					data: chartdata,
					xkey: 'y',
					ykeys: ["all_report"],
					labels: ["<?= lang('advance_salary') ?>"],
					lineColors: ["#7266ba"],
					parseTime: false,
					resize: true
				});

			});
		</script>
	<?php } ?>
	<script type="text/javascript">
		$(function() {
			if (typeof Morris === 'undefined') return;

			var my_chartdata = [
				<?php foreach ($advance_salary_info as $mkey => $my_advance_salary) {
					$my_month_name = date('F', safe_strtotime($year . '-' . $mkey)); // get full name of month by date query
					$my_total = 0;
					foreach ($my_advance_salary as $my_advance_salary) {
						if ($my_advance_salary->user_id == $this->session->userdata('user_id')) {
							$my_total += $my_advance_salary->advance_amount;
						}
					}
				?> {
						y: "<?= $my_month_name ?>",
						my_report: <?= $my_total ?>,
					},
				<?php } ?>

			];

			// Line Chart
			// -----------------------------------

			new Morris.Line({
				element: 'morris_line_my',
				data: my_chartdata,
				xkey: 'y',
				ykeys: ["my_report"],
				labels: ["<?= lang('my_advance_salary') ?>"],
				lineColors: ["#23b7e5"],
				parseTime: false,
				resize: true
			});

		});
	</script>
<?php } ?>
