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

const createSalary = async (req, res) => {
    const { grossSalary, totalDeduction, netSalary, month } = req.body;
    
    if (!grossSalary || !totalDeduction || !netSalary || !month) {
        return res.status(400).json({ message: 'All salary fields are required' });
    }
    
    try {
        const [result] = await pool.execute(
            'INSERT INTO salary (grossSalary, totalDeduction, netSalary, month) VALUES (?, ?, ?, ?)',
            [grossSalary, totalDeduction, netSalary, month]
        );
        
        res.status(201).json({ 
            message: 'Salary created successfully',
            salaryID: result.insertId
        });
    } catch (error) {
        console.error('Create salary error:', error);
        res.status(500).json({ message: 'Failed to create salary', error: error.message });
    }
};

const getAllSalaries = async (req, res) => {
    try {
        const [salaries] = await pool.execute('SELECT * FROM salary ORDER BY salaryID DESC');
        res.json(salaries);
    } catch (error) {
        console.error('Get salaries error:', error);
        res.status(500).json({ message: 'Failed to fetch salaries', error: error.message });
    }
};

const getSalaryById = async (req, res) => {
    const { id } = req.params;
    
    try {
        const [salaries] = await pool.execute('SELECT * FROM salary WHERE salaryID = ?', [id]);
        
        if (salaries.length === 0) {
            return res.status(404).json({ message: 'Salary not found' });
        }
        
        res.json(salaries[0]);
    } catch (error) {
        console.error('Get salary error:', error);
        res.status(500).json({ message: 'Failed to fetch salary', error: error.message });
    }
};

const updateSalary = async (req, res) => {
    const { id } = req.params;
    const { grossSalary, totalDeduction, netSalary, month } = req.body;
    
    try {
        const [result] = await pool.execute(
            'UPDATE salary SET grossSalary = ?, totalDeduction = ?, netSalary = ?, month = ? WHERE salaryID = ?',
            [grossSalary, totalDeduction, netSalary, month, id]
        );
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Salary not found' });
        }
        
        res.json({ message: 'Salary updated successfully' });
    } catch (error) {
        console.error('Update salary error:', error);
        res.status(500).json({ message: 'Failed to update salary', error: error.message });
    }
};

const deleteSalary = async (req, res) => {
    const { id } = req.params;
    
    try {
        const [departments] = await pool.execute('SELECT * FROM department WHERE salaryID = ?', [id]);
        if (departments.length > 0) {
            return res.status(400).json({ message: 'Cannot delete salary as it is linked to a department' });
        }

        const [employees] = await pool.execute('SELECT * FROM employee WHERE salaryID = ?', [id]);
        if (employees.length > 0) {
            return res.status(400).json({ message: 'Cannot delete salary as it is linked to an employee' });
        }
        
        const [result] = await pool.execute('DELETE FROM salary WHERE salaryID = ?', [id]);
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Salary not found' });
        }
        
        res.json({ message: 'Salary deleted successfully' });
    } catch (error) {
        console.error('Delete salary error:', error);
        res.status(500).json({ message: 'Failed to delete salary', error: error.message });
    }
};

module.exports = { createSalary, getAllSalaries, getSalaryById, updateSalary, deleteSalary };