<?php
$datatable = true;
echo message_box('success');
echo message_box('error');
$created = can_action('24', 'created');
$deleted = can_action('24', 'deleted');

$filter_options = array(
	'' => lang('all'),
	'admin' => lang('admin'),
	'staff' => lang('staff'),
	'client' => lang('client'),
	'active' => lang('active'),
	'deactive' => lang('deactive'),
	'banned' => lang('banned'),
);

?>
<div class="space-y-4">
	<div class="rounded-2xl border border-border bg-card shadow-sm">
		<div class="px-6 py-5 flex flex-col md:flex-row md:items-center md:justify-between gap-3 border-b border-border">
			<div>
				<h3 class="text-xl font-bold text-foreground"><?= lang('users'); ?></h3>
			</div>
			<div class="flex flex-wrap gap-2">
				<div id="user_view_toggle_fallback" class="inline-flex items-center rounded-lg border border-border bg-muted/30 p-1">
					<button type="button" data-view-toggle="list" class="inline-flex items-center justify-center rounded-md p-2 text-xs font-semibold text-foreground hover:bg-card" title="<?= lang('list') ?>">
						<i data-lucide="list" class="h-4 w-4"></i>
					</button>
					<button type="button" data-view-toggle="grid" class="inline-flex items-center justify-center rounded-md p-2 text-xs font-semibold text-foreground hover:bg-card" title="<?= lang('grid') ?>">
						<i data-lucide="layout-grid" class="h-4 w-4"></i>
					</button>
				</div>
				<div class=" gap-3">
					<div class="min-w-[220px]">
						<?= form_select_group('user_filter', '', $filter_options, '', false, array('id' => 'user_filter')); ?>
					</div>
				</div>


			</div>
		</div>



		<div class="p-6">
			<div id="user_list_view" class="table-responsive">
				<table class="table table-striped DataTables" id="DataTables" width="100%">
					<thead class="text-xs uppercase text-muted-foreground">
						<tr>
							<?php if (!empty($deleted)) : ?>
								<th class="w-10"><input type="checkbox" id="select_all"></th>
							<?php endif; ?>
							<th class="py-2 px-3"><?= lang('photo') ?></th>
							<th class="py-2 px-3"><?= lang('name') ?></th>
							<th class="py-2 px-3"><?= lang('username') ?></th>
							<th class="py-2 px-3"><?= lang('active') ?></th>
							<th class="py-2 px-3"><?= lang('user_type') ?></th>
							<?php $show_custom_fields = custom_form_table(13, null);
							if (!empty($show_custom_fields)) {
								foreach ($show_custom_fields as $c_label => $v_fields) {
									if (!empty($c_label)) {
							?>
										<th class="py-2 px-3"><?= $c_label ?> </th>
							<?php }
								}
							}
							?>
							<th class="py-2 px-3"><?= lang('action') ?></th>

						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</div>
			<div id="user_grid_view" class="hidden">
				<div id="user_grid_cards" class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3"></div>
			</div>
		</div>
	</div>
</div>

