const User = require('../models/User');
const UsersDailySteps = require('../models/UsersDailySteps');
const UsersDailyAdds = require('../models/UsersDailyAdds');
const UserTokens = require('../models/UserTokens');
const Support = require('../models/Support');

const CMS = require('../models/CMS');
const authService = require('../../services/auth.service');
const bcryptService = require('../../services/bcrypt.service');
const emailService = require('../../services/email.service');
const helperService = require('../../services/helpers.service');

const { includes } = require('lodash');

exports.register = async (req, res) => {
  const { body } = req;
  console.log(body)
  var foundError = false;
  var valueNotFound = {};

  if (body.email === undefined || body.email.trim() === "") {
    valueNotFound['email'] = "This field is required!";
    foundError = true;
  }
  if (body.password === undefined || body.password.trim() === "") {
    valueNotFound['password'] = "This field is required!";
    foundError = true;
  } 
  if (body.name === undefined || body.name.toString().trim() === "") {
    valueNotFound['name'] = "This field is required!";
    foundError = true;
  }
  if (body.twoFactor === undefined || body.twoFactor === "" || body.twoFactor === null) {
    valueNotFound['twoFactor'] = "This field is required!";
    foundError = true;
  }
  const address = Math.floor(10000000000 + Math.random() * 90000000000);
  var message = null
  if (foundError) {
    return helperService().badRequest([valueNotFound], "All field is required.", res)
  }else{
    if (body.twoFactor === 1) {
      let user = await User.findOne({
        where: {
          email: body.email,
          is_verify: 1
        }
      })
      if(!user){
        message = "Email not Found!!";
        foundError = true;
      }

      if(user){
        if(user.account_status === 1){
          message = "User already registered with this email!";
          foundError = true;
        }
      }
      if (foundError) {
        return helperService().badRequest([], message, res)
      }

      try {    
        if(user.account_status === 2){
          var encrypted = bcryptService().convertPassword(body.password)

          const userupdate = await User.update({
              password: encrypted,
              account_status: 1,
              name: body.name,
              two_factor: body.twoFactor,
              otp: null,
              otp_date: null,
              withdraw_address: address
            },{
              where: {
                email: body.email
              }
            }
          )

          const userObj = await User.findOne({
            where: {
              email: body.email,
            },
            attributes:['id', 'name','email', 'phone'],
          });
          const token = authService().issue({ id: userObj.id, user_id: userObj.id, name: userObj.name });
          return helperService().success({ token, user: userObj }, "Register and login successfull", res)
        }
      } catch (err) {
        return helperService().serverError(err, res)
      }
    }else if(body.twoFactor === 0){
      let user = await User.findOne({
        where: {
          email: body.email,
        }
      })
      if(user){
        message = "User already registered with this email!";
        foundError = true;
      }
      if (foundError) {
        return helperService().badRequest([], message, res)
      }
      try {    
        var encrypted = bcryptService().convertPassword(body.password)
        const userupdate = await User.create({
            password: encrypted,
            account_status: 1,
            is_verify: 1,
            phone: null,
            name: body.name,
            email: body.email,
            two_factor: body.twoFactor,
            otp: null,
            otp_date: null,
            withdraw_address: address
          }
        )
        const userObj = await User.findOne({
          where: {
            email: body.email,
          },
          attributes:['id', 'name','email', 'phone'],
        });
        const token = authService().issue({ id: userObj.id, user_id: userObj.id, name: userObj.name });
        return helperService().success({ token, user: userObj }, "Register and login successfull", res)
      } catch (err) {
        return helperService().serverError(err, res)
      }
    }
  }
};
exports.sendTwoFactorAuthentication = async (req, res) => {
  var { email, phone } = req.body
  var foundError = false;
  var valueNotFound = {};
  if (email == null || email == '') {
    valueNotFound['email'] = "This field is required!!";
    foundError = true;
  }
  var regexPhone = new RegExp("^([0-9]{9,10})$");
  if (phone === undefined || phone.toString().trim() == "") {
    valueNotFound['phone'] = "This field is required!!";
    foundError = true;
  }else if(phone.length < 5){
    valueNotFound['phone'] = "Not a valid phone number ";
    foundError = true;
  }
  // } else if (regexPhone.test(phone) === false) {
  //   valueNotFound['phone'] = "Not a valid phone number (only enter 9 or 10 digit mobile number & must not include spaces or special characters)";
  //   foundError = true;
  // }

  if (foundError) {
    return helperService().badRequest([valueNotFound], "Validation error.", res)
  }
  try {
    const otp = Math.floor(100000 + Math.random() * 900000);
    const otp_date = new Date()

    const existUser = await User.findOne({
      where: {
        email,
      }
    })
    
    if (existUser) {
      if(existUser.account_status == 2){
        const createOtp = await User.update({
          otp,
          otp_date
        },{
          where: {
            email,
          }
        })
        const html = `
          Hello ,<br/><br/>
          Please use this code to verify your account. <br/>
          `+ otp + `
          <br/><br/>
          Thanks.
          `;
          emailService.sendEmail("verify-account", email, html);
        return helperService().success([], "OTP sent successfully", res)
      }else{
        return helperService().badRequest([], "User already registered with this email!", res)
      }
    }else{
      const user = await User.create({
        email,
        phone,
        password: 'XXXXXX',
        is_verify: 0,
        account_status: 2,
        otp,
        otp_date
      })
      const html = `
        Hello ,<br/><br/>
        Please use this code to verify your account. <br/>
        `+ otp + `
        <br/><br/>
        Thanks.
        `;
      emailService.sendEmail("verify-account", email, html);
      return helperService().success([], "OTP send successfully", res)
    }
  }
  catch (err) {
    return helperService().serverError(err, res)
  }
}
exports.verifyTwoFactorAuthentication = async (req, res) => {
  var { code, email, type } = req.body,
    valueNotFound = {},
    foundError = false;
    message = null;
  if (code === null || code === "") {
    valueNotFound['code'] = "This field is required!!";
    foundError = true;
  }
  if (email === null || email === "") {
    valueNotFound['email'] = "This field is required!!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([valueNotFound], "Validation error.", res)
  }
  const existUser = await User.findOne({ where: { email } });
  if (existUser === null) {
    message = "Email not found!!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([], message, res)
  }
  if (existUser.otp === code) {
    try {
      await User.update({
          is_verify: 1,
          account_status: 2,
          otp: null,
          otp_date: null,
        },
        {
          where: {
            id: existUser.id
          }
        }
      )
      if(type === 'l'){
        const token = authService().issue({ id: existUser.id, user_id: existUser.id, name: existUser.name });
        return helperService().success({ token, user: existUser }, "Login successfull", res)
      }else{
        return helperService().success([], "User verified successfully.", res)
      }
    }
    catch (err) {
      return helperService().serverError(err, res)
    }
  }
  else {
    return helperService().badRequest([], "Incorrect code.", res)
  }
}
exports.resetCode = async (req, res) => {
  var { email } = req.body
  var foundError = false;
  var message = null;
  if (email == null || email == '') {
    message = "This field is required!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([], message, res)
  }
  try {
    const otp = Math.floor(100000 + Math.random() * 900000);
    const otp_date = new Date()

    const existUser = await User.findOne({
      where: {
        email,
      }
    })
    
    if (existUser) {
      if(existUser.account_status == 1){
        const createOtp = await User.update({
          forgot_password_token: otp,
        },{
          where: {
            email,
          }
        })
        const html = `
          Hello ,<br/><br/>
          Please use this code to reset your password. <br/>
          `+ otp + `
          <br/><br/>
          Thanks.
          `;
          emailService.sendEmail("forgot-password", email, html);
        return helperService().success([], "OTP sent successfully", res)
      }else{
        return helperService().badRequest([], "Invalid Email!", res)
      }
    }else{
      return helperService().badRequest([], "User not found!", res)
    }
  }
  catch (err) {
    return helperService().serverError(err, res)
  }
}
exports.verifyResetCode = async (req, res) => {
  var { code, email } = req.body,
    valueNotFound = {},
    foundError = false;
    message = null;
  if (code === null || code === "") {
    valueNotFound['code'] = "This field is required!!";
    foundError = true;
  }
  if (email === null || email === "") {
    valueNotFound['email'] = "This field is required!!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([valueNotFound], "Validation error.", res)
  }
  const existUser = await User.findOne({ where: { email } });
  if (existUser === null) {
    message = "Email not found!!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([], message, res)
  }
  console.log('existUser.forgot_password_token', existUser.forgot_password_token)
  if (existUser.forgot_password_token == code) {
    try {
      await User.update({
          forgot_password_token: null,
        },
        {
          where: {
            id: existUser.id
          }
        }
      )
      return helperService().success([], "otp verify successfully.", res)
    }
    catch (err) {
      return helperService().serverError(err, res)
    }
  }else {
    return helperService().badRequest([], "Incorrect code.", res)
  }
}
exports.changedPassword = async (req, res) => {
  const { code, password, email } = req.body;
  let  valueNotFound = {},
    foundError = false,
    message = null;
  if (code === null || code === "") {
    valueNotFound['code'] = "This field is required!";
    foundError = true;
  }
  if (password === undefined || password.trim() === "") {
    valueNotFound['passowrd'] = "This field is required!";
    foundError = true;
  } 
  if (foundError) {
    return helperService().badRequest([], 'Validation error.', res)
  }
  const existUser = await User.findOne({ where: { email } });
  if (existUser === null) {
    message = "Email not found!!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([], message, res)
  }
  var encrypted = bcryptService().convertPassword(password)
  if (existUser.forgot_password_token == code) {
    try {
      const upgrade = await User.update({
          forgot_password_token: null,
          password: encrypted,
        },
        {
          where: {
            id: existUser.id
          }
        }
      )
      return helperService().success([], "Password has been changed", res);
    } catch (err) {
      return helperService().serverError(err, res)
    }
  }else {
    return helperService().badRequest([], "Incorrect code.", res)
  }
} 
exports.login = async (req, res) => {
  const { email, password } = req.body;

  if (email && password) {
    try {
      const user = await User.findOne({
        where: {
          email,
          role: 0,
          status: 1,
          is_verify: 1,
        },
        attributes:['id', 'name','email', 'phone', 'password', 'two_factor'],
      });
      if (!user) {
        return helperService().badRequest([], "User not found.", res)
      }
      if(user.account_status == 0){
        return helperService().badRequest([], "Your account has blocked.", res)
      }else if(user.account_status == 2){
        return helperService().badRequest([], "User doesn't exist.", res)
      }else{
        if (bcryptService().comparePassword(password, user.password)) {
          if(user.two_factor == 0){
            const token = authService().issue({ id: user.id, user_id: user.id, name: user.name });
            return helperService().success({ token, user }, "Login successfull", res)
          }else{
            const otp = Math.floor(100000 + Math.random() * 900000);
            const otp_date = new Date()

            const updateOtp = await User.update({
              otp,
              otp_date
            },{
              where: {
                email,
              }
            })
            const html = `
              Hello ,<br/><br/>
              Please use this code to verify your account. <br/>
              `+ otp + `
              <br/><br/>
              Thanks.
              `;
              emailService.sendEmail("verify-account", email, html);
            return helperService().success([], "OTP sent successfully", res)
            // return helperService().success([{ user }], "Otp sent successfull", res)
          }
        }else{
          return helperService().badRequest([], "Incorrect Password", res)
        }
      }
    } catch (err) {
      return helperService().serverError(err, res)
    }
  }
  return helperService().badRequest([], "Email or password is not correct", res)
};
exports.cms = async (req, res) => {
  var { slug } = req.query;
  if (slug) {
    try {
      const services = await CMS.findOne({
        attributes:['id','name','title','content','slug'],
        where: {
          slug,
          status: 1
        }
      });
      if (services == null) {
        return helperService().badRequest([], "Slug not found", res);
      }
      return helperService().success(services, "Slug found", res);
    } catch (err) {
      return helperService().serverError(err, res)
    }
  }
  else {
    return helperService().badRequest([], "Slug is required", res);
  }
}
exports.upgradeAccount = async (req, res) => {
  const { token } = req.body;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }
      const user_id = data.user_id
      try {
        const upgrade = await User.update({
            premium_account: 1,
          },
          {
            where: {
              id: user_id
            }
          }
        )
        return helperService().success([], "Account upgrade successful", res);
      } catch (err) {
        return helperService().serverError(err, res)
      }
    });
  } else {
    return helperService().badRequest([], "Token is required", res);
  }
}
exports.profile = async (req, res) => {
  const { token } = req.query;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }
      try {
        const user_id = data.user_id
        const user = await User.findOne({
            where: {
              id: user_id,
            },
            attributes: ["id", "name", "total_steps", "premium_account"],
            include: [{
              model: UserTokens,
              required: false,
              attributes: ["id", "total_earned"],
            }]
        });
        return helperService().success(user, "success", res);
      } catch (err) {
          return helperService().serverError(err, res)
      }
    });
  } else {
    return helperService().badRequest([], "Token is required", res);
  }
};
exports.adds = async (req, res) => {
  const { token, date  } = req.body;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }
      try {
        const user_id = data.user_id
        const adds = await UsersDailyAdds.findOne({
          where: {
            user_id,
            date
          },
          attributes: ["id", "add_views"],
        });
        if(adds){
          if(adds.add_views < 3){
            const add_views = parseInt(adds.add_views) + 1
            const upgrade = await UsersDailyAdds.update(
              {
                add_views
              },
              {
                where: {
                  user_id,
                  date
                }
              }
            )
          }else{
            return helperService().success([], "Adds limit has been reached", res);
          }
        }else{
          await UsersDailyAdds.create(
            {
              user_id,
              add_views: 1,
              date
            }
          )
        }
        return helperService().success([], "success", res);
      } catch (err) {
          return helperService().serverError(err, res)
      }
    });
  } else {
    return helperService().badRequest([], "Token is required", res);
  }
};
exports.customerSupport = async (req, res) => {
  const { token, email, issue  } = req.body;
  let valueNotFound = {},
    foundError = false;
  if (token) {
    authService().verify(token, async (err, data) => {
      if (err) {
        return helperService().unauthorized(res);
      }
      try {
        if (email == null || email == '') {
          valueNotFound['email'] = "This field is required!";
          foundError = true;
        }
        if (issue == null || issue == '') {
          valueNotFound['issue'] = "This field is required!";
          foundError = true;
        }
        if (foundError) {
          return helperService().badRequest([valueNotFound], 'validation error.', res)
        }
        const user_id = data.user_id
        await Support.create(
          {
            user_id,
            issue,
            email
          }
        )
        return helperService().success([], "Ticket sent successfully", res);
      } catch (err) {
          return helperService().serverError(err, res)
      }
    });
  } else {
    return helperService().badRequest([], "Token is required", res);
  }
};


