const { pool } = require('../config/db');

// Get month name helper
function getMonthName(month) {
    const months = {
        '1': 'January', '2': 'February', '3': 'March', '4': 'April',
        '5': 'May', '6': 'June', '7': 'July', '8': 'August',
        '9': 'September', '10': 'October', '11': 'November', '12': 'December'
    };
    return months[month] || month;
}

// Generate monthly payroll report
const getMonthlyPayroll = async (req, res) => {
    const { month } = req.query;
    
    console.log('Generating report for month:', month);
    
    if (!month) {
        return res.status(400).json({ message: 'Month is required' });
    }
    
    try {
        // Get all employees with their salary info
        const [employees] = await pool.execute(`
            SELECT 
                e.empID,
                e.fname,
                e.lname,
                e.position,
                d.deptName as department,
                s.grossSalary,
                s.totalDeduction,
                s.netSalary,
                s.month
            FROM employee e
            LEFT JOIN department d ON e.deptCode = d.deptCode
            LEFT JOIN salary s ON e.salaryID = s.salaryID
        `);
        
        console.log('Total employees found:', employees.length);
        
        // Filter by month
        const filteredEmployees = employees.filter(emp => {
            return emp.month && parseInt(emp.month) === parseInt(month);
        });
        
        console.log(`Filtered employees for month ${month}:`, filteredEmployees.length);
        
        // Calculate totals
        let totalGrossSalary = 0;
        let totalDeduction = 0;
        let totalNetSalary = 0;
        
        filteredEmployees.forEach(emp => {
            totalGrossSalary += parseFloat(emp.grossSalary) || 0;
            totalDeduction += parseFloat(emp.totalDeduction) || 0;
            totalNetSalary += parseFloat(emp.netSalary) || 0;
        });
        
        const reportData = {
            reportMonth: month,
            monthName: getMonthName(month),
            employeeCount: filteredEmployees.length,
            employees: filteredEmployees.map(emp => ({
                FirstName: emp.fname || 'N/A',
                LastName: emp.lname || 'N/A',
                Position: emp.position || 'N/A',
                Department: emp.department || 'No Department',
                GrossSalary: parseFloat(emp.grossSalary) || 0,
                TotalDeduction: parseFloat(emp.totalDeduction) || 0,
                NetSalary: parseFloat(emp.netSalary) || 0
            })),
            summary: {
                totalGrossSalary: totalGrossSalary,
                totalDeduction: totalDeduction,
                totalNetSalary: totalNetSalary
            },
            generatedAt: new Date()
        };
        
        res.json(reportData);
        
    } catch (error) {
        console.error('Generate report error:', error);
        res.status(500).json({ 
            message: 'Failed to generate report', 
            error: error.message 
        });
    }
};

// Get available months
const getAvailableMonths = async (req, res) => {
    try {
        const [months] = await pool.execute(`
            SELECT DISTINCT month 
            FROM salary 
            WHERE month IS NOT NULL
            ORDER BY month DESC
        `);
        
        const monthsWithNames = months.map(m => ({
            month: m.month,
            monthName: getMonthName(m.month.toString())
        }));
        
        res.json(monthsWithNames);
        
    } catch (error) {
        console.error('Get months error:', error);
        // Return default months if error
        const defaultMonths = [
            { month: '1', monthName: 'January' },
            { month: '2', monthName: 'February' },
            { month: '3', monthName: 'March' },
            { month: '4', monthName: 'April' },
            { month: '5', monthName: 'May' },
            { month: '6', monthName: 'June' },
            { month: '7', monthName: 'July' },
            { month: '8', monthName: 'August' },
            { month: '9', monthName: 'September' },
            { month: '10', monthName: 'October' },
            { month: '11', monthName: 'November' },
            { month: '12', monthName: 'December' }
        ];
        res.json(defaultMonths);
    }
};

// Make sure all functions are exported
module.exports = { 
    getMonthlyPayroll, 
    getAvailableMonths 
};