//const sendEmail = require("../../../managers/mailManager");
const { transformDateTimeField } = require("../../../managers/formatDateTime");

const db = require("../../../managers/dbConfig");
const bcryptjs = require("bcryptjs");

const adminRegister = async (req, res) => {
  const salt = await bcryptjs.genSalt(12);
  let { firstName, lastName, email, phone_num, password, confirmpassword } =
    req.body;

  if (!firstName || !lastName || !email || !phone_num || !password)
    throw "please fill all field";
  if (password !== confirmpassword)
    throw "password and confirm-password do not match";

  const hashedPassword = await bcryptjs.hash(password, salt);

  const sql =
    "INSERT INTO hospital_man(firstName, lastName, email, phone_num, password) VALUE(?,?,?,?,?)";
  const sql1 = "SELECT COUNT(*) FROM hospital_man WHERE email = ?";
  const sql2 =
    "SELECT id,email,phone_num,date_time FROM hospital_man WHERE email = ?";

  const [rows] = await db.query(sql1, [email]);
  const getAdmin = rows[0]["COUNT(*)"];

  if (getAdmin > 0) throw "Admin with this email already exist";
  await db.query(sql, [firstName, lastName, email, phone_num, hashedPassword]);

  const [getNewUser] = await db.query(sql2, [email]);
  const subject = `Welcome to ${process.env.hosp_name} – Important Next Steps`;

  const message = `
  <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${process.env.hosp_name} EMR System</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
        }
         .container {
            max-width: 500px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin: 20px auto; /* Reducing top margin to fix extra space */
        }
        .btn {
            display: inline-block;
            padding: 10px 15px;
            margin-top: 10px;
            color: #fff;
            background-color: #007bff;
            text-decoration: none;
            border-radius: 5px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .footer {
            margin-top: 20px;
            font-size: 14px;
            color: #777;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Welcome to ${process.env.hosp_name}!</h2>
        <p>Dear <strong>${firstName} ${lastName}</strong>,</p>
        <p>We’re excited to have you on board.</p>
        <p>Your account has been created. Before you start using your account, please change your default password by clicking on "forgot password" at the login page.</p>
        
        <p>If you have any issues, please contact technical support.</p>
        <p>Best regards,</p>
        <p><strong>Abdullahi Olaniyan</strong><br>
        <strong>Technical officer</strong><br>
        <strong>${process.env.hosp_name}</strong></p><br>
         <div class="footer">
            &copy; ${new Date().getFullYear()} G.O. Developers Group. All rights reserved.
        </div>
    </div>
</body>
</html>
`;

  // // await sendEmail(email, subject, message);

  res.status(201).json({
    status: "success",
    message: "New admin successfully Registered",
    data: getNewUser[0],
  });
};

const getAdmin = async (req, res) => {
  let { name, limit, offset, page } = req.pagination;

  const sql1 = `SELECT *  FROM hospital_man WHERE firstName LIKE ? OR phone_num LIKE ?`;
  const sql = `SELECT * FROM hospital_man ORDER BY id ASC LIMIT ? OFFSET ?`;
  let details;

  if (name) {
    const [validName] = await db.execute(sql1, [`%${name}%`, `%${name}%`]);

    if (validName.length === 0) throw "No matching record found";
    // id = validName[0]["id"];

    details = validName;
  } else {
    [details] = await db.execute(sql, [limit, offset]);
  }

  const data = transformDateTimeField(details);
  //console.log(staffDetails);

  res.status(200).json({
    status: "success",
    page,
    data,
  });
};

const deleteAdmin = async (req, res) => {
  const { id } = req.query;
  //console.log(id);
  if (!id) throw "staff ID is required!";
  const adminExistSql = "SELECT id FROM hospital_man WHERE id=?";
  const deleteSql = "DELETE FROM hospital_man WHERE id=?";
  const [adminExist] = await db.execute(adminExistSql, [id]);
  //console.log(adminExist);
  if (adminExist.length == 0) throw `admin with ID-- ${id} NOT found`;

  await db.execute(deleteSql, [id]);
  res.status(204).json({
    status: "success",
    message: `admin with ID-- ${id} successfully deleted`,
  });
};
module.exports = { adminRegister, getAdmin, deleteAdmin };