exports.supportScreenCode = async (req, res) => {
  var { email,issue } = req.body
  var foundError = false;
  var message = null;
  var supportEamil = "thehumbleminer@protonmail.com";
  if (email == null || email == '') {
    message = "This field is required!";
    foundError = true;
  }
  if (foundError) {
    return helperService().badRequest([], message, res)
  }
  try {
    

    const existUser = await User.findOne({
      where: {
        email,
      }
    })
    
    if (existUser) {
      if(existUser.account_status == 1){
      
        const html = `
          
          User Email: `+ email + ` <br/> 
          User Name: `+ existUser.name + ` <br/> 
          Issue: `+ issue + ` <br/> 
          <br/>    
          <br/><br/>
          Thanks.
          `;

          var user_id = existUser.id;
          var name = existUser.name;
          emailService.sendEmail("support-ticket", supportEamil, html);
          await Support.create(
          {
            user_id,
            name,
            issue,
            email
          }
        )
        return helperService().success([], "Thanks we'll contact you shortly", res)
      }else{
        return helperService().badRequest([], "Invalid Email!", res)
      }
    }else{
      return helperService().badRequest([], "User not found!", res)
    }
  }
  catch (err) {
    return helperService().serverError(err, res)
  }
}

// exports.update = async (req, res) => {

