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

// Get footer data from MongoDB
const getFooterData = async () => {
  const footer = await Footer.findOne({ name: "default" });

  if (!footer) {
    return {
      logo: {
        src: '',
        alt: ''
      },
      about: {
        title: "About GGC",
        description: "",
        mapLink: {
          text: "Check on google map",
          url: "",
        },
      },
      address: {
        text: "",
        address2: "",
        mapUrl: "",
      },
      contact: {
        phone: "",
        hours: "",
        email: "",
      },
      columns: [],
      social: {
        links: [],
      },
      copyright: {
        text: "",
      },
    };
  }

  return footer.toObject();
};

// API to get footer data
exports.api = async (req, res) => {
  try {
    // Lấy footer data
    const footer = await getFooterData();

    // Xử lý URL cho logo và các hình ảnh khác
    const processedData = addBaseUrlToImages(footer);

    res.json(processedData);
  } catch (err) {
    console.error("API Error:", err);
    res.status(500).json({ error: "Error loading footer data" });
  }
};

// API để lấy toàn bộ footer data
exports.getFooterData = async (req, res) => {
  try {
    const footerData = await getFooterData();
    const processed = addBaseUrlToImages(footerData);
    res.json(processed);
  } catch (error) {
    console.error("Error getting footer data:", error);
    res.status(500).json({ error: "Error loading footer data" });
  }
};

// Render admin view
exports.index = async (req, res) => {
  try {
    const data = await getFooterData();
    const frontendUrl = process.env.FRONTEND_URL || "http://localhost:3000";

    // Ensure image paths are absolute for admin preview
    const processedData = addBaseUrlToImages(data);

    res.render("admin/footer/index", {

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

// Cập nhật dữ liệu footer
exports.update = async (req, res) => {
  try {
    let footerData = req.body;
    if (footerData.footerJson) {
      try {
        footerData = JSON.parse(footerData.footerJson);
      } catch (err) {
        console.warn('Invalid footerJson payload, falling back to req.body');
      }
    }

    // Tìm footer hiện có hoặc tạo mới nếu không tồn tại
    let footer = await Footer.findOne({ name: "default" });

    if (!footer) {
      footer = new Footer({
        name: "default",
        about: footerData.about || {
          title: "About GGC",
          description: "",
          mapLink: { text: "Check on google map", url: "" },
        },
        address: footerData.address || {
          text: "",
          address2: "",
          mapUrl: "",
          link2: "",
        },
        contact: footerData.contact || { phone: "", hours: "", email: "" },
        columns: Array.isArray(footerData.columns) ? footerData.columns : [],
        social: footerData.social || { links: [] },
        copyright: footerData.copyright || { text: "" },
      });
    } else {
      // Cập nhật các trường
      if (footerData.about) {
        footer.about = {
          title: footerData.about.title || footer.about?.title || "About GGC",
          description: footerData.about.description || footer.about?.description || "",
          mapLink: {
            text: footerData.about.mapLink?.text || footer.about?.mapLink?.text || "Check on google map",
            url: footerData.about.mapLink?.url || footer.about?.mapLink?.url || ""
          }
        };
      }
      if (footerData.address) {
        // Đảm bảo address2 tồn tại để tránh undefined trong view/schema
        footer.address = {
          ...(footer.address?.toObject
            ? footer.address.toObject()
            : footer.address),
          ...footerData.address,
          address2:
            footerData.address.address2 !== undefined
              ? footerData.address.address2
              : footer.address?.address2 || "",
          link2:
            footerData.address.link2 !== undefined
              ? footerData.address.link2
              : footer.address?.link2 || "",
        };
      }
      if (footerData.contact) footer.contact = footerData.contact;
      if (Array.isArray(footerData.columns))
        footer.columns = footerData.columns;
      if (footerData.social && Array.isArray(footerData.social.links))
        footer.social = footerData.social;
      if (footerData.copyright && typeof footerData.copyright.text === "string")
        footer.copyright = footerData.copyright;
    }

    await footer.save();

    req.flash("success_msg", "Footer updated successfully");

    // Redirect back to the active tab
    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");
  }
};
