// Admin dashboard functionality let items = []; let reservations = []; let currentView = 'grid'; // Default view mode // Check authentication function checkAuth() { const token = localStorage.getItem('token'); const role = localStorage.getItem('userRole'); if (!token || role !== 'admin') { window.location.href = '/index.html'; } } // Initialize page async function initializePage() { try { checkAuth(); await loadItems(); displayUserInfo(); setupEventListeners(); // Move this after displayUserInfo to ensure DOM is ready console.log('Page initialization complete'); } catch (error) { console.error('Error during page initialization:', error); throw error; // Re-throw to be caught by the outer try-catch } } // Display user info function displayUserInfo() { const username = localStorage.getItem('username'); document.getElementById('userInfo').textContent = `Admin: ${username}`; } // Load items from server async function loadItems() { try { console.log('Loading items...'); const response = await fetch('/api/items', { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); const data = await response.json(); console.log('Received items:', data); if (!response.ok) { throw new Error(data.message || 'Failed to load items'); } items = data; displayItems(); } catch (error) { console.error('Error loading items:', error); alert('Failed to load items: ' + error.message); } } // Display items based on current view mode function displayItems() { if (currentView === 'grid') { displayGridView(); } else { displayListView(); } } // Display items in grid view function displayGridView() { const itemsGrid = document.getElementById('itemsGrid'); document.getElementById('itemsList').classList.add('d-none'); itemsGrid.classList.remove('d-none'); itemsGrid.innerHTML = items.map(item => `
${item.description || 'No description available'}
Location: ${item.location}
Quantity: ${item.quantity}
Reserved: ${item.reserved || 0}
