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/teacher/"); // ✅ 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 add = async(req, res, next)=>{
    const image = req.file ? req.file.filename : null;
    try{
        const {name, dob, gendar, relagion, bgroup, fname, mname, address, e_experience, contactno, randid, status, join_date} = req.body;
        const check = `SELECT * FROM teachers WHERE contactno = ?`;
        const create = `INSERT INTO teachers (name, image, dob, gendar, relagion, bgroup, fname, mname, address, e_experience, contactno, randid, join_date, status)
        VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)`;
        db.query(check, [contactno], (checkerr, resscheck)=>{
            if(resscheck.length > 0){
                return res.status(400).json({message:'Teacher record is already exits!'})
            }
            db.query(create, [name, image, dob, gendar, relagion, bgroup, fname, mname, address, e_experience, contactno, randid, join_date, status], (err,result)=>{
                if(err){
                    return res.status(400).json({message:err})
                }
             res.status(200).json({message:'Save record.'})
            });
        })
    }catch(err){
        next(err)
    }
}

const application = async(req, res, next)=>{
    try{
        const get = `SELECT * FROM teachers WHERE status = 0`;
        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:'Teachers application 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/teacher', 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 for student ID ${teacher.id}:`, err.message);
                    return { ...teacher, imageBase64: null };
                }
                })
            );
            res.status(200).json({message:'Found records.', data:withImages})
        })
    }catch(err){
        next(err)
    }
}

const allteacher = async(req, res, next)=>{
    try{
        const get = `SELECT * FROM teachers WHERE status = 1`;
        // const get = `SELECT * FROM students`;
        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:'Teachers 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/teacher', 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 for student ID ${teacher.id}:`, err.message);
                    return { ...teacher, imageBase64: null };
                }
                })
            );
            res.status(200).json({message:'Found records.', data:withImages})
        })
    }catch(err){
        next(err)
    }
}

// Query -> Where -> id.
const whereteacher = async(req, res, next)=>{
    const studentid = req.userid;
    try{
        const get = `SELECT * FROM teachers WHERE id = ?`;
        db.query(get, [studentid],(err, result)=>{
            if(err) return res.status(400).json({message:'Get Request faild!'})
            if(result.length===0) return res.status(401).json({message:'Student data is empty!'})
            res.status(200).json({message:'Found record.', data:result})
        })
    }catch(err){
        next(err)
    }
}
// Delete users.
const deleteteacher = async(req, res, next)=>{
    const {uid} = req.body;
    try{
        const selectimage = `SELECT image FROM teachers WHERE id = ?`;
        const deletereq = `DELETE FROM teachers WHERE id =?`;
        // new
        db.query(selectimage, [uid], (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, [uid],(err, result)=>{
                    if(err) return res.status(400).json({message:'Delete Request faild!'})
                    res.status(200).json({message:'Deleted teacher record..'})
                })
            }else{
                 // unlink here.
            const filePath = path.join(__dirname, "../uploads/teacher/", img);
            fs.unlink(filePath, (err) => {
                if (err) {
                  console.error("Error deleting file:", err);
                } else {
                // complete step 4.
                db.query(deletereq, [uid],(err, result)=>{
                if(err) return res.status(400).json({message:'Delete Request faild!'})
                return res.status(200).json({message:'Deleted admission record..'})
                })
                }
              });
            }
        })
    }catch(err){
        next(err)
    }
}
// Update teacher.
const updateteacherstatus = async(req, res, next)=>{
    const {status, id} = req.body
    const update = `UPDATE teachers SET status = ? WHERE id = ?`;
    try {
        db.query(update, [status, id], (err,result)=>{
            if(err) return res.status(4000).json({message:err})
            res.status(200).json({message:'updated status.'})
        })
    } catch (error) {
        next(error)
    }
}
const updateteacher = async(req, res, next)=>{
    const {uid, name, oldimage, dob, gendar, relagion, bgroup, fname, mname, address, e_experience, contactno, randid, join_date} = req.body;
    try{
        const image = req.file ? req.file.filename : oldimage=='null' || oldimage==null ? null : oldimage;
        const updated = `UPDATE teachers SET name = ?, image = ?, dob = ?, gendar = ?, relagion = ?, bgroup = ?, fname = ?, mname = ?, address = ?, e_experience = ?, contactno = ?, randid = ?, join_date = ? WHERE id = ?`;
        console.log(image)
        if(req.file && oldimage){
            // unlink here.
            try{
                const filePath = path.join(__dirname, "../uploads/teacher/", oldimage);
                fs.unlink(filePath, (err) => {
                    if (err) {
                      console.error(" ");
                    }
                  });
            }catch(err){ console.log('unspected error!') }
        }
        db.query(updated, [name, image, dob, gendar, relagion, bgroup, fname, mname, address, e_experience, contactno, randid, join_date, uid],(err, result)=>{
            if(err) return res.status(400).json({message:'Update Request faild!'})
            res.status(200).json({message:'Updated teacher record..'})
        })
    }catch(err){
        next(err)
    }
}

