const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Cource, Ketexamtest, Certificate, Ketexamque, Topic, SubTopic,
  Subdomain, Practicetest, Video, MindMap, Company, User, Cohort, KnowledgeAsses,
  EmailTemplates, Practiceque, HybridSchedule, QueDBUpdate, PracticeAppque } = require("../models");

exports.alldropdown = async (req, res) => {
  const course = await Cource.findAll({
    where: {
      status: 0
    },
  });
  const certi = await Certificate.findAll({
    where: {
      status: 0
    },
  });

  const topic = await Topic.findAll({
    where: {
      status: 0
    },
  });
  const stopic = await SubTopic.findAll({
    where: {
      status: 0
    },
  });
  let dom = await db_helper.query("select id,CONCAT_WS(' ',domain_number,domin_name) as domin_name,certi_id from domains where status=0")
  const sdomain = await Subdomain.findAll({
    where: {
      status: 0
    },
  });
  let response = { "Course": course, "Certificate": certi, "Topic": topic, "SubTopic": stopic, "Domain": dom[0], "SubDomain": sdomain };
  res.status(200).send(API._200(await response));
};
exports.ptbyid = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let data = await Practicetest.findOne({
    where: {
      status: 0,
      id: input.id,
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  var response;
  const acr = await db.sequelize.query("SELECT * FROM acronyms where certi_id=" + data.certi_id + " and status=0")
    .then(function (data) {
      return Array.from(new Set(data[0]));
    });
  response = {
    "acronums": acr,
    "id": data.id,
    "practice_name": data.practice_name,
    "certi_id": data.certi_id,
    "time": data.time,
    "type": data.type,
    "description": data.description,
    "status": data.status,
    "createdAt": data.createdAt,
    "updatedAt": data.updatedAt,
    "certificate": data.certificate
  };
  res.status(200).send(API._200(await response));
};
exports.review_guide_progress = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var topics = await Topic.findAll({
    where: {
      certi_id: input.certi_id,
      status: 0
    },
    attributes: ['id', 'topic_name', 'd_id', 'sd_id']
  });
  const all_flash_count = await db_helper.query("SELECT count(*) ttlflash,topic_id FROM flashcards WHERE status=0 group by topic_id");

  const flashcard_point = await db_helper.query("select sum(case when correct=1 then 1 else 0 end) correct, sum(case when correct=1 then 0 else 1 end) incorrect,topic_id from flashcard_offlines as fo left join flashcards as f on f.id=fo.cid where UserId=" + input.user_id + " and cohort_id=" + input.cohort_id + " group by f.topic_id");

  let all_vid_min_view = await db_helper.query("select type_id,type from video_mind_views where  cohort_id=" + input.cohort_id + " and user_id=" + input.user_id + " and is_completed=1");
  let all_summ_ref_view = await db_helper.query("select card_id,card_type,topic_id from card_views where  cohort_id=" + input.cohort_id + " and user_id=" + input.user_id);


  let data = [];
  for (let i = 0; i < topics.length; i++) {

    let summaryPercentage = 0;
    let completed_summary = all_summ_ref_view[0].filter(x => x.topic_id == topics[i].id && x.card_type == 'Summary').length
    summaryPercentage = completed_summary

    let referencePercentage = 0;
    let completed_refer = all_summ_ref_view[0].filter(x => x.topic_id == topics[i].id && x.card_type == 'References').length
    referencePercentage = completed_refer;

    let videos = await db_helper.query("select id,topic_id from videos where status=0 and find_in_set(" + topics[i].id + ",topic_id)");
    let completed_video = 0
    for (let v = 0; v < videos[0].length; v++) {
      completed_video = all_vid_min_view[0].filter(x => x.type_id == videos[0][v].id && x.type == 'VIDEO').length
    }
    let all_video_length = videos[0].length;
    let videoPercentage = 0;
    if (completed_video > 0) {
      videoPercentage = (completed_video * 100) / all_video_length;
    }

    let mindmaps = await db_helper.query("select id,topic_id from mind_maps where status=0 and find_in_set(" + topics[i].id + ",topic_id)");
    let completed_mindmaps = 0
    for (let v = 0; v < mindmaps[0].length; v++) {
      completed_mindmaps = all_vid_min_view[0].filter(x => x.type_id == mindmaps[0][v].id && x.type == 'MIND').length
    }
    let all_mindmaps_length = mindmaps.length;
    let mindmapsPercentage = 0;
    if (completed_mindmaps > 0) {
      mindmapsPercentage = (completed_mindmaps * 100) / all_mindmaps_length;
    }

    let ttl_flash = all_flash_count[0].filter(x => x.topic_id == topics[i].id)
    let total_flashcard = ttl_flash.length > 0 ? ttl_flash[0].ttlflash : 0;
    let flsh_point = flashcard_point[0].filter(x => x.topic_id == topics[i].id)
    let fp_correct = flsh_point.length > 0 ? flsh_point[0].correct : 0;
    let fp_incorrect = flsh_point.length > 0 ? flsh_point[0].incorrect : 0;

    let flash_inc_per = 0;
    let flash_cor_per = 0;
    if (total_flashcard > 0 && fp_correct > 0) {
      flash_inc_per = Math.round((fp_incorrect * 100) / total_flashcard);
      flash_cor_per = Math.round((fp_correct * 100) / total_flashcard);
    }
    else {
      flash_inc_per = 0;
      flash_cor_per = 0;
    }

    data.push({
      title: topics[i].topic_name,
      id: topics[i].id,
      flash_inc_per: flash_inc_per,
      flash_cor_per: flash_cor_per,
      videoPercentage: videoPercentage,
      mindmapsPercentage: mindmapsPercentage,
      referencePercentage: referencePercentage > 0 ? 100 : 0,
      summaryPercentage: summaryPercentage > 0 ? 100 : 0
    })
  }
  res.status(200).send(API._200(await data));
};
exports.usp_getreviewguide = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const time = await db_helper.query("call getreviewguide(" + input.u_id + ",'" + input.cohort_id + "','" + input.cource_id + "','" + input.method_id + "','" + input.method_type + "','" + input.material_type + "','" + input.cource_id + "')")
  for (let i = 0; i < time.length; i++) {
    time[i].subdomains = JSON.parse(time[i].subdomains);
  }
  res.status(200).send(API._200(await time));
};
exports.all_video_mind = async (req, res) => {
  const vid = await Video.findAll({
    attributes: ['id', 'certi_id', 'video_title'],
    where: {
      status: 0
    }
  });
  const mind = await MindMap.findAll({
    attributes: ['id', 'name', 'certi_id'],
    where: {
      status: 0
    }
  });

  let response = { "Videos": vid, "MindMaps": mind };
  res.status(200).send(API._200(await response));
};
exports.allcatexams = async (req, res) => {
  const cat = await Ketexamtest.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  let data = [];
  for (let i = 0; i < cat.length; i++) {
    const course = cat[i].course_id;
    const acr = cat[i].acronums;
    let course_ids = course.join(",");
    let acroIds = acr.join(",");

    let c = await db_helper.query("SELECT * FROM cources where id in(" + course_ids + ")");
    let acronyms = [];
    if (acroIds) {
      acronyms = await db_helper.query("SELECT id,short_name,full_name FROM acronyms where id in(" + acroIds + ")");
    }
    const question = await Ketexamque.findAll({
      where: {
        status: 0,
        test_id: cat[i].id
      }
    });

    data.push({
      "acronum_ids": cat[i].acronum_ids,
      "acronums": acronyms[0],
      "certi_id": cat[i].certi_id,
      "certificate": cat[i].certificate,
      "course": c[0],
      "course_id": cat[i].course_id,
      "createdAt": cat[i].createdAt,
      "id": cat[i].id,
      "ketexam_name": cat[i].ketexam_name,
      "status": cat[i].status,
      "time": cat[i].time,
      "updatedAt": cat[i].updatedAt,
      "questions": question
    })
  }
  res.status(200).send(API._200(await data));
};
exports.allcompany = async (req, res) => {
  var company = await Company.findAll({
    where: {
      status: 0
    }
  });
  let data = [];

  for (let i = 0; i < company.length; i++) {
    var cohortstudent = await db_helper.query("select count(uu.id)studentcount,ifnull(group_concat(uu.id),'') userslist,coh.id,coh.cohort_name from cohorts coh left join users uu on find_in_set (uu.id, coh.userslist) where coh.status=0 and coh.company_id=" + company[i].id + " group by coh.id");

    var user = await User.findAll({
      where: {
        roll_id: 4,
        company_id: company[i].id
      }
    });
    var cohort = await Cohort.findAll({
      where: {
        status: 0,
        company_id: company[i].id
      },
      include: [{
        model: Cource,
        attributes: ['id', 'course_name', 'description']
      }]
    });
    var cohortstudent
    if (cohort.length > 0) {
      cohort.forEach(element => {
        element.userslist = cohortstudent[0].find(x => x.id == element.id).userslist
      });
    }

    data.push({ id: company[i].id, name: company[i].name, address: company[i].address, notes: company[i].notes, status: company[i].status, createdAt: company[i].createdAt, clients: user, cohorts: cohort, cohortstudent: cohortstudent })
  }
  res.status(200).send(API._200(await data));
};
exports.allexams = async (req, res) => {
  const email = await EmailTemplates.findAll({
    attributes: ['id', 'name', 'certi_id'],
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  const ka = await KnowledgeAsses.findAll({
    attributes: ['id', 'knowass_name', 'certi_id'],
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  const pt = await Practicetest.findAll({
    attributes: ['id', 'practice_name', 'certi_id'],
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  const cat = await Ketexamtest.findAll({
    attributes: ['id', 'ketexam_name', 'certi_id'],
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  let cat_count = await db_helper.query("SELECT count(*) ttlque,kt.id test_id from ketexamtests kt left join ketexamques kq on find_in_set(kt.id,kq.exam_id) where kq.status=0 and kt.status=0 group by kt.id");
  let practiceIds = pt.map(a => a.id);
  let practice_count = await db_helper.query("select count(*) ttlque,test_id from practiceques where test_id in(" + practiceIds + ") group by test_id");
  let kaIds = ka.map(a => a.id);
  let ka_count = await db_helper.query("select count(*) ttlque,ass_id from know_ass_ques where ass_id in(" + kaIds + ") group by ass_id");
  let response = { "ka_count": ka_count[0], "cat_count": cat_count[0], "practice_count": practice_count[0], "KnowledgeAssessments": ka, "PracticeExams": pt, "CatExams": cat, "EmailTemplates": email };
  res.status(200).send(API._200(await response));
};
exports.allknowass = async (req, res) => {
  const knowledgeAsses = await KnowledgeAsses.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  let data = [];
  for (let i = 0; i < knowledgeAsses.length; i++) {
    let ka_count = await db_helper.query("select count(*) ttlque from know_ass_ques where status=0 and find_in_set(" + knowledgeAsses[i].id + ",ass_id)");
    await data.push({
      "certi_id": knowledgeAsses[i].certi_id,
      "createdAt": knowledgeAsses[i].createdAt,
      "id": knowledgeAsses[i].id,
      "image": knowledgeAsses[i].image,
      "knowass_name": knowledgeAsses[i].knowass_name,
      "status": knowledgeAsses[i].status,
      "updatedAt": knowledgeAsses[i].updatedAt,
      "certificate": knowledgeAsses[i].certificate,
      "total_question": ka_count[0][0].ttlque
    })
  }
  res.status(200).send(API._200(await data));
};
exports.allpractice = async (req, res) => {
  const cat = await Practicetest.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  let data = [];
  for (let i = 0; i < cat.length; i++) {
    const course = cat[i].course_id;
    const acr = cat[i].acronums;
    let course_ids = course.join(",");
    let acroIds = acr.join(",");

    let c = await db_helper.query("SELECT * FROM cources where id in(" + course_ids + ")");
    let acronyms = [];
    if (acroIds) {
      acronyms = await db_helper.query("SELECT id,short_name,full_name FROM acronyms where id in(" + acroIds + ")");
    }
    const question = await Practiceque.findAll({
      where: {
        status: 0,
        test_id: cat[i].id
      },
      order: [
        ['seq_number', 'ASC'],
      ],
    });
    data.push({
      "acronum_ids": cat[i].acronum_ids,
      "acronums": acronyms[0],
      "certi_id": cat[i].certi_id,
      "certificate": cat[i].certificate,
      "course": c[0],
      "course_id": cat[i].course_id,
      "createdAt": cat[i].createdAt,
      "description": cat[i].description,
      "id": cat[i].id,
      "practice_name": cat[i].practice_name,
      "status": cat[i].status,
      "time": cat[i].time,
      "type": cat[i].type,
      "updatedAt": cat[i].updatedAt,
      "questions": question
    })
  }
  res.status(200).send(API._200(await data));
};
exports.allscore = async (req, res) => {
  res.status(200).send(API._200(db_helper.allData("Scores")));
};
exports.alluser = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const Op = db.Sequelize.Op;
  const companies = await db.sequelize.query("select GROUP_CONCAT(id) id from companies where name like '%" + input.search + "%'")
    .then(function (data) {
      return Array.from(new Set(data[0]));
    })
  let sortBy = "id";
  let direction = "asc";
  if (input.active && input.direction) {
    sortBy = input.active;
    direction = input.direction;
  }
  var user = await User.findAndCountAll({
    where: {
      roll_id: 3,
      status: 0,

      [Op.or]: [{
        email: {
          [Op.like]: '%' + input.search + '%'
        }
      },
      {
        company_id: [companies[0].id]
      },
      {
        name: {
          [Op.like]: '%' + input.search + '%'
        }
      },
      {
        aliasname: {
          [Op.like]: '%' + input.search + '%'
        }
      }
      ]
    },
    order: [
      [sortBy, direction]
    ],
    limit: [((input.page - 1) * input.limit), input.limit],
  })
  for (let i = 0; i < user.rows.length; i++) {
    var all = await db_helper.query(`select id,cohort_name from cohorts where status=0 and FIND_IN_SET(${user.rows[i].id},userslist)`);
    user.rows[i].notes = all[0];
    var company = await db_helper.query(`select id,name from companies where status=0 and id=${user.rows[i].company_id}`);
    user.rows[i].stripe_customer_id = company[0];
  }
  res.status(200).send(API._200(await user));
};
exports.by = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.selectByWhere("AdminLogs", input)));
};
exports.cohortall = async (req, res) => {
  const result = await Cohort.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  })
  if (result.length > 0) {
    for (let j = 0; j < result.length; j++) {
      result[j] = result[j]
      const knowassessments = await result[j].knowassessments;
      const practicetests = await result[j].practicetests;
      const cattests = await result[j].ketexamtests;
      const users = await result[j].userslist;
      const company = await result[j].company_id;
      const template = await result[j].template_id;
      const videos = await result[j].videos;
      const mindmaps = await result[j].mindmaps;
      const email_templates = await result[j].email_templates;

      if (videos != "") {
        let data1 = await db_helper.query("select id,video_title from videos where id in(" + videos + ")");
        result[j].videos = data1[0];
        let eschedule = await db_helper.query("select * from cohort_schedules where type_id in(" + videos + ") and cohort_id=" + result[j].id + " and type='video'");
        result[j].video_schedule = eschedule[0];
      } else {
        result[j].videos = [];
        result[j].video_schedule = [];
      }
      if (mindmaps != "") {
        let data1 = await db_helper.query("select id,name from mind_maps where id in(" + mindmaps + ")");
        result[j].mindmaps = data1[0];
        let eschedule = await db_helper.query("select * from cohort_schedules where type_id in(" + mindmaps + ") and cohort_id=" + result[j].id + " and type='mindmap'");
        result[j].mindmap_schedule = eschedule[0];
      } else {
        result[j].mindmaps = [];
        result[j].mindmap_schedule = [];
      }
      if (company != "") {
        let data0 = await db_helper.query("select id,name from companies where id in(" + company + ")");
        result[j].company = data0[0];
      } else {
        result[j].company = [];
      }
      if (template != "") {
        let data0 = await db_helper.query("select id,name from templates where id=" + template);
        result[j].templates = data0[0];
      } else {
        result[j].templates = [];
      }
      if (email_templates != "") {
        let data1 = await db_helper.query("select id,name,certi_id from email_templates where id in(" + email_templates + ")");
        result[j].email_templates = data1[0];
        let eschedule = await db_helper.query("select * from cohort_schedules where type_id in(" + email_templates + ") and cohort_id=" + result[j].id + " and type='EMAIL'");
        result[j].email_schedule = eschedule[0];
      } else {
        result[j].email_templates = [];
        result[j].email_schedule = [];
      }

      if (knowassessments != "") {
        let data1 = await db_helper.query("select id,knowass_name from knowledge_asses where id in(" + knowassessments + ")");
        result[j].knowledge_asses = data1[0];
        let kschedule = await db_helper.query("select * from cohort_schedules where type_id in(" + knowassessments + ")  and cohort_id=" + result[j].id + " and  type='KA'");
        result[j].knowledge_schedule = kschedule[0];
      } else {
        result[j].knowledge_asses = [];
        result[j].knowledge_schedule = [];
      }
      if (practicetests != "") {
        let data2 = await db_helper.query("select id,practice_name from practicetests where id in(" + practicetests + ")");
        result[j].practicetests = data2[0];
        let pschedule = await db_helper.query("select * from cohort_schedules where type_id in(" + practicetests + ") and cohort_id=" + result[j].id + " and type='PRACTICE'");
        result[j].practice_schedule = pschedule[0];
      } else {
        result[j].practicetests = [];
        result[j].pschedule = [];
      }
      if (cattests != "") {
        let data3 = await db_helper.query("select id,ketexam_name from ketexamtests where id in(" + cattests + ")");
        result[j].ketexamtests = data3[0];
        let catschedule = await db_helper.query("select * from cohort_schedules where type_id in(" + cattests + ") and cohort_id=" + result[j].id + " and type='CAT'");
        result[j].cat_schedule = catschedule[0];
      } else {
        result[j].ketexamtests = [];
        result[j].catschedule = [];
      }
      if (users != "") {
        let data4 = await db_helper.query("select id,name,email from users where id in(" + users + ")");
        result[j].user = data4[0];
      } else {
        result[j].user = [];
      }
    }
  }
  res.status(200).send(API._200(await result));
};

exports.deletepracticefeedback = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange("QueDBUpdate", input.id)));
};
exports.getknowassbyid = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let knowQueData = await db_helper.query("select * from know_ass_ques where status=0 and find_in_set(" + input.ass_id + ",ass_id)")
  res.status(200).send(API._200(await knowQueData));
};
exports.hybrid_addcohort = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var err = [];
  var data = {
    "cohort_name": input.cohort_name,
    "certi_id": input.certi_id,
    "cource_id": input.cource_id,
    "knowassessments": input.knowassessments,
    "practicetests": input.practicetests,
    "ketexamtests": input.ketexamtests,
    "flashcard_app": input.flashcard_app,
    "practice_que_app": input.practice_que_app,
    "events": input.tevents,
    "userslist": input.userslist,
    "location": input.location,
    "email_templates": input.email_templates,
    "company_id": input.company_id,
    "time_zone": input.time_zone,
    "template_id": input.template_id,
    "video_access": input.video_access,
    "mindmap_access": input.mindmap_access,
    "summary_access": input.summary_access,
    "reference_access": input.reference_access,
    "KA_access": input.KA_access,
    "PT_access": input.PT_access,
    "CAT_access": input.CAT_access,
    "livechat_access": input.livechat_access,
    "liveq_access": input.liveq_access,
    "liveevent_access": input.liveevent_access,
    "start_date": input.start_date,
    "flashcard_access": input.flashcard_access,
    "question_access": input.question_access,
    "method_id": input.method_id,
    "access_duration": input.access_duration,
    "course_type": input.course_type,
    "videos": input.videos,
    "mindmaps": input.mindmaps,
    "live_events": input.live_events,
    "baseline_ka": input.baseline_ka,
    "baseline_ka_schedule": input.baseline_ka_schedule
  };

  const cohort = await Cohort.create(data).catch((ex) => err = ex.errors[0]);
  if (input.schedule) {
    let schedule = input.schedule
    let cohort_id = cohort.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].cohort_id = cohort_id;
      await HybridSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (input.flashcard_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=2 where id in(" + input.userslist + ")");
    }
  }
  if (input.practice_que_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=2 where id in(" + input.userslist + ")");
    }
  }
  if (err.length > 0) {
    res.status(404).send(API._404({ message: err.message }));
  }
  res.status(200).send(API._200(await cohort));
};

