const { Sequelize, Op } = require("sequelize");
const noticeEmail = require("../../helpers/noticeEmail");
const Profile = require("../../../models").profiles;
const User = require("../../../models").users;
const Level = require("../../../models").levels;
const StudyMode = require("../../../models").study_modes;
const Department = require("../../../models").departments;
const Institute = require("../../../models").institutes;
const ActivityLog = require("../../../models").activity_log;
const CurrentSession = require("../../../models").sessions;
const ProjectSubmission = require("../../../models").project_submissions;
const ProjectTopic = require("../../../models").project_topics;


exports.schoolSettings = async (req, res) => {
    try {
      const session = await CurrentSession.findOne({
        where: { status: true },
        raw: true,
      });
  
      const totalStudentPromise = User.count({
        where: { role: 7, session_id: session.id },
      });
      const totalStaffPromise = User.count({ where: { role: { [Op.ne]: 7 },session_id: session.id  } });
      const totalDepartmentPromise = Department.count();
      const totalFacultyPromise = Institute.count();
      const totalTopicSubmittedPromise = ProjectTopic.count({where:{session_id: session.id }});
      const totalTopicApprovedPromise = ProjectTopic.count({
        where: { is_approved: true, active: true,session_id: session.id  },
      });
      const totalTopicRejectedPromise = ProjectTopic.count({
        where: { is_approved: false, active: false,session_id: session.id  },
      });
      const totalTopicPendingPromise = ProjectTopic.count({
        where: { is_approved: false, active: true, session_id: session.id  },
      });
      const totalResearchSubmittedPromise = ProjectSubmission.count({where:{session_id: session.id }});
      const totalResearchApprovedPromise = ProjectSubmission.count({
        where: { is_approved: true, active: true,session_id: session.id },
      });
      const totalResearchRejectedPromise = ProjectSubmission.count({
        where: { is_approved: false, active: false, session_id: session.id },
      });
      const totalResearchPendingPromise = ProjectSubmission.count({
        where: { is_approved: false, active: true, session_id: session.id },
      });
  
      const [
        totalStudent,
        totalStaff,
        totalDepartment,
        totalFaculty,
        totalTopicSubmitted,
        totalTopicApproved,
        totalTopicRejected,
        totalTopicPending,
        totalResearchSubmitted,
        totalResearchApproved,
        totalResearchRejected,
        totalResearchPending,
      ] = await Promise.all([
        totalStudentPromise,
        totalStaffPromise,
        totalDepartmentPromise,
        totalFacultyPromise,
        totalTopicSubmittedPromise,
        totalTopicApprovedPromise,
        totalTopicRejectedPromise,
        totalTopicPendingPromise,
        totalResearchSubmittedPromise,
        totalResearchApprovedPromise,
        totalResearchRejectedPromise,
        totalResearchPendingPromise,
      ]);
  
      const months = getMonthsOfYear();
      const activitiesPromises = months.map((month) =>
        ActivityLog.count({
          where: {
            createdAt: {
              [Op.between]: [month.start, month.end],
            },
          },
        })
      );
      const topicsPromises = months.map((month) =>
        ProjectTopic.count({
          where: {
            createdAt: {
              [Op.between]: [month.start, month.end],
            },
          },
        })
      );
      const researchPromises = months.map((month) =>
        ProjectSubmission.count({
          where: {
            createdAt: {
              [Op.between]: [month.start, month.end],
            },
          },
        })
      );
  
      const [activities, topics, research] = await Promise.all([
        Promise.all(activitiesPromises),
        Promise.all(topicsPromises),
        Promise.all(researchPromises),
      ]);
      return res.render("admin/index.ejs", {
        user: req.user,
        sessions: req.sessions,
        totalStudent,
        totalStaff,
        totalDepartment,
        totalFaculty,
        totalTopicSubmitted,
        totalTopicApproved,
        totalTopicRejected,
        totalTopicPending,
        totalResearchSubmitted,
        totalResearchApproved,
        totalResearchRejected,
        totalResearchPending,
        activities,
        topics,
        research,
        error: false,
      });
    } catch (error) {
        console.log(error)
      return res.render("admin/index.ejs", {
        user: req.user,
        sessions: req.sessions,
        error: error.message,
      });
    }
  };
  

exports.sendNoticeMail = async (req, res) => {
    try {
    const users = await Profile.findAll({
        where:{role_id:6},
        include:[
            {model:User}
        ]
    });
    for(const user of JSON.parse(JSON.stringify(users))){
        if(user?.user?.email){
            console.log(user.user.email)
            console.log(user.firstname)

         const sendRestEmail = await noticeEmail(user.user.email, user.firstname);
        }
    }
    return res.status(200).send({success:true,message:"mail sent"});
    } catch (error) {
        console.log(error)
        return res.status(500).send({success:false, message:error.message})
    }
};

function getMonthsOfYear() {
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const months = [];

  for (let month = 0; month < 12; month++) {
    const startDate = new Date(currentYear, month, 1);
    const endDate = new Date(currentYear, month + 1, 0);

    const startFormatted = startDate.toISOString().split("T")[0];
    const endFormatted = endDate.toISOString().split("T")[0];

    months.push({
      month: month + 1,
      start: startFormatted,
      end: endFormatted,
    });
  }

  return months;
}