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

$created = can_action('130', 'created');
$edited = can_action('130', 'edited');
$deleted = can_action('130', 'deleted');

$all_form = $this->db->order_by('form_id', 'DESC')->get('tbl_form')->result();
$forms_count = !empty($all_form) ? count($all_form) : 0;
$total_fields = (int) $this->db->count_all('tbl_custom_field');
$active_fields = (int) $this->db->where('status', 'active')->count_all_results('tbl_custom_field');
?>

<div class="space-y-6">
	<div class="rounded-2xl border border-border bg-card p-6 shadow-sm">
		<div class="flex flex-col gap-5 xl:flex-row xl:items-start xl:justify-between">
			<div class="space-y-2">
				<p class="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground"><?= lang('settings'); ?></p>
				<h1 class="text-2xl font-semibold text-foreground"><?= lang('custom_field'); ?></h1>
				<p class="max-w-2xl text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('custom_field'); ?>. <?= lang('build_custom_fields_for_your_modules'); ?></p>
			</div>
			<div class="grid grid-cols-1 gap-3 sm:grid-cols-3 xl:min-w-[420px]">
				<div class="rounded-xl border border-border bg-background px-4 py-3">
					<div class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('total'); ?></div>
					<div class="mt-2 text-2xl font-semibold text-foreground"><?= $total_fields; ?></div>
					<div class="text-xs text-muted-foreground"><?= lang('custom_field'); ?></div>
				</div>
				<div class="rounded-xl border border-border bg-background px-4 py-3">
					<div class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('active'); ?></div>
					<div class="mt-2 text-2xl font-semibold text-foreground"><?= $active_fields; ?></div>
					<div class="text-xs text-muted-foreground"><?= lang('published'); ?></div>
				</div>
				<div class="rounded-xl border border-border bg-background px-4 py-3">
					<div class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('modules'); ?></div>
					<div class="mt-2 text-2xl font-semibold text-foreground"><?= $forms_count; ?></div>
					<div class="text-xs text-muted-foreground"><?= lang('available_forms'); ?></div>
				</div>
			</div>
		</div>
	</div>

	<div class="rounded-2xl border border-border bg-card shadow-sm">
		<div class="flex flex-col gap-4 border-b border-border px-6 py-5 lg:flex-row lg:items-center lg:justify-between">
			<div>
				<h2 class="text-lg font-semibold text-foreground"><?= lang('custom_field') . ' ' . lang('list'); ?></h2>
				<p class="text-sm text-muted-foreground"><?= lang('filter_and_manage_custom_fields_by_module'); ?></p>
			</div>
			<div class="flex flex-col gap-3 sm:flex-row sm:items-start">
				<?= form_lookup_group('custom_field_filter_form_id', lang('custom_field_for'), '', '', false, array('id' => 'custom_field_filter_form_id'), '', array('type' => 'form', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('modules'), 'onchange' => 'customFieldFormFilter')); ?>
				<button type="button" id="custom_field_filter_reset" class="inline-flex items-center justify-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-semibold text-foreground hover:bg-muted sm:mt-6">
					<i data-lucide="rotate-ccw" class="h-4 w-4"></i>
					<?= lang('reset'); ?>
				</button>
				<?php if (!empty($created) || !empty($edited)) { ?>
					<?= btn_modal(
						'admin/settings/custom_field',
						lang('new_field'),
						lang('new_field'),
						'xl',
						'plus',
						array('class' => 'inline-flex shrink-0 items-center justify-center gap-2 rounded-lg bg-slate-900 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white sm:mt-6')
					); ?>
				<?php } ?>
			</div>
		</div>

		<div class="p-6">
			<div class="overflow-x-auto" id="custom_field_table_container">
				<table class="table table-striped DataTables w-full text-sm" id="DataTables" cellspacing="0" width="100%">
					<thead>
						<tr>
							<th><?= lang('label') ?></th>
							<th><?= lang('custom_field_for') ?></th>
							<th><?= lang('type') ?></th>
							<th><?= lang('active') ?></th>
							<?php if (!empty($edited) || !empty($deleted)) { ?>
								<th class="col-options no-sort text-right"><?= lang('action') ?></th>
							<?php } ?>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
	var option = 0;

	$(document).ready(function () {
		var customFieldListBase = base_url + "admin/settings/custom_fieldList";
		var customFieldFilter = '';
		var customFieldTableLoaded = false;
		var customFieldTableHtml = $('#DataTables').prop('outerHTML');

		function reloadCustomFieldTable() {
			var url = customFieldListBase + (customFieldFilter ? "/" + customFieldFilter : "");
			var $container = $('#custom_field_table_container');
			if (!$('#DataTables').length && customFieldTableHtml) {
				$container.html(customFieldTableHtml);
			}
			var $table = $('#DataTables');
			if (!$table.length) {
				return;
			}
			if ($.fn.dataTable && $.fn.dataTable.isDataTable($table)) {
				$table.DataTable().destroy();
				$table.find('tbody').empty();
			}
			$table.attr('data-erp-datatable-source-url', url);
			if (typeof fire_datatable === 'function') {
				fire_datatable(url, 'DataTables');
			}
		}

		function setCustomFieldFilter(id) {
			id = id || '';
			if (customFieldTableLoaded && customFieldFilter === id) {
				return;
			}
			customFieldFilter = id;
			customFieldTableLoaded = true;
			reloadCustomFieldTable();
		}

		function showCustomFieldStatusMessage(type, message) {
			if (!message) {
				return;
			}
			if (window.toaster && typeof window.toaster[type] === 'function') {
				window.toaster[type](message);
				return;
			}
			if (window.toastr && typeof window.toastr[type] === 'function') {
				window.toastr[type](message);
				return;
			}
			alert(message);
		}

		list = customFieldListBase;

		window.customFieldFormFilter = function (id) {
			setCustomFieldFilter(id);
		};

		document.addEventListener('lookup:change', function (event) {
			var wrapper = event.detail && event.detail.wrapper ? event.detail.wrapper : null;
			if (!wrapper) {
				return;
			}
			var hiddenInput = wrapper.querySelector('[data-lookup-hidden]');
			if (!hiddenInput) {
				return;
			}
			if (hiddenInput.name === 'custom_field_filter_form_id') {
				setCustomFieldFilter(hiddenInput.value || event.detail.id || '');
			}
		});

		$(document).on('change', 'input[name="custom_field_filter_form_id"][data-lookup-hidden]', function () {
			setCustomFieldFilter(this.value || '');
		});

		$(document).on('change', '[data-custom-field-status]', function () {
			var checkbox = this;
			var id = checkbox.getAttribute('data-id');
			var status = checkbox.checked ? 'active' : 'deactive';
			var previousStatus = checkbox.checked ? 'deactive' : 'active';

			if (!id) {
				return;
			}

			checkbox.disabled = true;
			$.ajax({
				url: base_url + "admin/settings/change_field_status/" + id,
				type: "POST",
				dataType: "json",
				data: {
					status: status
				},
				success: function (response) {
					if (!response || !response.success) {
						checkbox.checked = previousStatus === 'active';
						showCustomFieldStatusMessage('error', response && response.message ? response.message : "Could not update status.");
						return;
					}
					showCustomFieldStatusMessage('success', response.message || "Status updated.");
					reloadCustomFieldTable();
				},
				error: function () {
					checkbox.checked = previousStatus === 'active';
					showCustomFieldStatusMessage('error', "Could not update status.");
				},
				complete: function () {
					checkbox.disabled = false;
				}
			});
		});

		$('#custom_field_filter_reset').on('click', function () {
			var wrap = document.querySelector('#custom_field_filter_form_id').closest('[data-lookup]');
			if (!wrap) {
				customFieldFilter = '';
				reloadCustomFieldTable();
				return;
			}
			var hidden = wrap.querySelector('[data-lookup-hidden]');
			var input = wrap.querySelector('[data-lookup-input]');
			var clearBtn = wrap.querySelector('[data-lookup-clear]');
			if (hidden) {
				hidden.value = '';
			}
			if (input) {
				input.value = '';
			}
			if (clearBtn) {
				clearBtn.classList.add('hidden');
			}
			customFieldFilter = '';
			reloadCustomFieldTable();
		});

		setCustomFieldFilter('');
	});
</script>
