const model = require('../Model')
const jwt = require("jsonwebtoken");
const SecretKey = process.env.SECRET_KEY;

const PlansController = {
    createIndividualPlan: async (req, res) => {
        try {
          // Extract data from request body
          const { title, searchAllowed, allowedPersons,  price,allowedEmployees , role } = req.body;
      
          let newPlan;
          // Create a new individual plan in the database using Sequelize
          if(allowedEmployees==null){
             newPlan = await model.userplans.create({
                title,
                searchAllowed,
                allowedPersons,
                price,
                role
                // allowedEmployees
                
              });
          }else if(allowedEmployees!=null){
            newPlan = await model.userplans.create({
                title,
                // searchAllowed,
                // allowedPersons,
                price,
                allowedEmployees,
                role
                
              });
          }
          
      
          // Respond with success message and saved plan data
          return res.status(201).json({
            success: true,
            message: 'Individual plan created successfully',
            data: newPlan,
          });
        } catch (err) {
          console.error('Error creating individual plan:', err);
          return res.status(500).json({
            success: false,
            message: 'Failed to create individual plan',
            error: err.message,
          });
        }
      },
      subcsribe:async (req, res) => {
        try {
          // const { userId } = req.body;
          // console.log("Session Metadata:", { userId });
          const userId= '675b4cbbf8afd11631f028e7';
      
          // Find the user by ID
          const user = await model.User.findOne({ _id: userId });
          const compnayId=user.CompanyId
          const compnay = await model.CompanyandUser.findOne({ _id: user.CompanyId});
          console.log(
            "Found user Company",compnay
          );
          compnay.AllowedUsers = 5;
          user.role = "admin";
         user.subscriptionValid = new Date();
         user.subscriptionValid.setDate(user.subscriptionValid.getDate() + 30);
          
          if (user) {
            console.log("User found:", user);
      
            // Update the user's credit in memory
            user.credit = 430;
            user.sessionAllowed=1;
      
            // Save the updated user to the database
            const savedUser = await user.save();
            const comp = await compnay.save();
            console.log("Updated and saved User:", savedUser);
      
            return res.status(200).json({
              message: "User credit updated successfully.",
              user: savedUser,
              compnay:comp
            });
          } else {
            console.log("User not found");
            return res.status(404).json({ message: "User not found" });
          }
        } catch (error) {
          console.error("Error updating user credit:", error);
          res.status(500).json({ message: "Internal Server Error", error });
        }
      },
      paymentSucces:async (req, res) => {
        try {
          // Extract user ID from request params
          const { userId } = req.params; // Assuming the user ID is passed as a URL parameter
      
          // Validate if userId is provided
          if (!userId) {
            return res.status(400).json({
              success: false,
              message: 'User ID is required',
            });
          }
      
          // Find the user in the MongoDB database
          const user = await model.User.findById(userId);
      
          // If user is not found, return an error response
          if (!user) {
            return res.status(404).json({
              success: false,
              message: 'User not found',
            });
          }
      
        
          // Generate a JWT token
          const token = jwt.sign(
            { id: user._id, email: user.email, role: user.role}, // Payload
            SecretKey, // Secret key
            { expiresIn: '7d' } // Token expiration time
          );
      
          // Send the successful response
          return res.status(200).json({
            success: true,
            message: 'Login successful',
            planSelected: true,
            data: {
              token: token,
              role: user.role,
              name: user.name,
              id: user._id,
            },
          });
        } catch (error) {
          // Handle server errors
          console.error('Error fetching user or generating token:', error);
          return res.status(500).json({
            success: false,
            message: 'Internal Server Error',
          });
        }
      }

};

module.exports = PlansController;