const { success } = require("../../handlers");
const { Setting, Contact } = require("../../models");
const { getReqInformation } = require("../../utils/Common");

const index = async (req, res) => {
  let user = req.session?.user ?? {};
  let { baseUrl, endPoint } = getReqInformation(req);
  let successMessage = req.flash("success")[0];
  let errorMessage = req.flash("error")[0];
  let settings = await Setting.findAll({
    attributes: ["key", "value"],
    raw: true,
  });
  let finalSettings = {};
  settings.map((e) => {
    finalSettings[e.key] = e.value;
  });
  return res.render("contact/index.ejs", {
    baseUrl,
    endPoint,
    user,
    successMessage,
    errorMessage,
    setting: finalSettings,
    settings: finalSettings,
  });
};

const addContact = async (req, res) => {
  try {
    let payload = req.body;
    await Contact.create(payload);

    return success(res, {
      msg: "Contact details saved we will back to you!!",
    });
  } catch (err) {
    req.flash("error", "Something went wrong!!");
    return success(res, {
      status: false,
      msg: "Something went wrong!!",
    });
  }
};

module.exports = {
  index,
  addContact,
};
