const User = require('../models/User'); // Ensure the path is correct based on your file structure
const bcrypt = require('bcryptjs'); // Use bcryptjs

// Create a new user
exports.createUser = async (req, res) => {
  try {
    const { username, email, password, passcode, roleId, companyId, branchId,allowedBranchId,kitchenId } = req.body;


    // Hash the password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

   const exstingPasscode=await User.findOne({passcode});

    if(exstingPasscode){
      return res.status(400).json({ message: 'Passcode already exists' });
    }
    // Create a new user instance
    const user = new User({
      username,
      email,
      passcode,
      password: hashedPassword,
      companyId,
      branchId,
      kitchenId:kitchenId?kitchenId:null,
      allowedBranchId,
      roleId
    });
  

    // Save the user to the database
    const savedUser = await user.save();
    res.status(201).json(savedUser);
  } catch (error) {
    console.error('Error creating user:', error.message);
    res.status(500).json({ error: error.message });
  }
};

exports.getAllUsers = async (req, res) => {
    try {
      // Populate 'companyId' and 'branchId' with their details from the respective collections
      const users = await User.find({companyId:req.query.companyId})
        .populate('companyId') // Populate the company details
        .populate('branchId') // Populate the branch details
        .populate('roleId')
        .populate('kitchenId') // 
  
      res.status(200).json(users);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  };
  
// Get a single user by ID

exports.getUserByPasscode1 = async (req, res) => {
  try {
    console.log("User by passcode called");
  
   const passcode = req.query.passcode.trim();
   console.log(passcode);
    const user1 = await User.find();
    console.log(user1);
    const user = user1.find((user) => user.passcode === passcode);
    if (!user) {
      console.log("User not found", req.query);

      return res.status(404).json({ error: 'User not found' });
    }
    res.status(200).json({ userId: user._id, waiterName: user.username });
  } catch (error) {
    console.error('Error fetching user by passcode:', error);
    res.status(500).json({ error: error.message });
  }
};
exports.getUserById = async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.status(200).json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// Update a user by ID
exports.updateUser = async (req, res) => {
  try {
    const { username, email, password, passcode, roleId,companyName, companyId, branchName, branchId, allowedBranchId,kitchenId } = req.body;



    const existingPasscode = await User.findOne({
      passcode, // Check for matching passcode
      username: { $ne: username }, // Exclude the current user based on userId
    });
    
    if (existingPasscode) {
      return res.status(400).json({ message: 'Passcode already exists' });
    }
    
   
    let hashedPassword;
    if (password) {
      // Hash the password if it's provided in the update
      const salt = await bcrypt.genSalt(10);
      hashedPassword = await bcrypt.hash(password, salt);
    }

    // Find and update the user by ID
    const updatedUser = await User.findByIdAndUpdate(
      req.params.id,
      {
        username,
        email,
        passcode,
       // password: hashedPassword || undefined,
        companyName,
        companyId,
        branchName,
        branchId,
        kitchenId:kitchenId || null,
        allowedBranchId,
        roleId
      },
      { new: true, runValidators: true }
    );

    if (!updatedUser) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.status(200).json(updatedUser);
  } catch (error) {
    console.error('Error updating user:', error.message);
    res.status(500).json({ error: error.message });
  }
};

// Delete a user by ID
exports.deleteUser = async (req, res) => {
  try {
    const deletedUser = await User.findByIdAndDelete(req.params.id);
    if (!deletedUser) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.status(200).json({ message: 'User deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};
