const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { AppSupport, Cohort } = require("../models");
const multer = require('multer');
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname);
  }
});
const upload = multer({ storage: storage }).single('file');

exports.all = async (req, res) => {
  const all_Data = await AppSupport.findAll({
    where: {
      status: 0
    },
    order: [
      ['createdAt', 'DESC'],
    ],
    include: [{
      model: User,
      attributes: ['id', 'name', 'email']
    }],

  })
  res.status(200).send(API._200(await all_Data));
};
exports.bulk_student = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let resdata = {};
  let bulk = {
    "name": input.data.name,
    "roll_id": input.data.roll_id,
    "allow_access": input.data.allow_access,
    "is_temp": input.data.is_temp,
    "password": input.data.password,
    "email": input.data.email,
    "company_id": input.data.company_id,
    "is_selfpaced": input.data.is_selfpaced
  }

  const users = await db_helper.addData("User", bulk)
  let cohortmessage = "";
  let checkcohort = false;
  if (!users.message) {
    resdata["userstatus"] = 1;
    resdata["message"] = "Success";
    for (let i = 0; i < input.data.cohort.length; i++) {
      var cohortdata = await db_helper.query("select * from cohorts where id=" + input.data.cohort[i].cohort_id + " and find_in_set(" + users.id + ",userslist)");
      if (cohortdata[0].length <= 0) {
        const cohort = await Cohort.findByPk(input.data.cohort[i].cohort_id);
        let uid = cohort.userslist;
        if (uid.length > 0)
          cohort.userslist = uid + "," + users.id;
        else
          cohort.userslist = users.id + "";
        await cohort.save();
        let accessDuration = {
          "user_id": users.id,
          "cohort_id": input.data.cohort[i].cohort_id,
          "plan_id": input.data.cohort[i].plan_id,
          "plan_type": input.data.cohort[i].plan_type,
          "access_duration": input.data.cohort[i].access_duration
        }
        const cc = await db_helper.selectByWhere("AccessDuration", accessDuration);
        if (cc.length > 0) {
          accessDuration['id'] = cc[0].id;
          await db_helper.update("AccessDuration", accessDuration);
        } else {
          await db_helper.addData("AccessDuration", accessDuration);
        }
        let save_transaction = {
          "user_id": users.id,
          "payment_type": input.data.cohort[i].payment_type,
          "plan_id": input.data.cohort[i].plan_id,
          "access_duration": input.data.cohort[i].access_duration,
          "amount": "Enroll by admin",
          "certi_id": input.data.cohort[i].certi_id,
          "cohort_id": input.data.cohort[i].cohort_id,
        }
        await db_helper.addData("PaymentTransaction", save_transaction)
        if (!checkcohort) {
          resdata["cohortstatus"] = 1;
          resdata["cohortmessage"] = "Success";
          resdata["cohortmessage"] = uid;
        }
      }
      else {
        resdata["cohortstatus"] = 0;
        resdata["cohortmessage"] = "Failed";
        checkcohort = true;
      }
    }
  }
  else {

    if (users.message == "Oops. Looks like email already exist.") {
      var userdetails = await db_helper.query("select * from users where email='" + input.data.email + "'");
      resdata["userstatus"] = 0;
      resdata["message"] = "Oops. Looks like email already exist.";
      for (let i = 0; i < input.data.cohort.length; i++) {

        var cohortdata = await db_helper.query("select * from cohorts where id=" + input.data.cohort[i].cohort_id + " and find_in_set(" + userdetails[0][0].id + ",userslist)");
        if (cohortdata[0].length <= 0) {
          const cohort = await Cohort.findByPk(input.data.cohort[i].cohort_id);
          let uid = cohort.userslist;
          if (uid.length > 0)
            cohort.userslist = uid + "," + userdetails[0][0].id;
          else
            cohort.userslist = userdetails[0][0].id + "";
          await cohort.save();
          let accessDuration = {
            "user_id": userdetails[0][0].id,
            "cohort_id": input.data.cohort[i].cohort_id,
            "plan_id": input.data.cohort[i].plan_id,
            "plan_type": input.data.cohort[i].plan_type,
            "access_duration": input.data.cohort[i].access_duration
          }
          const cc = await db_helper.selectByWhere("AccessDuration", accessDuration);
          if (cc.length > 0) {
            accessDuration['id'] = cc[0].id;
            await db_helper.update("AccessDuration", accessDuration);
          } else {
            await db_helper.addData("AccessDuration", accessDuration);
          }
          let save_transaction = {
            "user_id": userdetails[0][0].id,
            "payment_type": input.data.cohort[i].payment_type,
            "plan_id": input.data.cohort[i].plan_id,
            "access_duration": input.data.cohort[i].access_duration,
            "amount": "Enroll by admin",
            "certi_id": input.data.cohort[i].certi_id,
            "cohort_id": input.data.cohort[i].cohort_id,
          }
          await db_helper.addData("PaymentTransaction", save_transaction)
          if (!checkcohort) {
            resdata["cohortstatus"] = 1;
            resdata["cohortmessage"] = "Success";
          }
        }
        else {
          resdata["cohortstatus"] = 0;
          resdata["cohortmessage"] = "Failed";
          checkcohort = true;
        }
      }
    }
    else {
      resdata["userstatus"] = 2;
      resdata["message"] = "Failed";
      resdata["cohortstatus"] = 0;
      resdata["cohortmessage"] = "Failed";
    }
  }
  res.status(200).send(API._200(await resdata));
};
exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('AppSupport', input.id)));
};
exports.sendEmail = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let data = {
    to: input.to,
    subject: input.subject,
    text: input.text
  }
  await helper.sendMail(data)
  res.status(200).send(API._200({ message: "Email sent success" }));
};
exports.uploadFile = async (req, res) => {
  upload(req, res, async function (err) {
    if (err) {
      res.status(400).send(API._400({ message: "File upload failed" }));
    } else {
      const fileName = req.file.filename;
      res.status(200).send(API._200({ fileName: fileName }));
    }
  })
};