//   const { first_name, last_name, token, email, phone } = req.body;
//   var foundError = false;
//   var valueNotFound = {};
//   if (email == undefined || email.trim() == "") {
//     valueNotFound['email'] = "This field is required!!";
//     foundError = true;
//   }
//   if (first_name == undefined || first_name.trim() == "") {
//     valueNotFound['first_name'] = "This field is required!!";
//     foundError = true;
//   }
//   if (last_name == undefined || last_name.trim() == "") {
//     valueNotFound['last_name'] = "This field is required!!";
//     foundError = true;
//   }

//   var regexPhone = new RegExp("^([0-9]{9,10})$");
//   if (phone == undefined || phone.toString().trim() == "") {
//     valueNotFound['phone'] = "This field is required!!";
//     foundError = true;
//   } else if (regexPhone.test(phone) === false) {
//     valueNotFound['phone'] = "Not a valid phone number (only enter 9 or 10 digit mobile number & must not include spaces or special characters)";
//     foundError = true;
//   }

//   if (foundError) {
//     return helperService().badRequest([valueNotFound], "Validation error.", res)
//   }
//   authService().verify(token, async (err, data) => {
//     if (err) {
//       return helperService().unauthorized(res)
//     }

//     try {
//       const user = await User
//         .findOne({
//           where: {
//             id: data.id,
//           },
//         });

