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

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

$invoiceFilter = $this->invoice_model->get_invoice_filter();
$active_filter = 'recurring';

$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'];
}

$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">
	<section class="rounded-xl border border-border bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
		<div class="hidden px-4 pt-4" id="recurringFiltersShell">
			<div class="grid gap-4 rounded-lg border border-border bg-slate-50 p-4 dark:border-slate-700 dark:bg-slate-800/60 xl:grid-cols-[1.5fr_auto]">
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
					<?= form_select_group('recurring_status_filter', lang('status'), $status_options, $selected_status, false, array('id' => 'recurring_status_filter')); ?>
					<?= form_select_group('recurring_period_filter', lang('invoice_date'), $period_options, $selected_period, false, array('id' => 'recurring_period_filter')); ?>
					<?= form_select_group('recurring_year_filter', lang('year'), $year_options, $selected_year, false, array('id' => 'recurring_year_filter', 'data-search' => 'true')); ?>
				</div>
				<div class="flex flex-wrap items-end justify-end gap-2">
					<div class="min-w-0 w-full sm:min-w-[10rem] sm:w-auto">
						<?= form_dropdown_lookup_group('project', lang('by') . ' ' . lang('project'), 'recurringProjectFilter', array('icon' => 'briefcase')); ?>
					</div>
					<div class="min-w-0 w-full sm:min-w-[10rem] sm:w-auto">
						<?= form_dropdown_lookup_group('client', lang('by') . ' ' . lang('client'), 'recurringClientFilter', array('icon' => 'user')); ?>
					</div>
					<div class="min-w-0 w-full sm:min-w-[10rem] sm:w-auto">
						<?= form_dropdown_lookup_group('staff', lang('by') . ' ' . lang('sales') . ' ' . lang('agent'), 'recurringAgentFilter', array('icon' => 'user-check', 'type' => 'staff')); ?>
					</div>
					<button type="button" id="clear_recurring_filters" 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">
						<i data-lucide="rotate-ccw" class="h-4 w-4"></i>
						<span><?= lang('clear') ?></span>
					</button>
				</div>
			</div>
		</div>

		<div class="px-4 py-4">
			<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="recurringTableLengthSlot" class="erp-invoice-control-slot"></div>
					<div id="recurringTableActionSlot" class="erp-invoice-control-slot"></div>
				</div>
				<div class="flex w-full max-w-full items-center justify-end xl:max-w-xs">
					<div id="recurringTableSearchSlot" class="erp-invoice-control-slot erp-invoice-control-slot--search"></div>
				</div>
			</div>
		</div>

		<div class="table-responsive px-4 pb-4">
			<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('invoice') ?></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('client_name') ?></th>
						<th class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-300"><?= lang('due_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(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 }
							}
						}
						?>
						<?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 RECURRING_INVOICE_LIST_BASE_URL = base_url + "admin/invoice/recurringinvoiceList";
	list = RECURRING_INVOICE_LIST_BASE_URL;

	function recurringListUrl(filter, searchType) {
		filter = filter || "";
		searchType = searchType || "";
		if (searchType && !filter) {
			searchType = "";
		}
		var url = RECURRING_INVOICE_LIST_BASE_URL;
		if (filter) {
			url += "/" + encodeURIComponent(filter);
			if (searchType) {
				url += "/" + encodeURIComponent(searchType);
			}
		}
		return url;
	}

	function applyRecurringFilter(filter, searchType) {
		var url = recurringListUrl(filter, searchType);
		list = url;
		if (typeof table_url === "function") {
			table_url(url);
		} else if (typeof fire_datatable === "function") {
			fire_datatable(url, 'DataTables');
		}
	}

	$(function () {
		var statusSelect = document.getElementById('recurring_status_filter');
		var periodSelect = document.getElementById('recurring_period_filter');
		var yearSelect = document.getElementById('recurring_year_filter');
		var clearBtn = document.getElementById('clear_recurring_filters');
		var filterToggle = document.getElementById('recurringHeaderFilterToggle') || document.getElementById('recurringFilterToggle');
		var filterShell = document.getElementById('recurringFiltersShell');

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

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

		function setFilterPanelOpen(open) {
			if (!filterShell || !filterToggle) return;
			filterShell.classList.toggle('hidden', !open);
			filterShell.hidden = !open;
			filterToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
		}

		if (filterToggle) {
			filterToggle.addEventListener('click', function () {
				setFilterPanelOpen(filterShell.classList.contains('hidden'));
			});
		}

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

		window.recurringProjectFilter = function (id) {
			applyRecurringFilter(id, 'by_project');
		};
		window.recurringClientFilter = function (id) {
			applyRecurringFilter(id, 'by_client');
		};
		window.recurringAgentFilter = function (id) {
			applyRecurringFilter(id, 'by_agent');
		};

		setFilterPanelOpen(false);
	});
</script>
