const User = require("../models/User1");
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);
  const { name, email, contact, password } = req.body;
console.log("Received data:");
  if (!name || !email || !contact || !password) {
    return res.status(500).json({ message: "Empty Fields" });
  }
  console.log("Received data:");

  try {
    const lastUser = await User.findOne().sort({ createdAt: -1 }).exec();
    let accountNumber = 12000786;

    if (lastUser && lastUser.accountNumber) {
      const lastAccountNumber = parseInt(lastUser.accountNumber, 10);
      if (!isNaN(lastAccountNumber)) {
        accountNumber = lastAccountNumber + 1;
      } else {
        console.error("Invalid account number:", lastUser.accountNumber);
      }
    }

    // Prepare user but DO NOT save yet
    const user = new User({ ...req.body, accountNumber });

    // Attempt to send email FIRST
    const emailResult = await Email.signupuseremail({ email: email }); // Pass object with `email` only
    if (emailResult !== 'Email sent successfully!') {
        throw new Error("Email sending failed");
    }
    
    // Save user only after email success
    const savedUser = await user.save();
    console.log("hhhhh", savedUser)
    console.log("Received data:");

    return res.status(200).json({ message: "success", user: savedUser }); 

  } catch (error) {
    console.error("Signup Error:", error);
    return res.status(500).json({ success: false, message: error.message || "Internal server error" });
  }
};


exports.collectemail = async function (req, res) {
  try {
    const { email } = req.body;
    console.log("Received email:", email);

    if (!email) {
      return res.status(400).json({ success: false, message: "Email is required." });
    }

    // Check if email already exists
    const existingUser = await Users1.findOne({ email });
    if (existingUser) {
      return res.status(409).json({ success: false, message: "Email already registered." });
    }

    // Save new email
    const newUser = new Users1({ email });
    await newUser.save();

    return res.status(201).json({ success: true, message: "Email saved successfully." });
  } catch (error) {
    console.error("Signup Error:", error);
    return res.status(500).json({ success: false, message: error.message || "Internal server error" });
  }
};



exports.contactus = async function (req, res) {
  console.log("Abc===>>>", req.body);
  const { name, email, contact, message } = req.body;

  if (!name || !email || !contact || !message) {
    return res.status(400).json({ message: "Empty Fields" });
  }

  try {
    await Email.sendtoadmin({ name, email, contact, message }); // only pass the email now
    await Email.contactusformemail(email); // only pass the email now
    res.status(200).json({ message: "Email sent successfully" });
  } catch (error) {
    console.error("Signup Error:", error);
    return res.status(500).json({ success: false, message: error.message || "Internal server 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: "success" })
      }
    });
  } catch (error) {
    console.log("is match 1st error===>>>")
    res.status(404).json({ success: false, message: error.message });
  }
};