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

<?php
$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');
}

$created = can_action('13', 'created');
$edited = can_action('13', 'edited');
$deleted = can_action('13', 'deleted');
$invoiceFilter = $this->invoice_model->get_invoice_filter();
$active_filter = $type;
$h_s = config_item('invoice_state');

$status_filters = array();
$period_filters = array();
$year_filters = array();
if (!empty($invoiceFilter)) {
	foreach ($invoiceFilter 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('invoice_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'];
}
$header_year_options = array();
foreach ($year_filters as $filter) {
	$header_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 : '';
$current_cycle_label = $selected_status ? $status_options[$selected_status] : ($selected_period ? $period_options[$selected_period] : ($selected_year ? $year_options[$selected_year] : date('Y')));
$header_selected_year = $selected_year;
if (empty($header_selected_year)) {
	$default_header_year = '_' . date('Y');
	if (array_key_exists($default_header_year, $header_year_options)) {
		$header_selected_year = $default_header_year;
	} elseif (!empty($header_year_options)) {
		$header_selected_year = array_key_first($header_year_options);
	}
}

$recurring_url = base_url('admin/invoice/recurring_invoice');
$create_invoice_url = base_url('admin/invoice/createinvoice');
$batch_payments_btn = btn_modal(
	'admin/invoice/make_payment?reset=1',
	lang('batch') . ' ' . lang('payments'),
	'Add Payments',
	'xl',
	'credit-card',
	array('class' => 'inline-flex items-center gap-2 rounded-lg border border-border bg-white px-3 py-2 text-xs font-semibold text-slate-700 shadow-sm hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800')
);
$zip_invoice_btn = btn_modal(
	'admin/invoice/zipped/invoice',
	lang('zip_invoice'),
	lang('zip_invoice'),
	'md',
	'archive',
	array('class' => 'inline-flex items-center gap-2 rounded-lg border border-border bg-white px-3 py-2 text-xs font-semibold text-slate-700 shadow-sm hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800')
);
?>

<div class="erp-page space-y-4">
	<div id="invoice_state_report_div" class="rounded-xl border border-border bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900"></div>

		<section class="rounded-xl border border-border bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
			<div class="px-4 py-4">
				<div class="mb-4 flex flex-wrap items-center justify-between gap-3 border-b border-border pb-4 dark:border-slate-700">
					<div>
						<p class="text-sm font-semibold text-foreground"><?= lang('invoice'); ?> Workspace</p>
						<p class="text-xs text-muted-foreground">Handle recurring billing, batch payments, exports, and new invoices from one place.</p>
					</div>
					<div class="flex flex-wrap items-center justify-end gap-2">
						<a href="<?= $recurring_url; ?>" class="inline-flex items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-4 py-2.5 text-sm font-semibold text-amber-700 shadow-sm transition-colors hover:bg-amber-100 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-200 dark:hover:bg-amber-950/60">
							<i data-lucide="repeat" class="h-4 w-4"></i>
							<span><?= lang('recurring_invoice'); ?></span>
						</a>
						<?= $batch_payments_btn; ?>
						<?= $zip_invoice_btn; ?>
						<?php if (!empty($created) || !empty($edited)) { ?>
							<a href="<?= $create_invoice_url; ?>" class="inline-flex items-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-primary/90">
								<i data-lucide="plus" class="h-4 w-4"></i>
								<span><?= lang('create_invoice'); ?></span>
							</a>
						<?php } ?>
					</div>
				</div>
				<div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
					<div class="flex flex-wrap items-center gap-2">
						<div id="invoiceTableLengthSlot" class="erp-invoice-control-slot"></div>
						<div id="invoiceTableActionSlot" class="erp-invoice-control-slot"></div>
						<?php if (!empty($deleted)) { ?>
							<button type="button" class="hidden inline-flex items-center gap-2 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-semibold text-rose-600" id="invoiceBulkDelete"><i data-lucide="trash-2" class="h-4 w-4"></i><span><?= lang('bulk_delete'); ?></span></button>
						<?php } ?>
						<span id="invoiceBulkMeta" class="hidden text-xs font-medium text-muted-foreground"></span>
					</div>
					<div class="flex w-full max-w-full items-center justify-end xl:max-w-xs">
						<div id="invoiceTableSearchSlot" class="erp-invoice-control-slot erp-invoice-control-slot--search"></div>
					</div>
				</div>
			</div>
		</div>

		<div class="mt-3">
			<table class="table table-striped DataTables bulk_table w-full text-sm" id="DataTables" cellspacing="0" width="100%">
				<thead>
					<tr>
						<?php if (!empty($deleted)) { ?>
							<th class="w-10 text-center text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300" data-orderable="false">
								<label class="inline-flex h-4 w-4 items-center justify-center">
									<input id="select_all" type="checkbox" class="h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
								</label>
							</th>
						<?php } ?>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('invoice'); ?></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('project'); ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('invoice_date'); ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('due_date'); ?></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('sales') . ' ' . lang('agent'); ?></th>
						<?php $show_custom_fields = custom_form_table(9, 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 }
							}
						} ?>
						<th class="col-options no-sort text-right text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('action'); ?></th>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
		</div>
	</section>
