const { addBaseUrlToImages } = require("../utils/imageHelper");
const Footer = require("../models/footer");

// GET /api/footer - Public API cho website và CMS load dữ liệu
exports.getFooter = async (req, res) => {
    try {
        const footer = await Footer.getSingle();
        const processedData = addBaseUrlToImages(footer.toObject());

        res.json(processedData);
    } catch (error) {
        console.error("Error getting footer:", error);
        res.status(500).json({
            error: "Failed to get footer data",
        });
    }
};

// PUT /api/admin/footer - Update toàn bộ footer cho CMS
exports.updateFooter = async (req, res) => {
    try {
        let updateData = req.body;

        console.log("=== FOOTER UPDATE REQUEST RECEIVED ===");
        console.log("Raw body:", JSON.stringify(req.body, null, 2));

        // Nếu có footerJson, parse nó (tương tự Header logic)
        if (updateData.footerJson && typeof updateData.footerJson === "string") {
            try {
                const parsedData = JSON.parse(updateData.footerJson);
                console.log("✓ Parsed footerJson successfully:", parsedData);
                updateData = parsedData;
            } catch (e) {
                console.error("✗ Error parsing footerJson:", e.message);
                return res.status(400).json({
                    success: false,
                    message: "Invalid JSON in footerJson: " + e.message,
                });
            }
        }

        // Lấy footer hiện tại hoặc tạo mới (giống Header logic)
        let footer = await Footer.findOne();

        if (!footer) {
            console.log("No existing footer found, creating new one");
            footer = new Footer(updateData);
            await footer.save();
            console.log("✓ Footer created:", footer._id);
        } else {
            console.log("✓ Found existing footer:", footer._id);
            // Merge với dữ liệu cũ thay vì overwrite (giống Header)
            Object.assign(footer, updateData);
            await footer.save();
            console.log("✓ Footer updated successfully");
        }

        const processedData = addBaseUrlToImages(footer.toObject());

        console.log("Updated footer data:", JSON.stringify(processedData, null, 2));

        res.json({
            success: true,
            message: "Footer updated successfully",
            data: processedData,
        });
    } catch (error) {
        console.error("✗ Error updating footer:", error);
        res.status(500).json({
            success: false,
            error: "Failed to update footer: " + error.message,
        });
    }
};

// Render admin view (giữ lại cho UI hiện tại)
exports.index = async (req, res) => {
    try {
        const data = await Footer.getSingle();
        const processedData = addBaseUrlToImages(data.toObject());

        res.render("admin/footer/index", {
            title: "Footer Management",
            data: processedData,
        });
    } catch (error) {
        console.error("Error in footer index:", error);
        req.flash("error_msg", "An error occurred while loading the page");
        res.redirect("/admin/dashboard");
    }
};

// Update method cho form hiện tại (giống Header pattern)
exports.update = async (req, res) => {
    try {
        let updateData = req.body;

        console.log("=== FOOTER FORM UPDATE REQUEST RECEIVED ===");
        console.log("Raw body:", JSON.stringify(req.body, null, 2));

        // Nếu có footerJson, parse nó (giống Header logic)
        if (updateData.footerJson && typeof updateData.footerJson === "string") {
            try {
                const parsedData = JSON.parse(updateData.footerJson);
                console.log("✓ Parsed footerJson successfully:", parsedData);
                updateData = parsedData;
            } catch (e) {
                console.error("✗ Error parsing footerJson:", e.message);
                req.flash("error_msg", "Invalid JSON in footerJson: " + e.message);
                return res.redirect("/admin/footer");
            }
        }

        // Lấy footer hiện tại hoặc tạo mới (giống Header)
        let footer = await Footer.findOne();

        if (!footer) {
            console.log("No existing footer found, creating new one");
            footer = new Footer(updateData);
            await footer.save();
            console.log("✓ Footer created:", footer._id);
            req.flash("success_msg", "Footer created successfully");
        } else {
            console.log("✓ Found existing footer:", footer._id);
            // Merge với dữ liệu cũ (giống Header)
            Object.assign(footer, updateData);
            await footer.save();
            console.log("✓ Footer updated successfully");
            req.flash("success_msg", "Footer updated successfully");
        }

        const activeTab = req.body.activeTab || "about";
        res.redirect(`/admin/footer?activeTab=${activeTab}`);
    } catch (err) {
        console.error("✗ Error updating footer:", err);
        req.flash("error_msg", err.message || "Error updating footer");
        res.redirect("/admin/footer");
    }
};

// Legacy API endpoints (giữ lại cho tương thích)
exports.api = exports.getFooter;
exports.getFooterData = exports.getFooter;
