const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const passport = require('passport');
const request = require('request');
const axios = require('axios');
const multer = require('multer');
const path = require('path');
const flash = require('connect-flash');
const session = require('express-session');
const bodyParser = require("body-parser");
const methodOverride = require('method-override')
const router = express.Router();
var https = require('follow-redirects').https;
var fs = require('fs');
const moment = require('moment');
const today = moment();
const bcrypt = require('bcryptjs');
var convert = require('color-convert');
const nodemailer = require("nodemailer");
const util = require('util')
const unlinkFile = util.promisify(fs.unlink)
const { ToadScheduler, SimpleIntervalJob, Task } = require('toad-scheduler');
const scheduler = new ToadScheduler();


var https = require('follow-redirects').https;
var async = require('async');
const crypto = require('crypto');

// Load User model
const User = require('../models/User');
const Company = require('../models/Company');
const Client = require('../models/Client');
const Consultation = require('../models/Consultation');

const { ensureAuthenticated, forwardAuthenticated } = require('../config/auth');



// Login Page
router.get('/login', forwardAuthenticated, (req, res) => res.render('login'));


// Register Page
router.get('/eregister', (req, res) => res.render('eregister'));

router.post('/register', async  (req, res)=>{
  console.log(req.body)

  var countryAndCurrency = req.body.country;
var split = countryAndCurrency.split(",");
var country = split[0];
var currency = split[1];
 const { companyPhone, companyName, main_currency, practice_countries, companyEmail, mainColor,  fullName, charge, password} = req.body; 

  var udate = today.format('DDMMYYYYHHMMSS')
  var date = today.format('DD MM YYYY HH MM');
  var phone = companyPhone;
  var email = companyEmail;
  var role = "admin";
  var otherCurrencies = [];
  paymentMethodKey = "test"
 
 if (req.body.currency && req.body.amount) {
  const otherCurrency = req.body.currency.reduce((acc, cur, index) => {
  acc.push({ [cur]: req.body.amount[index] });
  return acc;
}, []);
  otherCurrencies.push(otherCurrency);
  }

  

if (phone && email && companyEmail && companyPhone) {
  
        
  

       Company.create({main_currency:main_currency, practice_countries: practice_countries, otherCurrencies: otherCurrencies,  paymentMethodKey:paymentMethodKey, perConsultationCharge: charge, date: date, phone: companyPhone, name: companyName, email: companyEmail, country:country, setUpPaid: false, isActive:false },
          function(err, company) {
            if (err){
              console.log('we are here')
              res.send(err)
            };
            
            company.save()
              .then(company => {

                console.log(company)
                  if (phone.length >=1) {
  
  let errors = [];

  if (!email || !phone || !password ) {
    let error_msg = "It appears you haven't filled all the required spaces"
    res.render('eregister', {error_msg})
  }
   if (errors.length > 0) {
    let error_msg = "It appears you haven't filled all the required spaces"
    res.render('eregister', {error_msg})
  } else {
    User.findOne({ email: email }).then(user => {
      if (user) {
        let error_msg = 'It appears you are already signed up with that email address. To create another business, login and click "Add Business"'
console.log("delete" +company)
Company.deleteOne({_id: company._id }, function(err) {
    if (!err) {
           console.log('good');
    }
    else {
            console.log('gooder');
    }
});
     res.render('login', {
        
          error_msg
        });
      } else {

console.log("at user")
        var isVerified = false;
        var companiesOwning =company.accountNumber;
        const newUser = new User({
          
          phone,
          date,
          email,
          password,
          isVerified,
          companiesOwning, 
          role, 
          fullName
         

        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => {
                console.log("I am user" +user)

          Company.updateOne({accountNumber: company.accountNumber}, {$set: {owner: user._id}}, function(err, res){
 if(err){
      res.send(err)
    }
   
  })
                

 let success_msg = 'Signed up successfully'

     res.render('pay', {
        
          success_msg,
          currency: main_currency,
          company
        });
    
  
    
                console.log("new........... " +newUser)
              })
              .catch(err => console.log(err));
          });
        });
      }
    });
  }

   }

               })

            }

          )
    




} else {
  let error_msg = "Kindly ensure the following are filled up; company email address, company phone number, your email addresss and your phone number"
     res.render('eregister', {error_msg})
}

})