</div>

<script>
	list = base_url + "admin/invoice/invoiceList<?= !empty($active_filter) ? '/' . rawurlencode($active_filter) : '' ?>";
	window.erpDatatablePreload = window.erpDatatablePreload || {};
	window.erpDatatablePreload.DataTables = window.erpDatatablePreload.DataTables || {};
	<?php if (!empty($datatable_preload)) { ?>
	window.erpDatatablePreload.DataTables["list"] = <?= json_encode($datatable_preload, JSON_UNESCAPED_SLASHES) ?>;
	<?php } ?>
	bulk_url = base_url + "admin/invoice/bulk_delete";

	(function($) {
		let currentInvoiceFilter = <?= json_encode($active_filter); ?> || "";
		let currentInvoiceSearchType = "";
		const QUICK_STATE_KEY = 'invoice_quick_stats_hidden';
		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'))) ?>;
		const QUICK_STATE_SHOW_ALWAYS_TEXT = <?= json_encode(trim(lang('show') . ' ' . lang('quick_state') . ' ' . lang('always'))) ?>;
		const QUICK_STATE_HIDE_ALWAYS_TEXT = <?= json_encode(trim(lang('hide') . ' ' . lang('quick_state') . ' ' . lang('always'))) ?>;
		const QUICK_STATE_DEFAULT_HIDDEN = <?= $h_s == 'none' ? 'true' : 'false' ?>;
		const DEFAULT_INVOICE_YEAR_FILTER = <?= json_encode($header_selected_year ?: ('_' . date('Y'))) ?>;

		function getInvoiceTable() {
			if (!$.fn.dataTable || !$.fn.dataTable.isDataTable('#DataTables')) {
				return null;
			}
			return $('#DataTables').DataTable();
		}

		function buildInvoiceUrl(filterBy, searchType) {
			let url = base_url + "admin/invoice/invoiceList";
			if (!filterBy) {
				return url;
			}
			url += "/" + encodeURIComponent(filterBy);
			if (searchType) {
				url += "/" + encodeURIComponent(searchType);
			}
			return url;
		}

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

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

		function syncSelects(filterBy, searchType) {
			const statusSelect = document.getElementById('invoice_status_filter');
			const periodSelect = document.getElementById('invoice_period_filter');
			const yearSelect = document.getElementById('invoice_year_filter');
			const quickYearSelect = document.getElementById('invoiceQuickYearFilter');

			if (searchType) {
				clearSelect(statusSelect);
				clearSelect(periodSelect);
				clearSelect(yearSelect);
				if (quickYearSelect) {
					quickYearSelect.value = DEFAULT_INVOICE_YEAR_FILTER;
				}
				return;
			}

			clearSelect(statusSelect);
			clearSelect(periodSelect);
			clearSelect(yearSelect);

			if (statusSelect && statusSelect.querySelector('option[value="' + filterBy + '"]')) {
				statusSelect.value = filterBy;
				refreshSelect(statusSelect);
				if (quickYearSelect) {
					quickYearSelect.value = DEFAULT_INVOICE_YEAR_FILTER;
				}
				return;
			}
			if (periodSelect && periodSelect.querySelector('option[value="' + filterBy + '"]')) {
				periodSelect.value = filterBy;
				refreshSelect(periodSelect);
				if (quickYearSelect) {
					quickYearSelect.value = DEFAULT_INVOICE_YEAR_FILTER;
				}
				return;
			}
			if (yearSelect && yearSelect.querySelector('option[value="' + filterBy + '"]')) {
				yearSelect.value = filterBy;
				refreshSelect(yearSelect);
				if (quickYearSelect) {
					quickYearSelect.value = filterBy;
				}
				return;
			}
			if (quickYearSelect) {
				quickYearSelect.value = DEFAULT_INVOICE_YEAR_FILTER;
			}
		}

		function setInvoiceSummary(text) {
			const summary = document.getElementById('invoiceFilterSummary');
			if (summary) {
				summary.textContent = text || 'Current year';
			}
		}

		function getSelectedInvoiceIds() {
			return $('#DataTables tbody .js-invoice-row-check:checked').map(function() {
				return $(this).val();
			}).get();
		}

		function updateInvoiceSelectionState() {
			const ids = getSelectedInvoiceIds();
			const bulkBtn = document.getElementById('invoiceBulkDelete');
			const meta = document.getElementById('invoiceBulkMeta');
			const rowChecks = $('#DataTables tbody .js-invoice-row-check');
			const allChecked = rowChecks.length > 0 && rowChecks.length === ids.length;

			$('#select_all').prop('checked', allChecked);

			if (bulkBtn) {
				bulkBtn.classList.toggle('hidden', ids.length === 0);
			}
			if (meta) {
				meta.textContent = ids.length ? ids.length + ' selected' : '';
				meta.classList.toggle('hidden', ids.length === 0);
			}
		}

		function getStoredQuickState() {
			try {
				const stored = localStorage.getItem(QUICK_STATE_KEY);
				if (stored === null) {
					return QUICK_STATE_DEFAULT_HIDDEN;
				}
				return stored === '1';
			} catch (err) {
				return QUICK_STATE_DEFAULT_HIDDEN;
			}
		}

		function syncQuickStateButtons(hidden) {
			const toggleButton = document.getElementById('quick_state');
			if (toggleButton) {
				toggleButton.setAttribute('aria-expanded', hidden ? 'false' : 'true');
				toggleButton.setAttribute('title', hidden ? QUICK_STATE_SHOW_TEXT : QUICK_STATE_HIDE_TEXT);
				toggleButton.setAttribute('aria-label', hidden ? QUICK_STATE_SHOW_TEXT : QUICK_STATE_HIDE_TEXT);
				const label = toggleButton.querySelector('[data-quick-state-label]');
				if (label) {
					label.textContent = 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 setQuickState(hidden, persist) {
			const report = document.getElementById('state_report');
			if (!report) {
				syncQuickStateButtons(hidden);
				return false;
			}

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

			if (persist) {
				try {
					localStorage.setItem(QUICK_STATE_KEY, hidden ? '1' : '0');
				} catch (err) {}
			}

			return true;
		}

		function applySavedQuickState() {
			return setQuickState(getStoredQuickState(), false);
		}

		async function loadInvoiceSummary() {
			if (typeof window.ins_data !== 'function') return;
			await window.ins_data(base_url + 'admin/invoice/invoice_state_report');
			applySavedQuickState();
			await window.ins_data(base_url + 'admin/invoice/invo_data');
		}

		window.applyInvoiceFilter = function(filterBy, searchType, label) {
			currentInvoiceFilter = filterBy || "";
			currentInvoiceSearchType = searchType || "";
			syncSelects(currentInvoiceFilter, currentInvoiceSearchType);
			setInvoiceSummary(label || (currentInvoiceFilter ? currentInvoiceFilter.replace(/_/g, ' ') : 'Current year'));

			const url = buildInvoiceUrl(currentInvoiceFilter, currentInvoiceSearchType);
			list = url;
			if (typeof fire_datatable === 'function') {
				fire_datatable(url, 'DataTables');
			} else if (typeof table_url === 'function') {
				table_url(url);
			} else {
				const table = getInvoiceTable();
				if (table) {
					table.ajax.reload();
				}
			}
		};

		window.invoiceProjectFilter = function(id) {
			window.applyInvoiceFilter(id, 'by_project', 'Filtered by project');
		};
		window.invoiceClientFilter = function(id) {
			window.applyInvoiceFilter(id, 'by_client', 'Filtered by client');
		};
		window.invoiceAgentFilter = function(id) {
			window.applyInvoiceFilter(id, 'by_agent', 'Filtered by sales agent');
		};

		$(document).on('click', '[data-invoice-filter-action]', function(e) {
			e.preventDefault();
			const $item = $(this);
			const $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('invoice-filter-label') || 'Current year');
			$dropdown.prop('open', false);
			const filterBy = $item.data('invoice-filter') || '';
			const searchType = $item.data('invoice-search') || '';
			const label = $item.data('invoice-filter-label') || 'Current year';
			window.applyInvoiceFilter(filterBy, searchType, label);
		});

		$(document).on('change', '#invoice_status_filter, #invoice_period_filter, #invoice_year_filter', function() {
			const value = this.value || '';
			const label = value ? ($(this).find('option:selected').text() || 'Filtered invoices') : 'Current year';
			window.applyInvoiceFilter(value, '', label);
		});

		$(document).on('change', '#select_all', function() {
			$('#DataTables tbody .js-invoice-row-check').prop('checked', this.checked);
			updateInvoiceSelectionState();
		});

		$(document).on('change', '#DataTables tbody .js-invoice-row-check', function() {
			updateInvoiceSelectionState();
		});

		$(document).on('click', '#invoiceBulkDelete', function() {
			const ids = getSelectedInvoiceIds();
			if (!ids.length) return;
			if (!window.confirm(<?= json_encode(lang('delete_alert')) ?>)) return;

			$.ajax({
				url: bulk_url,
				type: 'POST',
				dataType: 'json',
				data: {
					ids: ids,
					csrf_token: typeof getCookie === 'function' ? getCookie('csrf_cookie') : ''
				}
			}).always(function() {
				const table = getInvoiceTable();
				if (table) {
					table.ajax.reload(null, false);
				}
				$('#select_all').prop('checked', false);
				updateInvoiceSelectionState();
				loadInvoiceSummary();
			});
		});

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

		$(document).on('click', '[data-invoice-quick-state-always]', function() {
			try {
				localStorage.removeItem(QUICK_STATE_KEY);
			} catch (err) {}
		});

		$('#DataTables').on('draw.dt', function() {
			updateInvoiceSelectionState();
		});

		$(async function() {
			['invoice_status_filter', 'invoice_period_filter', 'invoice_year_filter', 'invoiceQuickYearFilter'].forEach(function(id) {
				const select = document.getElementById(id);
				if (!select || select.dataset.invoiceFilterBound === '1') return;
				select.dataset.invoiceFilterBound = '1';
				select.addEventListener('change', function() {
					const value = this.value || '';
					const label = value ? (this.options[this.selectedIndex] ? this.options[this.selectedIndex].text : 'Filtered invoices') : 'Current year';
					window.applyInvoiceFilter(value, '', label);
				});
			});
			setInvoiceSummary(<?= json_encode($selected_status ? $status_options[$selected_status] : ($selected_period ? $period_options[$selected_period] : ($selected_year ? $year_options[$selected_year] : 'Current year'))) ?>);
			await loadInvoiceSummary();
		});
	})(jQuery);
</script>
