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

<?php
if (!function_exists('tu_initials')) {
	function tu_initials($name) {
		$parts = preg_split('/\s+/', trim((string) $name));
		$a = isset($parts[0][0]) ? $parts[0][0] : '?';
		$b = (count($parts) > 1 && isset($parts[count($parts) - 1][0])) ? $parts[count($parts) - 1][0] : '';
		return strtoupper($a . $b);
	}
}
$users = isset($users) && is_array($users) ? $users : array();
$total_users = isset($total_users) ? (int) $total_users : count($users);
$activeN = 0; $susN = 0; $blockN = 0;
foreach ($users as $u) {
	if ($u['status'] === 'active') $activeN++;
	if ($u['status'] === 'suspended') $susN++;
	if ($u['status'] === 'blocked') $blockN++;
}
?>

<div class="care-admin" id="teenUsers">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-8">
				<p class="ca-kicker">People</p>
				<h1 class="ca-title"><?php echo isset($page_title) ? htmlspecialchars($page_title) : 'Users'; ?></h1>
				<p class="ca-sub mb-0">Search, filter, and moderate teen accounts. Passwords and private chats are not shown.</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'); ?>">Dashboard</a>
				</div>
			</div>
		</div>
	</div>

	<div class="row g-3 mb-4">
		<div class="col-6 col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-users"></i></div>
				<p class="ca-stat-label">Total</p>
				<div class="ca-stat-value"><?php echo (int) $total_users; ?></div>
			</div>
		</div>
		<div class="col-6 col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-user-check"></i></div>
				<p class="ca-stat-label">Active</p>
				<div class="ca-stat-value"><?php echo (int) $activeN; ?></div>
			</div>
		</div>
		<div class="col-6 col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-user-slash"></i></div>
				<p class="ca-stat-label">Suspended</p>
				<div class="ca-stat-value"><?php echo (int) $susN; ?></div>
			</div>
		</div>
		<div class="col-6 col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-ban"></i></div>
				<p class="ca-stat-label">Blocked</p>
				<div class="ca-stat-value"><?php echo (int) $blockN; ?></div>
			</div>
		</div>
	</div>

	<div class="ca-card">
		<div class="ca-card-header">
			<div class="d-flex flex-column flex-xl-row align-items-xl-center justify-content-xl-between gap-3">
				<div>
					<h5 class="ca-card-title mb-1"><i class="fa-solid fa-users me-2 text-primary"></i>All users</h5>
					<p class="mb-0">Sortable table with search and pagination.</p>
				</div>
				<div class="d-flex flex-wrap gap-2 align-items-stretch">
					<span class="badge rounded-pill ca-pill bg-light text-dark border align-self-center" id="userCountLabel">Showing 0</span>
					<div class="input-group" style="min-width: 220px;">
						<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 name, username, email">
					</div>
					<select class="form-select" id="statusFilter" style="width: 160px;">
						<option value="all">All statuses</option>
						<option value="active">Active</option>
						<option value="suspended">Suspended</option>
						<option value="blocked">Blocked</option>
						<option value="deleted">Deleted</option>
					</select>
					<select class="form-select" id="ageFilter" style="width: 150px;">
						<option value="all">All ages</option>
						<option value="13-14">13–14</option>
						<option value="15-16">15–16</option>
						<option value="17-18">17–18</option>
						<option value="18-19">18–19</option>
					</select>
					<select class="form-select" id="sortBy" style="width: 170px;">
						<option value="created_desc">Newest first</option>
						<option value="created_asc">Oldest first</option>
						<option value="name_asc">Name A–Z</option>
						<option value="name_desc">Name Z–A</option>
					</select>
				</div>
			</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>Profile</th>
							<th>Username</th>
							<th>Email</th>
							<th>Age group</th>
							<th>Location</th>
							<th>Registered</th>
							<th>Subscription</th>
							<th>Status</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="tu-empty">
					<i class="fa-regular fa-face-frown"></i>
					<div class="fw-semibold">No users match</div>
					<div class="small">Try a different search or clear filters.</div>
				</div>
			</div>
			<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 px-3 py-3 border-top" id="pagerWrap">
				<select class="form-select form-select-sm" id="pageSize" style="width: 110px;">
					<option value="10">10 / page</option>
					<option value="25">25 / page</option>
					<option value="50">50 / page</option>
				</select>
				<nav><ul class="pagination pagination-sm mb-0" id="pager"></ul></nav>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="tuConfirmModal" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content" style="border-radius: 16px;">
			<div class="modal-header border-0">
				<h5 class="modal-title fw-bold" id="tuConfirmTitle">Confirm</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body pt-0" id="tuConfirmBody"></div>
			<div class="modal-footer border-0">
				<button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
				<button type="button" class="btn btn-danger" id="tuConfirmOk">Confirm</button>
			</div>
		</div>
	</div>
