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

// CREATE employee - Insert operation
const createEmployee = async (req, res) => {
    const { fname, lname, position, address, telephone, gender, hireDate, deptCode, salaryID } = req.body;
    
    console.log('Creating employee:', { fname, lname, position, telephone, gender, hireDate, deptCode, salaryID });
    
    if (!fname || !lname || !position || !telephone || !gender || !hireDate || !deptCode || !salaryID) {
        return res.status(400).json({ message: 'All required fields must be filled' });
    }
    
    try {
        const [result] = await pool.execute(
            'INSERT INTO employee (fname, lname, position, address, telephone, gender, hireDate, deptCode, salaryID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [fname, lname, position, address || null, telephone, gender, hireDate, deptCode, salaryID]
        );
        
        console.log('Employee created with ID:', result.insertId);
        
        res.status(201).json({ 
            message: 'Employee created successfully',
            empID: result.insertId
        });
    } catch (error) {
        console.error('Create employee error:', error);
        res.status(500).json({ message: 'Failed to create employee: ' + error.message });
    }
};

// READ all employees - Fixed version
const getAllEmployees = async (req, res) => {
    try {
        console.log('Fetching all employees...');
        
        // First, check if tables exist and get employees
        const [employees] = await pool.execute(`
            SELECT 
                e.*,
                d.deptName,
                d.deptCode as departmentCode,
                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(`Found ${employees.length} employees`);
        res.json(employees);
        
    } catch (error) {
        console.error('Get all employees error:', error);
        
        // Try a simpler query if the first one fails
        try {
            console.log('Trying simpler query...');
            const [employees] = await pool.execute('SELECT * FROM employee');
            res.json(employees);
        } catch (simpleError) {
            console.error('Simple query also failed:', simpleError);
            res.status(500).json({ 
                message: 'Failed to fetch employees', 
                error: error.message,
                details: 'Check if employee table exists'
            });
        }
    }
};

// READ single employee
const getEmployeeById = async (req, res) => {
    const { id } = req.params;
    
    try {
        const [employees] = await pool.execute(`
            SELECT e.*, d.deptName, 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
            WHERE e.empID = ?
        `, [id]);
        
        if (employees.length === 0) {
            return res.status(404).json({ message: 'Employee not found' });
        }
        
        res.json(employees[0]);
    } catch (error) {
        console.error('Get employee error:', error);
        res.status(500).json({ message: 'Failed to fetch employee', error: error.message });
    }
};

// UPDATE employee
const updateEmployee = async (req, res) => {
    const { id } = req.params;
    const { fname, lname, position, address, telephone, gender, hireDate, deptCode, salaryID } = req.body;
    
    try {
        const [result] = await pool.execute(
            'UPDATE employee SET fname = ?, lname = ?, position = ?, address = ?, telephone = ?, gender = ?, hireDate = ?, deptCode = ?, salaryID = ? WHERE empID = ?',
            [fname, lname, position, address, telephone, gender, hireDate, deptCode, salaryID, id]
        );
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Employee not found' });
        }
        
        res.json({ message: 'Employee updated successfully' });
    } catch (error) {
        console.error('Update employee error:', error);
        res.status(500).json({ message: 'Failed to update employee', error: error.message });
    }
};

// DELETE employee
const deleteEmployee = async (req, res) => {
    const { id } = req.params;
    
    try {
        const [result] = await pool.execute('DELETE FROM employee WHERE empID = ?', [id]);
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Employee not found' });
        }
        
        res.json({ message: 'Employee deleted successfully' });
    } catch (error) {
        console.error('Delete employee error:', error);
        res.status(500).json({ message: 'Failed to delete employee', error: error.message });
    }
};

module.exports = { 
    createEmployee, 
    getAllEmployees, 
    getEmployeeById, 
    updateEmployee, 
    deleteEmployee 
};