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

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, "uploads/theme/"); // ✅ 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 });

function query(sql, params) {
    return new Promise((resolve, reject) => {
        db.query(sql, params, (err, results) => {
            if (err) return reject(err);
            resolve(results);
        });
    });
}

const get = async(req, res, next)=>{
    try {
        const sql = `SELECT * FROM theme`;
        const committesql = `SELECT * FROM committee`;
        const instructorsql = `SELECT * FROM instructors`;
        const limitgallery = `SELECT image FROM gallery WHERE type = 0 ORDER BY createat DESC LIMIT 6`;
        const limitnotice = `SELECT * FROM notices WHERE type !=4 AND status = 1 ORDER BY createat DESC LIMIT 6`;
        const scrollnotice = `SELECT * FROM notices WHERE type = 4 AND status = 1 ORDER BY createat DESC LIMIT 6`;
        const gallerysql = `SELECT image FROM gallery WHERE type = 0 ORDER BY createat DESC`;
        const noticessql = `SELECT * FROM notices WHERE type !=4 AND status = 1 ORDER BY createat DESC`;
        const classsql = `SELECT id, name FROM classes`;
        const sessionsql = `SELECT id, session FROM session`;
        const departmentsql = `SELECT id, name FROM departments`;

        const classd = await query(classsql)
        const session = await query(sessionsql)
        const department = await query(departmentsql)

        const theme = await query(sql)
        const instructor = await query(instructorsql)
        const committee = await query(committesql)
        const gallerylimit = await query(limitgallery)
        const noticelimit = await query(limitnotice)
        const noticescroll = await query(scrollnotice)
        const notices = await query(noticessql)
        const gallery = await query(gallerysql)

         res.status(200).json({message:'all right.', 
            theme:theme[0], instructor:instructor, committee:committee, limitgallery:gallerylimit,
         limitnotice:noticelimit, scrollnotice:noticescroll, notices:notices, gallery:gallery, classd:classd, session:session, department:department})
    } catch (error) {
        next(error)
    }
}

const update = async(req, res, next)=>{
    const id = 1;
    const {about_text, showcase_image, contact_no, map_url, fb_page_url} = req.body
    const newshowcase_image = req.file ? req.file?.filename : showcase_image
    const sql = `UPDATE theme SET about_text = ?, showcase_image = ?, contact_no = ?, map_url = ?, fb_page_url = ? WHERE id = ?`;
    try {
        if(req.file){
            // unlink here.
            try{
                const filePath = path.join(__dirname, "../uploads/theme/", showcase_image);
                fs.unlink(filePath, (err) => {
                    if (err) {
                      console.error(" ");
                    }
                  });
            }catch(err){ console.log('unspected error!') }
        }
        db.query(sql, [about_text, newshowcase_image, contact_no, map_url, fb_page_url, id], (err, result)=>{
            if(err) return res.status(400).json({message:err})
            res.status(200).json({message:'updated theme information.'})
        })
    } catch (error) {
        next(error)
    }
}

module.exports = {get, update, upload}