</div>

<script>
(function () {
	var users = <?php echo json_encode(array_values($users), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
	var viewBase = <?php echo json_encode(base_url('admin/user_view/')); ?>;
	var editBase = <?php echo json_encode(base_url('admin/user_edit/')); ?>;
	var statusBase = <?php echo json_encode(base_url('admin/user_status/')); ?>;
	var deleteBase = <?php echo json_encode(base_url('admin/user_delete/')); ?>;
	var q = '';
	var statusFilter = 'all';
	var ageFilter = 'all';
	var sortBy = 'created_desc';
	var page = 1;
	var pageSize = 10;
	var pending = null;

	function el(id) { return document.getElementById(id); }
	function escapeHtml(str) {
		return String(str == null ? '' : str)
			.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;').replace(/'/g, '&#039;');
	}
	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 statusBadge(st) {
		var map = {
			active: 'ca-status--active',
			suspended: 'ca-status--suspended',
			blocked: 'ca-status--danger',
			deleted: 'ca-status--muted'
		};
		var cls = map[st] || 'ca-status--muted';
		return '<span class="ca-status ' + cls + '">' + escapeHtml(st ? st.charAt(0).toUpperCase() + st.slice(1) : '—') + '</span>';
	}
	function filtered() {
		var list = users.filter(function (u) {
			if (statusFilter !== 'all' && u.status !== statusFilter) return false;
			if (ageFilter !== 'all' && String(u.ageGroup || '') !== ageFilter) return false;
			if (q) {
				var hay = ((u.displayName || '') + ' ' + (u.username || '') + ' ' + (u.email || '') + ' ' + (u.uid || '')).toLowerCase();
				if (hay.indexOf(q) === -1) return false;
			}
			return true;
		});
		list.sort(function (a, b) {
			if (sortBy === 'name_asc') return String(a.displayName || a.username || '').localeCompare(String(b.displayName || b.username || ''));
			if (sortBy === 'name_desc') return String(b.displayName || b.username || '').localeCompare(String(a.displayName || a.username || ''));
			if (sortBy === 'created_asc') return (a.createdAt || 0) - (b.createdAt || 0);
			return (b.createdAt || 0) - (a.createdAt || 0);
		});
		return list;
	}
	function confirmAction(title, body, okClass, onOk) {
		el('tuConfirmTitle').textContent = title;
		el('tuConfirmBody').textContent = body;
		var ok = el('tuConfirmOk');
		ok.className = 'btn ' + (okClass || 'btn-danger');
		pending = onOk;
		bootstrap.Modal.getOrCreateInstance(el('tuConfirmModal')).show();
	}
	el('tuConfirmOk').addEventListener('click', function () {
		var fn = pending;
		pending = null;
		bootstrap.Modal.getOrCreateInstance(el('tuConfirmModal')).hide();
		if (fn) fn();
	});

	function postStatus(uid, status) {
		var body = new FormData();
		body.append('status', status);
		return fetch(statusBase + encodeURIComponent(uid), {
			method: 'POST',
			headers: { 'Accept': 'application/json' },
			body: body
		}).then(function (r) { return r.json(); });
	}

	function render() {
		var list = filtered();
		var pages = Math.max(1, Math.ceil(list.length / pageSize));
		if (page > pages) page = pages;
		var start = (page - 1) * pageSize;
		var slice = list.slice(start, start + pageSize);
		el('userCountLabel').textContent = 'Showing ' + slice.length + ' of ' + list.length;
		el('usersTbody').innerHTML = slice.map(function (u) {
			var name = u.displayName || u.username || 'Teen';
			var avatar = u.photoUrl
				? '<img class="tu-avatar" src="' + escapeHtml(u.photoUrl) + '" alt="">'
				: '<span class="tu-avatar tu-avatar--fallback">' + escapeHtml(initials(name)) + '</span>';
			var st = u.status || 'active';
			var actions = '';
			if (st === 'suspended') {
				actions += '<button type="button" class="dropdown-item" data-act="status" data-status="active" data-uid="' + escapeHtml(u.uid) + '">Unsuspend</button>';
			} else if (st !== 'deleted') {
				actions += '<button type="button" class="dropdown-item" data-act="status" data-status="suspended" data-uid="' + escapeHtml(u.uid) + '">Suspend</button>';
			}
			if (st !== 'blocked' && st !== 'deleted') {
				actions += '<button type="button" class="dropdown-item" data-act="status" data-status="blocked" data-uid="' + escapeHtml(u.uid) + '">Block</button>';
			}
			if (st !== 'deleted') {
				actions += '<button type="button" class="dropdown-item text-danger" data-act="delete" data-uid="' + escapeHtml(u.uid) + '" data-name="' + escapeHtml(name) + '">Delete</button>';
			} else {
				actions += '<button type="button" class="dropdown-item" data-act="status" data-status="active" data-uid="' + escapeHtml(u.uid) + '">Restore</button>';
			}
			return '<tr>' +
				'<td><div class="d-flex align-items-center gap-2">' + avatar + '<div class="fw-semibold text-truncate">' + escapeHtml(name) + '</div></div></td>' +
				'<td>' + (u.username ? ('@' + escapeHtml(u.username)) : '<span class="text-muted">—</span>') + '</td>' +
				'<td class="small">' + (u.email ? escapeHtml(u.email) : '<span class="text-muted">—</span>') + '</td>' +
				'<td><span class="ca-role-chip">' + escapeHtml(u.ageGroup || '—') + '</span></td>' +
				'<td class="small text-muted">' + escapeHtml(u.locationLabel || '—') + '</td>' +
				'<td class="small text-muted">' + escapeHtml(u.createdAtLabel || '—') + '</td>' +
				'<td><span class="ca-role-chip">' + escapeHtml(u.subscription || 'Free') + '</span></td>' +
				'<td>' + statusBadge(st) + '</td>' +
				'<td class="text-end"><div class="dropdown">' +
					'<button class="btn btn-sm btn-light dropdown-toggle" data-bs-toggle="dropdown">Actions</button>' +
					'<ul class="dropdown-menu dropdown-menu-end">' +
						'<li><a class="dropdown-item" href="' + viewBase + encodeURIComponent(u.uid) + '">View</a></li>' +
						'<li><a class="dropdown-item" href="' + editBase + encodeURIComponent(u.uid) + '">Edit</a></li>' +
						'<li><hr class="dropdown-divider"></li>' + actions +
					'</ul></div></td></tr>';
		}).join('');
		el('usersEmpty').classList.toggle('d-none', slice.length > 0);
		var pager = el('pager');
		pager.innerHTML = '';
		for (var i = 1; i <= pages; i++) {
			pager.innerHTML += '<li class="page-item ' + (i === page ? 'active' : '') + '"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>';
		}
	}

	el('userSearch').addEventListener('input', function () { q = this.value.toLowerCase(); page = 1; render(); });
	el('statusFilter').addEventListener('change', function () { statusFilter = this.value; page = 1; render(); });
	el('ageFilter').addEventListener('change', function () { ageFilter = this.value; page = 1; render(); });
	el('sortBy').addEventListener('change', function () { sortBy = this.value; render(); });
	el('pageSize').addEventListener('change', function () { pageSize = parseInt(this.value, 10) || 10; page = 1; render(); });
	el('pager').addEventListener('click', function (e) {
		var a = e.target.closest('a[data-page]');
		if (!a) return;
		e.preventDefault();
		page = parseInt(a.getAttribute('data-page'), 10) || 1;
		render();
	});
	el('teenUsers').addEventListener('click', function (e) {
		var btn = e.target.closest('[data-act]');
		if (!btn) return;
		var uid = btn.getAttribute('data-uid');
		var act = btn.getAttribute('data-act');
		if (act === 'delete') {
			confirmAction('Delete user', 'Mark "' + (btn.getAttribute('data-name') || uid) + '" as deleted? This can be restored later.', 'btn-danger', function () {
				fetch(deleteBase + encodeURIComponent(uid), { method: 'POST', headers: { 'Accept': 'application/json' } })
					.then(function (r) { return r.json(); })
					.then(function (json) {
						if (!json || !json.ok) throw new Error((json && json.error) || 'Delete failed');
						users = users.map(function (u) { if (u.uid === uid) u.status = 'deleted'; return u; });
						render();
					}).catch(function (err) { alert(err.message || 'Delete failed'); });
			});
			return;
		}
		if (act === 'status') {
			var st = btn.getAttribute('data-status');
			var label = st === 'active' ? 'restore / unsuspend' : st;
			confirmAction('Change status', 'Set this user to ' + st + '?', st === 'blocked' ? 'btn-danger' : 'btn-primary', function () {
				postStatus(uid, st).then(function (json) {
					if (!json || !json.ok) throw new Error((json && json.error) || 'Update failed');
					users = users.map(function (u) { if (u.uid === uid) u.status = st; return u; });
					render();
				}).catch(function (err) { alert(err.message || 'Update failed'); });
			});
		}
	});
	render();
})();
</script>