//       if (!user) {
//         return helperService().badRequest([], "User not found.", res)
//       }
//       const updated = await User
//         .update({
//           first_name,
//           last_name,
//           email
//         }, {
//           where: {
//             id: data.id
//           }
//         });
//       const customerUpdated = await Customer.update({
//         phone
//       }, {
//         where: {
//           user_id: data.id
//         }
//       })

//       if (!updated) throw ('Error while Updating');
//       return helperService().success([], "User updated.", res)
//     } catch (err) {
//       return helperService().serverError(err, res)
//     }


//   });

// };
// exports.validate = async (req, res) => {
//   const { token } = req.query;

//   authService().verify(token, async (err, data) => {
//     if (err) {
//       return helperService().unauthorized(res)
//     }
//     var user = await User.findByPk(data.id, {
//       include: [
//         {
//           model: Customer,
//           required: true,
//           attributes:['id','phone','image', 'age_verified'],
//           include: [{
//             model: CustomerDeliveryAddress,
//             required: false,
//             attributes:['id','address1','address2','zip'],
//             where: {
//               status: 1
//             }
//           }]
//         }
//       ],
//       attributes:['id','first_name','last_name','email','longitude','latitude'],
//     });
//     return helperService().success([user], "", res)
//   });
// };
// exports.getAll = async (req, res) => {
//   try {
//     const users = await User.findAll();