exports.hybrid_class_all = async (req, res) => {
  const result = await Cohort.findAll({
    where: {
      status: 0,
      course_type: 'hybrid'
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  })
  if (result.length > 0) {
    for (let j = 0; j < result.length; j++) {
      result[j] = result[j].toJSON()
      const users = await result[j].userslist;
      const company = await result[j].company_id;
      const template = await result[j].template_id;

      if (company != "") {
        let data0 = await db_helper.query("select id,name from companies where id in(" + company + ")");
        result[j].company = data0[0];
      } else {
        result[j].company = [];
      }
      if (template != "") {
        let data0 = await db_helper.query("select id,name from hybrid_templates where id=" + template);
        result[j].templates = data0[0];
      } else {
        result[j].templates = [];
      }
      if (users != "") {
        let data4 = await db_helper.query("select id,name,email from users where id in(" + users + ")");
        result[j].user = data4[0];
      } else {
        result[j].user = [];
      }
    }
  }
  res.status(200).send(API._200(await result));
};
exports.hybrid_class_delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const template = await Cohort.findByPk(input.id)
  if (!template) {
    res.status(404).send(API._404({ message: `hybridclass with id: ${input.id} was not found` }));
  }
  template.status = 1
  let result = template.save();
  await db.sequelize.query("delete from hybrid_schedules where cohort_id= :id", { replacements: { id: input.id } })
  res.status(200).send(API._200(await result));
};
exports.hybrid_class_get_save_schedule = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const sub = await HybridSchedule.findAll({
    where: {
      cohort_id: input.cohort_id
    }
  });
  res.status(200).send(API._200(await sub));
};
exports.hybrid_updatecohort = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const tmp = await Cohort.findByPk(input.id)
  if (!tmp) {
    res.status(200).send(API._200({ message: `Cohort with id: ${input.id} was not found` }));
  }
  if (input.cohort_name) tmp.cohort_name = input.cohort_name;
  if (input.certi_id) tmp.certi_id = input.certi_id;
  if (input.cource_id) tmp.cource_id = input.cource_id;
  if (input.knowassessments) tmp.knowassessments = input.knowassessments;
  if (input.practicetests) tmp.practicetests = input.practicetests;
  if (input.ketexamtests) tmp.ketexamtests = input.ketexamtests;
  tmp.events = input.tevents;
  if (input.userslist) tmp.userslist = input.userslist;
  if (input.location) tmp.location = input.location;
  if (input.company_id) tmp.company_id = input.company_id;
  if (input.email_templates) tmp.email_templates = input.email_templates;
  if (input.time_zone) tmp.time_zone = input.time_zone;
  if (input.template_id) tmp.template_id = input.template_id;
  if (input.start_date) tmp.start_date = input.start_date;
  if (input.flashcard_access) tmp.flashcard_access = input.flashcard_access;
  if (input.question_access) tmp.question_access = input.question_access;
  if (input.method_id) tmp.method_id = input.method_id;
  if (input.access_duration) tmp.access_duration = input.access_duration;
  if (input.course_type) tmp.course_type = input.course_type;
  tmp.live_events = input.live_events ? input.live_events : "";
  if (input.videos) tmp.videos = input.videos;
  if (input.mindmaps) tmp.mindmaps = input.mindmaps;
  if (input.baseline_ka) tmp.baseline_ka = input.baseline_ka;
  tmp.video_access = input.video_access;
  tmp.mindmap_access = input.mindmap_access;
  tmp.summary_access = input.summary_access;
  tmp.reference_access = input.reference_access;
  tmp.KA_access = input.KA_access;
  tmp.PT_access = input.PT_access;
  tmp.CAT_access = input.CAT_access;
  tmp.livechat_access = input.livechat_access;
  tmp.liveq_access = input.liveq_access;
  tmp.liveevent_access = input.liveevent_access;
  tmp.flashcard_access = input.flashcard_access;
  tmp.question_access = input.question_access;
  tmp.baseline_ka_schedule = input.baseline_ka_schedule;


  let result = await tmp.save();
  if (input.schedule) {
    await db.sequelize.query("delete from hybrid_schedules where cohort_id= :id", { replacements: { id: input.id } })

    let schedule = input.schedule
    let cohort_id = input.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].cohort_id = cohort_id;
      await HybridSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (input.flashcard_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=2 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_flashcard=2 where id in(" + tmp.userslist.join() + ")");
    }
  } else {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=0 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_flashcard=0 where id in(" + tmp.userslist.join() + ")");
    }
  }
  if (input.practice_que_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=2 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_practque=2 where id in(" + tmp.userslist.join() + ")");
    }
  } else {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=0 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_practque=0 where id in(" + tmp.userslist.join() + ")");
    }
  }
  res.status(200).send(API._200(await result));
};

