const express = require('express');
const db = require('./db'); // Emeza ko iyi db.js yawe ikoresha mysql2/promise
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cors());

const SECRET_KEY = "smartpark_secret_2026";

// --- 1. AUTHENTICATION ---
app.post('/api/login', async (req, res) => {
    const { Email, Password } = req.body;
    
    console.log("Login Attempt:", Email, Password); 

    try {
        // Gushaka umukoresha ufite iyo Email
        const [users] = await db.query("SELECT * FROM users WHERE Email = ?", [Email]);
        
        if (users.length === 0) {
            return res.status(400).json({ message: "User not found" });
        }

        // Gukosora logic ya password:
        // Twakura ya "!" kuko yari iteye ikibazo
        if (Password !== users[0].Password) {
            return res.status(400).json({ message: "Invalid password" });
        }

        const token = jwt.sign({ id: users[0].UserID }, SECRET_KEY, { expiresIn: '1h' });
        res.json({ token, message: "Login Successful" });
    } catch (err) { 
        console.error("Database Error:", err);
        res.status(500).json({ error: err.message }); 
    }
});
// --- 2. OPERATIONS: Employee & Department ---
app.post('/api/employee', async (req, res) => {
    try {
        const { employeeNumber, FirstName, LastName, Position, Address, Telephone, Gender, hiredDate, DepartementCode } = req.body;
        await db.query("INSERT INTO Employee VALUES (?,?,?,?,?,?,?,?,?)", 
            [employeeNumber, FirstName, LastName, Position, Address, Telephone, Gender, hiredDate, DepartementCode]);
        res.status(201).json({ message: "Employee added successfully" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

app.get('/api/department', async (req, res) => {
    try {
        const [rows] = await db.query("SELECT * FROM Department");
        res.json(rows);
    } catch (err) { res.status(500).json({ error: err.message }); }
});

app.post('/api/department', async (req, res) => {
    try {
        // 1. Twongereyeho TotalDeduction mu kwakira amakuru (destructuring)
        const { DepartementCode, DepartementName, GrossSalary, TotalDeduction } = req.body;

        // 2. SQL Query igomba kuba ifite inkingi 4
        // Ni byiza kwandika inkingi ku mugaragaro kugira ngo wirinde amakosa
        const sql = "INSERT INTO Department (DepartementCode, DepartementName, GrossSalary, TotalDeduction) VALUES (?, ?, ?, ?)";
        
        await db.query(sql, [DepartementCode, DepartementName, GrossSalary, TotalDeduction]);
        
        res.status(201).json({ message: "Department added successfully" });
    } catch (err) { 
        res.status(500).json({ error: err.message }); 
    }
});
app.post('/api/salary', async (req, res) => {
    try {
        const { employeeNumber, GlossSalary, TotalDeduction, NetSalary, month } = req.body;
        // Twongeramo CURRENT_DATE kugira ngo Reports zibone itariki
        await db.query(
            "INSERT INTO Salary (employeeNumber, GlossSalary, TotalDeduction, NetSalary, month, transactionDate) VALUES (?,?,?,?,?, CURRENT_DATE)", 
            [employeeNumber, GlossSalary, TotalDeduction, NetSalary, month]
        );
        res.status(201).json({ message: "Salary added successfully" });
    } catch (err) { 
        res.status(500).json({ error: err.message }); 
    }
});

// --- 3. SALARY MANAGEMENT ---
app.get('/api/salary', async (req, res) => {
    const [rows] = await db.query("SELECT * FROM Salary");
    res.json(rows);
});

// CREATE
app.post('/api/salary', async (req, res) => {
    const { employeeNumber, GlossSalary, TotalDeduction, NetSalary, month } = req.body;
    await db.query("INSERT INTO Salary (employeeNumber, GlossSalary, TotalDeduction, NetSalary, month) VALUES (?,?,?,?,?)", 
    [employeeNumber, GlossSalary, TotalDeduction, NetSalary, month]);
    res.status(201).json({ message: "Added" });
});

// UPDATE
app.put('/api/salary/:id', async (req, res) => {
    const { employeeNumber, GlossSalary, TotalDeduction, NetSalary, month } = req.body;
    const SalaryID = req.params.id; // Iyi ID iva muri URL
    
    await db.query(
        "UPDATE Salary SET employeeNumber=?, GlossSalary=?, TotalDeduction=?, NetSalary=?, month=? WHERE SalaryID=?", 
        [employeeNumber, GlossSalary, TotalDeduction, NetSalary, month, SalaryID]
    );
    res.json({ message: "Updated successfully" });
});

// DELETE
app.delete('/api/salary/:id', async (req, res) => {
    const SalaryID = req.params.id;
    await db.query("DELETE FROM Salary WHERE SalaryID=?", [SalaryID]);
    res.json({ message: "Deleted successfully" });
});
app.post('/api/employee', async (req, res) => {
    try {
        const { employeeNumber, FirstName, LastName, Position, Address, Telephone, Gender, hiredDate, DepartementCode } = req.body;
        
        // REBA HANO: Ongera uyu murongo
        console.log("Data received from frontend:", req.body); 

        await db.query("INSERT INTO Employee VALUES (?,?,?,?,?,?,?,?,?)", 
            [employeeNumber, FirstName, LastName, Position, Address, Telephone, Gender, hiredDate, DepartementCode]);
        
        res.status(201).json({ message: "Employee added successfully" });
    } catch (err) { 
        console.error("Database Error:", err); // Ibi bizaguha impamvu nyayo ya 500
        res.status(500).json({ error: err.message }); 
    }
});
app.get('/api/employee', async (req, res) => {
    try {
        const [rows] = await db.query("SELECT employeeNumber, FirstName, LastName FROM Employee");
        res.json(rows);
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// --- 4. REPORTS ---
// Hano ni API yo gufata Salary list yuzuye ifite amazina y'abakozi
app.get('/api/reports', async (req, res) => {
    try {
        const sql = `
            SELECT 
                e.FirstName, e.LastName, 
                d.DepartementName, 
                s.GlossSalary, s.TotalDeduction, s.NetSalary, s.month 
            FROM salary s
            JOIN employee e ON s.employeeNumber = e.employeeNumber
            JOIN department d ON e.DepartementCode = d.DepartementCode
        `;
        const [rows] = await db.query(sql);
        res.json(rows);
    } catch (err) {
        console.error("Database Error:", err);
        res.status(500).json({ error: err.message });
    }
});
app.listen(5000, () => console.log("Server running on http://localhost:5000"));