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

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

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

$type = $this->uri->segment(5);
if (empty($type)) {
	$type = '_' . date('Y');
}

$proposalFilter = $this->proposal_model->get_invoice_filter();
$active_filter = $type;
$h_s = config_item('proposal_state');

$status_filters = array();
$period_filters = array();
$year_filters = array();
if (!empty($proposalFilter)) {
	foreach ($proposalFilter 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('proposal') . ' ' . 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="proposals_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 class="bg-slate-50 text-slate-500 dark:bg-slate-800/60 dark:text-slate-300">
						<tr>
							<th><?= lang('proposal') ?> #</th>
							<th><?= lang('proposal_date') ?></th>
							<th><?= lang('expire_date') ?></th>
							<th><?= strtoupper(lang('to')) ?></th>
							<th><?= lang('amount') ?></th>
							<th><?= lang('status') ?></th>
							<th><?= lang('tags') ?></th>
							<?php $show_custom_fields = custom_form_table(11, null);
							if (!empty($show_custom_fields)) {
								foreach ($show_custom_fields as $c_label => $v_fields) {
									if (!empty($c_label)) { ?>
										<th><?= $c_label ?></th>
							<?php }
								}
							}
							?>
							<?php if (!empty($edited) || !empty($deleted)) { ?>
								<th class="col-options no-sort hidden-print text-right"><?= lang('action') ?></th>
							<?php } ?>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<script>
	const PROPOSALS_LIST_BASE_URL = base_url + "admin/proposals/proposalsList";
	list = PROPOSALS_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 pendingProposalQuickState = null;

	function reloadProposals(filter, searchType) {
		filter = filter || '';
		searchType = searchType || '';
		if (searchType && !filter) {
			searchType = '';
		}
		var url = PROPOSALS_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 syncProposalQuickStateButton(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 setProposalQuickState(hidden) {
		const report = document.getElementById('state_report');
		pendingProposalQuickState = !!hidden;
		if (!report) {
			syncProposalQuickStateButton(hidden);
			return;
		}

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

	$(function() {
		var statusSelect = document.getElementById('proposal_status_filter');
		var periodSelect = document.getElementById('proposal_period_filter');
		var yearSelect = document.getElementById('proposal_year_filter');

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

		window.proposalInvoiceFilter = function(id) {
			reloadProposals(id, 'by_invoice');
		};
		window.proposalEstimateFilter = function(id) {
			reloadProposals(id, 'by_estimates');
		};
		window.proposalAgentFilter = function(id) {
			reloadProposals(id, 'by_agent');
		};

		$(document).on('click', '[data-proposal-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('proposal-filter-label') || '<?= html_escape(lang('all')); ?>');
			$dropdown.prop('open', false);
			reloadProposals($item.data('proposal-filter') || '', $item.data('proposal-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;
			setProposalQuickState(hidden);
		});

		$(document).off('click.proposalQuickStats', '.filter_by_type')
			.on('click.proposalQuickStats', '.filter_by_type', function(e) {
				e.preventDefault();
				var filter_by = $(this).attr('id') || '';
				if (statusSelect) {
					statusSelect.value = filter_by;
					refreshSelect(statusSelect);
				}
				reloadProposals(filter_by);
			});

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