const {
  transformDateTimeField,
  getFormattedDateTime,
  getCurrentYearMonth,
} = require("../../../../managers/formatDateTime");
const db = require("../../../../managers/dbConfig");
const { decryptRecords } = require("../../../../managers/decryption");
//const sendEmail = require("../../../../managers/mailManager");

const cdashBoard = async (req, res) => {
  const userProfile = req.user;
  if (
    userProfile.cadre !== "Doctor" &&
    userProfile.cadre !== "Nurse" &&
    userProfile.cadre !== "CHP" &&
    userProfile.cadre !== "CHO" &&
    userProfile.rank !== 1
  )
    throw "You're not permitted to Access this Resources";

  const currentYearMonth = getCurrentYearMonth();
  const year = new Date().getFullYear();
  const startDate = `${year}-01`;
  const endDate = `${year}-12`;
  let monthlyTxCount;

  const date = getFormattedDateTime();

  const sql = `SELECT tx.*, patients.firstName, patients.lastName 
  FROM tx
  LEFT JOIN patients ON tx.patient_id = patients.patient_id
  ORDER BY tx.id DESC 
  LIMIT 10`;

  const sql1 = `SELECT total_count
  FROM counters
  WHERE table_name = ? AND month_year = ?`;

  const sql2 = `SELECT COUNT(*) FROM tx WHERE DATE(date_time)=?`;

  const sql3 = `SELECT SUM(total_count) AS total_tx
  FROM counters
  WHERE table_name = ?
  AND month_year BETWEEN ? AND ?`;

  const [txCountToday] = await db.execute(sql2, [date]);
  const todayTxCount = txCountToday[0]["COUNT(*)"];

  const [tx_count] = await db.execute(sql1, ["tx", currentYearMonth]);
  if (tx_count[0]) {
    monthlyTxCount = tx_count[0].total_count;
  }

  const [y_count] = await db.execute(sql3, ["tx", startDate, endDate]);
  const yearlyTxCount = y_count[0].total_tx;

  //const [tx_count] = await db.execute(sql1, ["tx", currentYearMonth]);

  const [getRxHx] = await db.execute(sql);
  const rxHx = getRxHx;

  const sanitizedDateTime = transformDateTimeField(rxHx);

  const encryptedData = [
    "c_o",
    "hx",
    "drug_hx",
    "o_e",
    "lab_inv",
    "diag",
    "rx",
    "dr_note",
  ];
  const decryptedData = decryptRecords(
    sanitizedDateTime,
    process.env.enc_key,
    encryptedData
  );

  //   const message = `YOU JUST LOGIN SUCCESSFULLY, WELCOME TO YOUR DASHBOARD`;
  //   const subject = `GREETINGS`;

  //   let email = req.user.email;
  //   sendEmail(email, subject, message);

  res.status(200).json({
    message: "Hello from dashboard",
    userProfile,
    todayTxCount,
    monthlyTxCount,
    yearlyTxCount,
    hx: decryptedData,
    // Time: currentDate,
  });
};

module.exports = cdashBoard;
