const catchAsync = require("../Utils/CatchAsync");
const Post = require("./../Models/post");
const User = require("./../Models/user");
const Category = require("./../Models/category");

const APIFeature = require("./../Utils/apiFeatures");
const AppError = require("../Utils/AppError");

exports.homePage = catchAsync(async (req, res) => {
  const date = Date.now();
  const doc = await Post.find({
    status: "public",
    publishedAt: { $lt: date },
  })
    .limit(3)
    .populate("author", "workfield name");

  return res.status(200).render("public/Home", {
    layout: "./layouts/mainLayoute",
    path: "home",
    title: "Content planet Agency",
    doc,
  });
});
exports.aboutUs = async(req, res) => {
   const date = Date.now();
    const doc = await Post.find({
    status: "public",
    publishedAt: { $lt: date },
  })
    .limit(3)
    .populate("author", "workfield name");

  return res.render("public/aboutUs", {
    layout: "./layouts/mainLayoute",
    path: "aboutus",
    title: "About Us",
     doc,
  });
};
exports.contactUs = (req, res) => {
  res.render("public/contactUs", {
    layout: "./layouts/mainLayoute",
    path: "contactus",
    title: "Contact Us",
  });
};

exports.content = (req, res) => {
  res.render("public/Content", {
    layout: "./layouts/mainLayoute",
    path: "content",
    title: "Content",
  });
};

exports.error404 = (req, res) => {
  res.status(404).json({ message: "page notfound" });
};

exports.post = catchAsync(async (req, res) => {
  let suggested = [];
  const doc = await Post.findOne({ slug: req.params.slug });
  if (!doc) return res.status(404).render("/errorPage");
  if (doc.relatedPosts) {
    doc.relatedPosts.map(async (el) => {
      const doc = await Post.findById(el).populate(
        "author",
        "workfield photo name"
      );
      suggested.push(doc);
    });
  }
  res.status(200).render("public/Post", {
    layout: "./layouts/mainLayoute",
    path: "post",
    doc,
    suggested,
    title: "Blog",
  });
});
exports.blog = catchAsync(async (req, res) => {
  const currentPage = parseInt(req.query.page, 10) || 1;
  const date = Date.now();

  const features = new APIFeature(
    Post.find({
      status: "public",
      publishedAt: { $lt: date },
    }).populate("author", "name workfield"),
    req.query
  ).paginate();

  const doc = await features.query.sort("-publishedAt");

  const suggested = await Post.findOne({
    status: "public",
    publishedAt: { $lt: date },
    promote: "true",
  }).populate("author", "name workfield photo");

  const countDocument = await Post.countDocuments({
    status: "public",
    publishedAt: { $lt: date },
  });

  const pages = Math.ceil(countDocument / 1); // Use real page size if needed

  res.status(200).render("public/Posts", {
    layout: "./layouts/mainLayoute",
    path: "blog",
    doc,
    pages,
    suggested: suggested || undefined,
    currentPage, // already a number
    title: "Content Planet blog",
  });
});


exports.search = async (req, res) => {
  const search = req.query.search || "";
  const category = req.query.category || "";
  //current baraye avalin page pagination estefade mishe inja va hich rabti be manaye current nadare
  var currentPage = req.query.page || 1;
  const date = Date.now();
  let queryObj = {};
  if (search) {
    if (req.query.category) {
      cconsole.log("cat");
      queryObj = {
        $and: [
          {
            $or: [
              { name: { $regex: `${search}` } },
              { description: { $regex: `${search}` } },
              { tags: { $regex: `${search}` } },
            ],
          },
          {
            status: "public",
            publishedAt: { $lt: date },
          },
          {
            category: category,
          },
        ],
      };
    } else {
      queryObj = {
        $and: [
          {
            $or: [
              { name: { $regex: `${search}` } },
              { title: { $regex: `${search}` } },
              { description: { $regex: `${search}` } },
              { tags: { $regex: `${search}` } },
            ],
          },
          {
            status: "public",
            publishedAt: { $lt: date },
          },
        ],
      };
    }
  }
  const features = new APIFeature(Post.find(queryObj), req.query)
    .limitFields()
    .paginate();

  const doc = await features.query.sort("-createdAt");

  const countDocument = await Post.find(queryObj).countDocuments();
  let pages = Math.ceil(countDocument / 9);

  if (currentPage > pages - 3 && pages > 4) currentPage = pages - 3;
  else if (pages < 4) currentPage = 1;

  res.status(200).render("public/Posts", {
    layout: "./layouts/mainLayoute",
    path: "blog",
    doc,
    suggested: undefined,
    pages,
    currentPage: currentPage * 1,
    category,
    title: "Content Planet",
  });
};

exports.category = async (req, res, next) => {
  var currentPage = req.query.page || 1;
  const regex = /\/([^\/]+)/g;
  const date = Date.now();
  console.log("hi");

  let match;
  const extractedValues = [];
  while ((match = regex.exec(req.url)) !== null) {
    extractedValues.push(match[1]);
  }
  console.log(extractedValues);
  if (extractedValues.length > 0) {
    const category = await Category.findOne({
      tree: extractedValues.toString(),
    });

    if (!category) return next(new AppError("Not Found", 404));

    const doc = await Post.find({
      status: "public",
      publishedAt: { $lt: date },
      category: { $regex: extractedValues.toString() },
    });

    const results = await Post.find({
      status: "public",
      publishedAt: { $lt: date },
      category: { $regex: extractedValues.toString() },
    }).countDocuments();

    const suggested = await Post.findOne({
      status: "public",
      publishedAt: { $lt: date },
      promote: "true",
      category: { $regex: extractedValues.toString() },
    });
    let pages = Math.ceil(results / 9);

    if (currentPage > pages - 3 && pages > 4) currentPage = pages - 3;
    else if (pages < 4) currentPage = 1;

    res.status(200).render("public/Posts", {
      layout: "./layouts/mainLayoute",
      path: "blog",
      doc,
      suggested,
      pages,
      currentPage: currentPage * 1,
      category,
      title: "Content Planet Blog",
    });
  } else {
    return next(new AppError("Not Found", 404));
  }
};

exports.catChecker = catchAsync(async (req, res, next) => {
  if (req.params.category) {
    const { category } = req.params;

    const result = await Category.exists({
      tree: { $regex: category, $options: "i" },
    });

    if (!result) {
      return next(new AppError("Not Found", 404));
    }
  }
  next();
});
