const User = require("../models/User");
const Email = require("../controllers/email");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const ejs = require("ejs");
const path = require("path");
const OTPController = require("./OTPController");



// @route GET api/user
// @desc Returns all users
// @access Public
exports.signup = async function (req, res) {
  console.log("Abc===>>>", req.body)
  let body = req.body;
  const { firstname, lastname, email, phNum, password, allowemail, allowsms } = req.body;
  if (
    !firstname ||
    !lastname ||
    !email ||
    !phNum ||
    allowsms === undefined ||
    allowemail === undefined ||
    !password
  ) {
    res.status(500).json({ message: "Empty Fields" })
  } else {
    try {
      User.findOne().sort({ createdAt: -1 }).exec(async (err, lastUser) => {
        if (err) {
          console.error("Error finding last user:", err);
          return res.status(500).json({ success: false, message: "Error finding last user" });
        }

        let accountNumber = 12000786;

        if (lastUser && lastUser.accountNumber) {
          // Convert the string accountNumber to a number
          const lastAccountNumber = parseInt(lastUser.accountNumber, 10);

          // Check if the conversion was successful
          if (!isNaN(lastAccountNumber)) {
            // Increment the accountNumber
            accountNumber = lastAccountNumber + 1;
          } else {
            console.error("Invalid account number:", lastUser.accountNumber);
          }
        }

        const user = new User(body);

        try {
          const savedUser = await user.save(); 
          await Email.verifyUserEmail(body, User); 
          res.status(200).json({ message: "success", user: savedUser });
        } catch (saveError) {
          console.error("Error saving user:", saveError);
          res.status(500).json({ success: false, message: saveError?.message || saveError });
        }
      });
    } catch (error) {
      console.error("Error:", error);
      res.status(500).json({ success: false, message: "Internal server error" });
    }

  }
};



exports.VerifyEmail = async (req, res, next) => {
  let enteredOTP = req.params.otp;
  let email = req.params.email;
  let data = {
    email: email,
    otp: enteredOTP
  }
  try {
    // console.log("req.params.email", req.params.email);
    let storedOTP = await OTPController.VerifyOtp(email , enteredOTP);
    console.log("storedOTP", storedOTP);
    const filter = { email: req.params.email };
    const update = { verified: true }; 
    const user = await User.findOneAndUpdate(filter, update, { new: true });
    console.log("abc====",user)
    if (storedOTP && enteredOTP === storedOTP) {

      if (!user)
        return next({
          success: false,
          data: {},
          message: "User Not found",
          status: 404,
        });
      let _id = User._id;
      return res.status(200).json({
        success: true,
        data: {
          _id,
        },
        message: "Email Verified Successfully",
        status: 200,
      });
    } else {
      return next({
        success: false,
        data: {},
        message: "OTP Used/Expired",
        status: 404,
      });
    }
  } catch (error) {
    return next(error);
  }
};












exports.login = async function (req, res) {
  console.log("Abc===>>>", req.body)
  // const {password, email, } = req.body;
  const email = req.body.email
  const password = req.body.password
console.log("abc====", email , password)
try {
  User.findOne({ email: email, password: password }, (err, response) => {
      console.log("Response-Login=====>>>>", response);
      if (response === null) {
        console.log("err=====", err)
        res.json({ message: "User Not Found" })
      } else {
        console.log("user found", response)
        res.status(200).json({ response, message: "successLogin" })
      }
    });
  } catch (error) {
    console.log("is match 1st error===>>>")
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetAllUser = async function (req, res) {
  try {
    User.find((err, response) => {
      if (response === null) {
        res.json({ message: "User Not Found" })
      } else {
        console.log("user found")
        res.status(200).json({ response })
      }
    });
  } catch (error) {
    console.log("is match 1st error===>>>")
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.updateData = async function (req, res) {
  let id = req.params.id;
  try {
    const response = await User.updateOne({ _id: id }, { verified: true });
    console.log("abc======", response )
    if (response === undefined || response === null) {
      return res.json({ message: "User Not Found" });
    } else {
      console.log("User found and updated");
      return res.status(200).json({ message: "User updated successfully" });
    }
  } catch (error) {
    console.log("Error:", error.message);
    return res.status(500).json({ success: false, message: error.message });
  }
};



exports.forgotPassVerifyEmail = async (req, res, next) => {
  try {
    console.log("req.params.email", req.params.email);
    let email = req.params.email
    const user = await User.findOne({ email: email });
    let emailsent = await Email.forgotPassVerifyEmail(user)
    console.log("User===",emailsent);

    if (!user) {
      return res.status(404).json({
        success: false,
        message: "User not found",
        status: 404,
      });
    }
          return res.status(200).json({
        success: true,
            data: emailsent,
        message: "We have just sent link in email",
        status: 200,
      });
  //   }
  } catch (error) {
    return next(error);
  }
};

exports.PasschangeForget = async (req, res, next) => {
  try {
    console.log("req.body", req.body);
    let id = req.body.id;
    let newpass = req.body.pass1;
    const user = await User.updateOne({ _id: id }, { password: newpass });
    const getUser = await User.findOne({ _id: id });
    if (!getUser) {
      return res.status(404).json({
        success: false,
        message: "User not found",
        status: 404,
      });
    }
    let emailsent = await Email.PasswordSuccessUpdate(getUser)
    console.log("User===", emailsent);

    return res.status(200).json({
      success: true,
      data: user,
      message: emailsent,
      status: 200,
    });
    //   }
  } catch (error) {
    return next(error);
  }
};
