<%- include('top') %>

<script type="text/javascript">
	app.auth.forceLogin('app_sso_admin');

	// ── Overview (stats, recent signups, inactive users) ────────────────────
	async function loadDashboard() {
		try {
			const stats = await app.api.get('user/stats');

			// Stat cards
			document.getElementById('stat-total').textContent   = stats.totalUsers;
			document.getElementById('stat-active').textContent  = stats.activeUsers;
			document.getElementById('stat-inactive').textContent = stats.inactiveUsers;
			document.getElementById('stat-groups').textContent  = stats.totalGroups;
			
			try {
			    const dirRes = await app.api.get('directory-admin/resources');
			    const resources = dirRes.results || [];
			    document.getElementById('stat-hosts').textContent = resources.filter(r => r.kind === 'host').length;
			    document.getElementById('stat-services').textContent = resources.filter(r => r.kind === 'service').length;
			    document.getElementById('stat-oauth').textContent = resources.filter(r => r.kind === 'oauth').length;
			    document.getElementById('directory-stats-row').style.display = '';
			} catch (err) {}

			document.getElementById('dashboard-overview').style.display = '';
		} catch(e) {
			if (e && (e.status === 401 || e.name === 'Insufficient Permission')) {
				location.replace('/');
			} else {
				console.error('Dashboard load error:', e);
			}
		}
	}

	async function exportUsers() {
		const resp = await fetch('/api/user/export', {
			headers: { 'auth-token': localStorage.getItem('APIToken') }
		});
		const blob = await resp.blob();
		const a = document.createElement('a');
		a.href = URL.createObjectURL(blob);
		a.download = 'users.csv';
		a.click();
	}

	async function loadMetrics() {
		try {
			const data = await app.api.get('metrics/executive');
			if (data && data.results) {
				const renderList = (items, id) => {
					const el = document.getElementById(id);
					el.innerHTML = '';
					if (!items || items.length === 0) {
						el.innerHTML = '<li class="list-group-item text-muted">No data available</li>';
						return;
					}
					items.forEach(item => {
						el.innerHTML += `<li class="list-group-item d-flex justify-content-between align-items-center">
							${item.value}
							<span class="badge bg-primary rounded-pill">${item.score}</span>
						</li>`;
					});
				};
				renderList(data.results.ips, 'metrics-ips');
				renderList(data.results.users, 'metrics-users');
				renderList(data.results.services, 'metrics-services');
			}
		} catch (e) {
			console.error('Failed to load metrics:', e);
		}
	}

	// ── Notifications (compose + history) ────────────────────────────────────
	async function loadHistory() {
		try {
			const data = await app.api.get('notification');
			const list = data.results || [];
			list.forEach(function(n) {
				n.created_on_fmt = moment(n.created_on).fromNow();
				n.filter_label = formatFilterLabel(n.filter_type, n.filter_value, n.active_only);
			});
			$.scope.notificationHistory.push(...list);
		} catch(e) {
			if (e && e.status === 401) location.replace('/');
			else console.error('Failed to load notification history:', e);
		}
	}

	function formatFilterLabel(type, value, active_only) {
		const suffix = active_only ? ' (active only)' : '';
		if (type === 'group')      return 'Groups: ' + value + suffix;
		if (type === 'users')      return 'Specific users';
		if (type === 'all_active') return 'All active users';
		if (type === 'all')        return 'All users';
		return type;
	}

	function toggleFilterInputs() {
		// No radio is checked by default (see f-all-active below) — a "send to
		// everyone" option must be a deliberate choice, not whatever happens to
		// be pre-selected when someone's just trying the form out.
		const checked = document.querySelector('input[name="notif-filter"]:checked');
		const type = checked ? checked.value : null;
		document.getElementById('notif-group-row').style.display  = type === 'group'  ? '' : 'none';
		document.getElementById('notif-users-row').style.display  = type === 'users'  ? '' : 'none';
		document.getElementById('notif-active-row').style.display = (type === 'group' || type === 'all') ? '' : 'none';
	}

	async function sendNotification() {
		const subject     = document.getElementById('notif-subject').value.trim();
		const message     = document.getElementById('notif-message').value.trim();
		const filterCheck = document.querySelector('input[name="notif-filter"]:checked');
		const groupValue  = document.getElementById('notif-group').value.trim();
		const usersValue  = document.getElementById('notif-users').value.trim();
		const activeOnly  = document.getElementById('notif-active-only').checked;
		const msgEl       = document.getElementById('notif-result');
		const $compose    = $('#notif-subject').closest('.card-body');

		if (!subject || !message) { app.messages.action('Subject and message are required.', $compose, 'danger'); return; }
		if (!filterCheck) { app.messages.action('Choose who to send this to.', $compose, 'danger'); return; }
		const filterType = filterCheck.value;

		let filter_value = '';
		if (filterType === 'group') filter_value = groupValue;
		if (filterType === 'users') filter_value = JSON.stringify(usersValue.split(',').map(s => s.trim()).filter(Boolean));

		// Broadcasting to everyone is easy to trigger by accident while just
		// trying the form out — make it a deliberate, confirmed action.
		if (filterType === 'all' || filterType === 'all_active') {
			const label = filterType === 'all' ? 'ALL users (including inactive)' : 'all ACTIVE users';
			const confirmed = await app.messages.confirm(`Send this notification to ${label}?`, $compose, 'warning');
			if (!confirmed) return;
		}

		msgEl.className = 'alert alert-info mt-2';
		msgEl.textContent = 'Sending…';
		msgEl.style.display = '';

		try {
			const result = await app.api.post('notification', {
				subject,
				message,
				filter_type: filterType,
				filter_value,
				active_only: activeOnly,
			});
			msgEl.className = 'alert alert-success mt-2';
			msgEl.textContent = `Sent to ${result.results.sent_count} recipient(s). ${result.results.failed_count} failed.`;

			const n = result.results;
			n.created_on_fmt = 'just now';
			n.filter_label   = formatFilterLabel(n.filter_type, n.filter_value, n.active_only);
			$.scope.notificationHistory.unshift([n]);

			// Reset form
			document.getElementById('notif-subject').value = '';
			document.getElementById('notif-message').value = '';
		} catch(e) {
			msgEl.className = 'alert alert-danger mt-2';
			msgEl.textContent = 'Failed: ' + ((e.responseJSON && e.responseJSON.message) || e.message || 'Unknown error');
		}
	}

	// ── Terms of Service ──────────────────────────────────────────────────
	async function loadTos() {
		try {
			const tos = await app.tos.get();
			document.getElementById('tos-content').value = tos.content;
			document.getElementById('tos-meta').textContent =
				'Last updated ' + moment(tos.updated_on, 'x').fromNow() + ' by ' + tos.updated_by;
		} catch(e) {
			console.error('Failed to load ToS:', e);
		}
	}

	function saveTos() {
		const content = document.getElementById('tos-content').value.trim();
		const resetAcceptance = document.getElementById('tos-reset-acceptance').checked;
		const msgEl = document.getElementById('tos-result');

		if (!content) {
			msgEl.className = 'alert alert-danger mt-2';
			msgEl.textContent = 'Terms of Service text cannot be empty.';
			msgEl.style.display = '';
			return;
		}

		app.tos.update({content, resetAcceptance}, function(error, data) {
			if (error) {
				msgEl.className = 'alert alert-danger mt-2';
				msgEl.textContent = 'Failed: ' + ((data && data.message) || error);
				msgEl.style.display = '';
				return;
			}
			msgEl.className = 'alert alert-success mt-2';
			msgEl.textContent = 'Saved.' + (data.resetCount ? ' ' + data.resetCount + ' user(s) will be asked to re-accept.' : '');
			msgEl.style.display = '';
			document.getElementById('tos-reset-acceptance').checked = false;
			loadTos();
		});
	}

	$(document).ready(function() {
		loadDashboard();
		loadHistory();
		toggleFilterInputs();
		loadTos();
		loadMetrics();
	});
