const User = require("../../models").users;
const Profile = require("../../models").profiles;
const ActivityLog = require("../../models").activity_log;
const Level = require("../../models").levels;
const StudyMode = require("../../models").study_modes;
const Department = require("../../models").departments;
const Institute = require("../../models").institutes;
const SchoolSessions = require("../../models").sessions;
const paymentHistory = require("../../models").payment_history;
const StudentSupervisor = require("../../models").student_supervisors;
const Subcriptions = require("../../models").subscriptions
const axios = require("axios");
const apiUrl = "https://request.corass.ng/play.php";
const Activity = require("../helpers/activity.helper");
const jwt = require("jsonwebtoken");
const CryptoJS = require("crypto-js");
var key = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
var iv = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
const CurrentSession = require("../../models").sessions;
const ODFORMS = require("../../models").odfel_forms;
const qr = require("qrcode");
function getFirstWordTitleCase(sentence) {
  const words = sentence.split(" ");
  const firstWord = words[0];

  const titleCaseFirstWord =
    firstWord.charAt(0).toUpperCase() + firstWord.slice(1).toLowerCase();

  return titleCaseFirstWord;
}
const { randomString } = require("../helpers/randomString");
const { where } = require("sequelize");

function timeSince(date) {
  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = seconds / 31536000;

  if (interval > 1) {
    return Math.floor(interval) + " years";
  }
  interval = seconds / 2592000;
  if (interval > 1) {
    return Math.floor(interval) + " months";
  }
  interval = seconds / 86400;
  if (interval > 1) {
    return Math.floor(interval) + " days";
  }
  interval = seconds / 3600;
  if (interval > 1) {
    return Math.floor(interval) + " hours";
  }
  interval = seconds / 60;
  if (interval > 1) {
    return Math.floor(interval) + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}

exports.home = (req, res) => {
  return res.render("index.ejs");
};
exports.studentLog = async (req, res) => {
  try {
    return res.render("login/logs.ejs", {
      error: false,
      success: {
        message: undefined,
      },
    });
  } catch (error) {}
};
exports.odfel = async (req, res) => {
  try {
    const departments = await Department.findAll()
    return res.render("login/odfel.ejs", {
      error: false,
      success: {
        message: undefined,
      },
      departments
    });
  } catch (error) {}
};
exports.odfelForm = async (req, res) => {
  try {
    const id = req.params.id;
    if(!id){
      return res.send("Invalid Form")
    }
    const record = await ODFORMS.findOne({where:{id}, raw:true});
    const session = await CurrentSession.findOne({where:{status:true}, raw: true})
    if(!record || record.txn_status != "success"){
      return res.send("Invalid Form")
    }
    const url = req.headers.host + req.url;
    console.log(url)
    qr.toDataURL(url, (err, src) => {
      if (err) res.send("An error occured!, Please try again or contact the admin");
  
      return res.render("acknownledge-odfel.ejs", {
        record:record,
        Session:session.name,
        src
      });
    });
   
  } catch (error) {
    console.log(error)
    return res.send("An error occured!, Please try again or contact the admin")
  }
};
exports.studentLogin = async (req, res) => {
  try {
    let {
      eloginID,
      fileControllers,
      fileControllerf,
      fileControllero,
      fileControllerp,
      fileControllerst,
    } = req.query;
  
    if (!eloginID) {
      return res.render("login/student.ejs", {
        error: false,
        success: {
          message: undefined,
        },
      });
    }
  
    const requestData = {
      eloginID: decodeURIComponent(eloginID.replace(/\s/g, "+")),
      fileControllers: decodeURIComponent(fileControllers?.replace(/\s/g, "+")),
      fileControllerf: decodeURIComponent(fileControllerf?.replace(/\s/g, "+")),
      fileControllero: decodeURIComponent(fileControllero?.replace(/\s/g, "+")),
      fileControllerp: decodeURIComponent(fileControllerp?.replace(/\s/g, "+")),
      fileControllerst: decodeURIComponent(fileControllerst?.replace(/\s/g, "+")),
    };
  
    const response = await axios.post(apiUrl, requestData);
    let profile = {}
    const user = await User.findOne({
      where: {
        username: response.data.username,
      },
      raw: true,
    });
    const matrci = response.data.username;
      const usernameArr = matrci.split("/");
      console.log(usernameArr);
      // Output: [ 'HND', '22', 'MEC', 'FT', '276' ];
      let department = {};
      if (usernameArr[2]) {
        department = await Department.findOne({
          where: {
            code: usernameArr[2],
          },
          raw: true,
          attributes: ["id"],
        });
      }
  
      let level = {};
      if (usernameArr[0]) {
        level = await Level.findOne({
          where: {
            code: usernameArr[0],
          },
          raw: true,
          attributes: ["id"],
        });
      }
      let study_mode = {};
      if (usernameArr[3]) {
        study_mode = await StudyMode.findOne({
          where: {
            code: usernameArr[3],
          },
          raw: true,
          attributes: ["id"],
        });
      }
    if (!user) {
      let session_id;
      const session = await CurrentSession.findOne({ where: { status: true } });
  
      if (session) {
        session_id = session.id;
      }
      const creatUser = await User.create({
        username: response.data.username,
        slug: randomString(20),
        password: CryptoJS.AES.encrypt(
          response.data.surname?.toUpperCase(),
          key,
          { iv: iv }
        ).toString(),
        role: 7,
        session_id,
      });
      profile =   await Profile.create({
        user_id: creatUser.id,
        department_id: department?.id,
        level_id: level?.id,
        study_mode_id: study_mode?.id,
        firstname: response.data.firstname,
        lastname: response.data.surname,
        middlename: response.data.othername,
        role_id: 7,
        session_id,
      });
      const studentSupervisor =  StudentSupervisor.findOne({where:{student_user_id:creatUser.id}, raw:true});
      if(!StudentSupervisor){
        await StudentSupervisor.create({
          student_user_id:creatUser.id ,
          project_type_id: 1,
          session_id,
          lecturer_user_id:"null"
        })
      }
      
    }else{
      const checkPro = await Profile.findOne({where:{user_id :user.id }, raw: true});
      await Profile.update({
        ...(!checkPro.level_id && {level_id: level?.id}),
        ...(!checkPro.study_mode_id && {study_mode_id: study_mode?.id}),
        ...(!checkPro.firstname && {firstname: response.data.firstname}),
        ...(!checkPro.lastname && {lastname: response.data.surname}),
        ...(!checkPro.middlename && {middlename: response.data.othername}),
      },
      {where:{
        id:checkPro.id
      }}
    );
    }
  
    // profile = await Profile.findOne({where:{user_id :user.id }, raw: true});

    const token = jwt.sign(
      {
        username: response.data.username,
      },
      process.env.JWT_pa
    );
  
    await User.update(
      {
        remember_token: token,
      },
      {
        where: {
          username: response.data.username,
        },
      }
    );
  
    await Activity("login", "User login", response.data.username);
    req.session.data = {
      token,
    };
    // console.log(response.data)
    return res.redirect("/student-dashboard");
  } catch (error) {
    console.log(error)
    return res.redirect("/student-login");
  }
};
exports.staffLogin = async (req, res) => {
  let {
    eloginID,
    fileControllers,
    fileControllerf,
    fileControllero,
    fileControllerp,
    fileControllerst,
  } = req.query;
  // return res.redirect("https://kp-staff.corass.ng/staff-login")
  if (!eloginID) {
    return res.render("login/staff.ejs", {
      error: false,
      success: {
        message: undefined,
      },
    });
  }

  const requestData = {
    eloginID: decodeURIComponent(eloginID.replace(/\s/g, "+")),
    fileControllers: decodeURIComponent(fileControllers.replace(/\s/g, "+")),
    fileControllerf: decodeURIComponent(fileControllerf.replace(/\s/g, "+")),
    fileControllero: decodeURIComponent(fileControllero.replace(/\s/g, "+")),
    fileControllerp: decodeURIComponent(fileControllerp.replace(/\s/g, "+")),
    fileControllerst: decodeURIComponent(fileControllerst.replace(/\s/g, "+")),
  };

  const response = await axios.post(apiUrl, requestData);

  const user = await User.findOne({
    where: {
      username: response.data.username,
    },
    raw: true,
  });
  if (!user) {
    const department = await Department.findOne({
      where: {
        code: getFirstWordTitleCase(response.data.department),
      },
      raw: true,
      attributes: ["id"],
    });
    const creatUser = await User.create({
      username: response.data.username,
      slug: randomString(20),
      password: CryptoJS.AES.encrypt("12345678", key, { iv: iv }).toString(),
      role: 6,
    });
    await Profile.create({
      user_id: creatUser.id,
      department_id: department?.id,
      firstname: response.data.firstname,
      lastname: response.data.surname,
      middlename: response.data.othername,
      role_id: 6,
    });
  }

  const token = jwt.sign(
    {
      username: response.data.username,
    },
    process.env.JWT_pa
  );

  await User.update(
    {
      remember_token: token,
    },
    {
      where: {
        username: response.data.username,
      },
    }
  );

  await Activity("login", "User login", response.data.username);
  req.session.data = {
    token,
  };

  return res.redirect("/staff-dashboard");
};
exports.profile = async (req, res) => {
  try {
    const user = await Profile.findOne({
      where: { user_id: req.user.id },
      attributes: [
        "department_id",
        "firstname",
        "lastname",
        "middlename",
        "photo_path",
      ],
      include: [
        {
          model: User,
          attributes: ["username", "email", "phone", "slug"],
        },
        {
          model: Department,
          attributes: ["id", "name"],
          include: [
            {
              model: Institute,
              attributes: ["name"],
            },
          ],
        },
      ],
    });
    const logs = [];
    const activityLog = await ActivityLog.findAll({
      where: { causer_id: req.user.username },
      limit: 7,
      order: [["createdAt", "DESC"]],
      attributes: ["createdAt", "description"],
    });
    for (const act of activityLog) {
      const timeAgo = timeSince(act.createdAt);
      logs.push({ description: act.description, createdAt: timeAgo });
    }

    const session = await SchoolSessions.findAll({});
    return res.render("login/profile.ejs", {
      userType: req.type,
      user: req.user,
      subscriptions: req.subscriptions,
      profile: user,
      activityLog: logs,
      sessions: session,
    });
  } catch (error) {
    console.log(error);
    return res.render("login/profile.ejs", {
      user: req.user,
      profile: {},
      subscriptions: req.subscriptions,
      error: error.message,
      activityLog: {},
    });
  }
};
exports.profile2 = async (req, res) => {
  try {
    const user = await Profile.findOne({
      where: { user_id: req.user.id },
      attributes: [
        "department_id",
        "firstname",
        "lastname",
        "middlename",
        "photo_path",
      ],
      include: [
        {
          model: User,
          attributes: ["username", "email", "phone", "slug"],
        },
        {
          model: Department,
          attributes: ["id", "name"],
          include: [
            {
              model: Institute,
              attributes: ["name"],
            },
          ],
        },
      ],
    });

    const session = await SchoolSessions.findAll({});
    return res.render("login/change_password.ejs", {
      userType: req.type,
      user: req.user,
      profile: user,
      subscriptions: req.subscriptions,
      sessions: session,
    });
  } catch (error) {
    console.log(error);
    return res.render("login/profile.ejs", {
      user: req.user,
      profile: {},
      subscriptions: req.subscriptions,
      error: error.message,
      activityLog: {},
      sessions: [],
    });
  }
};
exports.profile3 = async (req, res) => {
  return res.render("login/pay.ejs", {
    user: req.user,
    subscriptions: req.subscriptions,
  });
};
exports.deletePayment = async (req, res) => {
  try {
    var usernames = req.body.usernames;
    var secretKey = req.body.secretKey;
    var amount = req.body.amount

    const activeSession = await SchoolSessions.findOne({where:{status:true},attributes:["id"], raw: true});
    if (usernames.length > 0 && secretKey === "vskdbfkvfvdb0nw323nkdfnvfdv") {

      for(const username of usernames){

  
        const findUser = await User.findOne({
          where: {
            username
          },
        });

        if(!findUser) continue;
        if(findUser.payment_status == "PAID" && findUser.active === true) continue;

        const verifyPaymentHistory = await paymentHistory.create({
          txn_ref: `SCHPORTAL-${username}`,
          username,
          amount,
          txn_desc:"Payment was paid to school portal",
          txn_channel:"portal",
          package_id:1,
          session_id:activeSession.id,
          txn_status:"success"
        });
          const updateUser = {
            payment_status: "PAID",
            active: true,
          };
          const updatePaid = await User.update(updateUser, {
            where: {
              username
            },
          });
  
          const createSub = await Subcriptions.create({
            user_id: findUser.id,
            payment_id: `SCHPORTAL-${username}`,
            pakage_id: verifyPaymentHistory.package_id,
          });
  
          if (updatePaid && createSub) {
            // recordPaymentToSchoolPortal({
            //   amount: parseInt(verifyPaymentHistory.amount),
            //   username: event.data.metadata.matricNumber,
            //   payment_type: packageDetail.name,
            // });
            res.status(200).send();
          }

      }
    } else {
      res.status(401).send();
    }
  } catch (e) {
    console.log(e);

    res.status(500).send();
  }
};
