const db = require('../utils/db.js')
const multer = require('multer')
const path = require('path')
const fs = require("fs");


// Set up Multer storage (optional, saves file with original name)
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, "uploads/notice/"); // ✅ Save files in 'uploads/notice' folder
    },
    filename: (req, file, cb) => {
      cb(null, Date.now() + path.extname(file.originalname)); // Unique file name
    },
  });
  
  const upload = multer({ storage: storage });
  

// import controller function.

const notices = async(req, res, next)=>{
    const sql = `SELECT n.*,
    c.name AS class_name,
    s.name AS section_name,
    d.name AS department_name
    FROM notices n
    LEFT JOIN classes c ON n.classn = c.id
    LEFT JOIN sections s ON n.section = s.id
    LEFT JOIN departments d ON n.department = d.id
    ORDER BY n.createat`;
    try {
        db.query(sql, (err,result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length==0) return res.status(400).json({message:'empty notices!'})
            res.status(200).json({message:'notice found!', data:result})
        })
    } catch (error) {
        next(error)
    }
}

// public notice
const public_notices = async(req, res, next)=>{
    const sql = `SELECT n.*, 
    c.name AS class_name,
    s.name AS section_name,
    d.name AS department_name
    FROM notices n
    LEFT JOIN classes c ON n.classn = c.id
    LEFT JOIN sections s ON n.section = s.id
    LEFT JOIN departments d ON n.department = d.id
    WHERE n.type != 4 AND n.status = 1
    ORDER BY n.createat`;
    try {
        db.query(sql, (err,result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length==0) return res.status(400).json({message:'empty notices!'})
            res.status(200).json({message:'notice found!', data:result})
        })
    } catch (error) {
        next(error)
    }
}

// active notice
const hsc_notices = async(req, res, next)=>{
    const sql = `SELECT n.*,
    c.name AS class_name,
    s.name AS section_name,
    d.name AS department_name
    FROM notices n
    LEFT JOIN classes c ON n.classn = c.id
    LEFT JOIN sections s ON n.section = s.id
    LEFT JOIN departments d ON n.department = d.id
    WHERE n.type = 1 AND n.status = 1
    ORDER BY n.createat`;
    try {
        db.query(sql, (err,result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length==0) return res.status(400).json({message:'empty notices!'})
            res.status(200).json({message:'notice found!', data:result})
        })
    } catch (error) {
        next(error)
    }
}

const hons_notices = async(req, res, next)=>{
    const sql = `SELECT n.*,
    c.name AS class_name,
    s.name AS section_name,
    d.name AS department_name
    FROM notices n
    LEFT JOIN classes c ON n.classn = c.id
    LEFT JOIN sections s ON n.section = s.id
    LEFT JOIN departments d ON n.department = d.id
    WHERE n.type = 2 AND n.status = 1
    ORDER BY n.createat`;
    try {
        db.query(sql, (err,result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length==0) return res.status(400).json({message:'empty notices!'})
            res.status(200).json({message:'notice found!', data:result})
        })
    } catch (error) {
        next(error)
    }
}
const degree_notices = async(req, res, next)=>{
    const sql = `SELECT n.*,
    c.name AS class_name,
    s.name AS section_name,
    d.name AS department_name
    FROM notices n
    LEFT JOIN classes c ON n.classn = c.id
    LEFT JOIN sections s ON n.section = s.id
    LEFT JOIN departments d ON n.department = d.id
    WHERE n.type = 3 AND n.status = 1
    ORDER BY n.createat`;
    try {
        db.query(sql, (err,result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length==0) return res.status(400).json({message:'empty notices!'})
            res.status(200).json({message:'notice found!', data:result})
        })
    } catch (error) {
        next(error)
    }
}

const create = async(req, res)=>{
    const sql = `INSERT INTO notices (classn, section, department, title, attachment, publisheddate, type, status)
    VALUES(?,?,?,?,?,?,?,?) `;
    try {
          const {classn, section, department, title, publisheddate, type, status} = req.body
            // prepare the data.
            const document = req.file ? req.file.filename : null;
            db.query(sql, [classn, section, department, title, document, publisheddate, type, status], (err,result)=>{
                if(err) return res.status(400).json({message:err})
                res.status(200).json({ message: "Notice is created.", id:result.insertId});  
            })
    } catch (error) {
        console.error(error)
    }

}

const update = async(req, res)=>{
    const {id, classn, section, department, title, oldfilename, publisheddate, type, status} = req.body
    const sql = `UPDATE notices SET classn = ?, section = ?, department = ?, title = ?, attachment = ?, publisheddate = ?, type = ?, status = ? WHERE id = ? `;
    try {
            // prepare the data.
            if(req.file){
                console.log('New File come here..')
                const filePath = path.join(__dirname, "../uploads/notice/", oldfilename);
                fs.unlink(filePath, (err) => {
                    if (err) {
                      console.error("Error deleting file:", err);
                    } else {
                      console.log("File deleted successfully:", filePath);
                    }
                  });
            }
            const document = req.file ? req.file.filename : oldfilename;
            db.query(sql, [classn, section, department, title, document, publisheddate, type, status, id], (err, result)=>{
                if(err) return res.status(400).json({message:err})
                res.status(200).json({ message: "Notice is successfully updated." });
            })
    } catch (error) {
        console.error(error)
    }

}


const deleted = async(req, res, next)=>{
    const id = req.params.id;
    const sql = `DELETE FROM notices WHERE id = ?`;
    const find = `SELECT attachment FROM notices WHERE id = ?`;
    try {
        db.query(find, [id], (err, result)=>{
            if(err) return res.status(400).json({message:err})
            const oldfile = result[0].attachment;
            // unlink here.
            const filePath = path.join(__dirname, "../uploads/notice/", oldfile);
            fs.unlink(filePath, (err) => {
                if (err) {
                  console.error("Error deleting file:", err);
                } else {
                    // all right deleted record.
                db.query(sql, [id], (err2, result2)=>{
                if(err2) return res.status(400).json({message:err2})
                 res.status(203).json({message:'Notice is successfully removed.'})
                })
                }
              });
        })
    } catch (error) {
        next(error)
    }
}

module.exports = {upload, notices, create, update, deleted, public_notices, hsc_notices, hons_notices, degree_notices}