<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

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

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

$type = $this->uri->segment(5);
if (!empty($type) && !is_numeric($type)) {
	$ex = explode('_', $type);
	if ($ex[0] == 'c') {
		$c_id = $ex[1];
		$type = '_' . date('Y');
	}
}
if (empty($type)) {
	$type = '_' . date('Y');
}

$creditFilter = $this->credit_note_model->get_credit_note_filter();
$active_filter = $type;
$h_s = config_item('credit_note_state');

$status_filters = array();
$period_filters = array();
$year_filters = array();
if (!empty($creditFilter)) {
	foreach ($creditFilter as $filter) {
		$value = isset($filter['value']) ? $filter['value'] : '';
		if (strpos($value, '_') === 0 && is_numeric(substr($value, 1))) {
			$year_filters[] = $filter;
		} elseif (in_array($value, array('last_month', 'this_months'), true)) {
			$period_filters[] = $filter;
		} else {
			$status_filters[] = $filter;
		}
	}
}

$status_options = array('' => lang('all') . ' ' . lang('status'));
foreach ($status_filters as $filter) {
	$status_options[$filter['value']] = $filter['name'];
}
$period_options = array('' => lang('all') . ' ' . lang('credit_note') . ' ' . lang('date'));
foreach ($period_filters as $filter) {
	$period_options[$filter['value']] = $filter['name'];
}
$year_options = array('' => lang('all') . ' ' . lang('year'));
foreach ($year_filters as $filter) {
	$year_options[$filter['value']] = $filter['name'];
}

$selected_status = array_key_exists($active_filter, $status_options) ? $active_filter : '';
$selected_period = array_key_exists($active_filter, $period_options) ? $active_filter : '';
$selected_year = array_key_exists($active_filter, $year_options) ? $active_filter : '';
?>

<div class="erp-page space-y-4">
	<div id="credit_note_state_report_div"></div>

	<section class="rounded-xl border border-border bg-card shadow-sm">
		<div class="table-responsive p-2">
			<table class="table table-striped DataTables bulk_table w-full text-sm" id="DataTables" cellspacing="0" width="100%">
				<thead>
					<tr>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('credit_note') ?> #</th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('credit_note') . ' ' . lang('date') ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('client_name') ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('amount') ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('status') ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('tags') ?></th>
						<?php $show_custom_fields = custom_form_table(22, null);
						if (!empty($show_custom_fields)) {
							foreach ($show_custom_fields as $c_label => $v_fields) {
								if (!empty($c_label)) { ?>
									<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= $c_label ?></th>
							<?php }
							}
						}
						?>
						<?php if (!empty($edited) || !empty($deleted)) { ?>
							<th class="col-options no-sort hidden-print text-right text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('action') ?></th>
						<?php } ?>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
		</div>
	</section>
</div>

<script>
	list = base_url + "admin/credit_note/credit_noteList";
	const QUICK_STATE_SHOW_TEXT = <?= json_encode(trim(lang('show') . ' ' . lang('quick_state'))) ?>;
	const QUICK_STATE_HIDE_TEXT = <?= json_encode(trim(lang('hide') . ' ' . lang('quick_state'))) ?>;

	function reloadCreditNotes(filter, searchType) {
		var url = list;
		if (filter) {
			url += "/" + filter;
			if (searchType) {
				url += "/" + searchType;
			}
		}
		if (typeof table_url !== "undefined") {
			table_url(url);
		} else if (typeof fire_datatable === "function") {
			fire_datatable(url);
		}
	}

	function refreshSelect(select) {
		if (select && typeof select.refreshSelectpicker === "function") {
			select.refreshSelectpicker();
		}
	}

	function clearSelect(select) {
		if (!select) return;
		select.value = "";
		refreshSelect(select);
	}

	function syncCreditQuickStateButton(hidden) {
		const toggleButton = document.getElementById('quick_state');
		if (!toggleButton) {
			return;
		}

		toggleButton.setAttribute('aria-expanded', hidden ? 'false' : 'true');
		toggleButton.setAttribute('title', hidden ? QUICK_STATE_SHOW_TEXT : QUICK_STATE_HIDE_TEXT);
		toggleButton.setAttribute('data-tooltip', hidden ? QUICK_STATE_SHOW_TEXT : QUICK_STATE_HIDE_TEXT);
		toggleButton.setAttribute('aria-label', hidden ? QUICK_STATE_SHOW_TEXT : QUICK_STATE_HIDE_TEXT);

		const icon = toggleButton.querySelector('i[data-lucide]');
		if (icon) {
			icon.setAttribute('data-lucide', hidden ? 'panel-top-open' : 'panel-top-close');
		}

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

	function setCreditQuickState(hidden) {
		const report = document.getElementById('state_report');
		if (!report) {
			syncCreditQuickStateButton(hidden);
			return;
		}

		report.classList.toggle('hidden', hidden);
		report.hidden = hidden;
		report.style.display = hidden ? 'none' : '';
		syncCreditQuickStateButton(hidden);
	}



	$(function() {
		var statusSelect = document.getElementById('credit_status_filter');
		var periodSelect = document.getElementById('credit_period_filter');
		var yearSelect = document.getElementById('credit_year_filter');

		if (statusSelect) {
			statusSelect.addEventListener('change', function() {
				clearSelect(periodSelect);
				clearSelect(yearSelect);
				reloadCreditNotes(statusSelect.value);
			});
		}
		if (periodSelect) {
			periodSelect.addEventListener('change', function() {
				clearSelect(statusSelect);
				clearSelect(yearSelect);
				reloadCreditNotes(periodSelect.value);
			});
		}
		if (yearSelect) {
			yearSelect.addEventListener('change', function() {
				clearSelect(statusSelect);
				clearSelect(periodSelect);
				reloadCreditNotes(yearSelect.value);
			});
		}

		window.creditProjectFilter = function(id) {
			reloadCreditNotes(id, 'by_project');
		};
		window.creditClientFilter = function(id) {
			reloadCreditNotes(id, 'by_client');
		};
		window.creditAgentFilter = function(id) {
			reloadCreditNotes(id, 'by_agent');
		};
		$(document).on('click', '[data-credit-filter-action]', function(e) {
			e.preventDefault();
			var $item = $(this);
			var $dropdown = $item.closest('details');
			$dropdown.find('[data-header-filter-item]').removeClass('bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300');
			$dropdown.find('[data-header-filter-item]').addClass('text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800');
			$item.addClass('bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300');
			$item.removeClass('text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800');
			$dropdown.find('[data-header-filter-selected]').text($item.data('credit-filter-label') || '<?= html_escape(lang('all')); ?>');
			$dropdown.prop('open', false);
			reloadCreditNotes($item.data('credit-filter') || '', $item.data('credit-search') || '');
		});

		$(document).on('click', '#quick_state', function(e) {
			e.preventDefault();
			const report = document.getElementById('state_report');
			if (!report) {
				return;
			}
			const hidden = !report.classList.contains('hidden') && !report.hidden;
			setCreditQuickState(hidden);
		});

		if (window.ins_data) {
			const stateRequest = window.ins_data(base_url + 'admin/credit_note/credit_note_state_report');
			const applyCreditQuickState = function() {
				const toggleButton = document.getElementById('quick_state');
				const defaultHidden = toggleButton && toggleButton.getAttribute('data-default-hidden') === '1';
				setCreditQuickState(defaultHidden);
			};
			if (stateRequest && typeof stateRequest.then === 'function') {
				stateRequest.then(applyCreditQuickState);
			} else {
				applyCreditQuickState();
			}
		}

	});
</script>