<style>
	#DataTables tbody td:last-child {
		min-width: 230px;
	}

	#DataTables tbody td:last-child .btn_modal {
		display: inline-flex;
	}

	[data-view-toggle].is-active {
		background: var(--tw-color-card, #fff);
		box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
		color: var(--tw-color-primary, #4f46e5);
	}
</style>

<script type="text/javascript">
	var list = base_url + "admin/user/userList";
	$(document).ready(function() {
		const STORAGE_KEY = 'admin_user_view_mode';
		const $listView = $('#user_list_view');
		const $gridView = $('#user_grid_view');
		const $gridCards = $('#user_grid_cards');
		const $fallbackToggle = $('#user_view_toggle_fallback');
		const $refreshBtn = $('[data-view-refresh]');
		let currentFilter = $('#user_filter').val() || '';
		let initialBootstrapPending = true;

		const getListUrl = function() {
			let url = base_url + "admin/user/userList";
			if (currentFilter) {
				url += "/" + currentFilter;
			}
			return url;
		};

		const getGridUrl = function() {
			let url = base_url + "admin/user/userGrid";
			if (currentFilter) {
				url += "/" + currentFilter;
			}
			return url;
		};

		const escapeHtml = function(value) {
			return String(value || '')
				.replace(/&/g, '&amp;')
				.replace(/</g, '&lt;')
				.replace(/>/g, '&gt;')
				.replace(/"/g, '&quot;')
				.replace(/'/g, '&#039;');
		};

		const mountToolbarToggle = function() {
			$('#DataTables_wrapper .js-user-view-toggle').remove();
		};

		const syncToggleState = function(view) {
			$('[data-view-toggle]').removeClass('is-active text-primary').addClass('text-foreground').attr('aria-pressed', 'false');
			$('[data-view-toggle="' + view + '"]').addClass('is-active text-primary').removeClass('text-foreground').attr('aria-pressed', 'true');
		};

		const renderGrid = function(users) {
			if (!users || !users.length) {
				$gridCards.html('<div class="col-span-full rounded-xl border border-dashed border-border bg-muted/20 p-8 text-center text-sm text-muted-foreground"><?= lang('no_data') ?></div>');
				return;
			}

			const cards = users.map(function(user) {
				const activeBlock = user.can_toggle ?
					'<label class="change_user_status inline-flex items-center gap-2 text-xs font-medium text-foreground">' +
					'<input type="checkbox" data-id="' + user.user_id + '" class="h-4 w-4 rounded border-border text-indigo-600 focus:ring-indigo-500" ' + (user.active ? 'checked' : '') + '>' +
					'<span>' + (user.active ? '<?= lang('active') ?>' : '<?= lang('deactive') ?>') + '</span>' +
					'</label>' :
					'<span class="inline-flex items-center rounded-full border border-border bg-muted/30 px-2 py-1 text-xs font-semibold text-foreground">' + (user.active ? '<?= lang('active') ?>' : '<?= lang('deactive') ?>') + '</span>';

				const bannedBadge = user.banned ?
					'<span class="inline-flex items-center rounded-full border border-rose-200 bg-rose-50 px-2 py-1 text-[11px] font-semibold text-rose-700 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-300" title="' + escapeHtml(user.ban_reason) + '"><?= lang('banned') ?></span>' :
					'';

				const actionButtons = [];
				if (user.can_ban) {
					if (user.banned) {
						actionButtons.push('<a href="' + user.unban_url + '" class="inline-flex items-center justify-center rounded-md border border-emerald-200 bg-emerald-50 px-2.5 py-1.5 text-xs font-semibold text-emerald-700 hover:bg-emerald-100" title="<?= lang('unbanned') ?>"><i data-lucide="shield-check" class="h-3.5 w-3.5"></i></a>');
					} else {
						actionButtons.push('<a data-toggle="modal" data-target="#myModal" href="' + user.ban_url + '" class="btn_modal inline-flex items-center justify-center rounded-md border border-rose-200 bg-rose-50 px-2.5 py-1.5 text-xs font-semibold text-rose-700 hover:bg-rose-100" title="<?= lang('banned') ?>"><i data-lucide="ban" class="h-3.5 w-3.5"></i></a>');
					}
				}
				actionButtons.push('<a href="' + user.email_url + '" class="inline-flex items-center justify-center rounded-md border border-sky-200 bg-sky-50 px-2.5 py-1.5 text-xs font-semibold text-sky-700 hover:bg-sky-100" title="<?= lang('send') . ' ' . lang('wellcome_email') ?>"><i data-lucide="mail" class="h-3.5 w-3.5"></i></a>');
				if (user.can_edit) {
					actionButtons.push('<a href="' + user.edit_url + '" class="inline-flex items-center justify-center rounded-md border border-indigo-200 bg-indigo-50 px-2.5 py-1.5 text-xs font-semibold text-indigo-700 hover:bg-indigo-100" title="<?= lang('update') ?>"><i data-lucide="square-pen" class="h-3.5 w-3.5"></i></a>');
				}
				if (user.can_delete) {
					actionButtons.push('<a href="' + user.delete_url + '" onclick="return confirm(\'<?= lang('delete_alert') ?>\')" class="inline-flex items-center justify-center rounded-md border border-rose-200 bg-rose-50 px-2.5 py-1.5 text-xs font-semibold text-rose-700 hover:bg-rose-100" title="<?= lang('delete') ?>"><i data-lucide="trash-2" class="h-3.5 w-3.5"></i></a>');
				}

				return '<article class="rounded-xl border border-border bg-card p-4 shadow-sm">' +
					'<div class="flex items-start justify-between gap-3">' +
					'<a href="' + user.details_url + '" class="flex min-w-0 items-center gap-3">' +
					'<img src="' + escapeHtml(user.avatar) + '" alt="" class="h-10 w-10 rounded-full border border-border object-cover">' +
					'<div class="min-w-0">' +
					'<h4 class="truncate text-sm font-semibold text-foreground">' + escapeHtml(user.name) + '</h4>' +
					'<p class="truncate text-xs text-muted-foreground">@' + escapeHtml(user.username) + '</p>' +
					'</div>' +
					'</a>' +
					'<span class="inline-flex items-center rounded-full border border-border bg-muted/30 px-2 py-1 text-[11px] font-semibold text-foreground">' + escapeHtml(user.role) + '</span>' +
					'</div>' +
					'<div class="mt-4 flex items-center justify-between gap-2">' +
					'<div class="flex items-center gap-2">' + activeBlock + bannedBadge + '</div>' +
					'</div>' +
					'<div class="mt-4 flex flex-wrap items-center gap-1.5">' + actionButtons.join('') + '</div>' +
					'</article>';
			});

			$gridCards.html(cards.join(''));
			if (window.lucide && typeof window.lucide.createIcons === 'function') {
				window.lucide.createIcons();
			}
		};

		const loadGrid = function() {
			$gridCards.html('<div class="col-span-full rounded-xl border border-dashed border-border bg-muted/20 p-8 text-center text-sm text-muted-foreground"><?= lang('loading') ?>...</div>');
			$.getJSON(getGridUrl(), function(res) {
				if (res && res.status === 'success') {
					renderGrid(res.users || []);
				} else {
					renderGrid([]);
				}
			}).fail(function() {
				$gridCards.html('<div class="col-span-full rounded-xl border border-dashed border-rose-300 bg-rose-50 p-8 text-center text-sm text-rose-700"><?= lang('something_went_wrong') ?></div>');
			});
		};

		const reloadList = function(url) {
			if ($.fn.dataTable && $.fn.dataTable.isDataTable('#DataTables')) {
				table_url(url);
				mountToolbarToggle();
				return;
			}
			if (typeof fire_datatable === 'function') {
				fire_datatable(url, "DataTables");
				setTimeout(mountToolbarToggle, 120);
			}
		};

		const setViewMode = function(mode) {
			const view = mode === 'grid' ? 'grid' : 'list';
			localStorage.setItem(STORAGE_KEY, view);
			syncToggleState(view);

			if (view === 'grid') {
				$listView.addClass('hidden');
				$gridView.removeClass('hidden');
				loadGrid();
			} else {
				$gridView.addClass('hidden');
				$listView.removeClass('hidden');
				list = getListUrl(); // keep existing database/list function
				if (!initialBootstrapPending) {
					reloadList(list);
				}
			}
			$fallbackToggle.removeClass('hidden');
			mountToolbarToggle();
		};

		$(document).on('click', '[data-view-toggle]', function() {
			setViewMode($(this).data('view-toggle'));
		});

		$refreshBtn.on('click', function() {
			const activeMode = localStorage.getItem(STORAGE_KEY) || 'list';
			if (activeMode === 'grid') {
				loadGrid();
			} else {
				reloadList(getListUrl());
			}
		});

		$('#user_filter').on('change', function() {
			currentFilter = $(this).val() || '';
			const activeMode = localStorage.getItem(STORAGE_KEY) || 'list';
			if (activeMode === 'grid') {
				loadGrid();
			} else {
				reloadList(getListUrl());
			}
		});

		$('#DataTables').on('init.dt', function() {
			mountToolbarToggle();
		});

		const initialMode = localStorage.getItem(STORAGE_KEY) || 'list';
		setViewMode(initialMode);
		initialBootstrapPending = false;
		if (initialMode !== 'grid') {
			mountToolbarToggle();
		}
	});
</script>

<script>
	$(document).on("click", '.change_user_status input[type="checkbox"]', function() {
		var user_id = $(this).data().id;
		var status = $(this).is(":checked");
		if (status == true) {
			status = 1;
		} else {
			status = 0;
		}
		$.ajax({
			type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
			url: '<?= base_url() ?>admin/user/change_status/' + status + '/' +
				user_id, // the url where we want to POST
			dataType: 'json', // what type of data do we expect back from the server
			encode: true,
			success: function(res) {
				console.log(res);
				if (res) {
					toastr[res.status](res.message);
				} else {
					alert(<?= json_encode(lang('ajax_problem')) ?>);
				}
			}
		})
	});
</script>
