var express = require("express");
var router = express.Router({ mergeParams: true });
var User = require("../models/user");
var passport = require("passport");
var sendEmail = require('../tools/sendEmail');

//delete user
router.delete('/user', function (req, res) {
  User.deleteOne({ email: req.body.email }, function (err, user) {
    if (err) return res.json({ message: "failed", err: err });
    else
      return res.json({ message: "success" });
  });
  //  res.json({message:"pending"});
});


//get users
router.get("/users", isLoggedIn, function (req, res) {
  User.find({}, function (err, users) {
    if (err) {
      console.log(err);
    }
    else {
      res.json({ users });
    }
  })
});

//edit user profile
router.get("/current_user/profile", isLoggedIn, function (req, res) {
  res.render("user/profile");
});

//update profile info
router.put("/c_user/edit/profile", isLoggedIn, function (req, res) {
  console.log(req.body);
  User.findOne({ email: req.body.email }, function (err, user) {
    if (err) return res.redirect("/");
    if (user) {
      if (req.user.email != req.body.email) {
        return res.render("user/profile", { fail: true, desc: "email already used" });
      }
    }

    req.user.first_name = req.body.fname; req.user.last_name = req.body.lname;
    req.user.adress = req.body.adress; req.user.country = req.body.country;
    req.user.city = req.body.city; req.user.zip = req.body.zip;
    req.user.phone = req.body.phone;
    req.user.save(function () {
      if (req.user.email != req.body.email) {
        req.user.confirmed = false;
        req.user.email = req.body.email;
        req.user.save(function () { return res.redirect("/login"); });
      } else
        return res.redirect("/home");
    });
  });
});

//get user by email
router.get("/user/email/:email", isLoggedIn, function (req, res) {
  User.findOne({ email: req.params.email }, function (err, user) {
    if (err) {
      console.log(err);
    }
    else {
      console.log(user);
      res.json({ message: user ? "success" : "fail", user });
    }
  })
});

//check admin
router.get("/admin_info", function (req, res) {
  User.findOne({ role: 'admin' }, function (err, user) {
    if (err) {
      console.log(err);
      res.json({ message: "failed", err });
    }
    else if (user) {
      res.json({ message: "exists", user });
    }
    else
      res.json({ message: "failed" });
  })
});


/** register routes **/
router.get("/register", function (req, res) {
  res.render("register");
});

router.post("/register", function (req, res) {
  console.log(req.headers.host);
  User.findOne({ email: req.body.email }, function (err, user) {
    if (err) { console.log(err); return res.redirect("/login"); }
    else if (user) { console.log("user already exists"); return res.render("register", { fail: true, desc: "user already exists" }); }

    var newUser = new User({ role: "user", first_name: req.body.fname, last_name: req.body.lname, email: req.body.email, phone: req.body.phone, adress: req.body.adress, country: req.body.country, city: req.body.city, zip: req.body.zip });
    User.register(newUser, req.body.password, function (err, user) {
      if (err) { console.log(err); return res.redirect("/login"); }
      else {
        var mailOptions = {
          from: 'futureTech',
          to: req.body.email,
          subject: 'Confirm your account, futureTech',
          html: "Dear Mr " + req.body.lname + "," + "<br> we are inviting you to confirm your futureTech Shopping account by clicking this <a href='http://" + req.headers.host + "/confirm_account/" + user._id + "'>link</a>"
        };
        sendEmail(mailOptions);
        return res.render("user/verification");
      }
    });

  });
});

//confirm user account
router.get("/confirm_account/:user_id", function (req, res) {
  User.findOne({ _id: req.params.user_id }, function (err, user) {
    if (err) { console.log(err); return res.redirect("/login"); }
    else {
      user.confirmed = true;
      user.save(function () {
        res.redirect("/login");
      });
    }
  })
});