//     return res.status(200).json({ users });
//   } catch (err) {
//     return helperService().serverError(err, res)
//   }
// };
// exports.forgotPassword = async (req, res) => {
//   var { email } = req.body;
//   if (email !== null && email.trim() !== "") {
//     try {
//       const user = await User
//         .findOne({
//           where: {
//             email
//           },
//         });
//       if (!user) {
//         return helperService().badRequest([], "User not found.", res)
//       }
//       var token = Math.floor(100000 + Math.random() * 900000);;
//       const userUpdate = await User.update({ forgot_password_token: token }, { where: { id: user.id } });
//       const html = `
//             <b>Hello `+ user.first_name + ` !<br/><br/>
//             Please use this code to reset the password. <br/>
//             ` + token + `<br/><br/>
//             Thanks.
//         `;
//       emailService.sendEmail("forgot-password", email, html);
//       return helperService().success([], "Reset password email sent successfully", res)
//     }
//     catch (err) {
//       return helperService().serverError(err, res)
//     }
//   }
//   else {
//     return helperService().badRequest([], "Email is required.", res)
//   }
// }
// exports.resetPassword = async (req, res) => {
//   var { token, password, confirm_password } = req.body;
//   if (token) {
//     try {
//       if (password == undefined || password.trim() == "") {
//         return helperService().badRequest([], "Password field is required.", res)
//       }
//       else if (confirm_password == undefined || confirm_password !== password) {
//         return helperService().badRequest([], "Confirm password should match with password.", res)
//       }
//       const userToken = await User.findOne({ where: { forgot_password_token: token } });
//       if (!userToken) {
//         return helperService().unauthorized(res)
//       }
//       var encrypted = bcryptService().convertPassword(password);
//       const user = await User.update({ password: encrypted, forgot_password_token: null }, { where: { id: userToken.id } })
//       return helperService().success([], "Password successfully changed", res)
//     }
//     catch (err) {
//       return helperService().serverError(err, res)
//     }
//   }
//   else {
//     return helperService().unauthorized(res)
//   }
// }
// exports.changePassword = async (req, res) => {
//   var { current_password, new_password, confirm_password, token } = req.body;
//   try {
//     if (current_password == undefined || current_password.trim() == "") {
//       return helperService().badRequest([], "Current password field is required.", res)
//     }
//     else if (new_password == undefined || new_password.trim() == "") {
//       return helperService().badRequest([], "New password field is required.", res)
//     }
//     else if (confirm_password == undefined || confirm_password !== new_password) {
//       return helperService().badRequest([], "Confirm password should match with password.", res)
//     }
//     if (token) {
//       authService().verify(token, async (err, data) => {
//         if (err) {
//           return helperService().unauthorized(res)
//         }
//         var checkPassword = await User.findByPk(data.id);
//         if (bcryptService().comparePassword(current_password, checkPassword.password)) {
//           var changePassword = await User.update({
//             password: bcryptService().convertPassword(new_password)
//           },
//             {
//               where: {
//                 id: data.id
//               }
//             })
//           return helperService().success([], "Password changed successfully", res)
//         }
//         else {
//           return helperService().badRequest([], "Wrong current password", res)
//         }
//       })
//     }
//     else {
//       return helperService().unauthorized(res)
//     }
//   }
//   catch (err) {
//     return helperService().serverError(err, res)
//   }

