const OtherInfo = require("../../models/OtherInfo");
const Faq = require("../../models/Faq");
const CmsSection = require("../../models/CmsSection");
const Image = require("../../models/Image");
const { removeFile } = require("../../utils/removeFile");
const Location = require("../../models/Location");

exports.cmsController = {
  updateContactDetails: async (req, res) => {
    try {
      const { telephone, email, whatsapp, location } = req.body;

      await OtherInfo.findOneAndUpdate(
        { type: "contact" },
        {
          data: { telephone, email, whatsapp, location },
        }
      );

      return res
        .status(200)
        .json({ success: true, msg: "Changes saved successfully!" });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  getContactDetails: async (req, res) => {
    try {
      const contactDetails = await OtherInfo.findOne({ type: "contact" });
      return res.status(200).json({
        success: true,
        msg: "Contact Details",
        data: { ...contactDetails.data },
      });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  updatePrivacyPolicy: async (req, res) => {
    try {
      const { data } = req.body;

      await OtherInfo.findOneAndUpdate(
        { type: "privacyPolicy" },
        {
          data,
        }
      );

      return res
        .status(200)
        .json({ success: true, msg: "Changes saved successfully!" });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  getPrivacyPolicy: async (req, res) => {
    try {
      const privacyPolicy = await OtherInfo.findOne({ type: "privacyPolicy" });
      return res.status(200).json({
        success: true,
        msg: "Privacy Policy",
        data: privacyPolicy.data,
      });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  updateTermsNConditions: async (req, res) => {
    try {
      const { data } = req.body;

      await OtherInfo.findOneAndUpdate(
        { type: "terms&Conditions" },
        {
          data,
        }
      );

      return res
        .status(200)
        .json({ success: true, msg: "Changes saved successfully!" });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  getTermsNConditions: async (req, res) => {
    try {
      const termsNConditions = await OtherInfo.findOne({
        type: "terms&Conditions",
      });
      return res.status(200).json({
        success: true,
        msg: "Term & Conditions",
        data: termsNConditions.data,
      });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  addFaq: async (req, res) => {
    try {
      const { heading, paragraph } = req.body;

      const faq = new Faq({
        heading,
        paragraph,
      });

      await faq.save();

      return res
        .status(200)
        .json({ success: true, msg: "Faq added successfully!" });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  updateFaq: async (req, res) => {
    try {
      const { id, heading, paragraph } = req.body;

      await Faq.findByIdAndUpdate(id, {
        heading,
        paragraph,
      });

      return res
        .status(200)
        .json({ success: true, msg: "Faq updated successfully!" });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  deleteFaq: async (req, res) => {
    try {
      const { id } = req.body;

      const faq = await Faq.findByIdAndDelete(id);

      if (!faq) {
        return res.status(404).json({
          success: false,
          msg: "Not Found!",
        });
      }

      return res.status(200).json({
        success: true,
        msg: "Faq deleted successfully!",
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  getFaqDetails: async (req, res) => {
    try {
      const { id } = req.query;

      const faq = await Faq.findById(id).select("_id heading paragraph");

      if (!faq) {
        return res.status(404).json({
          success: false,
          msg: "Not Found!",
        });
      }

      return res.status(200).json({
        success: true,
        msg: "Faq",
        data: faq,
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  getAllFaqs: async (req, res) => {
    try {
      const faqs = await Faq.find().select("_id heading paragraph");

      return res.status(200).json({
        success: true,
        msg: "Faq",
        data: faqs,
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  addSection: async (req, res) => {
    try {
      const { heading, paragraph, page, sectionName, type } = req.body;
      const { file } = req;
      const hostname = req.hostname;
      let image;

      if (file && type === "img") {
        const imgUrl = `${hostname}/images/${file?.filename}`;

        image = new Image({
          fileName: file?.filename,
          url: imgUrl,
        });

        await image.save();
      }

      const imgData = image
        ? {
            id: image?._id,
            fileName: image?.fileName,
            url: image?.url,
          }
        : {};

      const section = new CmsSection({
        heading,
        paragraph,
        page,
        sectionName,
        type,
        img: imgData,
      });

      await section.save();

      return res
        .status(200)
        .json({ success: true, msg: "Section added successfully!" });
    } catch (err) {
      // console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!", err });
    }
  },
  updateSection: async (req, res) => {
    try {
      const { id, heading, paragraph, page, sectionName, type } = req.body;
      const { file } = req;
      const hostname = req.hostname;

      const section = await CmsSection.findById(id);

      if (file && section?.img && type === "img") {
        const path = `public/images/${section?.img?.fileName}`;
        removeFile(path);

        await Image.findByIdAndDelete(section?.img?.id);
      }

      let image = section.img || {};

      if (file && type === "img") {
        const imgUrl = `${hostname}/images/${file?.filename}`;

        image = new Image({
          fileName: file?.filename,
          url: imgUrl,
        });

        await image.save();
      }

      const imgData = image
        ? {
            id: image?._id,
            fileName: image?.fileName,
            url: image?.url,
          }
        : {};

      section.sectionName = sectionName;
      section.heading = heading;
      section.paragraph = paragraph;
      section.page = page;
      section.type = type;
      section.img = imgData;

      await section.save();

      return res
        .status(200)
        .json({ success: true, msg: "Changes saved successfully!" });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!", err });
    }
  },
  deleteSection: async (req, res) => {
    try {
      const { id } = req.body;

      const section = await CmsSection.findByIdAndDelete(id);

      if (!section) {
        return res.status(404).json({ success: false, msg: "Not Found!" });
      }

      if (section?.img && section?.type === "img") {
        const path = `public/images/${section?.img?.fileName}`;
        removeFile(path);

        await Image.findByIdAndDelete(section?.img?.id);
      }

      return res
        .status(200)
        .json({ success: true, msg: "Section deleted successfully!" });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!", err });
    }
  },
  getSections: async (req, res) => {
    try {
      const { page } = req.query;

      const sections = await CmsSection.find({ page });

      return res
        .status(200)
        .json({ success: true, msg: "Sections", data: sections });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  getSectionDetails: async (req, res) => {
    try {
      const { id } = req.query;

      const section = await CmsSection.findById(id);

      return res
        .status(200)
        .json({ success: true, msg: "Sections", data: section });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  addLocation: async (req, res) => {
    try {
      const {
        imgCaptions,
        heading,
        subHeading,
        name,
        keyFacts,
        interests,
        oppurtunityText,
      } = req.body;

      const imagesWithCaptions = imgCaptions?.map((item, index) => {
        return {
          img: {
            id: "",
            url: "",
          },
          caption: item,
        };
      });

      const location = new Location({
        images: imagesWithCaptions,
        heading,
        subHeading,
        name,
        keyFacts,
        interests,
        oppurtunityText,
      });

      await location.save();

      return res.status(200).json({
        success: true,
        msg: "Location added successfully!",
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  addLocationImages: async (req, res) => {
    try {
      const { id } = req.body;

      const { hostname } = req;
      const { files } = req;

      const location = await Location.findById(id);

      if (!location) {
        return res.status(404).json({ success: false, msg: "Not found!" });
      }

      const images = files?.map((item, index) => {
        return {
          fileName: item?.filename,
          url: `${hostname}/images/${item?.filename}`,
        };
      });

      const uploadedImages = await Image.insertMany(images);

      const imagesOfCaptions = uploadedImages?.map((img, index) => {
        return {
          id: img?._id,
          url: img?.url,
        };
      });

      for (let i = 0; i < imagesOfCaptions?.length; i++) {
        location.images[i] = {
          ...location.images[i],
          img: imagesOfCaptions[i],
        };
      }

      await location.save();

      return res.status(200).json({
        success: true,
        msg: "Location added successfully!",
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  updateLocation: async (req, res) => {
    try {
      const {
        id,
        imgCaptions,
        heading,
        subHeading,
        name,
        keyFacts,
        interests,
        oppurtunityText,
      } = req.body;

      const imagesWithCaptions = imgCaptions?.map((item, index) => {
        return {
          img: {
            id: "",
            url: "",
          },
          caption: item,
        };
      });

      await Location.findByIdAndUpdate(id, {
        images: imagesWithCaptions,
        heading,
        subHeading,
        name,
        keyFacts,
        interests,
        oppurtunityText,
      });

      return res.status(200).json({
        success: true,
        msg: "Location added successfully!",
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  updateLocationImages: async (req, res) => {
    try {
      const { id } = req.body;

      const { hostname } = req;
      const { files } = req;

      const location = await Location.findById(id);

      if (!location) {
        return res.status(404).json({ success: false, msg: "Not found!" });
      }

      const images = files?.map((item, index) => {
        return {
          fileName: item?.filename,
          url: `${hostname}/images/${item?.filename}`,
        };
      });

      const uploadedImages = await Image.insertMany(images);

      const imagesOfCaptions = uploadedImages?.map((img, index) => {
        return {
          id: img?._id,
          url: img?.url,
        };
      });

      for (let i = 0; i < imagesOfCaptions?.length; i++) {
        location.images[i] = {
          ...location.images[i],
          img: imagesOfCaptions[i],
        };
      }

      await location.save();

      return res.status(200).json({
        success: true,
        msg: "Location added successfully!",
      });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
};
