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

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

<?php
$created = can_action('14', 'created');
$edited = can_action('14', 'edited');
$deleted = can_action('14', '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');
}
?>

<div class="erp-page space-y-4">
	<div id="estimates_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('estimate') ?> #</th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('estimate') . ' ' . lang('date') ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('expire') . ' ' . 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(10, 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>
	const ESTIMATES_LIST_BASE_URL = base_url + "admin/estimates/estimatesList";
	list = ESTIMATES_LIST_BASE_URL;
	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'))) ?>;
	let pendingEstimateQuickState = null;

	function reloadEstimates(filter, searchType) {
		filter = filter || '';
		searchType = searchType || '';
		if (searchType && !filter) {
			searchType = '';
		}
		var url = ESTIMATES_LIST_BASE_URL;
		if (filter) {
			url += "/" + encodeURIComponent(filter);
			if (searchType) {
				url += "/" + encodeURIComponent(searchType);
			}
		}
		list = url;
		if (typeof table_url === "function") {
			table_url(url);
		} else if (typeof fire_datatable === "function") {
			fire_datatable(url, 'DataTables');
		}
	}

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

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

	function syncEstimateQuickStateButton(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 setEstimateQuickState(hidden) {
		const report = document.getElementById('state_report');
		pendingEstimateQuickState = !!hidden;
		if (!report) {
			syncEstimateQuickStateButton(hidden);
			return;
		}

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

	$(function() {
		var statusSelect = document.getElementById('estimate_status_filter');
		var periodSelect = document.getElementById('estimate_period_filter');
		var yearSelect = document.getElementById('estimate_year_filter');

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

		window.estimateProjectFilter = function(id) {
			reloadEstimates(id, 'by_project');
		};
		window.estimateClientFilter = function(id) {
			reloadEstimates(id, 'by_client');
		};
		window.estimateAgentFilter = function(id) {
			reloadEstimates(id, 'by_agent');
		};
		$(document).on('click', '[data-estimate-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('estimate-filter-label') || '<?= html_escape(lang('all')); ?>');
			$dropdown.prop('open', false);
			reloadEstimates($item.data('estimate-filter') || '', $item.data('estimate-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;
			setEstimateQuickState(hidden);
		});

		if (window.ins_data) {
			const stateRequest = window.ins_data(base_url + 'admin/estimates/estimates_state_report');
			const applyEstimateQuickState = function() {
				const toggleButton = document.getElementById('quick_state');
				const defaultHidden = toggleButton && toggleButton.getAttribute('data-default-hidden') === '1';
				setEstimateQuickState(pendingEstimateQuickState !== null ? pendingEstimateQuickState : defaultHidden);
			};
			if (stateRequest && typeof stateRequest.then === 'function') {
				stateRequest.then(applyEstimateQuickState);
			} else {
				applyEstimateQuickState();
			}
		}
	});
</script>