// Register Business Owner User - First Time
router.get('/eregister/:phone/:fullName/:email/:country/:password', (req, res) => {
  console.log('we are user register' + req.params)
var date = today.format('DD MM YYYY');
  const { phone, fullName, email, country, password} = req.params;
  if (phone.length >=10) {
  
  let errors = [];

  if (!email || !phone || !password ) {
    let error_msg = "An error happenned at registration, please try again"
    res.render('eregister', {error_msg})
  }
   if (errors.length > 0) {
    let error_msg = "An error happenned at registration, please try again"
    res.render('eregister', {error_msg})
  } else {
    User.findOne({ email: email }).then(user => {
      if (user) {
        let error_msg = 'The user already exists. Try Logging in or reseting password'

     res.render('login', {
        
          error_msg
        });
      } else {
        const newUser = new User({
          
          phone,
          date,
          email,
          password,  
          fullName
         

        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => {
              
               

 let success_msg = 'Signed up successfully'

     res.render('login', {
        
          success_msg
        });
    var message = {
      "ResultCode": 0,
      "ResultDesc": "Success"
    };
  
    res.json(message);
                console.log(newUser)
              })
              .catch(err => console.log(err));
          });
        });
      }
    });
  }

   }
});


router.get('/verifyemail/:email', function(req, res){
  User.findOne({email: req.params.email}).then(user =>{
        if (user) {
          console.log(user)

req.flash('success_msg', 'Email successfully verified, you can now proceed to login');
  res.redirect('/users/login');
 // let success_msg = 'Email successfully verified, you can now proceed to login'

 //     res.render('login', {
        
 //          success_msg
 //        });

           user.isVerified = true;

             user.save()
            .then(user => {
              console.log(user)

            })

        } else {
          res.send("The email address does not exist or you took over 3 days to verify the account and so the account was deleted. Please register again.")
        }
      })
         
                 
});


// Forgot Password
router.get('/passwordreset', function(req, res){
  res.render("passwordreset")
});

router.get('/reset', function(req, res){
  res.render("reset")
});

