const express = require('express');
const router = express.Router();
const db = require('../config/db');

// [CREATE] - Add a standard baseline salary matrix bracket row
router.post('', async (req, res) => {
    const { grosssalary, totaldeduction, month } = req.body;
    const netsalary = Number(grosssalary) - Number(totaldeduction);
    try {
        await db.query(
            'INSERT INTO salary (grosssalary, totaldeduction, netsalary, month) VALUES (?, ?, ?, ?)',
            [grosssalary, totaldeduction, netsalary, month]
        );
        res.status(201).json({ message: "Salary bracket tier formulated safely!" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [READ ALL] - Fetch baseline bracket tiers list layout
router.get('', async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM salary');
        res.json(rows);
    } catch (err) { res.status(500).json({ error: err.message }); }
});


// ==============================================================
// 🗓️ [NEW] FETCH DISTINCT MONTHS ACTUALLY PAID FROM DATABASE
// ==============================================================
router.get('/months/active', async (req, res) => {
    try {
        // Grab only the months that have records assigned to them in your system
        const [rows] = await db.query('SELECT DISTINCT month FROM salary ORDER BY month DESC');
        const monthsList = rows.map(r => r.month);
        
        // Always include the current real-world month as a default fallback option if the database is fresh
        const currentRealMonth = "May 2026"; 
        if (!monthsList.includes(currentRealMonth)) {
            monthsList.unshift(currentRealMonth);
        }
        
        res.json(monthsList);
    } catch (err) {
        console.error("❌ ERROR FETCHING DYNAMIC MONTHS:", err.message);
        res.status(500).json(["May 2026"]);
    }
});


// ==============================================================
// 📋 [READ FILTERED REPORT] - Get Payroll History By Specific Month
// ==============================================================
router.get('/report/:month', async (req, res) => {
    const targetMonth = req.params.month; // e.g., "May 2026"
    try {
        // Queries all employees alongside their computed compensation structures matching the target billing month cycle
        const [reportRows] = await db.query(`
            SELECT e.employeenumber, e.firstname, e.lastname, d.departmentname, 
                   s.grosssalary, s.totaldeduction, s.netsalary, s.month
            FROM employee e
            JOIN department d ON e.departmentnumber = d.departmentnumber
            JOIN salary s ON d.grosssalary = s.grosssalary
            WHERE s.month = ?
        `, [targetMonth]);

        res.json(reportRows);
    } catch (err) {
        console.error("❌ BACKEND MONTHLY REPORT ERROR:", err.message);
        res.status(500).json({ error: "Failed to compile monthly reporting data sheets." });
    }
});

// [UPDATE] - Alter an operational financial matrix bracket values row
router.put('/:gross', async (req, res) => {
    const { totaldeduction, month } = req.body;
    const netsalary = Number(req.params.gross) - Number(totaldeduction);
    try {
        await db.query(
            'UPDATE salary SET totaldeduction = ?, netsalary = ?, month = ? WHERE grosssalary = ?',
            [totaldeduction, netsalary, month, req.params.gross]
        );
        res.json({ message: "Salary matrix tier properties updated" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [DELETE] - Drop baseline matrix bracket row parameters
router.delete('/:gross', async (req, res) => {
    try {
        await db.query('DELETE FROM salary WHERE grosssalary = ?', [req.params.gross]);
        res.json({ message: "Salary baseline matrix row dropped cleanly" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// ==============================================================
// ⚡ [PROCESS DISBURSEMENT] - Set Month Dynamically on Payout
// ==============================================================
router.post('/pay', async (req, res) => {
    const { employeenumber, month } = req.body;
    
    if (!month) {
        return res.status(400).json({ error: "Please specify the payment month cycle." });
    }

    try {
        // 1. Fetch employee's current salary bracket link information
        const [details] = await db.query(`
            SELECT e.employeenumber, e.firstname, e.lastname, d.departmentname, s.grosssalary, s.totaldeduction, s.netsalary
            FROM employee e
            JOIN department d ON e.departmentnumber = d.departmentnumber
            JOIN salary s ON d.grosssalary = s.grosssalary
            WHERE e.employeenumber = ?
        `, [employeenumber]);

        if (details.length === 0) {
            return res.status(404).json({ error: "Staff profile has no valid assigned department or salary scale tier." });
        }

        const data = details[0];

        // 2. Dynamically update or verify this month's payroll record trace in your database 
        // This links the payment to the customized month typed or selected by the user
        await db.query(
            `UPDATE salary s
             JOIN department d ON d.grosssalary = s.grosssalary
             JOIN employee e ON e.departmentnumber = d.departmentnumber
             SET s.month = ?
             WHERE e.employeenumber = ?`,
            [month, employeenumber]
        );

        res.json({
            status: "PAID / VERIFIED",
            transactionId: `SP-${month.replace(/\s+/g, '').toUpperCase()}-${Math.floor(1000 + Math.random() * 9000)}`,
            dateOfIssue: new Date().toISOString().split('T')[0],
            billingMonth: month,
            employee: `${data.firstname} ${data.lastname}`,
            id: data.employeenumber,
            department: data.departmentname,
            breakdown: { gross: data.grosssalary, deductions: data.totaldeduction, netPayable: data.netsalary }
        });
    } catch (err) { 
        res.status(500).json({ error: "Financial engine runtime error", details: err.message }); 
    }
});

module.exports = router;