// }
// exports.addAddress = async (req, res) => {
//   const { body } = req;

//   var foundError = false;
//   var valueNotFound = {};
//   if (body.address1 == undefined || body.address1.trim() == "") {
//     valueNotFound['address1'] = "This field is required!!";
//     foundError = true;
//   }

//   var regexZip = new RegExp("^([0-9]{5,5})$");

// //   if (body.zip == undefined || body.zip.toString().trim() == "") {
// //     valueNotFound['zip'] = "This field is required!!";
// //     foundError = true;
// //   } else if (regexZip.test(body.zip) === false) {
// //     valueNotFound['zip'] = "Invalid zipcode (please enter 5 digit zipcode)!!";
// //     foundError = true;
// //   }
//     if (body.zip == undefined || body.zip.trim() == "") {
//       valueNotFound['zip'] = "This field is required!!";
//       foundError = true;
//     }
//     else if (!Number.isInteger(parseInt(body.zip))) {
//       valueNotFound['zip'] = "This field is incorrect!!";
//       foundError = true;
//     }
//   if (foundError) {
//     return helperService().badRequest([valueNotFound], "Validation errors", res)
//   }
//   if (body.token) {
//     authService().verify(body.token, async (err, data) => {
//       if (err) {
//         return helperService().unauthorized(res)
//       }
//       const customerAddr = await CustomerDeliveryAddress.create({
//         address1: body.address1,
//         address2: body.address2 || '',
//         customer_id: data.customer_id,
//         zip: body.zip,
//       })
//       return helperService().success([], "Address added successfully", res)
//     })
//   }
//   else {
//     return helperService().unauthorized(res)
//   }
// }
// exports.deleteAddress = async (req, res) => {
//   var { token, id } = req.body;
//   if (id) {
//     authService().verify(token, async (err, data) => {
//       if (err) {
//         return helperService().unauthorized(res)
//       }
//       await CustomerDeliveryAddress.update({ status: 0 }, {
//         where: {
//           id
//         }
//       })
//       return helperService().success([], "Address removed successfully", res)
//     })
//   }
//   else {
//     return helperService().badRequest([], "ID is required", res)
//   }
// }

// exports.updateImage = async (req, res) => {
//   var { token, image } = req.body;
//   if (token && image) {
//     authService().verify(token, async (err, data) => {
//       if (err) {
//         return helperService().unauthorized(res)
//       }

//         var imgLogo =  image;
//         var uri = null;
//         var imageUploadData;
//         if (imgLogo != undefined && imgLogo != "") {
//             imageUploadData = uploadImageApi.imageUpload(imgLogo);
//             uri = imageUploadData.imagePaths
//         } else {
//             uri = ''
//         }
//         await Customer.update({ image : uri }, {
//             where: {
//                 user_id: data.id
//             }
//         })

//       return helperService().success([], "Image updated successfully", res)
//     })
//   }
//   else {
//     return helperService().badRequest([], "Token & Image is required", res)
//   }
// }
// exports.googleAuth = async (req, res) => {
//   const { body } = req;
//   let first_name = "",
//     last_name = "",
//     email = "",
//     google_id = "",
//     photo = "";

//   if (body.user.name != null && body.user.name != "") {
//     first_name = body.user.name.split(' ')[0];
//     last_name = body.user.name.split(' ')[1] || '';
//   }
//   if (body.user.email != null && body.user.email != "") {

//     email = body.user.email;
//   }
//   if (body.user.id != null && body.user.id != "") {
//     google_id = body.user.id;
//   }
//   if (body.user.photo != null && body.user.photo != "") {
//     photo = body.user.photo;
//   }
//   let token_code = body.idToken;