// Datasheet
const countinfo = async(req, res, next)=>{
    try {
        // all student. male student. female student. other student. relagion student. other relagion student
        const gendarcount = `SELECT COUNT(id) AS allstudent FROM teachers WHERE gendar = ?`;
        const relagioncount = `SELECT COUNT(id) AS allstudent FROM teachers WHERE relagion = ?`;
        db.query(gendarcount, ['Male'], (err, result1)=>{
            db.query(gendarcount, ['Female'], (err, result2)=>{
                db.query(gendarcount, ['Other'], (err, result3)=>{
                    db.query(relagioncount, ['Islam'], (err, result4)=>{
                        const maledata = result1[0].allstudent;
                        const femaledata = result2[0].allstudent;
                        const othergendardata = result3[0].allstudent;
                        const allgendarstudent = parseInt(maledata)+parseInt(femaledata)+parseInt(othergendardata)
                        const islamstudent = result4[0].allstudent;
                        const otherrelagionstudent = allgendarstudent - parseInt(islamstudent);
                        const data = {
                            allstudent:allgendarstudent,
                            malestudent: maledata,
                            femalestudent: femaledata,
                            otherstudent: othergendardata,
                            rislamstudent: islamstudent,
                            rotherstudent: otherrelagionstudent
                        }
                        res.status(200).json({message:'Found records!', data:data})
                    });
                });
            });
        });
    } catch (error) {
        next(error)
    }
}

const datasheet = async(req, res, next)=>{
    try {
        // all student. male student. female student. other student. relagion student. other relagion student
        const gendarcount = `SELECT * FROM teachers WHERE gendar = ?`;
        const relagioncount = `SELECT * FROM teachers WHERE relagion = ?`;
        
        db.query(gendarcount, ['Male'], async(err, result1)=>{
            // step 1
            const withImages1 = await Promise.all(
                result1.map(async (teacher1) => {
                try {
                    if (!teacher1.image) {
                    return { ...teacher1, imageBase64: null };
                    }
                const imagePath = path.join(__dirname, '../uploads/teacher', teacher1.image); // <- adjust this path
                const imageBuffer = fs.readFileSync(imagePath);
                const base64 = imageBuffer.toString('base64');
                    return {
                    ...teacher1,
                    imageBase64: `data:image/jpeg;base64,${base64}`,
                    };
                } catch (err) {
                    return { ...teacher1, imageBase64: null };
                }
                })
            );
            // step 1
            db.query(gendarcount, ['Female'], async(err, result2)=>{
                // step 2
                const withImages2 = await Promise.all(
                    result2.map(async (teacher2) => {
                    try {
                        if (!teacher2.image) {
                        return { ...teacher2, imageBase64: null };
                        }
                    const imagePath = path.join(__dirname, '../uploads/teacher', teacher2?.image); // <- adjust this path
                    const imageBuffer = fs.readFileSync(imagePath);
                    const base64 = imageBuffer.toString('base64');
                        return {
                        ...teacher2,
                        imageBase64: `data:image/jpeg;base64,${base64}`,
                        };
                    } catch (err) {
                        return { ...teacher2, imageBase64: null };
                    }
                    })
                );
                db.query(gendarcount, ['Other'], async(err, result3)=>{
                // step 3
                const withImages3 = await Promise.all(
                    result3.map(async (teacher3) => {
                    try {
                        if (!teacher3.image) {
                        return { ...teacher3, imageBase64: null };
                        }
                    const imagePath = path.join(__dirname, '../uploads/teacher', teacher3?.image); // <- adjust this path
                    const imageBuffer = fs.readFileSync(imagePath);
                    const base64 = imageBuffer.toString('base64');
                        return {
                        ...teacher3,
                        imageBase64: `data:image/jpeg;base64,${base64}`,
                        };
                    } catch (err) {
                        return { ...teacher3, imageBase64: null };
                    }
                    })
                );
                    db.query(relagioncount, ['Islam'], (err, result4)=>{
                        const maledata = result1?.length || 0;
                        const femaledata = result2?.length || 0;
                        // assign withimage.
                        !result1 ? result1 = [] : result1 = withImages1
                        !result2 ? result2 = [] : result2 = withImages2
                        !result3 ? result3 = [] : result3 = withImages3
                        const allsdata = [...result1, ...result2, ...result3];

                        const othergendardata = result3?.length || 0;
                        const allgendarstudent = parseInt(maledata)+parseInt(femaledata)+parseInt(othergendardata)

                        const islamstudent = result4[0]?.allstudent || 0;
                        const otherrelagionstudent = allgendarstudent - parseInt(islamstudent);
                        const data = {
                            allsdata:allsdata,
                            allstudent:allgendarstudent,
                            malesdata:result1,
                            malestudent: maledata,
                            femalesdata:result2,
                            femalestudent: femaledata,
                            otherstudent: othergendardata,
                            rislamstudent: islamstudent,
                            rotherstudent: otherrelagionstudent
                        }
                        res.status(200).json({message:'Found records!', data:data})
                    });
                });
            });
        });
    } catch (error) {
        next(error)
    }
}

module.exports = {upload, application, add, allteacher, whereteacher, deleteteacher, updateteacherstatus, updateteacher, countinfo, datasheet}