const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { User, TeacherAccess, Books, Certificate, Company, ClientCohort } = require("../models");

exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('AdminLogs', input)));
};
exports.admin_login = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data)
  let email = data.email;
  let roll_id = 1;
  let password = await helper.getHashedPassword(data.password.toString());
  const user = await User.findOne({ where: { email, roll_id } });
  if (!user) {
    res.status(200).send(API._200({ message: "User not found", user_status: 404 }));
  }
  const passwordMatch = user.password === password;
  if (!passwordMatch) {
    res.status(200).send(API._200({ message: "Invalid password", user_status: 404 }));
  }
  res.status(200).send(API._200(user));
};
exports.all = async (req, res) => {
  res.status(200).send(API._200(await db_helper.allData('AdminLogs')));
};
exports.addbooks = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('Books', input)));
};
exports.addcompany = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('Company', input)));
};
exports.addteacher = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  if (data.password) data.password = await helper.getHashedPassword(data.password.toString());
  data.remember_token = helper.generateAuthToken();
  const user = await User.create(data).catch((ex) => console.log(ex));
  var teacher = {
    "user_id": user.id,
    "certi_Ids": data.certi_Ids
  };
  await TeacherAccess.create(teacher).catch((ex) => console.log(ex));
  res.status(200).send(API._200(await user));
};
exports.alladmin = async (req, res) => {
  var user = await User.findAll({
    where: {
      roll_id: 1
    }
  });
  user = user.map((res) => res.toJSON());
  if (!user) {
    res.status(404).send(API._404({ message: 'User was not found' }));
  }
  var q = [];
  for (let i = 0; i < user.length; i++) {
    q.push(`select id,cohort_name from cohorts where FIND_IN_SET(${user[i].id},userslist)`);
  }
  var all = await db_helper.query(q.join('; '));
  for (let j = 0; j < all[0].length; j++) {
    user[j].cohort = all[0][j];
  }
  res.status(200).send(API._200(await user));
};
exports.alluser = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const Op = db.Sequelize.Op;
  var user = await User.findAndCountAll({
    where: {
      roll_id: 3,
      status: 0,
      [Op.or]: [{
        email: {
          [Op.like]: '%' + input.search + '%'
        }
      },
      {
        name: {
          [Op.like]: '%' + input.search + '%'
        }
      }
      ]
    },
    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 FIND_IN_SET(${user.rows[i].id},userslist)`);
    user.rows[i].notes = all[0];
  }
  res.status(200).send(API._200(await user));
};
exports.allbooks = async (req, res) => {
  const all = await Books.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  })
  res.status(200).send(API._200(await all));
};
exports.allclient = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const Op = db.Sequelize.Op;
  let mycomp = await db.sequelize.query("select GROUP_CONCAT(id) id from companies where status=0 and 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) {
    if (input.active != "chortname") {
      sortBy = input.active;
      direction = input.direction;
    }
  }
  var clients = await User.findAndCountAll({
    where: {
      roll_id: 4,
      status: 0,
      [Op.or]: [{
        email: {
          [Op.like]: '%' + input.search + '%'
        }
      },
      {
        company_id: [mycomp[0].id]
      },
      {
        name: {
          [Op.like]: '%' + input.search + '%'
        }
      }
      ]
    },
    order: [
      [sortBy, direction]
    ],
  })
  let data = { count: clients.count, rows: [] };
  for (let i = 0; i < clients.rows.length; i++) {
    const cl = await ClientCohort.findAll({
      where: {
        status: 0,
        user_id: clients.rows[i].id
      }
    });
    const comp = await Company.findAll({
      where: {
        status: 0,
        id: clients.rows[i].company_id
      }
    });
    let cohort = [];
    let ccid = 0;
    if (cl.length > 0) {
      cohort = await db_helper.query("select id,cohort_name from cohorts where status=0 and id in(" + cl[0].cohortIds + ")");
      ccid = cl[0].id;
    }
    if (cohort.length > 0) {
      cohort = cohort[0];
    }
    data.rows.push({
      clientcohortId: ccid,
      id: clients.rows[i].id,
      name: clients.rows[i].name,
      email: clients.rows[i].email,
      roll_id: clients.rows[i].roll_id,
      email_verified_at: clients.rows[i].email_verified_at,
      email_verified: clients.rows[i].email_verified,
      calling_code: clients.rows[i].calling_code,
      mobile: clients.rows[i].mobile,
      profile_img: clients.rows[i].profile_img,
      permissions: clients.rows[i].permissions,
      password: clients.rows[i].password,
      remember_token: clients.rows[i].remember_token,
      free_flashcard: clients.rows[i].free_flashcard,
      free_practque: clients.rows[i].free_practque,
      free_flashccsp: clients.rows[i].free_flashccsp,
      pass_rest_code: clients.rows[i].pass_rest_code,
      avatar_url: clients.rows[i].avatar_url,
      is_first: clients.rows[i].is_first,
      aliasname: clients.rows[i].aliasname,
      is_temp: clients.rows[i].is_temp,
      notes: clients.rows[i].notes,
      address: clients.rows[i].address,
      status: clients.rows[i].status,
      company_id: clients.rows[i].company_id,
      cohorts: cohort,
      company: comp
    })
  }
  res.status(200).send(API._200(await data));
};
exports.allteacher = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const Op = db.Sequelize.Op;
  let mycomp = await db.sequelize.query("select GROUP_CONCAT(id) id from companies where status=0 and 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) {
    if (input.active != "chortname") {
      sortBy = input.active;
      direction = input.direction;
    }
  }
  var clients = await User.findAndCountAll({
    where: {
      roll_id: 4,
      status: 0,
      [Op.or]: [{
        email: {
          [Op.like]: '%' + input.search + '%'
        }
      },
      {
        company_id: [mycomp[0].id]
      },
      {
        name: {
          [Op.like]: '%' + input.search + '%'
        }
      }
      ]
    },
    order: [
      [sortBy, direction]
    ],
  })
  let data = { count: clients.count, rows: [] };
  for (let i = 0; i < clients.rows.length; i++) {
    const cl = await ClientCohort.findAll({
      where: {
        status: 0,
        user_id: clients.rows[i].id
      }
    });
    const comp = await Company.findAll({
      where: {
        status: 0,
        id: clients.rows[i].company_id
      }
    });
    let cohort = [];
    let ccid = 0;
    if (cl.length > 0) {
      cohort = await db_helper.query("select id,cohort_name from cohorts where status=0 and id in(" + cl[0].cohortIds + ")");
      ccid = cl[0].id;
    }
    if (cohort.length > 0) {
      cohort = cohort[0];
    }
    data.rows.push({
      clientcohortId: ccid,
      id: clients.rows[i].id,
      name: clients.rows[i].name,
      email: clients.rows[i].email,
      roll_id: clients.rows[i].roll_id,
      email_verified_at: clients.rows[i].email_verified_at,
      email_verified: clients.rows[i].email_verified,
      calling_code: clients.rows[i].calling_code,
      mobile: clients.rows[i].mobile,
      profile_img: clients.rows[i].profile_img,
      permissions: clients.rows[i].permissions,
      password: clients.rows[i].password,
      remember_token: clients.rows[i].remember_token,
      free_flashcard: clients.rows[i].free_flashcard,
      free_practque: clients.rows[i].free_practque,
      free_flashccsp: clients.rows[i].free_flashccsp,
      pass_rest_code: clients.rows[i].pass_rest_code,
      avatar_url: clients.rows[i].avatar_url,
      is_first: clients.rows[i].is_first,
      aliasname: clients.rows[i].aliasname,
      is_temp: clients.rows[i].is_temp,
      notes: clients.rows[i].notes,
      address: clients.rows[i].address,
      status: clients.rows[i].status,
      company_id: clients.rows[i].company_id,
      cohorts: cohort,
      company: comp
    })
  }
  res.status(200).send(API._200(await data));
};

exports.deletebook = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('Books', input.id)));
};
exports.deletecompany = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('Company', input.id)));
};
exports.updatebooks = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.update('Books', input)));
};
exports.updatecompany = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.update('Company', input)));
};
exports.updateteacher = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const user = await User.findByPk(input.id)
  if (!user) {
    res.status(404).send(API._404({ message: `User with id: ${input.id} was not found` }));
  }
  if (input.name) user.name = input.name;
  if (input.mobile) user.mobile = input.mobile;
  user.remember_token = helper.generateAuthToken();
  let success = await user.save();
  if (input.certi_Ids) {
    await db_helper.query("UPDATE teacher_accesses set certi_Ids='" + input.certi_Ids + "' WHERE user_id=" + input.id);
  }
  res.status(200).send(API._200(await success));
};