//   var role = await Role.findOne({
//     where: {
//       role: 'customer'
//     }
//   })
//   let role_id = role.id;
//   if (email && first_name && google_id) {
//     try {
//       const existuser = await User
//         .findOne({
//           where: {
//             email,
//           },
//           include: [{
//             model: Customer,
//             required: false
//           }]
//         });
//       if (existuser) {
//         await User.update({
//           google_id: google_id
//         }, { where: { id: existuser.id } });
//         const token = authService().issue({ id: existuser.id, customer_id: existuser.Customer.id, role: existuser.role_id, first_name: existuser.first_name, last_name: existuser.last_name });

//         //replace password with X
//         existuser.password = 'XXXXXX';

//         return helperService().success([{ token, user: existuser }], "Login successful", res);
//       } else {
//         const user = await User.create({
//           first_name,
//           last_name,
//           email,
//           google_id,
//           token_code,
//           role_id,
//           password: 'XXXXXX',
//         });
//         const customer = await Customer.create({
//           image: photo,
//           user_id: user.id
//         })

//         //replace password with X
//         // user.password = 'XXXXXX';

//         const token = authService().issue({ id: user.id, customer_id: customer.id, role: role_id, first_name: user.first_name, last_name: user.last_name });

//         //send otp on mail
//         // emailService().sendVerificationCodeEmail('otp', email, generated_otp, full_name);

//         return helperService().success([{ token, user }], "Registration and Login successful", res);
//       }
//     } catch (err) {
//       return helperService().serverError(err, res)
//     }
//   } else {
//     return helperService().badRequest([], "Please check the parameters - email, first_name, last_name or google_id", res)

//   }


//   //});

// };
// exports.appleAuth = async (req, res) => {
//   const body = req.body;
//   let full_name = ""
//   let email = ""
//   let apple_id = ""
//   if (body.fullName) {
//     if (body.fullName.givenName != null && body.fullName.givenName != "") {
//       first_name = body.fullName.givenName.split(' ')[0];
//       last_name = body.fullName.givenName.split(' ')[1] || '';
//     }
//   }
//   if (body.email != null && body.email != "") {
//     email = body.email;
//   }
//   if (body.user != null && body.user != "") {
//     apple_id = body.user;
//   }

//   let token_code = body.identityToken;
//   // let token = req.headers.authorization;
//   var role = await Role.findOne({
//     where: {
//       role: 'customer'
//     }
//   })
//   let role_id = role.id;
//   if (email != null && email != "" && email != undefined && apple_id != null && apple_id != "" && apple_id != undefined && first_name != null && first_name != "" && first_name != undefined) {
//     try {
//       const existuser = await User
//         .findOne({
//           where: {
//             email,
//           },
//           include: [{
//             model: Customer,
//             required: false
//           }]
//         });
//       if (existuser) {

//         await User.update(
//           {
//             apple_id: apple_id
//           },
//           {
//             where:
//             {
//               id: existuser.id
//             }
//           });

//         const token = authService().issue({ id: existuser.id, customer_id: existuser.Customer.id, role: existuser.role_id, first_name: existuser.first_name, last_name: existuser.last_name });

//         //replace password with X
//         existuser.password = 'XXXXXX';
//         return helperService().success([{ token, user: existuser }], "Login successful", res);
//       }
//       else {
//         const user = await User.create({
//           first_name,
//           last_name,
//           email,
//           apple_id,
//           token_code,
//           role_id,
//           password: 'XXXXXX',
//         });
//         const customer = await Customer.create({
//           user_id: user.id
//         })

//         //replace password with X
//         user.password = 'XXXXXX';

//         const token = authService().issue({ id: user.id, customer_id: customer.id, role: role_id, first_name: user.first_name, last_name: user.last_name });

//         return helperService().success([{ token, user }], "Registration and Login successful", res);
//       }

//     } catch (err) {
//       return helperService().serverError(err, res)
//     }
//   }
//   else {
//     if (apple_id != null && apple_id != "") {
//       try {
//         const existuser = await User
//           .findOne({
//             where: {
//               apple_id,
//             },
//             include: [
//               {
//                 model: Customer,
//                 required: false
//               }
//             ]
//           });
//         if (existuser) {

//           const token = authService().issue({ id: existuser.id, customer_id: null, role: existuser.role_id, first_name: existuser.first_name, last_name: existuser.last_name });

//           //replace password with X
//           existuser.password = 'XXXXXX';

//           return helperService().success([{ token, existuser }], "Login successful", res);
//         }
//       }
//       catch (err) {
//         return helperService().serverError(err, res)
//       }