exports.practiceappfeedback = async (req, res) => {
  const que = await QueDBUpdate.findAll({
    where: {
      status: 0
    },
    include: [{
      model: User,
      attributes: ['id', 'name', 'email']
    }, {
      model: PracticeAppque
    }]
  });
  res.status(200).send(API._200(await que));
};
exports.savescores = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  await db.sequelize.query("delete from scores");
  res.status(200).send(API._200(await db_helper.addData("Scores", input)));
};
exports.updatecohort = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const tmp = await Cohort.findByPk(input.id)
  if (!tmp) {
    res.status(404).send(API._404({ message: `Cohort with id: ${input.id} was not found` }));
  }
  if (input.cohort_name) tmp.cohort_name = input.cohort_name;
  if (input.certi_id) tmp.certi_id = input.certi_id;
  if (input.cource_id) tmp.cource_id = input.cource_id;
  if (input.knowassessments) tmp.knowassessments = input.knowassessments;
  if (input.practicetests) tmp.practicetests = input.practicetests;
  if (input.ketexamtests) tmp.ketexamtests = input.ketexamtests;
  tmp.events = input.tevents;
  if (input.userslist) tmp.userslist = input.userslist;
  if (input.location) tmp.location = input.location;
  if (input.company_id) tmp.company_id = input.company_id;
  if (input.email_templates) tmp.email_templates = input.email_templates;
  if (input.time_zone) tmp.time_zone = input.time_zone;
  if (input.template_id) tmp.template_id = input.template_id;
  if (input.start_date) tmp.start_date = input.start_date;
  if (input.flashcard_access) tmp.flashcard_access = input.flashcard_access;
  if (input.question_access) tmp.question_access = input.question_access;
  if (input.method_id) tmp.method_id = input.method_id;
  if (input.access_duration) tmp.access_duration = input.access_duration;
  if (input.course_type) tmp.course_type = input.course_type;
  tmp.live_events = input.live_events ? input.live_events : "";
  if (input.videos) tmp.videos = input.videos;
  if (input.mindmaps) tmp.mindmaps = input.mindmaps;
  if (input.baseline_ka) tmp.baseline_ka = input.baseline_ka;
  tmp.video_access = input.video_access;
  tmp.mindmap_access = input.mindmap_access;
  tmp.summary_access = input.summary_access;
  tmp.reference_access = input.reference_access;
  tmp.KA_access = input.KA_access;
  tmp.PT_access = input.PT_access;
  tmp.CAT_access = input.CAT_access;
  tmp.livechat_access = input.livechat_access;
  tmp.liveq_access = input.liveq_access;
  tmp.liveevent_access = input.liveevent_access;
  tmp.flashcard_access = input.flashcard_access;
  tmp.question_access = input.question_access;
  tmp.baseline_ka_schedule = input.baseline_ka_schedule;


  let result = await tmp.save();
  if (input.schedule) {
    await db.sequelize.query("delete from hybrid_schedules where cohort_id= :id", { replacements: { id: input.id } })

    let schedule = input.schedule
    let cohort_id = input.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].cohort_id = cohort_id;
      await HybridSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (input.flashcard_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=2 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_flashcard=2 where id in(" + tmp.userslist.join() + ")");
    }
  } else {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=0 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_flashcard=0 where id in(" + tmp.userslist.join() + ")");
    }
  }
  if (input.practice_que_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=2 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_practque=2 where id in(" + tmp.userslist.join() + ")");
    }
  } else {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=0 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_practque=0 where id in(" + tmp.userslist.join() + ")");
    }
  }
  res.status(200).send(API._200(await result));
};

exports.updatepracticefeedback = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const feed = await QueDBUpdate.findByPk(input.id)
  feed.addressed = input.addressed;
  if (input.notes)
    feed.notes = input.notes;
  res.status(200).send(API._200(await feed.save()));
};