const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Enrolluser, Flashcard, Domain, Subdomain, Topic, Certificate, Cource } = require("../models");

exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var err = [];
  const enrollusers = await Enrolluser.create(input).catch((ex) => err = ex.errors[0]);
  if (err.message) {
    res.status(404).send(API._404({ message: err.message }));
  };
  res.status(200).send(API._200(await enrollusers));
};
exports.update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let usr = {
    "u_id": input.u_id,
    "c_id": input.c_id
  }
  const cc = await db_helper.selectByWhere("Enrolluser", usr);
  let c = [];
  if (cc.length > 0) {
    const enrl = await db_helper.selectByPk("Enrolluser", cc[0].id);
    if (input.opt_in) enrl.opt_in = input.opt_in;
    if (input.schedule_date) enrl.schedule_date = input.schedule_date;
    c = enrl.save();
  } else {
    c = await Enrolluser.create(input).catch((ex) => err = ex.errors[0]);
  }
  res.status(200).send(API._200(await c));
};
exports.get_payment_transactions_by_user = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query("select id,user_id,email,cohort_id,amount,product_purchased,tier_essential from payment_transactions where (user_id=" + data.user_id + " OR email='" + data.email + "') AND cohort_id=" + data.cohort_id).then((res1) => {
    return Array.from(new Set(res1));
  })
  res.status(200).send(API._200(await result[0]));
};
exports.flashcardAll = async (req, res) => {
  const flashcard = Flashcard.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Domain,
      attributes: ['id', 'domin_name']
    }, {
      model: Subdomain,
      attributes: ['id', 'subdomain_name']
    }, {
      model: Topic,
      attributes: ['id', 'topic_name']
    }, {
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }, {
      model: Cource,
      attributes: ['id', 'course_name']
    }]
  });
  res.status(200).send(API._200(await flashcard));
};