//     }
//     else {
//       return helperService().badRequest([], "Please check the parameters - email, name or apple_id", res);
//     }

//   }
// };
// exports.checkDeliveryAddress = async (req, res) => {
//   var { zip } = req.body;
//   if (zip) {
//     try {
//       const locations = await Location.findOne({
//         where:
//         {
//           zip_code: zip,
//           status: 1
//         }
//       });
//       if (locations == null) {
//         return helperService().badRequest([], "zip does not qualify delivery areas", res);
//       }
//       return helperService().success([], "Zip qualifies delivery areas", res);
//     } catch (err) {
//       return helperService().serverError(err, res)
//     }
//   }
//   else {
//     return helperService().badRequest([], "Zip is required", res);
//   }
// }

// exports.ageVerification = async (req, res) => {
//   const { token, front, back, user_with_id } = req.body;
//   if (token && front && back && user_with_id) {
//     authService().verify(token, async (err, data) => {
//       if (err) {
//         return helperService().unauthorized(res)
//       }

//         var imgLogo =  front;
//         var uriFront = null;
//         var imageUploadData;
//         if (imgLogo != undefined && imgLogo != "") {
//             imageUploadData = uploadFrontId.imageUpload(imgLogo);
//             uriFront = imageUploadData.imagePaths
//         } else {
//             uriFront = ''
//         }

//         var imgLogo =  back;
//         var uriBack = null;
//         var imageUploadData;
//         if (imgLogo != undefined && imgLogo != "") {
//             imageUploadData = uploadBackId.imageUpload(imgLogo);
//             uriBack = imageUploadData.imagePaths
//         } else {
//             uriBack = ''
//         }
//         var imgLogo =  user_with_id;
//         var uriUserWithId = null;
//         var imageUploadData;
//         if (imgLogo != undefined && imgLogo != "") {
//             imageUploadData = uploadUserId.imageUpload(imgLogo);
//             uriUserWithId = imageUploadData.imagePaths
//         } else {
//             uriUserWithId = ''
//         }

//         await Customer.update(
//             { 
//                 front_id : uriFront,
//                 back_id : uriBack,
//                 user_with_id : uriUserWithId,
//             },{
//             where: {
//                 user_id: data.id
//             }
//         })

//       return helperService().success([], "Proof updated successfully", res)
//     })
//   }
//   else {
//     return helperService().badRequest([], "token, front, back and user_with_id  is required", res)
//   }
// }
// exports.addGoogleAddress = async (req, res) => {
//     const { body } = req;
//     var foundError = false;
//     var valueNotFound = {};
    
//     if (body.longitude == undefined || body.longitude.toString().trim() == "") {
//       valueNotFound['longitude'] = "This field is required!!";
//       foundError = true;
//     }
//     if (body.latitude == undefined || body.latitude.toString().trim() == "") {
//       valueNotFound['latitude'] = "This field is required!!";
//       foundError = true;
//     }
//     if (body.address1 == undefined || body.address1.trim() == "") {
//       valueNotFound['address1'] = "This field is required!!";
//       foundError = true;
//     }
  
//     if (body.zip == undefined || body.zip.trim() == "") {
//         valueNotFound['zip'] = "This field is required!!";
//         foundError = true;
//       }
//       else if (!Number.isInteger(parseInt(body.zip))) {
//         valueNotFound['zip'] = "This field is incorrect!!";
//         foundError = true;
//       }
  
//     if (foundError) {
//       return helperService().badRequest([valueNotFound], "Validation error.", res)
//     }
//     if (body.token) {
//         authService().verify(body.token, async (err, data) => {
//           if (err) {
//             return helperService().unauthorized(res)
//           }
//           const userupdate = await User.update({
//                 longitude: body.longitude,
//                 latitude: body.latitude,
//             },
//             {
//                 where: {
//                     id: data.id
//                 }
//             }
//           )
//           const checkCustomerAddr = await CustomerDeliveryAddress.findOne({
//               where:{
//                 customer_id: data.customer_id,
//               }
//           })
//           if(checkCustomerAddr){
//             const customerAddr = await CustomerDeliveryAddress.create({
//                 address1: body.address1,
//                 address2: body.address2 || '',
//                 customer_id: data.customer_id,
//                 zip: body.zip,
//               })
//           }
          
//           return helperService().success([], "Address added successfully", res)
//         })
//     }
//     else {
//     return helperService().unauthorized(res)
//     }
//   };
