<link href="<?php echo base_url('assets/css/admin-panel.css'); ?>" rel="stylesheet">

<style>
	.aoust-avatar {
		width: 36px;
		height: 36px;
		border-radius: 12px;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
		letter-spacing: 0.02em;
		color: #0f5132;
		background: rgba(25, 135, 84, 0.14);
		border: 1px solid rgba(25, 135, 84, 0.25);
	}
	.aoust-muted {
		color: rgba(33, 37, 41, 0.7);
	}
	.aoust-table-actions .btn {
		padding-inline: 0.75rem;
	}
</style>

<div class="care-admin" id="aoustUsers">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-8">
				<p class="ca-kicker">AOUST portal</p>
				<h1 class="ca-title"><?php echo isset($page_title) ? htmlspecialchars($page_title) : 'AOUST — User Management'; ?></h1>
				<p class="ca-sub mb-0">Filter, search, and manage users. Add/Edit via modal; delete with confirmation.</p>
			</div>
			<div class="col-lg-4">
				<div class="ca-nav justify-content-lg-end">
					<a class="btn btn-light" href="<?php echo base_url('admin/aoust'); ?>">Dashboard</a>
					<a class="btn btn-light" href="<?php echo base_url('admin/aoust_webinars'); ?>">Webinars</a>
					<a class="btn btn-primary" href="<?php echo base_url('admin/aoust_users'); ?>">Users</a>
				</div>
			</div>
		</div>
	</div>

	<div class="row g-3 mb-4" id="userKpis"></div>

	<div class="ca-card mb-4">
		<div class="ca-card-header d-flex flex-column flex-lg-row align-items-lg-center justify-content-lg-between gap-2">
			<div>
				<h5 class="ca-card-title mb-1"><i class="fa-solid fa-users-gear me-2 text-success"></i>Users</h5>
				<p class="mb-0">Use filters + search to quickly find accounts.</p>
			</div>
			<div class="d-flex align-items-stretch gap-2 flex-wrap justify-content-lg-end">
				<div class="d-flex flex-column justify-content-center order-2 order-lg-0">
					<span class="badge rounded-pill ca-pill bg-light text-dark border" id="userCountLabel">Showing 0</span>
				</div>

				<div class="btn-group order-0" role="group" aria-label="User type filters">
					<button type="button" class="btn btn-light border" data-user-type="au_pairs">Au pairs</button>
					<button type="button" class="btn btn-light border" data-user-type="family_host">Family host</button>
					<button type="button" class="btn btn-light border" data-user-type="agencies">Agencies</button>
				</div>

				<div class="input-group order-1" style="min-width: 280px;">
					<span class="input-group-text bg-white"><i class="fa-solid fa-magnifying-glass"></i></span>
					<input type="search" class="form-control" id="userSearch" placeholder="Search by name, email, or ID">
				</div>

				<select class="form-select order-3" id="statusFilter" style="width: 180px;">
					<option value="all">All statuses</option>
					<option value="active">Active</option>
					<option value="inactive">Inactive</option>
				</select>

				<a class="btn btn-ca-success order-4" href="<?php echo base_url('admin/aoust_users'); ?>">
					<i class="fa-solid fa-rotate me-2"></i>Refresh
				</a>
			</div>
		</div>
		<div class="ca-card-body p-0">
			<div class="ca-table-wrap border-0 rounded-0 border-top">
				<table class="table ca-table table-striped mb-0 align-middle">
					<thead>
						<tr>
							<th>Name</th>
							<th>Email</th>
							<th>Type</th>
							<th>Status</th>
							<th class="text-muted small">ID</th>
							<th class="text-end">Actions</th>
						</tr>
					</thead>
					<tbody id="usersTbody"></tbody>
				</table>
			</div>
			<div class="p-4 d-none" id="usersEmpty">
				<div class="text-center">
					<div class="mb-2"><i class="fa-regular fa-face-frown fs-2 text-muted"></i></div>
					<div class="fw-semibold">No results</div>
					<div class="aoust-muted small">Try clearing filters or searching a different keyword.</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