router.post('/passwordreset', function(req, res, next) {
  var email = req.body.email;
  async.waterfall([
    function(done) {
      crypto.randomBytes(2, function(err, buf) {
        var hex = buf.toString('hex');
  var token = parseInt(hex, 16);
        done(err, token);
      });
    },
    function(token, done) {
      User.findOne({ email: email }, function(err, user) {
        if (!user) {
          req.flash('error',  email + ' does not exist in our database.');
          return res.redirect('/users/passwordreset');
        }

        user.resetPasswordToken = token;
        user.resetPasswordExpires = Date.now() + 25920000; // 3 days

        user.save(function(err) {
          done(err, token, user);
        });
      });
    },
    function(token, user, done) {

      // Send welcome Email
                 // async..await is not allowed in global scope, must use a wrapper
async function main() {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  // let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.zoho.com",
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: "info@whispersapp.com", // generated ethereal user
      pass: "4612203106007Bc$", // generated ethereal password
    },
    tls: {
                rejectUnauthorized: false
            }
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Whispers App" <info@whispersapp.com>', // sender address
    to: user.email, // list of receivers
    subject: "Password Reset Link", // Subject line
     // text: "Hello world text",
     // plain text body
    html: '<body style="background-color: #002548;margin: 0;padding: 0;-webkit-text-size-adjust: none;text-size-adjust: none;box-sizing: border-box;"><table border="0" cellpadding="0" cellspacing="0" class="nl-container" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;background-color: #002548;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row row-1" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row-content stack" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;background-color: #003560;color: #000000;width: 600px;box-sizing: border-box;" width="600"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td class="column" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;font-weight: 400;text-align: left;vertical-align: top;padding-top: 0px;padding-bottom: 0px;border-top: 0px;border-right: 0px;border-bottom: 0px;border-left: 0px;box-sizing: border-box;" width="100%"><table border="0" cellpadding="20" cellspacing="0" class="image_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><div align="center" style="line-height: 10px;box-sizing: border-box;"><img alt="Whispers logo" src="https://www.whispersapp.com/img/whisperl.png" style="display: block;height: auto;border: 0;width: 240px;max-width: 100%;box-sizing: border-box;" title="Company logo" width="240"></div></td></tr></table></td></tr></tbody></table></td></tr></tbody></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="row row-2" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row-content stack" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;background-color: #003560;color: #000000;width: 600px;box-sizing: border-box;" width="600"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td class="column" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;font-weight: 400;text-align: left;vertical-align: top;padding-top: 0px;padding-bottom: 0px;border-top: 0px;border-right: 0px;border-bottom: 0px;border-left: 0px;box-sizing: border-box;" width="100%"><table border="0" cellpadding="0" cellspacing="0" class="image_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="width: 100%;padding-right: 0px;padding-left: 0px;box-sizing: border-box;"><div align="center" style="line-height: 10px;box-sizing: border-box;"><img alt="Welcome Image" src="https://www.whispersapp.com/img/service.jpg" style="display: block;height: auto;border: 0;width: 500px;max-width: 100%;box-sizing: border-box;" title="Happy Hanukkah header image" width="500"></div></td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="text_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;word-break: break-word;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="padding-bottom: 10px;padding-left: 10px;padding-right: 10px;padding-top: 60px;box-sizing: border-box;"><div style="font-family: "Times New Roman", Georgia, serif;box-sizing: border-box;"><div style="font-size: 14px;font-family: TimesNewRoman, "Times New Roman", Times, Beskerville, Georgia, serif;mso-line-height-alt: 16.8px;color: #ffffff;line-height: 1.2;box-sizing: border-box;"><p style="margin: 0;font-size: 14px;text-align: center;box-sizing: border-box;line-height: inherit;"><span style="font-size: 16px;box-sizing: border-box; color:#fff">Hi  </span></p></div></div></td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="heading_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="padding-bottom: 10px;padding-top: 10px;text-align: center;width: 100%;box-sizing: border-box;"><h1 style="margin: 0;color: #e7c390;direction: ltr;font-family: TimesNewRoman, "Times New Roman", Times, Beskerville, Georgia, serif;font-size: 35px;font-weight: normal;letter-spacing: normal;line-height: 120%;text-align: center;margin-top: 0;margin-bottom: 0;box-sizing: border-box;"><strong style="box-sizing: border-box; color:#fff;">Reseting your password?</strong></h1></td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="text_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;word-break: break-word;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="padding-bottom: 60px;padding-left: 10px;padding-right: 10px;padding-top: 10px;box-sizing: border-box;"><div style="font-family: "Times New Roman", Georgia, serif;box-sizing: border-box;"><div style="font-size: 14px;font-family: TimesNewRoman, "Times New Roman", Times, Beskerville, Georgia, serif;mso-line-height-alt: 16.8px;color: #ffffff;line-height: 1.2;box-sizing: border-box;"></div></div></td></tr></table></td></tr></tbody></table></td></tr></tbody></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="row row-3" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row-content stack" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;color: #000000;width: 600px;box-sizing: border-box;" width="600"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td class="column" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;font-weight: 400;text-align: left;vertical-align: top;padding-top: 5px;padding-bottom: 5px;border-top: 0px;border-right: 0px;border-bottom: 0px;border-left: 0px;box-sizing: border-box;" width="100%"><div class="spacer_block" style="height: 10px;line-height: 10px;font-size: 1px;box-sizing: border-box;"> </div></td></tr></tbody></table></td></tr></tbody></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="row row-4" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row-content stack" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;background-color: #f5f5f5;color: #000000;width: 600px;box-sizing: border-box;" width="600"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td class="column" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;font-weight: 400;text-align: left;vertical-align: top;padding-top: 35px;padding-bottom: 5px;border-top: 0px;border-right: 0px;border-bottom: 0px;border-left: 0px;box-sizing: border-box;" width="100%"><table border="0" cellpadding="0" cellspacing="0" class="heading_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="text-align: center;width: 100%;box-sizing: border-box;"><h2 style="margin: 0;color: #003560;direction: ltr;font-family: TimesNewRoman, "Times New Roman", Times, Beskerville, Georgia, serif;font-size: 24px;font-weight: normal;letter-spacing: normal;line-height: 120%;text-align: center;margin-top: 0;margin-bottom: 0;box-sizing: border-box;"><strong style="box-sizing: border-box;">You\'re receiving this because you or someone else requested to change your Whispers App Password</strong></h2></td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="text_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;word-break: break-word;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="padding-bottom: 35px;padding-left: 60px;padding-right: 60px;padding-top: 35px;box-sizing: border-box;"><div style="font-family: sans-serif;box-sizing: border-box;"><div style="font-size: 14px;mso-line-height-alt: 16.8px;color: #003560;line-height: 1.2;font-family: Arial, Helvetica Neue, Helvetica, sans-serif;box-sizing: border-box;"><p style="margin: 0;box-sizing: border-box;line-height: inherit;"><em style="box-sizing: border-box;">If you are not the one who requested for the reset, don\'t fret, your account is safe and your password will remain unchanged.</em></p><p style="margin: 0;mso-line-height-alt: 16.8px;box-sizing: border-box;line-height: inherit;"> </p><p style="margin: 0;box-sizing: border-box;line-height: inherit;">If you\'re the one who initiated the password reset process, please click on the link below to reset your password. <br>The link expires in 24 hours. </p><p style="margin: 0;mso-line-height-alt: 16.8px;box-sizing: border-box;line-height: inherit;"> </p><p style="margin: 0;mso-line-height-alt: 16.8px;box-sizing: border-box;line-height: inherit;"> </p><p style="margin: 0;mso-line-height-alt: 16.8px;box-sizing: border-box;line-height: inherit;"> </p></div></div></td></tr></table></td></tr></tbody></table></td></tr></tbody></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="row row-5" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row-content stack" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;color: #000000;width: 600px;box-sizing: border-box;" width="600"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td class="column" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;font-weight: 400;text-align: left;vertical-align: top;padding-top: 5px;padding-bottom: 5px;border-top: 0px;border-right: 0px;border-bottom: 0px;border-left: 0px;box-sizing: border-box;" width="100%"><div class="spacer_block" style="height: 10px;line-height: 10px;font-size: 1px;box-sizing: border-box;"> </div></td></tr></tbody></table></td></tr></tbody></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="row row-6" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td style="box-sizing: border-box;"><table align="center" border="0" cellpadding="0" cellspacing="0" class="row-content stack" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;background-color: #003560;color: #000000;width: 600px;box-sizing: border-box;" width="600"><tbody style="box-sizing: border-box;"><tr style="box-sizing: border-box;"><td class="column" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;font-weight: 400;text-align: left;vertical-align: top;padding-top: 0px;padding-bottom: 0px;border-top: 0px;border-right: 0px;border-bottom: 0px;border-left: 0px;box-sizing: border-box;" width="100%"><table border="0" cellpadding="0" cellspacing="0" class="heading_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="padding-bottom: 25px;padding-left: 20px;padding-right: 20px;padding-top: 55px;text-align: center;width: 100%;box-sizing: border-box;"><h2 style="margin: 0;color: #ffffff;direction: ltr;font-family: TimesNewRoman, "Times New Roman", Times, Beskerville, Georgia, serif;font-size: 24px;font-weight: normal;letter-spacing: normal;line-height: 120%;text-align: center;margin-top: 0;margin-bottom: 0;box-sizing: border-box;"><strong style="box-sizing: border-box; color:#fff;">Click here to reset...</strong></h2></td></tr></table><table border="0" cellpadding="0" cellspacing="0" class="button_block" role="presentation" style="mso-table-lspace: 0pt;mso-table-rspace: 0pt;box-sizing: border-box;" width="100%"><tr style="box-sizing: border-box;"><td style="text-align: center;padding-bottom: 50px;box-sizing: border-box;"><div align="center" style="box-sizing: border-box;"><!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="https://www.example.com" style="height:44px;width:190px;v-text-anchor:middle;" arcsize="0%" strokeweight="0.75pt" strokecolor="#E7C390" fill="false"><w:anchorlock/><v:textbox inset="0px,0px,0px,0px"><center style="color:#e7c390; font-family:Arial, sans-serif; font-size:16px"><![endif]--><a href="http://www.whispersapp.com/users/reset/' + email +'/'+ token +'" style="text-decoration: none;display: inline-block;color: #e7c390;background-color: transparent;border-radius: 0px;width: auto;border-top: 1px solid #E7C390;border-right: 1px solid #E7C390;border-bottom: 1px solid #E7C390;border-left: 1px solid #E7C390;padding-top: 5px;padding-bottom: 5px;font-family: Arial, Helvetica Neue, Helvetica, sans-serif;text-align: center;mso-border-alt: none;word-break: keep-all;box-sizing: border-box;" target="_blank"><span style="padding-left: 20px;padding-right: 20px;font-size: 16px;display: inline-block;letter-spacing: normal;box-sizing: border-box;"><span style="font-size: 16px;line-height: 2;word-break: break-word;mso-line-height-alt: 32px;box-sizing: border-box;">Reset Password</span></span></a><!--[if mso]></center></v:textbox></v:roundrect><![endif]--></div></td></tr></table></td></tr></tbody></table></td></tr></tbody></table></tbody></table></td></tr></tbody></table></body>', 
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);





 let success_msg = 'We\'ve sent a Reset Link to your email. Please click on it to reset the password'

     res.render('reset', {
        
          success_msg
        });

    }
     ], function(err) {
    if (err) return next(err);
     // req.flash('success_msg', `An e-mail has been sent to  with further instructions.`);
    res.redirect('/users/reset');
  });
});


