const bcryptjs = require("bcryptjs");
const db = require("../../../managers/dbConfig");
const { generateID } = require("../../../managers/idGenerator");
const sendEmail = require("../../../managers/mailManager");

const registerStaff = async (req, res) => {
  const adminRank = req.user.rank;

  if (adminRank !== 1) throw "You're Not permited To Use This Resource!!!";
  try {
    const salt = await bcryptjs.genSalt();
    const { email, firstName, lastName, password, phoneNum, cadre } = req.body;

    if (!email) throw "email is required";
    if (!firstName || !lastName)
      throw "both firstName and lastName must be provided";
    if (!phoneNum) throw "phone number is required";
    if (phoneNum.length < 11) throw "Incomplete Phone Number";
    if (!cadre) throw "cadre is required";
    if (!password) throw "please provide a password";

    const sql =
      "INSERT INTO staffs (firstName, lastName, email,phone_num, password, cadre ) VALUES (?, ?, ?,?,?,?)";
    const sql1 = "UPDATE staffs SET staff_id=? WHERE id = ?";
    const sql2 = "SELECT COUNT(*) FROM staffs WHERE email =? OR phone_num=?";
    const sql3 = "SELECT * FROM staffs WHERE email = ?";

    const connection = await db.getConnection();
    await connection.beginTransaction(); // Start transaction

    const [rows] = await connection.query(sql2, [email, phoneNum]);

    const staffExist = rows[0]["COUNT(*)"] > 0;
    // console.log(rows[0]);
    if (staffExist)
      throw "A Staff with this Email or Phone-Number already exist";
    const hashedPassword = await bcryptjs.hash(password, salt);

    await connection.query(sql, [
      firstName,
      lastName,
      email,
      phoneNum,
      hashedPassword,
      cadre,
    ]);

    const [getNewUser] = await connection.query(sql3, [email]);

    const staff_id = await generateID(getNewUser[0], req.user.branch_id);

    await connection.query(sql1, [staff_id, getNewUser[0].id]);
    const [updatedUser] = await connection.query(sql3, [email]);
    delete updatedUser[0].id;
    delete updatedUser[0].password;

    await connection.commit(); // Commit transaction
    connection.release();

    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: 600px;
                margin: 0 auto;
                padding: 20px;
                border: 1px solid #ddd;
                border-radius: 5px;
                background-color: #f9f9f9;
            }
            .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;
            }
        </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 admin officer or IT support.</p>
            <p>Best regards,</p>
            <p><strong>Makinde Odunayo</strong><br>
            <strong>Admin officer</strong><br>
            <strong>${process.env.hosp_name}</strong></p>
        </div>
    </body>
    </html>
     `;

    await sendEmail(email, subject, message);

    res.status(201).json({
      status: "successful",
      message: "New Staff registered successfully",
      data: updatedUser[0],
    });
  } catch (e) {
    res.status(400).json({
      error: e,
    });
  }
};

// updating an existing HMO record.

const updateStaffRecord = async (req, res) => {
  const {
    id,
    fName,
    lName,
    address,
    age,
    email,
    phone_num,
    gender,
    cadre,
    password,
    updated_by,
  } = req.body;

  // ✅ Check required field (ID is necessary to update a record)
  if (!id) throw "Staff ID is required for updating.";

  // ✅ SQL Queries (on separate lines)
  const checkStaffSql = `
        SELECT * 
        FROM staffs 
        WHERE staff_id = ?`;

  const updateStaffSql = `
        UPDATE staffs 
        SET firstName = ?,
            lastName = ?,
            age = ?,
            gender = ?,
            email = ?, 
            address = ?,
            phone_num = ?,
            password = ?, 
            cadre = ? 
        WHERE staff_id = ?`;

  // ✅ Check if the Staff exists
  const [existingStaff] = await db.execute(checkStaffSql, [id]);
  if (existingStaff.length === 0) throw `No Staff with ID ${id} found.`;

  // ✅ Update the Staff record
  await db.execute(updateStaffSql, [
    fName || existingStaff[0].firstName,
    lName || existingStaff[0].lastName,
    age || existingStaff[0].age,
    gender || existingStaff[0].gender,
    email || existingStaff[0].email,
    address || existingStaff[0].address,
    phone_num || existingStaff[0].phone_num,
    password || existingStaff[0].password,
    cadre || existingStaff[0].cadre,

    id,
  ]);

  res.status(200).json({
    status: "Success",
    message: `Staff record with ID ${id} updated successfully.`,
  });
};

module.exports = { registerStaff, updateStaffRecord };
