const Footer = require("../models/footer"); const { addBaseUrlToImages } = require("../utils/imageHelper"); // Helpers const getFooterDoc = async () => Footer.findOne().sort({ updatedAt: -1 }); const getFooterData = async () => (await getFooterDoc())?.toObject() || {}; const getDefaultFooterData = () => ({ brand: { logo: { image: "", href: "/", }, description: "", social: [], }, explore: { heading: "", links: [], }, contact: { heading: "", address: "", phone: "", email: "", }, newsletter: { heading: "", description: "", placeholder: "", buttonText: "", }, bottom: { copyright: "", links: [], }, }); // Admin: render management view with data from MongoDB exports.index = async (req, res) => { try { let data = await getFooterData(); const defaults = getDefaultFooterData(); // Merge defaults for any missing sections const sections = Object.keys(defaults); sections.forEach((s) => { data[s] = data[s] || defaults[s]; }); return res.render("admin/footer/index", { layout: "layouts/main", title: "Footer Management", data, currentPath: req.path, user: req.session.user, }); } catch (err) { console.error("Footer index error:", err); req.flash("error_msg", "Error loading footer data"); return req.session.save(() => res.redirect("/admin/dashboard")); } }; // Admin: parse req.body sections and save to MongoDB exports.update = async (req, res) => { try { const sections = ["brand", "explore", "contact", "newsletter", "bottom"]; let doc = await getFooterDoc(); if (!doc) { doc = new Footer({}); } let hasChanges = false; for (const section of sections) { if (req.body[section]) { try { const payload = JSON.parse(req.body[section]); doc[section] = payload; doc.markModified(section); hasChanges = true; } catch (e) { console.error(`Invalid JSON for ${section}:`, e.message); } } } if (!hasChanges) { req.flash("info_msg", "No changes were made"); return req.session.save(() => res.redirect("/admin/footer")); } await doc.save(); req.flash("success_msg", "Footer configuration has been updated!"); return req.session.save(() => res.redirect("/admin/footer")); } catch (err) { console.error("Footer update error:", err); req.flash("error_msg", `Update error: ${err.message}`); return req.session.save(() => res.redirect("/admin/footer")); } }; // Public API: return JSON data for frontend exports.api = async (req, res) => { try { let data = await getFooterData(); if (!data || Object.keys(data).length === 0) { data = getDefaultFooterData(); } const baseUrl = process.env.BACKEND_URL || `${req.protocol}://${req.get("host")}`; return res.json(addBaseUrlToImages(data, baseUrl)); } catch (err) { console.error("Footer API error:", err); return res.status(500).json({ error: "Error loading footer data" }); } }; // Aliases for routes/index.js compatibility exports.getFooter = exports.api; exports.updateFooter = exports.update;