/**
 * Admin Config JS
 * Contains configuration constants and helper functions for admin panel
 */

// API Configuration
const API_BASE_URL = "http://localhost/v0-church-attendance-system/api";

// Admin Application URLs
const ADMIN_APP_URLS = {
	LOGIN: "login.html",
	DASHBOARD: "index.html",
	USERS: "users.html",
	SERVICES: "services.html",
	ATTENDANCES: "attendances.html",
	TICKETS: "tickets.html",
	REPORTS: "reports.html",
};

// API Endpoints for Admin Operations
const API_ENDPOINTS = {
	// Admin Auth
	LOGIN: API_BASE_URL + "/admin/login",
	LOGOUT: API_BASE_URL + "/admin/logout",

	// Dashboard
	DASHBOARD_STATS: API_BASE_URL + "/admin/dashboard",

	// User Management
	USERS_LIST: API_BASE_URL + "/admin/users",
	USER_CREATE: API_BASE_URL + "/admin/users",
	USER_UPDATE: API_BASE_URL + "/admin/users",
	USER_DELETE: API_BASE_URL + "/admin/users",

	// Service Management
	SERVICES_LIST: API_BASE_URL + "/admin/services",
	SERVICE_CREATE: API_BASE_URL + "/admin/services",
	SERVICE_UPDATE: API_BASE_URL + "/admin/services",
	SERVICE_DELETE: API_BASE_URL + "/admin/services",
	SERVICE_TYPES: API_BASE_URL + "/admin/service-types",
	SERVICE_TEMPLATES: API_BASE_URL + "/admin/service-templates",
	SERVICE_OCCURRENCES: API_BASE_URL + "/admin/service-occurrences",

	// Attendance Management
	ATTENDANCES_LIST: API_BASE_URL + "/admin/attendance",
	ATTENDANCE_STATUS: API_BASE_URL + "/admin/attendance",

	// Rewards Management
	REWARDS_LIST: API_BASE_URL + "/admin/rewards",
	REWARD_CREATE: API_BASE_URL + "/admin/rewards",
	REWARD_UPDATE: API_BASE_URL + "/admin/rewards",
	REWARD_DELETE: API_BASE_URL + "/admin/rewards",
	REWARD_STATS: API_BASE_URL + "/admin/rewards/stats",

	// Tickets (Penalties) Management
	TICKETS_LIST: API_BASE_URL + "/admin/tickets",
	TICKET_CREATE: API_BASE_URL + "/admin/tickets",
	TICKET_UPDATE: API_BASE_URL + "/admin/tickets",
	TICKET_RESOLVE: API_BASE_URL + "/admin/tickets",
	TICKET_STATS: API_BASE_URL + "/admin/tickets/stats",

	// Reports
	REPORTS_GENERATE: API_BASE_URL + "/reports",

	// Department Management
	DEPARTMENTS_LIST: API_BASE_URL + "/admin/departments",
	DEPARTMENT_CREATE: API_BASE_URL + "/admin/departments",
	DEPARTMENT_UPDATE: API_BASE_URL + "/admin/departments",
	DEPARTMENT_DELETE: API_BASE_URL + "/admin/departments",
	DEPARTMENT_ARCHIVE: API_BASE_URL + "/admin/departments",
	DEPARTMENT_RESTORE: API_BASE_URL + "/admin/departments",

	ROLES_LIST: API_BASE_URL + "/admin/roles",
};

// Local Storage Keys for Admin
const STORAGE_KEYS = {
	TOKEN: "hpc_admin_token",
	USER: "hpc_admin_user",
};

// Helper: Get auth token
function getAuthToken() {
	return localStorage.getItem(STORAGE_KEYS.TOKEN);
}

// Helper: Set auth token
function setAuthToken(token) {
	localStorage.setItem(STORAGE_KEYS.TOKEN, token);
}

// Helper: Remove auth token
function removeAuthToken() {
	localStorage.removeItem(STORAGE_KEYS.TOKEN);
	localStorage.removeItem(STORAGE_KEYS.USER);
}

function checkAdminAuth() {
	const token = getAuthToken();
	const user = getUserData();

	if (!!token && user && user.role === "admin") {
		window.location.href = ADMIN_APP_URLS.LOGIN;
		return null;
	}
	return { token, user };
}

function getAuthHeaders() {
	const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
	return {
		"Content-Type": "application/json",
		Authorization: `Bearer ${token}`,
	};
}

// Helper: Get admin user data
function getUserData() {
	const userData = localStorage.getItem(STORAGE_KEYS.USER);
	return userData ? JSON.parse(userData) : null;
}

// Helper: Set admin user data
function setUserData(user) {
	localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(user));
}

// Helper: Check if admin is authenticated
function isAuthenticated() {
	const token = getAuthToken();
	const user = getUserData();
	return (
		!!token && user && (user.role === "admin" || user.role === "superadmin")
	);
}

// Helper: Redirect to login if not authenticated or not admin
function requireAuth() {
	if (!isAuthenticated()) {
		window.location.href = ADMIN_APP_URLS.LOGIN;
		return false;
	}
	return true;
}

