const Payroll = require("../models/Payroll");
const Employee = require("../models/Employee");

const getReports = async (req, res) => {
  try {
    const month = parseInt(req.query.month) || new Date().getMonth() + 1;
    const year = parseInt(req.query.year) || new Date().getFullYear();

    const payrolls = await Payroll.find({ month, year })
      .populate("employee")
      .sort({ "employee.lastName": 1 });

    const totalEmployees = await Employee.countDocuments();
    const totalPayrollAmount = payrolls.reduce((sum, p) => sum + p.netPay, 0);
    const totalAllowances = payrolls.reduce((sum, p) => sum + (p.allowances || 0), 0);
    const totalDeductions = payrolls.reduce((sum, p) => sum + (p.deductions || 0), 0);

    res.json({
      month,
      year,
      totalEmployees,
      payrollRecords: payrolls,
      totalPayrollAmount,
      totalAllowances,
      totalDeductions,
      recordCount: payrolls.length
    });
  } catch (error) {
    res.status(500).json({ message: "Report could not be generated", error: error.message });
  }
};

module.exports = {
  getReports
};
