const express = require("express")
const router = express.Router()
const Content = require("../../schema/Content")
const multer = require('multer')
const path = require('path')
const fs = require('fs')
// const upload = multer({ dest: 'uploads/' })
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const dir = './public/uploads/';
const fullPath = path.resolve(dir);
console.log("fullPath", fullPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
cb(null, fullPath);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "" + Date.now() + Math.ceil(Math.random() * 999) + '.' + file.originalname.split('.')[1]);
}
});
const imageFilter = (req, file, cb) => {
console.log("file", file)
// only image files
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
cb(null, true);
} else {
cb(null, false);
}
};
const uploadImage = multer({ storage: storage, fileFilter: imageFilter });
router.post('/', uploadImage.single('image'), async (req, res) => {
try {
const imageFile = req.file;
const { id, title, heading, subheading, tagline, paragraph, listItem, linktext, linkhref } = req.body
let link;
if (linktext) {
link = {
text: linktext,
link: linkhref
}
}
// const content = await Content.create({ title, heading, subheading, tagline, paragraph, listItem, link, imageUrl })
const updateObject = {
title,
heading,
subheading,
tagline,
paragraph,
listItem,
link
};
// Add imageUrl to the update object only if it's not null
if (imageFile !== null && imageFile !== undefined) {
updateObject.imageUrl = `uploads/${imageFile?.filename}`;
}
Content.findByIdAndUpdate(id, updateObject, { new: true }, (err, updatedDocument) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Updated Document:', updatedDocument);
}
});
res.status(200).redirect('/admin/dashboard?message=Content Updated...')
// console.log("content", C)
} catch (error) {
console.log(error.message)
res.status(500).json({error: error.message})
}
})
module.exports = router