// Helper: Make API request with admin authentication
async function apiRequest(url, options = {}) {
	const token = getAuthToken();

	const headers = {
		"Content-Type": "application/json",
		...options.headers,
	};

	if (token) {
		headers["Authorization"] = `Bearer ${token}`;
	}

	try {
		const response = await fetch(`${url}`, {
			...options,
			headers,
		});

		const data = await response.json();

		// Handle authentication errors
		if (response.status === 401 || response.status === 403) {
			removeAuthToken();
			window.location.href = "login.html";
			throw new Error("Authentication required");
		}

		if (!response.ok) {
			throw new Error(data.message || "Request failed");
		}

		return data;
	} catch (error) {
		console.error("API Request Error:", error);
		throw error;
	}
}

// Helper: Show toast message
function showMessage(message, type = "success") {
	const toast = document.createElement("div");
	toast.className = `toast toast-${type}`;
	toast.textContent = message;
	toast.style.cssText = `
		position: fixed;
		top: 20px;
		right: 20px;
		padding: 16px 24px;
		background: ${
			type === "success" ? "#10b981" : type === "error" ? "#ef4444" : "#f59e0b"
		};
		color: white;
		border-radius: 8px;
		box-shadow: 0 4px 6px rgba(0,0,0,0.1);
		z-index: 10000;
		animation: slideIn 0.3s ease-out;
	`;

	document.body.appendChild(toast);

	setTimeout(() => {
		toast.style.animation = "slideOut 0.3s ease-out";
		setTimeout(() => toast.remove(), 300);
	}, 3000);
}

// Helper: Get user initials
function getUserInitials(firstName, lastName) {
	const first = firstName ? firstName.charAt(0).toUpperCase() : "";
	const last = lastName ? lastName.charAt(0).toUpperCase() : "";
	return first + last || "AD";
}

// Helper: Format time (HH:MM:SS to 12-hour format)
function formatTime(timeString) {
	if (!timeString) return "--:--";
	const [hours, minutes] = timeString.split(":");
	const hour = Number.parseInt(hours);
	const ampm = hour >= 12 ? "PM" : "AM";
	const displayHour = hour % 12 || 12;
	return `${displayHour}:${minutes} ${ampm}`;
}

// Helper: Format date
function formatDate(dateString) {
	const date = new Date(dateString);
	return date.toLocaleDateString("en-US", {
		year: "numeric",
		month: "short",
		day: "numeric",
	});
}

// Helper: Format datetime
function formatDateTime(dateTimeString) {
	const date = new Date(dateTimeString);
	return date.toLocaleString("en-US", {
		month: "short",
		day: "numeric",
		year: "numeric",
		hour: "2-digit",
		minute: "2-digit",
	});
}

// Helper: Calculate time difference in minutes
function calculateTimeDifference(start, end) {
	const startTime = new Date(start);
	const endTime = new Date(end);
	const diff = endTime - startTime;
	return Math.floor(diff / 1000 / 60);
}

// Helper: Format duration (minutes to hours and minutes)
function formatDuration(minutes) {
	if (!minutes) return "--";
	const hours = Math.floor(minutes / 60);
	const mins = minutes % 60;
	return `${hours}h ${mins}m`;
}

// Helper: Format duration from seconds
function formatDurationFromSeconds(seconds) {
	if (!seconds) return "--";
	const hours = Math.floor(seconds / 3600);
	const minutes = Math.floor((seconds % 3600) / 60);
	return `${hours}h ${minutes}m`;
}

// Helper: Get status badge HTML
function getStatusBadge(status) {
	const badges = {
		active: '<span class="badge success">Active</span>',
		completed: '<span class="badge success">Completed</span>',
		pending: '<span class="badge warning">Pending</span>',
		cancelled: '<span class="badge danger">Cancelled</span>',
		verified: '<span class="badge success">Verified</span>',
		unverified: '<span class="badge warning">Unverified</span>',
	};
	return badges[status] || `<span class="badge">${status}</span>`;
}

// Helper: Get role badge class
function getRoleBadgeClass(role) {
	const classes = {
		admin: "danger",
		worker: "primary",
		delegate: "info",
		user: "success",
	};
	return classes[role] || "info";
}

// Helper: Logout admin
function logout() {
	if (confirm("Are you sure you want to logout?")) {
		removeAuthToken();
		window.location.href = ADMIN_APP_URLS.LOGIN;
	}
}

// Helper: Toggle sidebar (for mobile)
function toggleSidebar() {
	const sidebar =
		document.getElementById("adminSidebar") ||
		document.getElementById("sidebar");
	if (sidebar) {
		sidebar.classList.toggle("open");
	}
}

// Add CSS animation for toast
const style = document.createElement("style");
style.textContent = `
	@keyframes slideIn {
		from {
			transform: translateX(100%);
			opacity: 0;
		}
		to {
			transform: translateX(0);
			opacity: 1;
		}
	}
	@keyframes slideOut {
		from {
			transform: translateX(0);
			opacity: 1;
		}
		to {
			transform: translateX(100%);
			opacity: 0;
		}
	}
`;
document.head.appendChild(style);
