// Staff Management Module

let currentEditingStaff = null;

function loadStaffData() {
    // Check if user has staff management permission
    if (!hasPermission('staff')) {
        const staffSection = document.getElementById('staff');
        if (staffSection) {
            staffSection.innerHTML = `
                <div class="access-denied-message">
                    <div class="access-denied-icon">
                        <i class="fas fa-lock"></i>
                    </div>
                    <h3>Access Denied</h3>
                    <p>You do not have permission to access Staff Management.</p>
                    <p>Please contact your administrator for access.</p>
                </div>
            `;
        }
        return;
    }
    
    const staffTableBody = document.querySelector('#staff-table tbody');
    const staff = window.app.getData('staff');
    
    staffTableBody.innerHTML = staff.map(member => `
        <tr>
            <td>${member.name}</td>
            <td>${member.role}</td>
            <td>${member.department}</td>
            <td>${member.contact}</td>
            <td>${window.app.formatCurrency(parseFloat(member.salary || 0))}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editStaff(${member.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteStaff(${member.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');

    // Setup department filter
    const departmentFilter = document.getElementById('staff-department-filter');
    departmentFilter.addEventListener('change', filterStaffByDepartment);
    
    // Hide payroll button for non-admin users
    const payrollBtn = document.querySelector('[onclick="generateStaffPayroll()"]');
    if (payrollBtn && !hasPermission('payroll')) {
        payrollBtn.style.display = 'none';
    }
}

function filterStaffByDepartment() {
    const filter = document.getElementById('staff-department-filter').value;
    const staff = window.app.getData('staff');
    const filteredStaff = filter ? staff.filter(member => member.department === filter) : staff;
    
    const staffTableBody = document.querySelector('#staff-table tbody');
    staffTableBody.innerHTML = filteredStaff.map(member => `
        <tr>
            <td>${member.name}</td>
            <td>${member.role}</td>
            <td>${member.department}</td>
            <td>${member.contact}</td>
            <td>${window.app.formatCurrency(parseFloat(member.salary || 0))}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editStaff(${member.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteStaff(${member.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');
}

function showStaffModal(staffId = null) {
    const staff = staffId ? window.app.getData('staff').find(s => s.id === staffId) : null;
    const isEdit = !!staff;
    
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>${isEdit ? 'Edit Staff Member' : 'Add New Staff Member'}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="staff-form">
                    <div class="form-group">
                        <label for="staff-name">Full Name *</label>
                        <input type="text" id="staff-name" name="name" required 
                               value="${staff ? staff.name : ''}" placeholder="Enter full name">
                    </div>
                    
                    <div class="form-group">
                        <label for="staff-role">Role *</label>
                        <input type="text" id="staff-role" name="role" required 
                               value="${staff ? staff.role : ''}" placeholder="e.g., Speech Therapist, Receptionist">
                    </div>
                    
                    <div class="form-group">
                        <label for="staff-department">Department *</label>
                        <select id="staff-department" name="department" required>
                            <option value="">Select Department</option>
                            <option value="therapist" ${staff && staff.department === 'therapist' ? 'selected' : ''}>Therapist</option>
                            <option value="staff" ${staff && staff.department === 'staff' ? 'selected' : ''}>Staff</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="staff-contact">Contact Information *</label>
                        <input type="text" id="staff-contact" name="contact" required 
                               value="${staff ? staff.contact : ''}" placeholder="Phone number or email">
                    </div>
                    
                    <div class="form-group">
                        <label for="staff-salary">Monthly Salary *</label>
                        <input type="number" id="staff-salary" name="salary" required step="0.01" min="0"
                               value="${staff ? staff.salary : ''}" placeholder="Enter monthly salary">
                    </div>
                    
                    <div class="form-group">
                        <label for="staff-start-date">Start Date</label>
                        <input type="date" id="staff-start-date" name="startDate" 
                               value="${staff ? staff.startDate : ''}">
                    </div>
                    
                    <div class="form-group">
                        <label for="staff-notes">Notes</label>
                        <textarea id="staff-notes" name="notes" rows="3" 
                                  placeholder="Additional notes about the staff member">${staff ? staff.notes || '' : ''}</textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveStaff(${staffId})">
                    <i class="fas fa-save"></i> ${isEdit ? 'Update' : 'Add'} Staff
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    currentEditingStaff = staffId;
}

function saveStaff(staffId) {
    const form = document.getElementById('staff-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['name', 'role', 'department', 'contact', 'salary'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field} field`, 'error');
            return;
        }
    }
    
    const staffData = {
        id: staffId || window.app.generateId('staff'),
        name: formData.get('name'),
        role: formData.get('role'),
        department: formData.get('department'),
        contact: formData.get('contact'),
        salary: parseFloat(formData.get('salary')),
        startDate: formData.get('startDate') || new Date().toISOString().split('T')[0],
        notes: formData.get('notes') || '',
        createdAt: staffId ? undefined : new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    
    let staff = window.app.getData('staff');
    
    if (staffId) {
        // Update existing staff
        const index = staff.findIndex(s => s.id === staffId);
        if (index !== -1) {
            staff[index] = { ...staff[index], ...staffData };
        }
    } else {
        // Add new staff
        staff.push(staffData);
    }
    
    window.app.saveData('staff', staff);
    window.app.closeModal();
    loadStaffData();
    
    window.app.showNotification(
        `Staff member ${staffId ? 'updated' : 'added'} successfully!`,
        'success'
    );
}

function editStaff(staffId) {
    showStaffModal(staffId);
}

function deleteStaff(staffId) {
    if (confirm('Are you sure you want to delete this staff member? This action cannot be undone.')) {
        let staff = window.app.getData('staff');
        staff = staff.filter(s => s.id !== staffId);
        window.app.saveData('staff', staff);
        loadStaffData();
        window.app.showNotification('Staff member deleted successfully!', 'success');
    }
}

function generateStaffPayroll() {
    // Check if user has payroll permission
    if (!hasPermission('payroll')) {
        window.app.showNotification('Access denied. You do not have permission to generate payroll.', 'error');
        return;
    }
    
    const staff = window.app.getData('staff');
    
    if (staff.length === 0) {
        window.app.showNotification('No staff members found to generate payroll', 'error');
        return;
    }
    
    // Calculate payroll summary without deductions
    let totalSalaries = 0;
    
    const payrollData = staff.map(member => {
        const salary = parseFloat(member.salary || 0);
        totalSalaries += salary;
        
        return {
            id: member.id,
            name: member.name,
            role: member.role,
            department: member.department,
            salary: salary
        };
    });
    
    const averageSalary = staff.length > 0 ? totalSalaries / staff.length : 0;
    
    // Update payroll summary display
    document.getElementById('total-gross-pay').textContent = window.app.formatCurrency(totalSalaries);
    document.getElementById('total-staff-count').textContent = staff.length;
    document.getElementById('average-salary').textContent = window.app.formatCurrency(averageSalary);
    
    // Show payroll summary section
    document.getElementById('payroll-summary').style.display = 'block';
    
    // Show detailed payroll modal
    showPayrollModal(payrollData, { totalSalaries, averageSalary, staffCount: staff.length });
}

function showPayrollModal(payrollData, totals) {
    const currentDate = new Date().toLocaleDateString('en-US', { 
        year: 'numeric', 
        month: 'long' 
    });
    
    const modalContent = `
        <div class="modal" style="max-width: 700px;">
            <div class="modal-header">
                <h3>Staff Salary Report - ${currentDate}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div class="payroll-summary-header">
                    <div class="payroll-stat">
                        <span>Total Staff Salaries:</span>
                        <span>${window.app.formatCurrency(totals.totalSalaries)}</span>
                    </div>
                    <div class="payroll-stat">
                        <span>Staff Count:</span>
                        <span>${totals.staffCount}</span>
                    </div>
                    <div class="payroll-stat">
                        <span>Average Salary:</span>
                        <span>${window.app.formatCurrency(totals.averageSalary)}</span>
                    </div>
                </div>
                
                <div class="table-container" style="margin-top: 1rem;">
                    <table>
                        <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Role</th>
                                <th>Department</th>
                                <th>Salary</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${payrollData.map(employee => `
                                <tr>
                                    <td>${employee.name}</td>
                                    <td>${employee.role}</td>
                                    <td>${employee.department}</td>
                                    <td>${window.app.formatCurrency(employee.salary)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Close</button>
                <button type="button" class="btn btn-primary" onclick="exportPayroll()">
                    <i class="fas fa-download"></i> Export to CSV
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    
    // Store payroll data for export
    window.currentPayrollData = payrollData;
}

function exportPayroll() {
    if (window.currentPayrollData) {
        const exportData = window.currentPayrollData.map(employee => ({
            'Employee Name': employee.name,
            'Role': employee.role,
            'Department': employee.department,
            'Salary': employee.salary
        }));
        
        const currentDate = new Date().toISOString().split('T')[0];
        window.app.exportToCSV(exportData, `staff-salary-report-${currentDate}.csv`);
        window.app.showNotification('Staff salary report exported successfully!', 'success');
    }
}

// Add CSS for additional payroll styles
const payrollStyles = `
    <style>
        .btn-sm {
            padding: 0.375rem 0.75rem;
            font-size: 0.875rem;
            margin-right: 0.25rem;
        }
        
        .payroll-summary-header {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
            padding: 1rem;
            background: var(--light-gray);
            border-radius: var(--border-radius);
        }
        
        .payroll-summary-header .payroll-stat {
            background: var(--white);
            border-left: 4px solid var(--primary-teal);
        }
    </style>
`;

document.head.insertAdjacentHTML('beforeend', payrollStyles);