(function () {
	var users = [];
	var currentType = 'au_pairs';
	var searchQuery = '';
	var statusFilter = 'all';

	function el(id) { return document.getElementById(id); }
	function escapeHtml(str) {
		return String(str)
			.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
			.replaceAll('"', '&quot;').replaceAll("'", '&#039;');
	}
	function badgeForStatus(st) {
		var s = String(st || '').toLowerCase();
		if (s === 'active') return '<span class="badge bg-success-subtle text-success border border-success-subtle">Active</span>';
		if (s === 'inactive') return '<span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">Inactive</span>';
		return '<span class="badge bg-light text-dark border">—</span>';
	}
	function matchesSearch(u) {
		var q = (searchQuery || '').trim().toLowerCase();
		if (!q) return true;
		var hay = (u.name + ' ' + u.email + ' ' + u.uid).toLowerCase();
		return hay.indexOf(q) !== -1;
	}
	function matchesStatus(u) {
		if (statusFilter === 'all') return true;
		return String(u.status || '').toLowerCase() === statusFilter;
	}
	function initials(name) {
		var parts = String(name || '').trim().split(/\s+/).filter(Boolean);
		var a = parts[0] ? parts[0][0] : '?';
		var b = parts.length > 1 ? parts[parts.length - 1][0] : '';
		return (a + b).toUpperCase();
	}
	function renderKpis() {
		var total = users.length;
		var active = users.filter(function (u) { return String(u.status).toLowerCase() === 'active'; }).length;
		var inactive = users.filter(function (u) { return String(u.status).toLowerCase() === 'inactive'; }).length;
		var auPairs = users.filter(function (u) { return u.userType === 'au_pair'; }).length;
		var familyHosts = users.filter(function (u) { return u.userType === 'family_host'; }).length;
		var agencies = users.filter(function (u) { return u.userType === 'agency'; }).length;

		var kpis = [
			{ icon: 'fa-solid fa-users', label: 'Total accounts', value: total },
			{ icon: 'fa-solid fa-circle-check', label: 'Active', value: active },
			{ icon: 'fa-solid fa-circle-xmark', label: 'Inactive', value: inactive },
			{ icon: 'fa-solid fa-person', label: 'Au pairs', value: auPairs },
			{ icon: 'fa-solid fa-house', label: 'Family host', value: familyHosts },
			{ icon: 'fa-solid fa-building', label: 'Agencies', value: agencies }
		];

		el('userKpis').innerHTML = kpis.map(function (k) {
			return '' +
				'<div class="col-12 col-md-6 col-xl">' +
					'<div class="ca-stat h-100">' +
						'<div class="ca-stat-icon"><i class="' + k.icon + '"></i></div>' +
						'<p class="ca-stat-label">' + escapeHtml(k.label) + '</p>' +
						'<div class="display-6 fw-bold mb-0">' + escapeHtml(k.value) + '</div>' +
					'</div>' +
				'</div>';
		}).join('');
	}

	function render() {
		var filtered = users.filter(matchesStatus).filter(matchesSearch);

		var countLabel = el('userCountLabel');
		if (countLabel) {
			var totalInTab = users.length;
			var extra = '';
			if ((searchQuery || '').trim() || statusFilter !== 'all') {
				extra = ' · filtered';
			}
			countLabel.textContent = 'Showing ' + filtered.length + ' of ' + totalInTab + extra;
		}

		el('usersTbody').innerHTML = filtered
			.map(function (u) {
				var typeLabel = (u.userType === 'au_pair') ? 'Au pair'
					: (u.userType === 'family_host') ? 'Family host'
					: (u.userType === 'agency') ? 'Agency'
					: (u.userType || '—');
				var typeBadge = '<span class="badge bg-light text-dark border">' + escapeHtml(typeLabel) + '</span>';
				return '' +
					'<tr>' +
						'<td class="fw-semibold">' +
							'<div class="d-flex align-items-center gap-2">' +
								'<span class="aoust-avatar" aria-hidden="true">' + escapeHtml(initials(u.name)) + '</span>' +
								'<div class="min-w-0">' +
									'<div class="text-truncate">' + escapeHtml(u.name) + '</div>' +
									'<div class="aoust-muted small text-truncate">' + typeBadge + '</div>' +
								'</div>' +
							'</div>' +
						'</td>' +
						'<td class="text-truncate">' + (u.email ? ('<a class="text-decoration-none" href="mailto:' + escapeHtml(u.email) + '">' + escapeHtml(u.email) + '</a>') : '<span class="text-muted">—</span>') + '</td>' +
						'<td>' + typeBadge + '</td>' +
						'<td>' + badgeForStatus(u.status) + '</td>' +
						'<td class="text-muted small">' + escapeHtml(u.uid) + '</td>' +
						'<td class="text-end">' +
							'<div class="btn-group aoust-table-actions" role="group">' +
								'<a class="btn btn-sm btn-light border" href="<?php echo base_url('admin/aoust_user_view/'); ?>' + encodeURIComponent(u.uid) + '" title="View"><i class="fa-regular fa-eye"></i></a>' +
								'<a class="btn btn-sm btn-light border" href="<?php echo base_url('admin/aoust_user_edit/'); ?>' + encodeURIComponent(u.uid) + '" title="Edit"><i class="fa-regular fa-pen-to-square"></i></a>' +
								'<button class="btn btn-sm btn-outline-danger" data-action="delete" data-uid="' + escapeHtml(u.uid) + '" data-name="' + escapeHtml(u.name) + '" title="Delete"><i class="fa-regular fa-trash-can"></i></button>' +
							'</div>' +
						'</td>' +
					'</tr>';
			}).join('');

		var empty = el('usersEmpty');
		if (filtered.length === 0) empty.classList.remove('d-none');
		else empty.classList.add('d-none');
	}

	function setType(type) {
		currentType = type;
		var url = new URL(window.location.href);
		url.searchParams.set('type', type);
		window.history.replaceState(null, '', url.toString());
		document.querySelectorAll('[data-user-type]').forEach(function (b) {
			b.classList.remove('btn-primary'); b.classList.add('btn-light');
		});
		var activeBtn = document.querySelector('[data-user-type="' + type + '"]');
		if (activeBtn) { activeBtn.classList.add('btn-primary'); activeBtn.classList.remove('btn-light'); }
	}

	document.querySelectorAll('[data-user-type]').forEach(function (btn) {
		btn.addEventListener('click', function () {
			setType(btn.getAttribute('data-user-type'));
			loadUsers();
		});
	});

	el('userSearch').addEventListener('input', function () {
		searchQuery = el('userSearch').value || '';
		render();
	});
	el('statusFilter').addEventListener('change', function () {
		statusFilter = el('statusFilter').value || 'all';
		render();
	});

	document.getElementById('aoustUsers').addEventListener('click', function (e) {
		var btn = e.target.closest('button[data-action]');
		if (!btn) return;
		var action = btn.getAttribute('data-action');
		if (action === 'delete') {
			var uid = btn.getAttribute('data-uid');
			var name = btn.getAttribute('data-name') || uid;
			if (!uid) return;
			if (!confirm('Delete user "' + name + '"?')) return;
			deleteUser(uid);
		}
	});

	function normalizeRow(r) {
		var first = (r.firstName || '').trim();
		var last = (r.lastName || '').trim();
		var name = (first + ' ' + last).trim() || r.uid || '—';
		return {
			uid: String(r.uid || ''),
			name: name,
			email: r.email || '',
			userType: r.userType || '',
			status: r.isActive ? 'active' : 'inactive'
		};
	}

	async function loadUsers() {
		el('usersTbody').innerHTML = '';
		var empty = el('usersEmpty');
		if (empty) empty.classList.add('d-none');
		el('userCountLabel').textContent = 'Loading…';
		try {
			var res = await fetch('<?php echo base_url('admin/aoust_users_api'); ?>?type=' + encodeURIComponent(currentType), { headers: { 'Accept': 'application/json' } });
			var json = await res.json();
			if (!json || !json.ok) throw new Error((json && json.error) ? json.error : 'Failed to load users');
			users = (json.data || []).map(normalizeRow);
			renderKpis();
			render();
		} catch (err) {
			users = [];
			renderKpis();
			render();
			alert('Error: ' + (err && err.message ? err.message : err));
		}
	}

	async function deleteUser(uid) {
		try {
			var res = await fetch('<?php echo base_url('admin/aoust_user_delete/'); ?>' + encodeURIComponent(uid), {
				method: 'POST',
				headers: { 'Accept': 'application/json' }
			});
			var json = await res.json();
			if (!json || !json.ok) throw new Error((json && json.error) ? json.error : 'Delete failed');
			users = users.filter(function (u) { return u.uid !== uid; });
			renderKpis();
			render();
		} catch (err) {
			alert('Error: ' + (err && err.message ? err.message : err));
		}
	}

	(function initFromUrl() {
		var url = new URL(window.location.href);
		var t = url.searchParams.get('type') || 'au_pairs';
		if (!['au_pairs', 'family_host', 'agencies'].includes(t)) t = 'au_pairs';
		setType(t);
	})();

	loadUsers();
})();
</script>