</script>

<div class="container mt-4">
	<div class="row mb-3">
		<div class="col-12">
			<h4 class="mb-0"><i class="fa-solid fa-gauge-high"></i> Executive Dashboard</h4>
		</div>
	</div>

	<!-- Stats Card -->
	<div class="card shadow mb-4" id="dashboard-overview" style="display:none">
		<div class="card-header d-flex justify-content-between align-items-center">
			<div><i class="fa-solid fa-chart-pie"></i> Overview Stats</div>
			<button class="btn btn-sm btn-outline-secondary shadow-sm" onclick="exportUsers()">
				<i class="fa-solid fa-file-csv"></i> Export Users CSV
			</button>
		</div>
		<div class="card-body bg-light">
			<div class="row g-3">
				<div class="col-6 col-md-3">
					<div class="card shadow-sm text-center">
						<div class="card-body">
							<div class="display-6 fw-bold" id="stat-total">—</div>
							<div class="text-muted small"><i class="fa-solid fa-users"></i> Total Users</div>
						</div>
					</div>
				</div>
				<div class="col-6 col-md-3">
					<div class="card shadow-sm text-center border-success">
						<div class="card-body">
							<div class="display-6 fw-bold text-success" id="stat-active">—</div>
							<div class="text-muted small"><i class="fa-solid fa-circle-check"></i> Active</div>
						</div>
					</div>
				</div>
				<div class="col-6 col-md-3">
					<div class="card shadow-sm text-center border-danger">
						<div class="card-body">
							<div class="display-6 fw-bold text-danger" id="stat-inactive">—</div>
							<div class="text-muted small"><i class="fa-solid fa-lock"></i> Inactive</div>
						</div>
					</div>
				</div>
				<div class="col-6 col-md-3">
					<div class="card shadow-sm text-center border-info">
						<div class="card-body">
							<div class="display-6 fw-bold text-info" id="stat-groups">—</div>
							<div class="text-muted small"><i class="fa-solid fa-users-viewfinder"></i> Groups</div>
						</div>
					</div>
				</div>
			</div>
			
			<div class="row g-3 mt-1" id="directory-stats-row" style="display:none">
				<div class="col-4">
					<div class="card shadow-sm text-center border-secondary">
						<div class="card-body">
							<div class="display-6 fw-bold text-secondary" id="stat-hosts">—</div>
							<div class="text-muted small"><i class="fa-solid fa-server"></i> Hosts</div>
						</div>
					</div>
				</div>
				<div class="col-4">
					<div class="card shadow-sm text-center border-secondary">
						<div class="card-body">
							<div class="display-6 fw-bold text-secondary" id="stat-services">—</div>
							<div class="text-muted small"><i class="fa-solid fa-layer-group"></i> Services</div>
						</div>
					</div>
				</div>
				<div class="col-4">
					<div class="card shadow-sm text-center border-secondary">
						<div class="card-body">
							<div class="display-6 fw-bold text-secondary" id="stat-oauth">—</div>
							<div class="text-muted small"><i class="fa-solid fa-plug"></i> OAuth Integrations</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Notifications Card -->
	<div class="card shadow mb-4">
		<div class="card-header d-flex justify-content-between align-items-center">
			<div><i class="fa-solid fa-paper-plane"></i> Notifications</div>
		</div>
		<ul class="nav nav-tabs px-3 pt-2 border-bottom-0" role="tablist">
			<li class="nav-item" role="presentation">
				<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-compose" type="button" role="tab"><i class="fa-solid fa-pencil"></i> Compose</button>
			</li>
			<li class="nav-item" role="presentation">
				<button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-history" type="button" role="tab"><i class="fa-solid fa-clock-rotate-left"></i> History</button>
			</li>
		</ul>
		<div class="tab-content border-top">
			<div class="tab-pane fade show active p-4" id="tab-compose" role="tabpanel">
				<div class="row">
					<div class="col-lg-8">
						<div class="mb-3">
							<label class="form-label">Subject</label>
							<input type="text" class="form-control shadow-sm" id="notif-subject" placeholder="Maintenance window tonight" />
						</div>
						<div class="mb-3">
							<label class="form-label">Message <small class="text-muted">(HTML allowed)</small></label>
							<textarea class="form-control shadow-sm" id="notif-message" rows="6" placeholder="<p>Hello, we will be performing maintenance...</p>"></textarea>
						</div>
						<div class="mb-3">
							<label class="form-label">Send to</label>
							<div class="form-check">
								<input class="form-check-input" type="radio" name="notif-filter" id="f-all-active" value="all_active" onchange="toggleFilterInputs()">
								<label class="form-check-label" for="f-all-active">All active users</label>
							</div>
							<div class="form-check">
								<input class="form-check-input" type="radio" name="notif-filter" id="f-all" value="all" onchange="toggleFilterInputs()">
								<label class="form-check-label" for="f-all">All users (including inactive)</label>
							</div>
							<div class="form-check">
								<input class="form-check-input" type="radio" name="notif-filter" id="f-group" value="group" onchange="toggleFilterInputs()">
								<label class="form-check-label" for="f-group">Group members</label>
							</div>
							<div class="form-check">
								<input class="form-check-input" type="radio" name="notif-filter" id="f-users" value="users" onchange="toggleFilterInputs()">
								<label class="form-check-label" for="f-users">Specific users</label>
							</div>
						</div>

						<div id="notif-group-row" class="mb-3" style="display:none">
							<label class="form-label">Groups <small class="text-muted">(comma-separated)</small></label>
							<input type="text" class="form-control shadow-sm" id="notif-group" placeholder="host_hec-bot_admin, app_sso_admin" />
						</div>
						<div id="notif-users-row" class="mb-3" style="display:none">
							<label class="form-label">UIDs <small class="text-muted">(comma-separated)</small></label>
							<input type="text" class="form-control shadow-sm" id="notif-users" placeholder="wmantly, jsmith" />
						</div>
						<div id="notif-active-row" class="mb-3" style="display:none">
							<div class="form-check">
								<input class="form-check-input" type="checkbox" id="notif-active-only" checked>
								<label class="form-check-label" for="notif-active-only">Active members only</label>
							</div>
						</div>

						<button class="btn btn-primary shadow-sm" onclick="sendNotification()">
							<i class="fa-solid fa-paper-plane"></i> Send
						</button>
						<div id="notif-result" style="display:none" class="mt-3"></div>
					</div>
				</div>
			</div>
			
			<div class="tab-pane fade" id="tab-history" role="tabpanel">
				<div class="table-responsive">
					<table class="table table-striped table-hover mb-0">
						<thead>
							<tr>
								<th class="ps-3">Sent</th>
								<th>Subject</th>
								<th>Filter</th>
								<th class="text-center">✓</th>
								<th class="text-center pe-3">✗</th>
							</tr>
						</thead>
						<tbody jq-repeat="notificationHistory" jq-index-key="notification_id">
							<tr>
								<td class="ps-3"><small class="text-muted">{{created_on_fmt}}</small></td>
								<td><small>{{subject}}</small></td>
								<td><small class="text-muted">{{filter_label}}</small></td>
								<td class="text-center text-success"><small>{{sent_count}}</small></td>
								<td class="text-center text-danger pe-3"><small>{{failed_count}}</small></td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>

	<!-- TOS Card -->
	<div class="card shadow mb-5">
		<div class="card-header d-flex justify-content-between align-items-center">
			<div><i class="fa-solid fa-file-contract"></i> Terms of Service Editor</div>
			<small class="text-muted" id="tos-meta"></small>
		</div>
		<div class="card-body">
			<div class="mb-3">
				<label class="form-label">Content <small class="text-muted">(Markdown)</small></label>
				<textarea class="form-control shadow-sm" id="tos-content" rows="12"></textarea>
			</div>
			<div class="form-check mb-3">
				<input class="form-check-input" type="checkbox" id="tos-reset-acceptance">
				<label class="form-check-label" for="tos-reset-acceptance">
					Require all users to re-accept these terms
				</label>
			</div>
			<button class="btn btn-primary shadow-sm" onclick="saveTos()">
				<i class="fa-solid fa-floppy-disk"></i> Save
			</button>
			<div id="tos-result" style="display:none" class="mt-3"></div>
		</div>
	</div>

	<!-- Actionable Metrics Card -->
	<div class="card shadow mb-5">
		<div class="card-header d-flex justify-content-between align-items-center">
			<div><i class="fa-solid fa-chart-line"></i> Actionable Metrics (Last 7 Days)</div>
			<button class="btn btn-sm btn-outline-secondary shadow-sm" onclick="loadMetrics()">
				<i class="fa-solid fa-rotate-right"></i> Refresh
			</button>
		</div>
		<div class="card-body">
			<div class="row g-3">
				<div class="col-md-4">
					<div class="card shadow-sm h-100 border-danger">
						<div class="card-header bg-danger text-white"><i class="fa-solid fa-shield-halved"></i> Top Failed IPs</div>
						<ul class="list-group list-group-flush" id="metrics-ips">
							<li class="list-group-item text-muted">Loading...</li>
						</ul>
					</div>
				</div>
				<div class="col-md-4">
					<div class="card shadow-sm h-100 border-warning">
						<div class="card-header bg-warning text-dark"><i class="fa-solid fa-user-xmark"></i> Top Failed Accounts</div>
						<ul class="list-group list-group-flush" id="metrics-users">
							<li class="list-group-item text-muted">Loading...</li>
						</ul>
					</div>
				</div>
				<div class="col-md-4">
					<div class="card shadow-sm h-100 border-success">
						<div class="card-header bg-success text-white"><i class="fa-solid fa-plug"></i> Top Services Used</div>
						<ul class="list-group list-group-flush" id="metrics-services">
							<li class="list-group-item text-muted">Loading...</li>
						</ul>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<%- include('impersonate_modal') %>
<%- include('bottom') %>
