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

// import controller function

// Set up Multer storage (optional, saves file with original name)
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, "uploads/commitee/"); // ✅ 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 });

const create = async(req, res, next)=>{
    const image = req.file ? req.file.filename : null;  
    try{
        const {name, phone, occupation, education, email, join_date} = req.body;
        const check = `SELECT * FROM committee WHERE phone = ?`;
        const create = `INSERT INTO committee (name, image, phone, occupation, education, email, join_date)
        VALUES( ?, ?, ?, ?, ?, ?, ?)`;
        db.query(check, [phone], (checkerr, resscheck)=>{
            if(resscheck.length > 0){
                return res.status(400).json({message:'Instructor record is already exits!'})
            }
            db.query(create, [name, image, phone, occupation, education, email, join_date], (err,result)=>{
                if(err){
                    return res.status(400).json({message:err})
                }
             res.status(201).json({message:'Save record.'})
            });
        })
    }catch(err){
        next(err)
    }
}

const get = async(req, res, next)=>{
    try{
        const get = `SELECT * FROM committee`;
        db.query(get, async(err, result)=>{
            if(err) return res.status(400).json({message:'Get Request faild!'})
            if(result.length===0) return res.status(401).json({message:'Commitee data is empty!'})
            const withImages = await Promise.all(
                result.map(async (teacher) => {
                try {
                    if (!teacher.image) {
                    return { ...teacher, imageBase64: null };
                    }
                const imagePath = path.join(__dirname, '../uploads/commitee', teacher.image); // <- adjust this path
                const imageBuffer = fs.readFileSync(imagePath);
                const base64 = imageBuffer.toString('base64');
                    return {
                    ...teacher,
                    imageBase64: `data:image/jpeg;base64,${base64}`,
                    };
                } catch (err) {
                    console.error(`Failed to load image ID ${teacher.id}:`, err.message);
                    return { ...teacher, imageBase64: null };
                }
                })
            );
            res.status(200).json({message:'Found records.', data:withImages})
        })
    }catch(err){
        next(err)
    }
}


const deleted = async(req, res, next)=>{
    const id = req.params?.id;
    try{
        const selectimage = `SELECT image FROM committee WHERE id = ?`;
        const deletereq = `DELETE FROM committee WHERE id =?`;
        // new
        db.query(selectimage, [id], (err2, result2)=>{
            if(err2) return res.status(400).json({message:err2})
            const img = result2[0]?.image ? result2[0].image : null
            if(!img || img==null || img==''){
                db.query(deletereq, [id],(err, result)=>{
                    if(err) return res.status(400).json({message:'Delete Request faild!'})
                    res.status(200).json({message:'Deleted instructor record..'})
                })
            }else{
                 // unlink here.
            const filePath = path.join(__dirname, "../uploads/commitee/", img);
            fs.unlink(filePath, (err) => {
                if (err) {
                  console.error("Error deleting file:", err);
                } else {
                // complete step 4.
                db.query(deletereq, [id],(err, result)=>{
                if(err) return res.status(400).json({message:'Delete Request faild!'})
                return res.status(200).json({message:'Deleted member record..'})
                })
                }
              });
            }
        })
    }catch(err){
        next(err)
    }
}

const update = async(req, res, next)=>{
    const {id, name, oldimage, phone, occupation, education, email, join_date} = req.body;
    try{
        const image = req.file ? req.file.filename : oldimage=='null' || oldimage==null ? null : oldimage;
        const updated = `UPDATE committee SET name = ?, image = ?, phone = ?, occupation = ?, education = ?, email = ?, join_date = ? WHERE id = ?`;
        console.log(image)
        if(req.file && oldimage){
            // unlink here.
            try{
                const filePath = path.join(__dirname, "../uploads/commitee/", oldimage);
                fs.unlink(filePath, (err) => {
                    if (err) {
                      console.error(" ");
                    }
                  });
            }catch(err){ console.log('unspected error!') }
        }
        db.query(updated, [name, image, phone, occupation, education, email, join_date, id],(err, result)=>{
            if(err) return res.status(400).json({message:'Update Request faild!'})
            res.status(200).json({message:'Updated instructor record..'})
        })
    }catch(err){
        next(err)
    }
}


module.exports = {upload, create, deleted, update, get}