// Authentication Module

// Demo user credentials
const users = {
    admin: {
        password: 'admin123',
        role: 'admin',
        name: 'Administrator',
        permissions: {
            dashboard: true,
            staff: true,
            payroll: true,
            expenses: true,
            patients: true,
            schedule: true,
            stock: true,
            reports: true
        }
    },
    user: {
        password: 'user123',
        role: 'user',
        name: 'Staff User',
        permissions: {
            dashboard: true,
            staff: false,  // No staff management access
            payroll: false, // No payroll access
            expenses: true,
            patients: true,
            schedule: true,
            stock: true,
            reports: true
        }
    }
};

// Check if user is already logged in
function checkAuth() {
    const currentUser = sessionStorage.getItem('currentUser');
    if (currentUser) {
        const userData = JSON.parse(currentUser);
        if (userData && userData.username && users[userData.username]) {
            return userData;
        }
    }
    return null;
}

// Login function
function login(username, password) {
    const user = users[username];
    
    if (!user) {
        throw new Error('Invalid username');
    }
    
    if (user.password !== password) {
        throw new Error('Invalid password');
    }
    
    const userData = {
        username: username,
        role: user.role,
        name: user.name,
        permissions: user.permissions,
        loginTime: new Date().toISOString()
    };
    
    sessionStorage.setItem('currentUser', JSON.stringify(userData));
    return userData;
}

// Logout function
function logout() {
    sessionStorage.removeItem('currentUser');
    window.location.href = 'login.html';
}

// Check if user has permission for a specific module
function hasPermission(module) {
    const currentUser = checkAuth();
    if (!currentUser) return false;
    return currentUser.permissions[module] === true;
}

// Redirect to login if not authenticated
function requireAuth() {
    const currentUser = checkAuth();
    if (!currentUser) {
        window.location.href = 'login.html';
        return false;
    }
    return currentUser;
}

// Toggle password visibility
function togglePassword() {
    const passwordInput = document.getElementById('password');
    const passwordEye = document.getElementById('password-eye');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        passwordEye.className = 'fas fa-eye-slash';
    } else {
        passwordInput.type = 'password';
        passwordEye.className = 'fas fa-eye';
    }
}

// Login form handler
if (document.getElementById('login-form')) {
    document.getElementById('login-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const errorMessage = document.getElementById('error-message');
        
        try {
            const userData = login(username, password);
            
            // Show success message
            errorMessage.style.display = 'block';
            errorMessage.style.color = '#4CAF50';
            errorMessage.textContent = `Welcome, ${userData.name}! Redirecting...`;
            
            // Redirect to main application after a short delay
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 1500);
            
        } catch (error) {
            errorMessage.style.display = 'block';
            errorMessage.style.color = '#f44336';
            errorMessage.textContent = error.message;
            
            // Hide error after 3 seconds
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 3000);
        }
    });
}



// Initialize authentication on main app
function initializeAuth() {
    const currentUser = requireAuth();
    if (!currentUser) return;
    
    // Update user info display
    updateUserDisplay(currentUser);
    
    // Apply role-based access control
    applyRoleBasedAccess(currentUser);
}

// Update user display in header
function updateUserDisplay(userData) {
    const userWelcome = document.getElementById('user-welcome');
    const userRole = document.getElementById('user-role');
    
    if (userWelcome) {
        userWelcome.textContent = `Welcome, ${userData.name}`;
    }
    
    if (userRole) {
        userRole.innerHTML = `
            <i class="fas fa-id-badge"></i>
            <span>Role: ${userData.role.charAt(0).toUpperCase() + userData.role.slice(1)}</span>
        `;
    }
}

// Apply role-based access control
function applyRoleBasedAccess(userData) {
    const navLinks = document.querySelectorAll('.nav-link');
    
    navLinks.forEach(link => {
        const section = link.getAttribute('data-section');
        
        if (!userData.permissions[section]) {
            // Hide navigation item for sections without permission
            link.parentElement.style.display = 'none';
            
            // Add click handler to show access denied message
            link.addEventListener('click', function(e) {
                e.preventDefault();
                showAccessDeniedMessage();
            });
        }
    });
    
    // Hide staff management actions in dashboard for non-admin users
    if (!userData.permissions.staff) {
        const staffActions = document.querySelectorAll('[data-section="staff"]');
        staffActions.forEach(action => {
            action.style.display = 'none';
        });
    }
}

// Show access denied message
function showAccessDeniedMessage() {
    if (window.app && window.app.showNotification) {
        window.app.showNotification('Access denied. You do not have permission to view this section.', 'error');
    } else {
        alert('Access denied. You do not have permission to view this section.');
    }
}

// Toggle user dropdown
function toggleUserDropdown() {
    const dropdown = document.getElementById('user-dropdown');
    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
}

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdown = document.getElementById('user-dropdown');
    const dropdownBtn = document.querySelector('.dropdown-btn');
    
    if (dropdown && dropdownBtn && !dropdown.contains(event.target) && !dropdownBtn.contains(event.target)) {
        dropdown.style.display = 'none';
    }
});