//send account confirmation email
router.post("/account/send/email_verification", isLoggedIn, function (req, res) {
  var mailOptions = {
    from: 'FutureTech',
    to: req.user.email,
    subject: 'Confirm your account, FutureTech',
    html: "Dear Mr " + req.user.last_name + "," + "<br> we are inviting you to confirm your FutureTech Shopping account by clicking this <a href='http://" + req.headers.host + "/confirm_account/" + req.user._id + "'>link</a>"
  };
  sendEmail(mailOptions);
  return res.json({ message: "success" });
});


/*** login routes **/
router.get("/login/:status?", function (req, res) {
  if (req.params.status == "fail")
    res.render("login", { status: req.params.status });
  else
    res.render("login");
});


/*************  Reset password  ***************/
/*1- get reset password by email*/
router.get("/reset/password", function (req, res) {
  res.render("user/password_reset");
});

//2- send reset password link
router.post("/send_email/reset_password", function (req, res) {
  User.findOne({ email: req.body.email }, function (err, user) {
    if (err) { console.log(err); return res.json({ message: "fail", desc: "email doesn't exist" }); }
    if (!user) { console.log("email doesn't exist"); return res.json({ message: "fail", desc: "email doesn't exist" }); }
    let userToken = Date.now() + Math.random().toString(16).substr(2) + Math.random().toString().substr(2) + Math.random().toString(36).substr(2);
    user.reset_pass_token.token = userToken;
    user.reset_pass_token.expiry = Date.now() + 3900000;
    var mailOptions = {
      from: 'FutureTech',
      to: req.body.email,
      subject: 'Reset your Account password, FutureTech',
      html: "Dear customer," + "<br> You requested a password reset, to recover your Shopping account please click this <a href='http://" + req.headers.host + "/user/" + user._id + "/new_password/" + userToken + "'><b>link</b></a>. <br> If you didn't request any please ignore this message."
    };
    user.save(async function () {
      let emailresponse = await sendEmail(mailOptions);
      req.flash('info', 'A One time link to reset your password has been sent to your email');
      console.log('Email sent: ' + emailresponse);
      return res.json({ message: "success" });
    });
  });
});

//3- new pass page
router.get("/user/:user_id/new_password/:token", function (req, res) {
  let token = req.params.token;
  User.findOne({ _id: req.params.user_id, "reset_pass_token.token": token },
    function (err, user) {
      if (err) { console.log(err); return res.redirect("/"); }
      if (!user) { console.log("user not found with token or id"); req.flash('info', "Link already used"); return res.redirect("/login"); }
      if (user.reset_pass_token.expiry < Date.now()) {
        console.log("token expired");
        user.reset_pass_token = null;
        req.flash('info', "Time expired");
        return user.save(function () {
          res.redirect("/login");
        })
      }
      else res.render("user/new_pass", { user_id: req.params.user_id, token });
    })
});

//change password
router.post("/user/:user_id/change_password/:token", function (req, res) {
  let token = req.params.token;
  User.findOneAndUpdate({ _id: req.params.user_id, "reset_pass_token.token": token },
    { reset_pass_token: null }, function (err, user) {
      if (err) { console.log(err); req.flash('info', 'une erreur est survenue'); return res.redirect("/login"); }
      if (!user) { console.log("user doesn't exist"); req.flash('info', "Compte n'existe pas"); return res.redirect("/login"); }
      user.setPassword(req.body.new_pass, function () {
        user.save(function () {
          res.redirect("/login");
        });
      });
    });

});


/****************************/


//admin login
router.get("/admin/login/:status?", function (req, res) {
  if (req.params.status == "fail")
    res.render("login", { status: req.params.status });
  else
    res.render("login");
});

router.post("/login", passport.authenticate("local", {
  successRedirect: "/", //home redirect
  failureRedirect: "/login/fail" //redirect to login
}));
//post admin login
router.post("/admin/login", passport.authenticate("local", {
  successRedirect: "/admin", //admin redirect
  failureRedirect: "/admin/login/fail" //redirect to login
}));

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


//first admin




function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else {
    res.redirect("/login");
  }
}
module.exports = router;