// Reset the password

router.post('/reset', function(req, res){
  console.log(req.body)
  const passwordd = req.body.password;
  const email = req.body.email
async.waterfall([
  function(done){
  User.findOne({ resetPasswordToken: req.body.token, email: req.body.email, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
    if(!user){
      req.flash('error', 'Password reset token is invalid or has expired. Please try reseting again');
          return res.redirect('/users/passwordreset');
    }
      user.password = req.body.password;
        user.resetPasswordToken = undefined;
        user.resetPasswordExpires = undefined;




        bcrypt.genSalt(10, (err, salt)=>{
          bcrypt.hash(user.password, salt,(err, hash) =>{
            if (err) throw err;
            user.password = hash;
            user.save()
            .then(user =>{

console.log(passwordd + "changed")

 

let success_msg = 'Password succesfully changed. You can now proceed to login'

     res.render('login', {
        
          success_msg
        });
            })
          })
        })        
   
  })  
  }
  ])

})   


router.get('/reset/:email/:token', (req, res)=>{
 req.flash('success_msg', req.params.email);
 req.flash('email', 'req.params.email')
 req.flash('token', 'req.params.token')
  res.redirect('/users/reseted?data='+req.params.token )
})     


router.get('/reseted', (req, res)=>{
  console.log(req.url)
var token = req.url.slice(14)
console.log(token)
  
  res.render('reseted',{token})
}) 



     
           

router.post('/login', (req, res, next) => {
  passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/users/login',
    failureFlash: true
  })(req, res, next);
});

// Logout
router.get('/logout', (req, res) => {
  req.logout((err) => {
    if (err) {
      console.error(err);
      return res.status(500).send('An error occurred while logging out');
    }
    req.flash('success_msg', 'You are successfully logged out. See you back soon');
    res.redirect('/users/login');
  });
});


router.get('/', function(req, res){
  res.render('login')
});

module.exports = router;
