const db = require("../config/database");
const nodemailer = require("nodemailer");
// const date = new Date();
// console.log(date);


// const transporter  = nodemailer.createTransport({
//   service: 'Gmail',
//   auth:{
//     user:'noreply@ftvrealestate.in',
//     pass:'Fashiontv@123',
//   },
// });

const transporter = nodemailer.createTransport({
   host: "smtp.gmail.com",
//   host: "mail.ftvrealestate.in",
  port: 587,
  secureConnection: true,
  auth: {
    user: "noreply@ftvrealestate.in",
    pass: "ibnbleqfxidtsjwf",
  },
  tls: {
    rejectUnauthorized: false
}
});





module.exports = {
  user: (data, callBack) => {
    db.query(
      `insert into auth(name,email,password,status)values(?,?,?,?)`,
      [data.name, data.email, data.password, data.status],
      (error, results, fields) => {
        if (error) {
          return callBack(error);
        }
        return callBack(null, results);
      }
    );
  },

  create: (data, callBack) => {
    db.query(
      `SELECT * FROM enquires WHERE contact = ?`,
      [data.contact],
      (error, results, fields) => {
        if (error) {
          console.error("Database query error:", error);
          return callBack({ message: "Database query error" });
        }
  
        if (results.length > 0) {
          return callBack({ message: "User with this contact number already exists. Please use a different number." });
        }
  

        db.query(
          `INSERT INTO enquires(unique_code,fullname, email, contact, state, city, investment, message, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
          [
            data.uniqueId,
            data.fullname,
            data.email,
            data.contact,
            data.state,
            data.city,
            data.investment,
            data.message,
            data.created_at,
          ],
          (error, results, fields) => {
            if (error) {
              console.error("Database insertion error:", error);
              if (error.code === "ER_DUP_ENTRY") {
                return callBack({ message: "Duplicate entry. User with this unique code already exists." });
              } else {
                return callBack({ message: "Error occurred while inserting user." });
              }
            }
            return callBack(null, results);
          }
        );
      }
    );
  },
  
  
  

  // Assuming your getmeta function accepts query parameters
  getmeta: (metasource, callBack) => {
    db.query(
      `SELECT * FROM meta_content where meta_source_name = ?`,
      [metasource],
      (error, results, fields) => {
        if (error) {
          return callBack(error);
        }
        return callBack(null, results);
      }
    );
  },

  getUserByUserEmail: (email, callBack) => {
    db.query(
      `SELECT * FROM auth where email = ?`,
      [email],
      (error, results, fields) => {
        if (error) {
          callBack(error);
        }
        return callBack(null, results[0]);
      }
    );
  },

  contact: (data, callBack) => {
    db.query(
      `insert into contact(name,email,mobile,created_at)values(?,?,?,?)`,
      [data.name, data.email, data.mobile, data.created_at],
      (error, results, fields) => {
        if (error) {
          return callBack(error);
        }
        return callBack(null, results);
      }
    );
  },

  checkIfEmailExists: (subscribe_email, callBack) => {
    db.query(
      `SELECT * FROM newsletter where email = ?`,
      [subscribe_email],
      (error, results, fields) => {
        if (error) {
          callBack(error);
        }
        return callBack(null, results);
      }
    );
  },

  saleForceLeadResponse: (data, callBack) => {
    const timestamp =  new Date().toISOString().slice(0, 19).replace('T', ' ');
    const jsonData = JSON.stringify(data);

    db.query(
      `INSERT INTO saleforce_response (web_unique_code, lead_response, created_at) VALUES (?, ?, ?)`,
      [data.uniqueId, jsonData, timestamp],
      (error, results, fields) => {
        if (error) {
          return callBack(error);
        }
        return callBack(null, results);
      }
    );
  },
  

  addNewSubscriber: (data, callBack) => {
    db.query(
      `insert into newsletter(email,subscribe_status,created_at)values(?,?,?)`,
      [data.email, data.subscribe_status, data.created_at],
      // console.log(db),
      (error, results, fields) => {
        if (error) {
          callBack(error);
        }
        return callBack(null, results);
      }
    );
  },

  sandWelcomeEmail: (email, callBack) => {
    const mailOptions = {
      from: 'noreply@ftvrealestate.in',
      to: email,
      subject: 'Welcome to Our Newsletter!',
      text: 'Thank you for subscribing to our newsletter. We are excited to have you on board!',
    };

    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          console.error("Error sending email:", error);
          callBack(error, null);
      } else {
          console.log("Email sent:", info.response);
          callBack(null, true);
      }
  });
  }
};
