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/gallery/"); // ✅ 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 gallery = async(req, res, next)=>{
    const sql = `SELECT * FROM gallery`;
    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 public_gallery = async(req, res, next)=>{
    const sql = `SELECT * FROM gallery WHERE type = 0`;
    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 web_slider = async(req, res, next)=>{
    const sql = `SELECT * FROM gallery WHERE type = 1`;
    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 gallery (title, image, type, status)
    VALUES(?,?,?,?) `;
    try {
          const {title, type, status} = req.body
            // prepare the data.
            const image = req.file ? req.file.filename : null;
            db.query(sql, [title, image, type, status], (err,result)=>{
                if(err) return res.status(400).json({message:err})
                res.status(200).json({ message: "image is uploaded..", id:result.insertId});  
            })
    } catch (error) {
        console.error(error)
    }

}

const deleted = async(req, res, next)=>{
    const id = req.params.id;
    const sql = `DELETE FROM gallery WHERE id = ?`;
    const find = `SELECT image FROM gallery WHERE id = ?`;
    try {
        db.query(find, [id], (err, result)=>{
            if(err) return res.status(400).json({message:err})
            const oldfile = result[0].image;
            // unlink here.
            const filePath = path.join(__dirname, "../uploads/gallery/", 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:'Image is unlinked and removed.'})
                })
                }
              });
        })
    } catch (error) {
        next(error)
    }
}

module.exports = {upload, web_slider, public_gallery, gallery, create, deleted}