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

<?php
$posts = isset($posts) && is_array($posts) ? $posts : array();
$total_posts = isset($total_posts) ? (int) $total_posts : count($posts);
$visibleN = 0; $hiddenN = 0; $removedN = 0; $photoN = 0;
foreach ($posts as $p) {
	if ($p['status'] === 'visible') $visibleN++;
	if ($p['status'] === 'hidden') $hiddenN++;
	if ($p['status'] === 'removed') $removedN++;
	if (strtolower($p['contentType']) === 'photo' || !empty($p['images'])) $photoN++;
}
?>

<div class="care-admin" id="teenPosts">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-8">
				<p class="ca-kicker">Content</p>
				<h1 class="ca-title"><?php echo isset($page_title) ? htmlspecialchars($page_title) : 'Posts'; ?></h1>
				<p class="ca-sub mb-0">Live posts from the Teen Up feed. Precise coordinates 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-newspaper"></i></div>
				<p class="ca-stat-label">Total posts</p>
				<div class="ca-stat-value"><?php echo (int) $total_posts; ?></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-eye"></i></div>
				<p class="ca-stat-label">Visible</p>
				<div class="ca-stat-value"><?php echo (int) $visibleN; ?></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-image"></i></div>
				<p class="ca-stat-label">With photos</p>
				<div class="ca-stat-value"><?php echo (int) $photoN; ?></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-eye-slash"></i></div>
				<p class="ca-stat-label">Hidden / removed</p>
				<div class="ca-stat-value"><?php echo (int) ($hiddenN + $removedN); ?></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-photo-film me-2 text-primary"></i>All posts</h5>
					<p class="mb-0">Search by caption, author, or post ID.</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="postCountLabel">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="postSearch" placeholder="Search caption, user, ID">
					</div>
					<select class="form-select" id="typeFilter" style="width: 150px;">
						<option value="all">All types</option>
						<option value="Photo">Photo</option>
						<option value="Post">Post</option>
					</select>
					<select class="form-select" id="statusFilter" style="width: 150px;">
						<option value="all">All statuses</option>
						<option value="visible">Visible</option>
						<option value="hidden">Hidden</option>
						<option value="removed">Removed</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>Preview</th>
							<th>Content ID</th>
							<th>User</th>
							<th>Type</th>
							<th>Caption</th>
							<th>Reports</th>
							<th>Status</th>
							<th>Created</th>
							<th class="text-end">Actions</th>
						</tr>
					</thead>
					<tbody id="postsTbody"></tbody>
				</table>
			</div>
			<div class="p-4 d-none" id="postsEmpty">
				<div class="tu-empty">
					<i class="fa-regular fa-image"></i>
					<div class="fw-semibold">No posts 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">
				<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 posts = <?php echo json_encode(array_values($posts), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
	var viewBase = <?php echo json_encode(base_url('admin/post_view/')); ?>;
	var statusBase = <?php echo json_encode(base_url('admin/post_status/')); ?>;
	var q = '';
	var typeFilter = 'all';
	var statusFilter = 'all';
	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 statusBadge(st) {
		var map = { visible: 'ca-status--active', hidden: 'ca-status--pending', removed: 'ca-status--danger' };
		var cls = map[st] || 'ca-status--muted';
		var label = st ? st.charAt(0).toUpperCase() + st.slice(1) : '—';
		return '<span class="ca-status ' + cls + '">' + escapeHtml(label) + '</span>';
	}
	function filtered() {
		return posts.filter(function (p) {
			if (typeFilter !== 'all' && String(p.contentType || p.category || '') !== typeFilter) return false;
			if (statusFilter !== 'all' && p.status !== statusFilter) return false;
			if (q) {
				var hay = ((p.caption || '') + ' ' + (p.authorName || '') + ' ' + (p.id || '') + ' ' + (p.docId || '') + ' ' + ((p.topics || []).join(' '))).toLowerCase();
				if (hay.indexOf(q) === -1) return false;
			}
			return true;
		});
	}
	function confirmAction(title, body, okClass, onOk) {
		el('tuConfirmTitle').textContent = title;
		el('tuConfirmBody').textContent = body;
		el('tuConfirmOk').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 setStatus(id, status) {
		var body = new FormData();
		body.append('status', status);
		return fetch(statusBase + encodeURIComponent(id), {
			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) || 1);
		if (page > pages) page = pages;
		var start = (page - 1) * pageSize;
		var slice = list.slice(start, start + pageSize);
		el('postCountLabel').textContent = 'Showing ' + slice.length + ' of ' + list.length;
		el('postsTbody').innerHTML = slice.map(function (p) {
			var preview = p.preview
				? '<img class="tu-thumb" src="' + escapeHtml(p.preview) + '" alt="">'
				: '<span class="tu-thumb tu-thumb--empty"><i class="fa-regular fa-image"></i></span>';
			var caption = p.caption || '—';
			if (caption.length > 72) caption = caption.slice(0, 72) + '…';
			var st = p.status || 'visible';
			var actions = '';
			if (st !== 'hidden') actions += '<button type="button" class="dropdown-item" data-act="status" data-status="hidden" data-id="' + escapeHtml(p.docId) + '">Hide</button>';
			if (st !== 'visible') actions += '<button type="button" class="dropdown-item" data-act="status" data-status="visible" data-id="' + escapeHtml(p.docId) + '">Restore</button>';
			if (st !== 'removed') actions += '<button type="button" class="dropdown-item text-danger" data-act="status" data-status="removed" data-id="' + escapeHtml(p.docId) + '">Remove</button>';
			return '<tr>' +
				'<td>' + preview + '</td>' +
				'<td class="small"><code>' + escapeHtml(p.id || p.docId) + '</code></td>' +
				'<td class="fw-semibold">' + escapeHtml(p.authorName || '—') + '</td>' +
				'<td><span class="ca-role-chip">' + escapeHtml(p.contentType || 'Post') + '</span></td>' +
				'<td class="small">' + escapeHtml(caption) + '</td>' +
				'<td>' + Number(p.reportsCount || 0) + '</td>' +
				'<td>' + statusBadge(st) + '</td>' +
				'<td class="small text-muted">' + escapeHtml(p.createdAtLabel || '—') + '</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(p.docId) + '">View</a></li>' +
						'<li><hr class="dropdown-divider"></li>' + actions +
					'</ul></div></td></tr>';
		}).join('');
		el('postsEmpty').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('postSearch').addEventListener('input', function () { q = this.value.toLowerCase(); page = 1; render(); });
	el('typeFilter').addEventListener('change', function () { typeFilter = this.value; page = 1; render(); });
	el('statusFilter').addEventListener('change', function () { statusFilter = this.value; page = 1; 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('teenPosts').addEventListener('click', function (e) {
		var btn = e.target.closest('[data-act="status"]');
		if (!btn) return;
		var id = btn.getAttribute('data-id');
		var st = btn.getAttribute('data-status');
		var label = st === 'removed' ? 'Remove this post?' : (st === 'hidden' ? 'Hide this post from the feed?' : 'Restore this post?');
		confirmAction('Update post', label, st === 'removed' ? 'btn-danger' : 'btn-primary', function () {
			setStatus(id, st).then(function (json) {
				if (!json || !json.ok) throw new Error((json && json.error) || 'Update failed');
				posts = posts.map(function (p) { if (p.docId === id) p.status = st; return p; });
				render();
			}).catch(function (err) { alert(err.message || 'Update failed'); });
		});
	});
	render();
})();
</script>
