const mysql = require('mysql2');
const pool = require('../helpers/db').pool;
const nodemailer = require('nodemailer');
const util = require('util');
const e = require('express');
const {queryDb} = require("../helpers/db");
const crypto = require('crypto');
const {sendSimpleMail} = require("../helpers/sendSimpleMail");
const {main: sendCpanelMail} = require("../controllers/emailController");

let Lead = class{
    constructor(){
    }

    async sendMailContact(name, email, phone, message) {
        // send mail to user
        const from = process.env.CONTACT_USER_MAIL_FROM
        const to = email
        const subject = "We've received your message and we'll get back to you soon."
        const text = "Hello " + name + ", <p>Our colleagues will get back to you soon.</p> <p>Here is the info you've sent us:</p><br/> Name: " + name + "<br/> Email: " + email + "<br/>Phone: " + phone + "<br/> Message: " + message + "<br/><br/> <img style='margin:20px 0; max-width:200px;' src='https://24hrslocksmith.co.uk/uploads/img/logo/24hrslocksmith_logo.png'/> <br/> © 2022 <br/><br/>";
        await sendSimpleMail(from, to, subject, text)

        // send mail to admin
        const adminFrom = process.env.CONTACT_ADMIN_MAIL_FROM
        const adminTo = process.env.CONTACT_ADMIN_MAIL_TO
        await sendSimpleMail(adminFrom, adminTo, subject, text)
    }

    async sendMail(subject, name, email, phone, message){


        const date = new Date();
        let body = "";
        let bodyTWO = "";
        const leadsMail = "office@24hrslocksmith.co.uk";
        function retrieveInserted(query){
          return new Promise(function(resolve, reject) {
            pool.query(query, function (err, results, fields) {
              // console.log("err: " + err + " | result id: " + fields.name + " | results: " + JSON.stringify(results) + " | fields: " + fields);
              if (err) {
                  reject(err);
              } else {
                // console.log(JSON.stringify(fields));
                resolve(results);
              }
            });
          });
        }

        //if it's just a simple form message
        body = bodyTWO = "Hello " + name + ", <p>Our colleagues will get back to you soon.</p> <p>Here is the info you've sent us:</p><br/> Name: " + name + "<br/> Email: " + email + "<br/>Phone: " + phone + "<br/> Message: " + message + "<br/><br/> <img style='margin:20px 0; max-width:200px;' src='https://24hrslocksmith.co.uk/uploads/img/logo/24hrslocksmith_logo.png'/> <br/> © 2022 <br/><br/>";
        

        // create reusable transporter object using the default SMTP transport
        let transporter = nodemailer.createTransport({
          host: "mail.24hrslocksmith.co.uk",
          port: 465,
          secure: true, // true for 465, false for other ports
          auth: {
            user: "no-reply@24hrslocksmith.co.uk",
            pass: "t]{ZL]p8peL)",
          },
        });

        // send mail with defined transport object
        let info = await transporter.sendMail({
          from: '"24hrs Locksmith" <no-reply@24hrslocksmith.co.uk>', // sender address
          to: email, // list of receivers
          subject: subject, // Subject line
        //   text: "Hello world?", // plain text body
          html: body, // html body
        });

        // send mail with defined transport object
        let infoTWO = await transporter.sendMail({
          from: '"24hrs Locksmith" <no-reply@24hrslocksmith.co.uk>', // sender address
          to: leadsMail, // list of receivers
          subject: subject, // Subject line
        //   text: "Hello world?", // plain text body
          html: bodyTWO, // html body
        });

        console.log("Message sent: %s", info.messageId);


    }

    async insertInDb(name, email, phone, message, res, next){

        const date = new Date();
        const query = 'INSERT INTO ContactForm (`name`, `email`, `phone`, `message`, `date_add`) VALUES (' + mysql.escape(name) + ', ' + mysql.escape(email) + ', ' + mysql.escape(phone) + ', ' + mysql.escape(message) +  ', ' + mysql.escape(date) + ')';
        console.log(query);
        let queryExec = await pool.query(query, function (err, results, fields) {
            // try{
            //     let sol = results[0];
            //     console.log('The solution is: ', results);
            //     // this.endDbConn();
                
            // }catch{
            //     console.log("error: " + err);
            // }

        });
        next();
        // let queryFinish = await queryExec.then(function(pool){
        //     pool.end(function (err) {
        //         if (err) throw err;
        //         process.exit();
        //     });
        // });
        // return queryFinish;

        return queryExec;
    }

    async insertLead(email, phone, name, message, recaptchaScore){
        const date = mysql.escape(new Date())
        email = mysql.escape(email)
        phone = mysql.escape(phone)
        name = mysql.escape(name)
        message = mysql.escape(message)
        const recScore = typeof recaptchaScore !== 'undefined' && recaptchaScore ? recaptchaScore : null
        // const recScore = 0.8
        const query = `INSERT INTO ContactForm (name, email, phone, message, date_add, recaptcha_score) 
            VALUES (${name}, ${email}, ${phone}, ${message}, ${date}, ${recScore})`
        await queryDb(query)
    }

    createIdHash(id) {
        const content = id + process.env.QU_FORM_SALT;
        const sign = crypto
            .createHash('sha256')
            .update(content)
            .digest('hex')
        return id + '.' + sign
    }

    validateIdHash(idHash) {
        const id = idHash.split('.')[0]
        const correctIdHash = this.createIdHash(id)
        return (idHash === correctIdHash) ? id : null
    }

    async endDbConn(){
      // connection.release();
        // let queryFinish = await pool.end(function (err) {
        //     if (err) throw err;
        //     process.exit();
        // });
      return "1";
      // return queryFinish;
    }

}


module.exports = Lead;
