const User = require("../../../models").users;
const Profile = require("../../../models").profiles;
const DocumentCategory = require("../../../models").document_categories;
const ProjectSubmission = require("../../../models").project_submissions;
const Department = require("../../../models").departments;
const ProjectTopic = require("../../../models").project_topics;
const { Op } = require("sequelize");

const env = process.env.NODE_ENV || "development";
// const config = require(__dirname + '/../../../config/config.json')[env];
const Sequelize = require("sequelize");

const sequelize = require("../../../config/connection");

exports.viewStudentProject = async (req, res) => {
  try {
    const { docId } = req.params;
    const doc = await ProjectSubmission.findOne({
      where: {
        id: docId,
      },
      raw: true,
    });
    res.render("admin/staffViewTemplate.ejs", {
      doc,
      user: req.user,
      error: false,
      sessions: req.sessions,
    });
  } catch (error) {
    console.log(error);
    return res.render("admin/staffViewTemplate.ejs", {
      user: req.user,
      error: error.message,
      content: "",
    });
  }
};

exports.projects = async (req, res) => {
  try {
    const { username, id } = req.query;

    if(id) {
      await ProjectSubmission.update({ppo_paid:true},{ where: { id } });
    }
    const session_id = req.params.session_id
    let query = {};
    const departments = await Department.findAll({ where: { active: true } });
    let [projectInprogress] =
      await sequelize.query(`SELECT count(project_submissions.id) AS projectInprogress FROM project_submissions 
      INNER JOIN project_topics ON project_submissions.project_id  = project_topics.id 
      WHERE document_category_id <> '7' AND project_submissions.session_id = "${session_id}" `);

    let [projectRejected] =
      await sequelize.query(`SELECT count(project_submissions.id) AS projectInprogress FROM project_submissions 
      INNER JOIN project_topics ON project_submissions.project_id  = project_topics.id 
      WHERE project_submissions.active = '0' AND project_submissions.session_id = "${session_id}"`);

    let [projectCompleted] =
      await sequelize.query(`SELECT count(project_submissions.id) AS projectInprogress 
      FROM project_submissions 
      INNER JOIN project_topics ON project_submissions.project_id = project_topics.id
      WHERE document_category_id = '7' AND project_submissions.is_approved = '1' AND project_submissions.session_id = "${session_id}"`);
    let projects = [];

    if (username) {
      const user = await User.findOne({ where: { username }, raw: true });
      query.student_user_id = user.id;
    }
    const topics = await ProjectTopic.findAll({
      where: {
        active: true,
        // is_approved: true,
        ...query,
        session_id
      },
      limit: 10,
      include: [
        {
          model: ProjectSubmission,
          require: true,
          where: { document_category_id: 7,  active:true },
          include: [
            {
              model: DocumentCategory,
              attributes: ["name"],
            },
            {
              model: ProjectTopic,
              include: [
                {
                  model: User,
                  as: "student",
                  attributes: ["username"],
                  include: [
                    {
                      model: Profile,
                      attributes: ["firstname", "lastname", "middlename"],
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    });
    for (const topic of topics) {
      projects = [...projects, ...topic.project_submissions];
    }
    return res.render("admin/projects.ejs", {
      error: false,
      user: req.user,
      departments,
      projectInprogress,
      projectCompleted,
      projectRejected,
      sessions: req.sessions,
      projects: JSON.parse(JSON.stringify(projects)),
      session_id
    });
  } catch (error) {
    console.log(error);
    return res.render("admin/projects.ejs", {
      user: req.user,
      error: error.message,
      sessions: req.sessions,
      departments: [],
      projectInprogress: 0,
      projectCompleted: 0,
      projectRejected: 0,
      projects: [],
    });
  }
};
exports.projectsTopics = async (req, res) => {
  try {
    const { username, topic_id } = req.query;
    const session_id = req.params.session_id;
    let student_user_id = "";
    if (username) {
      const user = await User.findOne({ where: { username }, raw: true });
      student_user_id = user ? user.id : "";
    }
    if (topic_id) {
      await ProjectTopic.destroy({ where: { id: topic_id } });
    }
    const topics = await ProjectTopic.findAll({
      where: {
        session_id,
        ...(student_user_id && { student_user_id }),
      },
      limit: 10,
      include: [
        {
          model: User,
          as: "student",
          attributes: ["username"],
          include: [
            {
              model: Profile,
              attributes: ["firstname", "lastname", "middlename"],
            },
          ],
        },
        {
          model: User,
          as: "lecturer",
          attributes: ["username"],
          include: [
            {
              model: Profile,
              attributes: ["firstname", "lastname", "middlename", "title"],
            },
          ],
        },
      ],
    });

    return res.render("admin/project-topics.ejs", {
      error: false,
      user: req.user,
      sessions: req.sessions,
      projects: topics,
      session_id,
    });
  } catch (error) {
    console.log(error);
    return res.render("admin/project-topics.ejs", {
      user: req.user,
      error: error.message,
      sessions: req.sessions,
      projects: [],
    });
  }
};