
const Contact = require('../models/contacts');
const Otp = require('../models/otpdb');
var jwt = require('jsonwebtoken');
var nodemailer = require('nodemailer');
var mailer = require('../controllers/mailer');
var request = require("request");
var Count = require('../models/counter')
var crypto = require('crypto');
const Device = require('../models/device');
var ObjectId = require('mongodb').ObjectID;
var Utilities = require('../controllers/utilities.controller');
var mongoose = require('mongoose');
var org = require('../models/organisation')
var couponCode = require('../controllers/discountCode.controller');

const _poi = require('../models/poi');

//signUp and Email Verification

// first_name: "ddddd"
// last_name: "aaaaa"
// email: "ga@adnate.in"
// pass: "q1q1q1"
// phone: "4434345554"
// supAdmin: "59cbbdbe508f164aa2fef3d8"
// isDealer: true
// expdate: "2021-03-31T10:06:06.363Z"
// Dealer: "5ab471736a40122297759ae9"
// user_id: "13123234435"
module.exports.createUserPeronalTracker = function (req, res) {
  var pass = req.body.pass;
  // delete req.body.pass;
  req.body.salt = crypto.randomBytes(16).toString('hex');
  req.body.hash = crypto.pbkdf2Sync(pass, req.body.salt, 1000, 64, 'sha1').toString('hex');
  Contact.findOne({ $or: [{ "email": req.body.email }, { "phone": req.body.phone }] }).exec(function (err, data1) {
    if (err) return res.send(err);

    if (data1 == null) {
      var _contact = new Contact(req.body);
      _contact.save(function (err, data) {
        if (err) res.status(500).json({ "message": "Something Is Wrong" });
        res.send(data);
      })
    } else {
      if (data1.email == req.body.email)
        res.status(500).json({ "message": "email already exists" });
      if (data1.phone == req.body.phone)
        res.status(500).json({ "message": "Phone already exists" });
    }
  });

}
module.exports.createUser = function (req, res) {
  var pass = req.body.pass;
  // delete req.body.pass;
  req.body.salt = crypto.randomBytes(16).toString('hex');
  req.body.hash = crypto.pbkdf2Sync(pass, req.body.salt, 1000, 64, 'sha1').toString('hex');
  Contact.findOne({ $or: [{ "email": req.body.email }, { "phone": req.body.phone }] }).exec(function (err, data1) {
    if (err) return res.send(err);

    if (data1 == null) {
      var _contact = new Contact(req.body);
      _contact.save(function (err, data) {
        if (err) res.status(500).json({ "message": "Something Is Wrong" });
        res.send(data);
      })
    } else {
      if (data1.email == req.body.email)
        res.status(500).json({ "message": "email already exists" });
      if (data1.phone == req.body.phone)
        res.status(500).json({ "message": "Phone already exists" });
    }
  });

}

module.exports.createUserMany = function (req, res, next) {
  req.trackRoute = req.body.trackRoute;
  req.poi = req.body.poi;
  req.stopNames = req.body.stopNames;
  req.body = req.body.parent;

  //console.log("req.stopNames=>", req.stopNames);
  _poi.insertMany(req.stopNames, function (error, docs) {
    if (error) {
      return console.log("ADD STOP POI DONE ERROR");
    }
    // console.log("ADD STOP POI DONE", JSON.stringify(docs));
  });
  for (var i = 0; i < req.body.length; i++) {
    (function (reqdata, id) {
      Contact.findOne({ phone: reqdata.phone }, function (err, adventure) {
        if (adventure == null) {
          (function (addPRED, id2) {
            addPRED.salt = crypto.randomBytes(16).toString('hex');
            addPRED.hash = crypto.pbkdf2Sync('Reset@123', addPRED.salt, 1000, 64, 'sha1').toString('hex');
            var _contact = new Contact(addPRED);
            _contact.save(function (err, data) {
              if (id == (req.body.length - 1)) {
                //res.send({msg:'if allDONE!'});

                next();
              }
            })
          })(reqdata, id);
        } else {
          if (id == (req.body.length - 1)) {
            //res.send({msg:'else allDONE!'});
            next();
          }
        }
      })
    })(req.body[i], i);

  }
}
module.exports.createUserMany1 = function (req, res) {

  async function cm() {
    for (var dd in req.body) {

      Contact.findOne({ phone: req.body[dd].phone }, function (err, adventure) {
        if (err) return;
        if (adventure == null) {
          // 
          req.body[dd].salt = crypto.randomBytes(16).toString('hex');
          req.body[dd].hash = crypto.pbkdf2Sync('Reset@123', req.body[dd].salt, 1000, 64, 'sha1').toString('hex');
          var _contact = new Contact(req.body[dd]);

          _contact.save(function (err, data) {
            if (err) res.status(500).json({ "message": "Something Is Wrong" });
            // res.send(data);
          })

          // 
        }
      });

    }
  }
  cm().then(function (resp) {
    res.send({ "mag": "success" });
  })



}

module.exports.editUser = function (req, res) {
  var pass = req.body.pass;
  req.body.salt = crypto.randomBytes(16).toString('hex');
  req.body.hash = crypto.pbkdf2Sync(pass, req.body.salt, 1000, 64, 'sha1').toString('hex');

  Contact.update({ _id: req.body._id }, { $set: req.body }, { multi: true }, function (err, data) {
    if (err) return res.send(err);
    else
      res.send(data);
  });
}
module.exports.updateImagePath = function (req, res) {
  if (req.body.imageDoc) {

    Contact.update({ _id: req.body._id }, { $set: { imageDoc: req.body.imageDoc } }, { multi: true }, function (err, data) {
      if (err) return res.send(err);
      else
        res.send(data);
    });
  }

}


module.exports.signUp = function (req, res) {
  if (req.body.org_name) {
    newOrgJson = {
      organisation_name: req.body.org_name,
      phone: req.body.org_phone,
      email: req.body.org_email,
      website: req.body.org_website,
    };
    var newOrg = new org(JSON.parse(JSON.stringify(newOrgJson)));
    newOrg.save(function (err, organisation) {
      if (err) {
        res.status(500).json({ "message": "Something Is Wrong" } + err);
      }
      if (organisation) {

        if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") {
          return res.status(401).json({ "message": "Null Value Error" });
        }
        //superadmin can able to add dealer

        else if (req.body.sysadmin == true) {
          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) {
            if (error) {
              console.error(error);
            }
            Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) {
              if (err) {
                console.error(err);
              }
              if (req.body.email && req.body.phone) {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: organisation._id,
                  role: req.body.roles,
                  supAdmin: req.body.supAdmin,
                  email: req.body.email.toLowerCase(),
                  phone: req.body.phone,
                  email_verfi: true,
                  phone_verfi: true,
                  isDealer: true,
                  isSuperAdmin: false,
                  Dealer: req.body.Dealer,
                  supAdmin: req.body.supAdmin,
                  custumerid: 'c_' + cuscount.seq,
                  dealerid: 'd_' + dealcount.seq,
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                  //   phone:'noNumber'+ counter.seq
                };
                if (req.body.group != "") {
                  newUserJson.group = req.body.group;
                }

                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();

                // var newUser = new Contact(newUserJson);
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  else {
                    res.status(200).json({ "message": "Registered Sucessfully" });

                  }
                })
              }
            });
          });
        }
        else if (req.body.custumer == true) {
         
             var Distributer_string = req.body.user_id;
          var user_regex = new RegExp(["^", Distributer_string, "$"].join(""), "i");
          Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { user_id: user_regex }] }, function (err, user) {
            if (err) {
              console.error(err)
            }
            else if (user) {
              if (user.email == req.body.email) {
                res.status(200).json({ "message": "Email ID already exists" })
              } else if (req.body.user_id == user.user_id) {
                res.status(200).json({ "message": "USER_ID already exists" })
              } else if (user.phone == req.body.phone) {
                res.status(200).json({ "message": "Mobile Number already exists" })
              } else {
                res.status(200).json({ "message": "User Duplicate" })
              }
            }
            else{
            Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) {
              if (error) {
                console.error(error);
              }
              if (req.body.email && req.body.phone) {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: organisation._id,
                  supAdmin: req.body.supAdmin,
                  email: req.body.email.toLowerCase(),
                  phone: req.body.phone,
                  email_verfi: true,
                  phone_verfi: true,
                  isDealer: false,
                  Dealer: req.body.Dealer,
                  custumerid: 'c_' + counter.seq,
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                  // phone:'noNumber'+ counter.seq
  
                };
  
                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
  
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();
  
                // var newUser = new Contact(newUserJson);
  
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                    return;
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
  
                })
              }
              else if (req.body.email) {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: organisation._id,
                  email: req.body.email.toLowerCase(),
                  phone: "nophone" + counter.seq,
                  email_verfi: true,
                  phone_verfi: true,
                  isDealer: false,
                  supAdmin: req.body.supAdmin,
                  Dealer: req.body.Dealer,
                  custumerid: 'c_' + counter.seq,
  
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                  //   phone:'noNumber'+ counter.seq
  
                };
  
                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
  
  
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();
  
                // var newUser = new Contact(newUserJson);
  
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
  
                })
              }
              else if (req.body.phone) {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: organisation._id,
                  phone: req.body.phone,
                  email_verfi: true,
                  supAdmin: req.body.supAdmin,
                  phone_verfi: true,
                  isDealer: false,
                  Dealer: req.body.Dealer,
                  email: 'noEmail' + counter.seq,
  
                  custumerid: 'c_' + counter.seq,
  
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                  //  email:'noEmail'+ counter.seq
  
                };
  
                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
  
  
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();
                // var newUser = new Contact(newUserJson);
  
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
  
                })
              }
              else {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: organisation._id,
                  phone: req.body.phone,
                  email: req.body.email.toLowerCase(),
                  email_verfi: true,
                  phone_verfi: true,
                  supAdmin: req.body.supAdmin,
                  isDealer: false,
                  Dealer: req.body.Dealer,
                  custumerid: 'c_' + counter.seq,
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                };
                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
  
  
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();
                // var newUser = new Contact(newUserJson);
  
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
  
                })
              }
  
  
            })
          }
          })

        }
        else if (req.body.otp && req.body.phone) {
          var token;
          Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) {
            if (err) {
              console.error(err);
              return err;
            }
            if (otpres) {
              //
              var dbtime = new Date(otpres.timestamp);
              var curtime = new Date();
              var diffMs = (curtime - dbtime); // milliseconds between now & Christmas
              var diffDays = Math.floor(diffMs / 86400000); // days
              var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
              var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
              if (otpres.otp == req.body.otp) {
                Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) {
                  if (err) {
                    console.error(err)
                    return res.status(400).send(err);
                  }
                  else {
                    return res.status(200).json({ "message": "Mobile Verified" });
                  }
                });
              }
              else {
                res.status(500).json({ "message": "Didn't match otp" });
              }
            }
          })
        }
        else if (req.body.phone && req.body.email) {
          var Distributer_string = req.body.user_id;
          var user_regex = new RegExp(["^", Distributer_string, "$"].join(""), "i");
          Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { user_id: user_regex }] }, function (err, user) {
            if (err) {
              console.error(err)
            }
            else if (user) {
              if (user.email == req.body.email) {
                res.status(200).json({ "message": "Email ID already exists" })
              } else if (req.body.user_id == user.user_id) {
                res.status(200).json({ "message": "USER_ID already exists" })
              } else if (user.phone == req.body.phone) {
                res.status(200).json({ "message": "Mobile Number already exists" })
              } else {
                res.status(200).json({ "message": "User Duplicate" })
              }
            }
            else {
              function randomString(length, chars) {
                var mask = '';
                if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
                if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                if (chars.indexOf('#') > -1) mask += '0123456789';
                if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
                var result = '';
                for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
                return result;
              }
              var otprand = randomString(4, '#');
              var randomemail = randomString(16, '#aA!');

              Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
                if (req.body.dealer == true) {

                  Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                    var newUserJson = {

                      first_name: req.body.first_name,
                      last_name: req.body.last_name,
                      org_name: req.body.org_name,
                      supAdmin: req.body.supAdmin,
                      org: organisation._id,
                      email: req.body.email.toLowerCase(),
                      phone: req.body.phone,
                      email_verfi: true,
                      phone_verfi: true,
                      otp: otprand,
                      id_email_ver: randomemail,
                      isDealer: req.body.dealer,
                      dealerid: 'd_' + counter.seq,
                      custumerid: 'c_' + count.seq,

                      timezone: req.body.timezone
                    };
                    //console.log("Inside otp function0");

                    if (req.body.std_code) {
                      newUserJson['std_code'] = req.body.std_code;
                    }


                    var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                    newUser.setPassword(req.body.password);
                    newUser.setLastReportDate();
                    newUser.save(function (err) {
                      if (err) {
                        if (err.name === 'MongoError' && err.code === 11000) {
                          // Duplicate username
                          return res.status(200).send({ succes: false, message: 'User already exist!' });
                        }

                        // Some other error
                        return res.status(500).send(err);
                      }
                      else {
                        request({
                          uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + otprand,
                          method: "GET"
                        }, function (error, response, body) {
                          /* var jsonObj = JSON.parse(response.body);
                          if(jsonObj.MsgStatus == 'Sent'){
                            email(req.body.first_name,req.body.email,randomemail);
                            res.status(200).json({"message" : "OTP sent successfully"})
                            
                          }
                          else{
                            res.status(500).json({"message" : "OTP sent Failed"})
                            Contact.remove({"phone" :req.body.phone}).then(function(err){
                              if(err){
                                res.send(err);
                                return err;
                              }
                            });
                          } */
                          res.status(200).json({ "message": "OTP sent successfully1" })
                        });
                      }
                    })

                  })

                }
                else {
                  var newUserJson = {
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    org_name: req.body.org_name,
                    org: organisation._id,
                    supAdmin: req.body.supAdmin,
                    email: req.body.email.toLowerCase(),
                    phone: req.body.phone,
                    email_verfi: true,
                    phone_verfi: true,
                    otp: otprand,
                    id_email_ver: randomemail,
                    isDealer: req.body.dealer,
                    custumerid: 'c_' + count.seq,
                    timezone: req.body.timezone
                  };

                  // console.log("Inside otp function1");

                  if (req.body.std_code) {
                    newUserJson['std_code'] = req.body.std_code;
                  }


                  var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                  newUser.setPassword(req.body.password);
                  newUser.setLastReportDate();
                  newUser.save(function (err) {
                    if (err) {
                      res.status(500).json({ "message": "Something Is Wrong" } + err);
                    }
                    email(req.body.first_name, req.body.email, randomemail);
                    request({
                      uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20to%20validate%20your%20login ' + otprand,
                      method: "GET"
                    }, function (error, response, body) {
                      /* var jsonObj = JSON.parse(response.body);
                      if(jsonObj.MsgStatus == 'Sent'){
                        email(req.body.first_name,req.body.email,randomemail);
                        res.status(200).json({"message" : "OTP sent successfully"})
                        
                      }
                      else{
                        res.status(500).json({"message" : "OTP sent Failed"})
                        Contact.remove({"phone" :req.body.phone}).then(function(err){
                          if(err){
                            res.send(err);
                            return err;
                          }
                        });
                      } */
                      res.status(200).json({ "message": "OTP sent successfully2" })
                    });

                  })

                }

              })

            }
          })

        }


        else if (req.body.phone) {
          Contact.findOne({ "phone": req.body.phone }, function (err, ph) {
            if (err) {
              console.error(err);
            }
            else if (ph) {
              res.status(500).json({ "message": "Mobile Number already Exists" })
            }
            else {
              Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
                if (req.body.dealer == true) {
                  Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {

                    var newUserJson = {
                      first_name: req.body.first_name,
                      last_name: req.body.last_name,
                      org_name: req.body.org_name,
                      org: organisation._id,
                      phone: req.body.phone,
                      supAdmin: req.body.supAdmin,
                      password: req.body.password,
                      email_verfi: true,
                      phone_verfi: true,
                      isDealer: req.body.dealer,
                      dealerid: 'd_' + counter.seq,
                      custumerid: 'c_' + count.seq,
                      email: 'noEmail' + count.seq,

                      timezone: req.body.timezone
                    };

                    if (req.body.std_code) {
                      newUserJson['std_code'] = req.body.std_code;
                    }

                    let datastore = newUserJson;
                    //  let a = otp(newUserJson);
                    otp(newUserJson, function (final_data) {

                      if (final_data == true) {
                        res.status(200).json({ "message": "OTP Successfully Sent0" });
                      }
                      else {
                        res.status(500).json({ "message": "OTP sent Failed" })
                        Contact.remove({ "phone": req.body.phone }).then(function (err) {
                          if (err) {
                            // res.send(err);
                            //  return err;
                          }
                        });
                      }
                    })
                  })
                }
                else {
                  var newUserJson = {
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    org_name: req.body.org_name,
                    phone: req.body.phone,
                    supAdmin: req.body.supAdmin,
                    password: req.body.password,
                    isDealer: req.body.dealer,
                    custumerid: 'c_' + count.seq,
                    email: 'noEmail' + count.seq,
                    email_verfi: true,
                    phone_verfi: true,
                    timezone: req.body.timezone

                  };
                  // otp(newUserJson);
                  //  let a = otp(newUserJson);

                  if (req.body.std_code) {
                    newUserJson['std_code'] = req.body.std_code;
                  }


                  otp(newUserJson, function (final_data) {

                    if (final_data == true) {
                      res.status(200).json({ "message": "OTP Successfully Sent" });
                    }
                    else {
                      res.status(500).json({ "message": "OTP sent Failed" })
                      Contact.remove({ "phone": req.body.phone }).then(function (err) {
                        if (err) {
                          // res.send(err);
                          // return err;
                        }
                      });
                    }

                  })
                }

              })
            }
          })


        }



        else if (req.body.email) {

          var randomemail = Math.floor((Math.random() * 100000000000000) + 54);
          Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) {
            if (err) {
              console.error(err);
            }
            else if (em) {
              res.status(500).json({ "message": "Email ID already Exists" })
            }
            else {

              Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {

                if (req.body.dealer == true) {
                  Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                    var newUserJson = {
                      first_name: req.body.first_name,
                      last_name: req.body.last_name,
                      org_name: req.body.org_name,
                      org: organisation._id,
                      supAdmin: req.body.supAdmin,
                      email: req.body.email.toLowerCase(),
                      email_verfi: true,
                      phone_verfi: true,
                      id_email_ver: randomemail,
                      isDealer: req.body.dealer,
                      dealerid: 'd_' + counter.seq,
                      custumerid: 'c_' + count.seq,
                      phone: 'noNumber' + count.seq,

                      timezone: req.body.timezone
                    };

                    if (req.body.std_code) {
                      newUserJson['std_code'] = req.body.std_code;
                    }

                    var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                    newUser.setPassword(req.body.password);
                    newUser.setLastReportDate();

                    newUser.save(function (err) {
                      if (err) {
                        res.status(500).json({ "message": "Something Is Wrong" } + err);
                      }
                      res.status(200).json({ "message": "Registered Sucessfully" });

                    })
                    email(req.body.first_name, req.body.email, randomemail);
                  })

                }
                else {
                  var newUserJson = {
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    org_name: req.body.org_name,
                    supAdmin: req.body.supAdmin,
                    email: req.body.email.toLowerCase(),
                    email_verfi: true,
                    phone_verfi: true,
                    id_email_ver: randomemail,
                    isDealer: req.body.dealer,
                    custumerid: 'c_' + count.seq,
                    phone: 'noNumber' + count.seq,

                    timezone: req.body.timezone
                  };


                  if (req.body.std_code) {
                    newUserJson['std_code'] = req.body.std_code;
                  }


                  var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                  newUser.setPassword(req.body.password);
                  newUser.setLastReportDate();

                  newUser.save(function (err) {
                    if (err) {
                      res.status(500).json({ "message": "Something Is Wrong" } + err);
                    }
                    res.status(200).json({ "message": "Registered Sucessfully" });

                  })
                  email(req.body.first_name, req.body.email, randomemail);
                }
              })
            }
          })
        }
        else {
          res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" });
        }

      }
      else {
        res.status(400).send({ "message": "Server error" })
      }

    })
  }
  else {
    // if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") {
    //   return res.status(401).json({ "message": "Null Value Error" });
    // }
    //superadmin can able to add dealer

    // else
    if (req.body.sysadmin == true) {
      Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) {
        if (error) {
          console.error(error);
        }
        Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) {
          if (err) {
            console.error(err);
          }
          if (req.body.email && req.body.phone) {


            var user_string = req.body.user_id;
            var user_regex = new RegExp(["^", user_string, "$"].join(""), "i");

            Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { 'user_id': user_regex }] }, function (err, user) {
              if (err) {
                console.error(err)
              }
              else if (user) {
                if (user.email == req.body.email) {
                  res.status(200).json({ "message": "Email ID already exists" })
                } else if (req.body.user_id == user.user_id) {
                  res.status(200).json({ "message": "USER_ID already exists" })
                } else if (user.phone == req.body.phone) {
                  res.status(200).json({ "message": "Mobile Number already exists" })
                } else {
                  res.status(200).json({ "message": "User Duplicate" })
                }
              }
              else {

                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  role: req.body.roles,
                  group: req.body.group,
                  supAdmin: req.body.supAdmin,
                  email: req.body.email.toLowerCase(),
                  phone: req.body.phone,
                  email_verfi: true,
                  phone_verfi: true,
                  isDealer: true,
                  isSuperAdmin: false,
                  Dealer: req.body.Dealer,
                  supAdmin: req.body.supAdmin,
                  custumerid: 'c_' + cuscount.seq,
                  dealerid: 'd_' + dealcount.seq,
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                  //   phone:'noNumber'+ counter.seq
                };

                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }

                if (req.body.customer_role) {
                  newUserJson['customer_role'] = req.body.customer_role;
                }

                var admin_identifier = req.body.supAdmin;
                var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic';
                var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1';
                if (req.body.imageDoc) {
                  newUserJson.imageDoc = req.body.imageDoc;
                }
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();

                // var newUser = new Contact(newUserJson);
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                    return;
                  }
                  //   res.status(200).json({ "message": "Registered Sucessfully" });
                  var SMSURL = Utilities.getConfig().smsUrl;

                  var mobile_key = Utilities.getConfig().smsApiMobileKey;
                  var txt_key = Utilities.getConfig().smsApiTextKey;

                  // ======================================sms according to superAdmin =================================================
                  Contact.findOne({ _id: admin_identifier }, function (err, adminDetail) {
                    if (err) {
                      res.status(400).send({ "message": "not able to fetch supadmin" });

                    }

                    var msgOption = adminDetail.welcome_msg;
                    // Saanvi Security Solution
                    if ((msgOption != undefined) && (msgOption == true)) {
                      var organisationName = ((adminDetail.organisation_name != undefined) || (adminDetail.organisation_name != '')) ? adminDetail.organisation_name : 'OneQlik GPS';

                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password;
                      if (organisationName == 'Tractive VTS') {
                        SMSURL += '&sender=TRACTV';
                        var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login';
                      } else if (organisationName === 'IConnect Technologies') {
                        SMSURL = Utilities.getConfig().smsUrl_iconnect;
                        SMSURL += '&senderid=AMASEC';
                        mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect;
                        txt_key = Utilities.getConfig().smsApiTextKey_iconnect;
                        var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in';
                      } else if (organisationName === 'Saanvi Security Solution') {
                        SMSURL = Utilities.getConfig().smsUrl_saanvi;
                        mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi;
                        txt_key = Utilities.getConfig().smsApiTextKey_saanvi;
                        var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.saanvisecurity.in';
                      }
                      else {
                        SMSURL += '&sender=OneQlk';
                      }

                      request({
                        uri: SMSURL + mobile_key + req.body.phone + txt_key + userCred1,
                        method: "GET"
                      }, function (error, response, body) {
                        res.status(200).json({ "message": "Registered and Message Sent Successfuly" })
                      });

                    } else {
                      res.status(200).json({ "message": "Registered" })
                    }


                  })

                  // ======================================sms according to superAdmin =================================================

                })
              }
            })

          } else if (req.body.user_id) {
            var user_string = req.body.user_id;
            var user_regex = new RegExp(["^", user_string, "$"].join(""), "i");

            Contact.findOne({ 'user_id': user_regex }, function (err, user) {
              if (err) {
                console.error(err)
              }
              else if (user) {

                res.status(200).json({ "message": "User Duplicate" })

              }
              else {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  role: req.body.roles,
                  group: req.body.group,
                  supAdmin: req.body.supAdmin,
                  email: 'no_email' + cuscount.seq + '@testmail.com',
                  phone: 'no_phone' + cuscount.seq,
                  email_verfi: true,
                  phone_verfi: true,

                  isSuperAdmin: false,

                  supAdmin: req.body.supAdmin,
                  custumerid: 'c_' + cuscount.seq,
                  dealerid: 'd_' + dealcount.seq,
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  address: req.body.address,
                  expire_date: new Date(req.body.expdate)
                  //   phone:'noNumber'+ counter.seq
                };
                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }

                if (req.body.isDealer === true) {
                  newUserJson['isDealer'] = req.body.isDealer;
                } else {
                  newUserJson['isDealer'] = false;
                  newUserJson['Dealer'] = req.body.Dealer;
                }


                if (req.body.imageDoc) {
                  newUserJson.imageDoc = req.body.imageDoc;
                }
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();

                // var newUser = new Contact(newUserJson);
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                    return;
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
                })
              }
            })

          }

        });
      });
    }
    else if (req.body.custumer == true) {

      Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) {

        if (error) {
          console.error(error);
        }

        var user_string = req.body.user_id;
        var user_regex = new RegExp(["^", user_string, "$"].join(""), "i");
        Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { 'user_id': user_regex }] }, function (err, user) {
          
          if (err) {
            console.error(err)
          }
          else if ((user) && ((req.body.phone) || (req.body.email != null))) {
            if (user.email == req.body.email) {
              res.status(200).json({ "message": "Email ID already exists" })
            } else if (req.body.user_id == user.user_id) {
              res.status(200).json({ "message": "USER_ID already exists" })
            } else if (user.phone == req.body.phone) {
              res.status(200).json({ "message": "Mobile Number already exists" })
            } else {
              res.status(200).json({ "message": "User Duplicate" })
            }
          }else if((user)&&(req.body.phone == undefined)&&(req.body.email == null)){
            if(req.body.user_id == user.user_id){
              res.status(200).json({ "message": "USER_ID already exists" })
            }else{
              res.status(200).json({ "message": "Error in line 1084" })
            }
          }                                                                   
          else {
            if (req.body.email && req.body.phone) {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                email: req.body.email.toLowerCase(),
                phone: req.body.phone,
                supAdmin: req.body.supAdmin,
                email_verfi: true,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                custumerid: 'c_' + counter.seq,
                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                expire_date: new Date(req.body.expdate)
                //   phone:'noNumber'+ counter.seq

              };

              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }

              if (req.body.imageDoc) {
                newUserJson.imageDoc = req.body.imageDoc;
              }
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();

              // var newUser = new Contact(newUserJson);
              var admin_identifier = req.body.supAdmin;
              var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic';
              var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1';
              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                  return;
                }
                //   res.status(200).json({ "message": "Registered Sucessfully" });
                // console.log("INside Signup function");
                // console.log(req.body.phone);
                // console.log(req.body.password);
                var SMSURL = Utilities.getConfig().smsUrl;

                var mobile_key = Utilities.getConfig().smsApiMobileKey;
                var txt_key = Utilities.getConfig().smsApiTextKey;

                // ======================================sms according to superAdmin =================================================
                Contact.findOne({ _id: admin_identifier }, function (err, adminDetail) {
                  if (err) {
                    res.status(400).send({ "message": "not able to fetch supadmin" });

                  }


                  var msgOption = adminDetail.welcome_msg;


                  if ((msgOption != undefined) && (msgOption == true)) {
                    var organisationName = ((adminDetail.organisation_name != undefined) || (adminDetail.organisation_name != '')) ? adminDetail.organisation_name : 'OneQlik GPS';
                    var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password;
                    if (organisationName == 'Tractive VTS') {
                      SMSURL += '&sender=TRACTV';
                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login';
                    } else if (organisationName === 'IConnect Technologies') {
                      SMSURL = Utilities.getConfig().smsUrl_iconnect;
                      SMSURL += '&senderid=AMASEC';
                      mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect;
                      txt_key = Utilities.getConfig().smsApiTextKey_iconnect;
                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in';
                    } else if (organisationName === 'Saanvi Security Solution') {
                      SMSURL = Utilities.getConfig().smsUrl_saanvi;
                      mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi;
                      txt_key = Utilities.getConfig().smsApiTextKey_saanvi;
                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.saanvisecurity.in';
                    } else {
                      SMSURL += '&sender=OneQlk';
                    }



                    request({
                      uri: SMSURL + mobile_key + req.body.phone + txt_key + userCred1,
                      method: "GET"
                    }, function (error, response, body) {
                      res.status(200).json({ "message": "Registered and Message Sent Successfuly" })
                    });

                  } else {
                    res.status(200).json({ "message": "Registered" })
                  }
                })

                // ======================================sms according to superAdmin =================================================
              })
            }
            else if (req.body.email) {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                email: req.body.email.toLowerCase(),
                phone: "nophone" + counter.seq,
                email_verfi: true,
                supAdmin: req.body.supAdmin,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                custumerid: 'c_' + counter.seq,

                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                expire_date: new Date(req.body.expdate)
                //   phone:'noNumber'+ counter.seq

              };
              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }


              if (req.body.imageDoc) {
                newUserJson.imageDoc = req.body.imageDoc;
              }
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();

              // var newUser = new Contact(newUserJson);

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });


              })
            }
            else if (req.body.phone) {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                phone: req.body.phone,
                email_verfi: true,
                supAdmin: req.body.supAdmin,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                email: 'noEmail' + counter.seq,

                custumerid: 'c_' + counter.seq,

                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                expire_date: new Date(req.body.expdate)
                //  email:'noEmail'+ counter.seq

              };
              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }

              if (req.body.imageDoc) {
                newUserJson.imageDoc = req.body.imageDoc;
              }
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();
              // var newUser = new Contact(newUserJson);
              var admin_identifier = req.body.supAdmin;
              var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic';
              var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1';

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }

                var SMSURL = Utilities.getConfig().smsUrl;
                var mobile_key = Utilities.getConfig().smsApiMobileKey;
                var txt_key = Utilities.getConfig().smsApiTextKey;

                // ======================================sms according to superAdmin =================================================
                Contact.findOne({ _id: admin_identifier }, function (err, adminDetail) {
                  if (err) {
                    res.status(400).send({ "message": "not able to fetch supadmin" });

                  }

                  var msgOption = adminDetail.welcome_msg;

                  if ((msgOption != undefined) && (msgOption == true)) {
                    var organisationName = ((adminDetail.organisation_name != undefined) || (adminDetail.organisation_name != '')) ? adminDetail.organisation_name : 'OneQlik GPS';

                    var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password;

                    if (organisationName == 'Tractive VTS') {
                      SMSURL += '&sender=TRACTV';
                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login';
                    } else if (organisationName === 'IConnect Technologies') {
                      SMSURL = Utilities.getConfig().smsUrl_iconnect;
                      SMSURL += '&senderid=AMASEC';
                      mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect;
                      txt_key = Utilities.getConfig().smsApiTextKey_iconnect;
                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in';
                    } else if (organisation_name === 'Saanvi Security Solution') {
                      SMSURL = Utilities.getConfig().smsUrl_saanvi;
                      mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi;
                      txt_key = Utilities.getConfig().smsApiTextKey_saanvi;
                      var userCred1 = 'Dear%20' + req.body.first_name + "%20Welcome%20to%20" + organisationName + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + req.body.phone + '%20Password%20' + req.body.password + '%20WEB%20LOGIN%20' + 'http://www.saanvisecurity.in';
                    } else {
                      SMSURL += '&sender=OneQlk';
                    }


                    request({
                      uri: SMSURL + mobile_key + req.body.phone + txt_key + userCred1,
                      method: "GET"
                    }, function (error, response, body) {
                      res.status(200).json({ "message": "Registered and Message Sent Successfuly" })
                    });

                  } else {
                    res.status(200).json({ "message": "Registered" })
                  }
                })

                // ======================================sms according to superAdmin =================================================

              })
            }
            else {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                phone: 'no_phone' + counter.seq,
                supAdmin: req.body.supAdmin,
                email: 'no_email' + counter.seq + '@testmail.com',
                email_verfi: true,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                custumerid: 'c_' + counter.seq,
                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                expire_date: new Date(req.body.expdate)
              };


              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }


              if (req.body.imageDoc) {
                newUserJson.imageDoc = req.body.imageDoc;
              }
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();
              // var newUser = new Contact(newUserJson);

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });
              })
            }
          }
        })


      })

    }
    else if (req.body.otp && req.body.phone) {
      var token;
      Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) {
        if (err) {
          console.error(err);
          return err;
        }
        if (otpres) {
          //
          var dbtime = new Date(otpres.timestamp);
          var curtime = new Date();
          var diffMs = (curtime - dbtime); // milliseconds between now & Christmas
          var diffDays = Math.floor(diffMs / 86400000); // days
          var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
          var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
          if (otpres.otp == req.body.otp) {
            Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) {
              if (err) {
                console.error(err)
                return res.status(400).send(err);
              }
              else {
                return res.status(200).json({ "message": "Mobile Verified" });
              }
            });
          }
          else {
            res.status(500).json({ "message": "Didn't match otp" });
          }
        }
      })
    }
    else if (req.body.phone && req.body.email) {
      var Distributer_string = req.body.user_id;
      var user_regex = new RegExp(["^", Distributer_string, "$"].join(""), "i");

      Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }, { 'user_id': user_regex }] }, function (err, user) {
        if (err) {
          console.error(err)
        }
        else if (user) {

          if (user.email == req.body.email) {
            res.status(200).json({ "message": "Email ID already exists" })
          } else if (req.body.user_id == user.user_id) {
            res.status(200).json({ "message": "USER_ID already exists" })
          } else if (user.phone == req.body.phone) {
            res.status(200).json({ "message": "Mobile Number already exists" })
          } else {
            res.status(200).json({ "message": "User Duplicate" })
          }


        }
        else {
          function randomString(length, chars) {
            var mask = '';
            if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
            if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            if (chars.indexOf('#') > -1) mask += '0123456789';
            if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
            var result = '';
            for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
            return result;
          }
          var otprand = randomString(4, '#');
          var randomemail = randomString(16, '#aA!');

          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
            if (req.body.dealer == true) {

              Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                var newUserJson = {

                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  email: req.body.email.toLowerCase(),
                  phone: req.body.phone,
                  email_verfi: true,
                  supAdmin: req.body.supAdmin,
                  phone_verfi: true,
                  otp: otprand,
                  id_email_ver: randomemail,
                  isDealer: req.body.dealer,
                  dealerid: 'd_' + counter.seq,
                  custumerid: 'c_' + count.seq,
                  timezone: req.body.timezone
                };

                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
                if (req.body.organisation) {
                  newUserJson.organisation = req.body.organisation;
                  newUserJson.isSuperAdmin = req.body.isSuperAdmin;
                  newUserJson.isDealer = false;
                  newUserJson.phone_verfi = true;
                  newUserJson.organisation_name = req.body.organisation_name;
                  newUserJson.welcome_msg = req.body.welcome_msg;


                  newUserJson.user_id = req.body.user_id;
                }
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();
                newUser.save(function (err) {
                  if (err) {
                    if (err.name === 'MongoError' && err.code === 11000) {
                      // Duplicate username
                      return res.status(200).send({ succes: false, message: 'User already exist!' });
                    }

                    // Some other error
                    return res.status(500).send(err);
                  }
                  else {
                    request({
                      uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + otprand,
                      method: "GET"
                    }, function (error, response, body) {
                      /* var jsonObj = JSON.parse(response.body);
                      if(jsonObj.MsgStatus == 'Sent'){
                        email(req.body.first_name,req.body.email,randomemail);
                        res.status(200).json({"message" : "OTP sent successfully"})
                        
                      }
                      else{
                        res.status(500).json({"message" : "OTP sent Failed"})
                        Contact.remove({"phone" :req.body.phone}).then(function(err){
                          if(err){
                            res.send(err);
                            return err;
                          }
                        });
                      } */
                      res.status(200).json({ "message": "OTP sent successfully3" })
                    });
                  }
                })

              })

            }
            else {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                email: req.body.email.toLowerCase(),
                phone: req.body.phone,

                supAdmin: req.body.supAdmin,
                Dealer: req.body.supAdmin,
                phone_verfi: true,
                email_verfi: true,
                otp: otprand,
                id_email_ver: randomemail,
                isDealer: req.body.dealer ? req.body.dealer : req.body.isDealer,
                custumerid: 'c_' + count.seq,
                timezone: req.body.timezone,
                custumer: true
              };
              //console.log("Inside otp function3");
              //console.log("we are at 1158 while creating distributer");
              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }

              if (req.body.organisation) {
                newUserJson.organisation = req.body.organisation;
                newUserJson.user_id = req.body.user_id;
                newUserJson.isSuperAdmin = req.body.isSuperAdmin;
                newUserJson.organisation_name = req.body.organisation_name;
                newUserJson.welcome_msg = req.body.welcome_msg;
                newUserJson.isDealer = false;
                newUserJson.phone_verfi = true;
              }
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();
              if (req.body.purpose == "zettrack") {
                var smsUri = Utilities.getConfig().ZettracksmsUrl + "&mobileNos=" + req.body.phone + "&message=" + "Welcome%20to%20ZTrack%20Sreerampore%20Use%20this%20One%20Time%20Password%20to%20validate%20your%20login" + otprand;
              } else {
                var smsUri = Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20to%20validate%20your%20login ' + otprand;
              }
              newUser.save(function (err, userObj) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                email(req.body.first_name, req.body.email, randomemail);
                request({
                  uri: smsUri,
                  method: "GET"
                }, function (error, response, body) {
                  /* var jsonObj = JSON.parse(response.body);
                  if(jsonObj.MsgStatus == 'Sent'){
                    email(req.body.first_name,req.body.email,randomemail);
                    res.status(200).json({"message" : "OTP sent successfully"})
                    
                  }
                  else{
                    res.status(500).json({"message" : "OTP sent Failed"})
                    Contact.remove({"phone" :req.body.phone}).then(function(err){
                      if(err){
                        res.send(err);
                        return err;
                      }
                    });
                  } */
                  res.status(200).json({ "message": "OTP sent successfully", "user": userObj })
                });

              })

            }



          })



        }
      })

    }


    else if (req.body.phone) {
      Contact.findOne({ "phone": req.body.phone }, function (err, ph) {
        if (err) {
          console.error(err);
        }
        else if (ph) {
          res.status(500).json({ "message": "Mobile Number already Exists" })
        }
        else {
          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
            if (req.body.dealer == true) {
              Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {

                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  phone: req.body.phone,
                  supAdmin: req.body.supAdmin,
                  password: req.body.password,
                  phone_verfi: true,
                  email_verfi: true,
                  isDealer: req.body.dealer,
                  dealerid: 'd_' + counter.seq,
                  custumerid: 'c_' + count.seq,
                  email: 'noEmail' + count.seq,

                  timezone: req.body.timezone

                };

                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }
                let datastore = newUserJson;
                //  let a = otp(newUserJson);
                otp(newUserJson, function (final_data) {

                  if (final_data == true) {
                    res.status(200).json({ "message": "OTP Successfully Sent" });
                  }
                  else {
                    res.status(500).json({ "message": "OTP sent Failed" })
                    Contact.remove({ "phone": req.body.phone }).then(function (err) {
                      if (err) {
                        // res.send(err);
                        //  return err;
                      }
                    });

                  }

                })

              })


            }
            else {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                phone: req.body.phone,
                supAdmin: req.body.supAdmin,
                password: req.body.password,
                phone_verfi: true,
                email_verfi: true,
                isDealer: req.body.dealer,
                custumerid: 'c_' + count.seq,
                email: 'noEmail' + count.seq,

                timezone: req.body.timezone

              };
              // otp(newUserJson);
              //  let a = otp(newUserJson);

              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }
              otp(newUserJson, function (final_data) {
                if (final_data == true) {
                  res.status(200).json({ "message": "OTP Successfully Sent" });
                }
                else {
                  res.status(500).json({ "message": "OTP sent Failed" })
                  Contact.remove({ "phone": req.body.phone }).then(function (err) {
                    if (err) {
                      // res.send(err);
                      // return err;
                    }
                  });
                }

              })
            }

          })
        }
      })


    }



    else if (req.body.email) {

      var randomemail = Math.floor((Math.random() * 100000000000000) + 54);
      Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) {
        if (err) {
          console.error(err);
        }
        else if (em) {
          res.status(500).json({ "message": "Email ID already Exists" })
        }
        else {

          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {

            if (req.body.dealer == true) {
              Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  supAdmin: req.body.supAdmin,
                  email: req.body.email.toLowerCase(),
                  email_verfi: true,
                  phone_verfi: true,
                  id_email_ver: randomemail,
                  isDealer: req.body.dealer,
                  dealerid: 'd_' + counter.seq,
                  custumerid: 'c_' + count.seq,
                  phone: 'noNumber' + count.seq,

                  timezone: req.body.timezone
                };

                if (req.body.std_code) {
                  newUserJson['std_code'] = req.body.std_code;
                }

                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();

                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });

                })
                email(req.body.first_name, req.body.email, randomemail);
              })

            }
            else {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                email: req.body.email.toLowerCase(),
                email_verfi: true,
                phone_verfi: true,
                supAdmin: req.body.supAdmin,
                id_email_ver: randomemail,
                isDealer: req.body.dealer,
                custumerid: 'c_' + count.seq,
                phone: 'noNumber' + count.seq,

                timezone: req.body.timezone
              };
              if (req.body.std_code) {
                newUserJson['std_code'] = req.body.std_code;
              }

              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });


              })
              email(req.body.first_name, req.body.email, randomemail);
            }
          })


        }
      })


    }
    else {
      res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" });
    }

  }
}



// ==============================
module.exports.signUpZogo = function (req, res) {
  if (req.body.org_name) {
    //console.log("Inside function");
    newOrgJson = {
      organisation_name: req.body.org_name,
      phone: req.body.org_phone,
      email: req.body.org_email,
      website: req.body.org_website,
    };
    var newOrg = new org(JSON.parse(JSON.stringify(newOrgJson)));
    newOrg.save(function (err, organisation) {
      if (err) {
        res.status(500).json({ "message": "Something Is Wrong" } + err);
      }
      if (organisation) {

        if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") {
          return res.status(401).json({ "message": "Null Value Error" });
        }
        //superadmin can able to add dealer

        else if (req.body.sysadmin == true) {
          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) {
            if (error) {
              console.error(error);
            }
            Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) {
              if (err) {
                console.error(err);
              }
              if (req.body.email && req.body.phone) {
                console.log("1");
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: organisation._id,
                  role: req.body.roles,
                  group: req.body.group,
                  email: req.body.email.toLowerCase(),
                  phone: req.body.phone,
                  email_verfi: true,
                  phone_verfi: true,
                  isDealer: true,
                  isSuperAdmin: false,
                  Dealer: req.body.Dealer,
                  supAdmin: req.body.supAdmin,
                  custumerid: 'c_' + cuscount.seq,
                  dealerid: 'd_' + dealcount.seq,
                  timezone: req.body.timezone,
                  user_id: req.body.user_id,
                  status: req.body.status,
                  address: req.body.address,
                  purpose: "zogo",
                  expire_date: new Date(req.body.expdate)
                  //   phone:'noNumber'+ counter.seq
                };
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();

                // var newUser = new Contact(newUserJson);
                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
                })
              }
            });
          });
        }
        else if (req.body.custumer == true) {

          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) {

            if (error) {
              console.error(error);
            }
            if (req.body.email && req.body.phone) {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: organisation._id,
                email: req.body.email.toLowerCase(),
                phone: req.body.phone,
                email_verfi: true,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                custumerid: 'c_' + counter.seq,
                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                status: req.body.status,
                purpose: "zogo",
                expire_date: new Date(req.body.expdate)
                //   phone:'noNumber'+ counter.seq

              };
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();

              // var newUser = new Contact(newUserJson);

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                  return;
                }
                res.status(200).json({ "message": "Registered Sucessfully" });
              })
            }
            else if (req.body.email) {
              //console.log("2");
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: organisation._id,
                email: req.body.email.toLowerCase(),
                phone: "nophone" + counter.seq,
                email_verfi: true,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                custumerid: 'c_' + counter.seq,
                status: req.body.status,
                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                purpose: "zogo",
                expire_date: new Date(req.body.expdate)
                //   phone:'noNumber'+ counter.seq

              };
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();

              // var newUser = new Contact(newUserJson);

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });
              })
            }
            else if (req.body.phone) {
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: organisation._id,
                phone: req.body.phone,
                email_verfi: true,
                phone_verfi: true,
                isDealer: false,
                status: req.body.status,

                Dealer: req.body.Dealer,
                email: 'noEmail' + counter.seq,

                custumerid: 'c_' + counter.seq,

                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                expire_date: new Date(req.body.expdate)
                //  email:'noEmail'+ counter.seq

              };
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();
              // var newUser = new Contact(newUserJson);

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });
              })
            }
            else {
              // console.log("3");
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: organisation._id,
                phone: req.body.phone,
                email: req.body.email.toLowerCase(),
                email_verfi: true,
                phone_verfi: true,
                isDealer: false,
                Dealer: req.body.Dealer,
                custumerid: 'c_' + counter.seq,
                timezone: req.body.timezone,
                user_id: req.body.user_id,
                address: req.body.address,
                status: req.body.status,
                purpose: "zogo",
                expire_date: new Date(req.body.expdate)
              };
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();
              // var newUser = new Contact(newUserJson);

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });
              })
            }


          })

        }
        else if (req.body.otp && req.body.phone) {

          var token;
          Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) {
            if (err) {
              console.error(err);
              return err;
            }
            if (otpres) {
              //
              var dbtime = new Date(otpres.timestamp);
              var curtime = new Date();
              var diffMs = (curtime - dbtime); // milliseconds between now & Christmas
              var diffDays = Math.floor(diffMs / 86400000); // days
              var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
              var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
              if (otpres.otp == req.body.otp) {
                Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) {
                  if (err) {
                    console.error(err)
                    return res.status(400).send(err);
                  }
                  else {
                    return res.status(200).json({ "message": "Mobile Verified" });
                  }
                });
              }
              else {
                res.status(500).json({ "message": "Didn't match otp" });
              }
            }
          })
        }
        else if (req.body.phone && req.body.email) {
          Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }] }, function (err, user) {
            if (err) {
              console.error(err)
            }
            else if (user) {
              res.status(200).json({ "message": "Email ID or Mobile Number already exists" })
            }
            else {
              function randomString(length, chars) {
                var mask = '';
                if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
                if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                if (chars.indexOf('#') > -1) mask += '0123456789';
                if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
                var result = '';
                for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
                return result;
              }
              var otprand = randomString(4, '#');
              var randomemail = randomString(16, '#aA!');

              Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
                if (req.body.dealer == true) {

                  Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                    //console.log("4");
                    var newUserJson = {

                      first_name: req.body.first_name,
                      last_name: req.body.last_name,
                      org_name: req.body.org_name,
                      org: organisation._id,
                      email: req.body.email.toLowerCase(),
                      phone: req.body.phone,
                      email_verfi: false,
                      phone_verfi: false,
                      otp: otprand,
                      status: req.body.status,
                      purpose: "zogo",
                      id_email_ver: randomemail,
                      isDealer: req.body.dealer,
                      dealerid: 'd_' + counter.seq,
                      custumerid: 'c_' + count.seq,

                      timezone: req.body.timezone
                    };
                    var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                    newUser.setPassword(req.body.password);
                    newUser.setLastReportDate();
                    newUser.save(function (err) {
                      if (err) {
                        if (err.name === 'MongoError' && err.code === 11000) {
                          // Duplicate username
                          return res.status(200).send({ succes: false, message: 'User already exist!' });
                        }

                        // Some other error
                        return res.status(500).send(err);
                      }
                      else {
                        request({
                          uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand,
                          method: "GET"
                        }, function (error, response, body) {
                          /* var jsonObj = JSON.parse(response.body);
                          if(jsonObj.MsgStatus == 'Sent'){
                            email(req.body.first_name,req.body.email,randomemail);
                            res.status(200).json({"message" : "OTP sent successfully"})
                            
                          }
                          else{
                            res.status(500).json({"message" : "OTP sent Failed"})
                            Contact.remove({"phone" :req.body.phone}).then(function(err){
                              if(err){
                                res.send(err);
                                return err;
                              }
                            });
                          } */
                          res.status(200).json({ "message": "OTP sent successfully" })
                        });
                      }
                    })

                  })

                }
                else {
                  //console.log("5");
                  var newUserJson = {
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    org_name: req.body.org_name,
                    org: organisation._id,
                    email: req.body.email.toLowerCase(),
                    phone: req.body.phone,
                    email_verfi: false,
                    phone_verfi: false,
                    otp: otprand,
                    status: req.body.status,
                    purpose: "zogo",
                    id_email_ver: randomemail,
                    isDealer: req.body.dealer,
                    custumerid: 'c_' + count.seq,

                    timezone: req.body.timezone
                  };
                  var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                  newUser.setPassword(req.body.password);
                  newUser.setLastReportDate();
                  newUser.save(function (err) {
                    if (err) {
                      res.status(500).json({ "message": "Something Is Wrong" } + err);
                    }
                    email(req.body.first_name, req.body.email, randomemail);
                    request({
                      uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand,
                      method: "GET"
                    }, function (error, response, body) {
                      /* var jsonObj = JSON.parse(response.body);
                      if(jsonObj.MsgStatus == 'Sent'){
                        email(req.body.first_name,req.body.email,randomemail);
                        res.status(200).json({"message" : "OTP sent successfully"})
                        
                      }
                      else{
                        res.status(500).json({"message" : "OTP sent Failed"})
                        Contact.remove({"phone" :req.body.phone}).then(function(err){
                          if(err){
                            res.send(err);
                            return err;
                          }
                        });
                      } */
                      res.status(200).json({ "message": "OTP sent successfully" })
                    });
                  })
                }
              })
            }
          })

        }
        else if (req.body.phone) {
          Contact.findOne({ "phone": req.body.phone }, function (err, ph) {
            if (err) {
              console.error(err);
            }
            else if (ph) {
              res.status(500).json({ "message": "Mobile Number already Exists" })
            }
            else {
              Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
                if (req.body.dealer == true) {
                  Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                    // console.log("6");
                    var newUserJson = {
                      first_name: req.body.first_name,
                      last_name: req.body.last_name,
                      org_name: req.body.org_name,
                      org: organisation._id,
                      phone: req.body.phone,
                      status: req.body.status,
                      password: req.body.password,
                      isDealer: req.body.dealer,
                      dealerid: 'd_' + counter.seq,
                      custumerid: 'c_' + count.seq,
                      email: 'noEmail' + count.seq,
                      purpose: "zogo",
                      timezone: req.body.timezone

                    };
                    let datastore = newUserJson;
                    //  let a = otp(newUserJson);
                    otp(newUserJson, function (final_data) {

                      if (final_data == true) {
                        res.status(200).json({ "message": "OTP Successfully Sent" });
                      }
                      else {
                        res.status(500).json({ "message": "OTP sent Failed" })
                        Contact.remove({ "phone": req.body.phone }).then(function (err) {
                          if (err) {
                            // res.send(err);
                            //  return err;
                          }
                        });

                      }

                    })

                  })


                }
                else {
                  //console.log("7");
                  var newUserJson = {
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    org_name: req.body.org_name,
                    phone: req.body.phone,
                    password: req.body.password,
                    isDealer: req.body.dealer,
                    status: req.body.status,
                    custumerid: 'c_' + count.seq,
                    email: 'noEmail' + count.seq,
                    purpose: "zogo",
                    timezone: req.body.timezone

                  };
                  // otp(newUserJson);
                  //  let a = otp(newUserJson);
                  otp(newUserJson, function (final_data) {

                    if (final_data == true) {
                      res.status(200).json({ "message": "OTP Successfully Sent" });
                    }
                    else {
                      res.status(500).json({ "message": "OTP sent Failed" })
                      Contact.remove({ "phone": req.body.phone }).then(function (err) {
                        if (err) {
                          // res.send(err);
                          // return err;
                        }
                      });
                    }

                  })
                }

              })
            }
          })


        }



        else if (req.body.email) {

          var randomemail = Math.floor((Math.random() * 100000000000000) + 54);
          Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) {
            if (err) {
              console.error(err);
            }
            else if (em) {
              res.status(500).json({ "message": "Email ID already Exists" })
            }
            else {

              Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {

                if (req.body.dealer == true) {
                  Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                    //console.log("8");
                    var newUserJson = {
                      first_name: req.body.first_name,
                      last_name: req.body.last_name,
                      org_name: req.body.org_name,
                      org: organisation._id,
                      email: req.body.email.toLowerCase(),
                      email_verfi: false,
                      phone_verfi: false,
                      status: req.body.status,
                      id_email_ver: randomemail,
                      isDealer: req.body.dealer,
                      dealerid: 'd_' + counter.seq,
                      custumerid: 'c_' + count.seq,
                      phone: 'noNumber' + count.seq,
                      purpose: "zogo",
                      timezone: req.body.timezone
                    };



                    var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                    newUser.setPassword(req.body.password);
                    newUser.setLastReportDate();

                    newUser.save(function (err) {
                      if (err) {
                        res.status(500).json({ "message": "Something Is Wrong" } + err);
                      }
                      res.status(200).json({ "message": "Registered Sucessfully" });
                    })
                    email(req.body.first_name, req.body.email, randomemail);
                  })

                }
                else {
                  //console.log("9");
                  var newUserJson = {
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    org_name: req.body.org_name,
                    email: req.body.email.toLowerCase(),
                    email_verfi: false,
                    status: req.body.status,
                    phone_verfi: false,
                    id_email_ver: randomemail,
                    isDealer: req.body.dealer,
                    custumerid: 'c_' + count.seq,
                    phone: 'noNumber' + count.seq,
                    purpose: "zogo",
                    timezone: req.body.timezone
                  };

                  var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                  newUser.setPassword(req.body.password);
                  newUser.setLastReportDate();

                  newUser.save(function (err) {
                    if (err) {
                      res.status(500).json({ "message": "Something Is Wrong" } + err);
                    }
                    res.status(200).json({ "message": "Registered Sucessfully" });
                  })
                  email(req.body.first_name, req.body.email, randomemail);
                }
              })


            }
          })


        }
        else {
          res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" });
        }

      }
      else {
        res.status(400).send({ "message": "Server error" })
      }

    })
  }
  else {
    if (req.body.email == null && req.body.phone == null || req.body.email == undefined && req.body.phone == undefined || req.body.email == "undefined" && req.body.phone == "undefined") {
      return res.status(401).json({ "message": "Null Value Error" });
    }
    //superadmin can able to add dealer

    else if (req.body.sysadmin == true) {
      Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, cuscount) {
        if (error) {
          console.error(error);
        }
        Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (err, dealcount) {
          if (err) {
            console.error(err);
          }
          if (req.body.email && req.body.phone) {
            //console.log("10");
            var newUserJson = {
              first_name: req.body.first_name,
              last_name: req.body.last_name,
              org_name: req.body.org_name,
              org: req.body.org_id,
              role: req.body.roles,
              group: req.body.group,
              status: req.body.status,
              email: req.body.email.toLowerCase(),
              phone: req.body.phone,
              email_verfi: true,
              phone_verfi: true,
              isDealer: true,
              isSuperAdmin: false,
              Dealer: req.body.Dealer,
              supAdmin: req.body.supAdmin,
              custumerid: 'c_' + cuscount.seq,
              dealerid: 'd_' + dealcount.seq,
              timezone: req.body.timezone,
              user_id: req.body.user_id,
              address: req.body.address,
              purpose: "zogo",
              expire_date: new Date(req.body.expdate)
              //   phone:'noNumber'+ counter.seq
            };
            var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
            newUser.setPassword(req.body.password);
            newUser.setLastReportDate();

            // var newUser = new Contact(newUserJson);
            newUser.save(function (err) {
              if (err) {
                res.status(500).json({ "message": "Something Is Wrong" } + err);
              }
              res.status(200).json({ "message": "Registered Sucessfully" });
            })
          }
        });
      });
    }
    else if (req.body.custumer == true) {

      Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, counter) {

        if (error) {
          console.error(error);
        }
        if (req.body.email && req.body.phone) {
          //console.log("11");
          var newUserJson = {
            first_name: req.body.first_name,
            last_name: req.body.last_name,
            org_name: req.body.org_name,
            org: req.body.org_id,
            email: req.body.email.toLowerCase(),
            phone: req.body.phone,
            email_verfi: true,
            phone_verfi: true,
            isDealer: false,
            Dealer: req.body.Dealer,
            custumerid: 'c_' + counter.seq,
            timezone: req.body.timezone,
            user_id: req.body.user_id,
            status: req.body.status,
            address: req.body.address,
            purpose: "zogo",
            expire_date: new Date(req.body.expdate)
            //   phone:'noNumber'+ counter.seq

          };
          var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
          newUser.setPassword(req.body.password);
          newUser.setLastReportDate();

          // var newUser = new Contact(newUserJson);

          newUser.save(function (err, u) {
            if (err) {
              res.status(500).json({ "message": "Something Is Wrong" } + err);
              return;
            }
            res.status(200).json({ "message": "Registered Sucessfully" });


          })
        }
        else if (req.body.email) {
          //console.log("12");
          var newUserJson = {
            first_name: req.body.first_name,
            last_name: req.body.last_name,
            org_name: req.body.org_name,
            org: req.body.org_id,
            email: req.body.email.toLowerCase(),
            phone: "nophone" + counter.seq,
            email_verfi: true,
            phone_verfi: true,
            status: req.body.status,
            isDealer: false,
            Dealer: req.body.Dealer,
            custumerid: 'c_' + counter.seq,
            purpose: "zogo",
            timezone: req.body.timezone,
            user_id: req.body.user_id,
            address: req.body.address,
            expire_date: new Date(req.body.expdate)
            //   phone:'noNumber'+ counter.seq

          };
          var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
          newUser.setPassword(req.body.password);
          newUser.setLastReportDate();

          // var newUser = new Contact(newUserJson);

          newUser.save(function (err) {
            if (err) {
              res.status(500).json({ "message": "Something Is Wrong" } + err);
            }
            res.status(200).json({ "message": "Registered Sucessfully" });
          })
        }
        else if (req.body.phone) {
          //console.log("13");
          var newUserJson = {
            first_name: req.body.first_name,
            last_name: req.body.last_name,
            org_name: req.body.org_name,
            org: req.body.org_id,
            phone: req.body.phone,
            email_verfi: true,
            phone_verfi: true,
            status: req.body.status,
            isDealer: false,
            Dealer: req.body.Dealer,
            email: 'noEmail' + counter.seq,
            purpose: "zogo",
            custumerid: 'c_' + counter.seq,

            timezone: req.body.timezone,
            user_id: req.body.user_id,
            address: req.body.address,
            expire_date: new Date(req.body.expdate)
            //  email:'noEmail'+ counter.seq

          };
          var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
          newUser.setPassword(req.body.password);
          newUser.setLastReportDate();
          // var newUser = new Contact(newUserJson);

          newUser.save(function (err) {
            if (err) {
              res.status(500).json({ "message": "Something Is Wrong" } + err);
            }
            res.status(200).json({ "message": "Registered Sucessfully" });
          })
        }
        else {
          //console.log("14");
          var newUserJson = {
            first_name: req.body.first_name,
            last_name: req.body.last_name,
            org_name: req.body.org_name,
            org: req.body.org_id,
            phone: req.body.phone,
            email: req.body.email.toLowerCase(),
            email_verfi: true,
            phone_verfi: true,
            isDealer: false,
            Dealer: req.body.Dealer,
            custumerid: 'c_' + counter.seq,
            timezone: req.body.timezone,
            user_id: req.body.user_id,
            address: req.body.address,
            purpose: "zogo",
            status: req.body.status,
            expire_date: new Date(req.body.expdate)
          };
          var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
          newUser.setPassword(req.body.password);
          newUser.setLastReportDate();
          // var newUser = new Contact(newUserJson);

          newUser.save(function (err) {
            if (err) {
              res.status(500).json({ "message": "Something Is Wrong" } + err);
            }
            res.status(200).json({ "message": "Registered Sucessfully" });
          })
        }


      })

    }
    else if (req.body.otp && req.body.phone) {
      var token;
      Contact.findOne({ "phone": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) {
        if (err) {
          console.error(err);
          return err;
        }
        if (otpres) {
          //
          var dbtime = new Date(otpres.timestamp);
          var curtime = new Date();
          var diffMs = (curtime - dbtime); // milliseconds between now & Christmas
          var diffDays = Math.floor(diffMs / 86400000); // days
          var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
          var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
          if (otpres.otp == req.body.otp) {
            Contact.update({ _id: otpres._id }, { $set: { phone_verfi: true } }, function (err, result) {
              if (err) {
                console.error(err)
                return res.status(400).send(err);
              }
              else {
                // otpres.email
                //console.log(otpres.email);
                var mailOptions = {
                  from: Utilities.getConfig().mailUserZogo, // sender address
                  to: otpres.email, // gaurav.gupta@adnate.in list of receivers
                  subject: 'Zogorides', // Subject line
                  //  text: "New Task",
                  html: `<body><div style="margin:0;padding:0;background-color:#ffffff;font-family:Roboto,RobotoDraft,Helvetica,Arial,sans-serif"> <div style="padding:0;width:100%;margin:0;min-width:100%;color:#000;font-weight:normal;text-align:left;line-height:28px;font-size:14px"> <table style="border-spacing:0;border:0;padding:0;vertical-align:top;border-collapse:collapse;text-align:center;background-color:#ececec;height:100%;padding-top:0;font-size:14px;line-height:28px;color:#000;width:100%"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="font-size:14px;color:#000;padding:0;margin:0;text-align:left;line-height:28px;font-weight:normal;word-break:break-word;border-collapse:collapse;vertical-align:top"> <br> <table style="border-spacing:0;border-collapse:collapse;border:0;padding:0;vertical-align:top;text-align:center;width:600px;margin:0 auto;background-color:#ffffff"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="font-size:14px;color:#000;padding:0;margin:0;text-align:left;line-height:28px;font-weight:normal;word-break:break-word;border-collapse:collapse;vertical-align:top"> <table style="border-spacing:0;border-collapse:collapse;border:0;padding:0;vertical-align:top;text-align:left;width:100%;background:#f2f8f3"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td width="100%" style="word-break:break-word;color:#000;padding:0;margin:0;border-collapse:collapse;line-height:28px;font-size:14px;font-weight:normal;text-align:left;vertical-align:middle;height:70px;padding-left:20px"> <a href="https://www.zogorides.com/" style="outline:none;color:#0067ff;text-decoration:none;display:inline;width:100%;height:100%" target="_blank"> <img src="https://i.imgur.com/LmwlUHP.png" style="outline:none;text-decoration:none;width:auto;max-width:100%;clear:both;border:none;display:inline;vertical-align:middle;float:none"> </a> </td> </tr> </tbody> </table> <table style="border-spacing:0;border-collapse:collapse;border:0;padding:0;vertical-align:top;text-align:left;width:100%"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="color:#000;border-collapse:collapse;margin:0;text-align:left;font-size:14px;font-weight:normal;line-height:25px;padding:10px 10px 5px;vertical-align:top;width:100%"> <img src="https://i.imgur.com/skoAwvg.jpg" style="outline:none;text-decoration:none;width:auto;max-width:100%;clear:both;border:none;display:inline;vertical-align:middle;float:none"> </td> </tr> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="word-break:break-word;color:#000;border-collapse:collapse;margin:0;text-align:left;font-size:14px;font-weight:normal;line-height:25px;padding:10px 10px 5px;vertical-align:top;width:100%"> <div style="padding:0"> <table style="border-spacing:0;border-collapse:collapse;border:0;padding:0;vertical-align:top;text-align:left;width:100%"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="font-size:14px;color:#000;border-collapse:collapse;margin:0;text-align:left;line-height:28px;font-weight:normal;word-break:break-word;vertical-align:top;padding:0 6%"> <p style="color:#000;padding:0;margin:0;text-align:left;line-height:28px;font-weight:bold;font-size:18px;margin-bottom:20px;margin-top:20px">` + "Hi " + otpres.first_name + `<br> </p> <p style="color:#000;font-weight:normal;padding:0;margin:0;text-align:left;line-height:28px;font-size:14px;margin-bottom:20px"><b>Thanks for joining <span>Zogorides</span>.</b></p> <p style="color:#000;font-weight:normal;padding:0;margin:0;text-align:left;line-height:28px;font-size:14px;margin-bottom:20px">Now that you have signed up, book and enjoy your ride. </p> <div style="width:auto;height:auto;margin:0 auto;margin-bottom:20px;background:#fefefe;border:#f2f2f2 1px solid;border-top:#42c662 3px solid"> <div> </div> </div> <p style="color:#000;font-weight:normal;padding:0;margin:0;text-align:left;line-height:28px;font-size:14px;margin-bottom:20px"> Thanks! <br><span>Zogorides</span> Team </p> <hr style="color:#d9d9d9;background-color:#d9d9d9;height:1px;border:none"> </td> </tr> </tbody> </table> </div> </td> </tr> </tbody> </table> <table style="border-spacing:0;border-collapse:collapse;border:0;padding:0;vertical-align:top;text-align:left;width:100%;margin-bottom:30px"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="font-size:14px;color:#000;border-collapse:collapse;margin:0;line-height:28px;font-weight:normal;word-break:break-word;text-align:right;padding:0 15px 12px;vertical-align:middle"> <table style="border-spacing:0;border-collapse:collapse;border:0;padding:0;vertical-align:top;text-align:left;width:100%"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="word-break:break-word;color:#000;padding:0;margin:0;text-align:left;border-collapse:collapse;font-size:14px;font-weight:normal;line-height:16px;vertical-align:middle;height:16px"> <p style="font-weight:normal;padding:0;text-align:left;color:#9b9b9b;margin:10px 2% 10px 0;line-height:14px;font-size:12px"> Â© 2019 Zogorides. <span style="float:right">Join the conversation</span> </p> </td> <td width="4%" style="word-break:break-word;color:#000;padding:0;margin:0;text-align:left;border-collapse:collapse;font-size:14px;font-weight:normal;line-height:16px;vertical-align:middle;height:16px"> <a href="#0.1_" title="facebook" style="outline:none;color:#0067ff"> <img src="https://i.imgur.com/UahBzgC.png" style="outline:none;text-decoration:none;width:auto;max-width:100%;clear:both;border:none;display:inline"> </a> </td> <td width="4%" style="word-break:break-word;color:#000;padding:0;margin:0;text-align:left;border-collapse:collapse;font-size:14px;font-weight:normal;line-height:16px;vertical-align:middle;height:16px"> <a href="#0.1_" title="twitter" style="outline:none;color:#0067ff"> <img src="https://i.imgur.com/1FivtOW.png" style="outline:none;text-decoration:none;width:auto;max-width:100%;clear:both;border:none;display:inline"> </a> </td> </tr> </tbody> </table> </td> </tr> <tr style="padding:0;vertical-align:top;text-align:left"> <td style="word-break:break-word;color:#000;border-collapse:collapse;margin:0;text-align:left;font-size:14px;font-weight:normal;line-height:16px;padding:0 15px 0;vertical-align:middle;height:16px"> <p style="font-weight:normal;padding:0;text-align:left;color:#9b9b9b;margin:10px 2% 10px 0;line-height:14px;font-size:12px"> Please do not reply directly to this email. </p> <p style="font-weight:normal;padding:0;text-align:left;color:#9b9b9b;margin:10px 2% 10px 0;line-height:14px;font-size:12px">You can get help from our <a href="https://www.zogorides.com/#faq" style="outline:none;color:#42c662;font-style:italic" target="_blank">knowledge base</a>. </p> <p style="font-weight:normal;padding:0;text-align:left;color:#9b9b9b;margin:10px 2% 10px 0;line-height:14px;font-size:12px"> If you don't want to receive emails like this again, please <a href="#0.1_" style="outline:none;color:#42c662;font-style:italic">click here</a>to unsubscribe.</p><br> <p style="text-align:center;font-size:12px;color:#9b9b9b"> Plot No â?&#147; 23 Sector-18 Gurgaon,Haryana 122002 <br> <a href="mailto:info@zogorides.com" target="_blank">info@zogorides.com</a> , <a href="mailto:support@zogorides.com" target="_blank">support@zogorides.com</a> <br> <a style="text-align:center;font-size:12px;color:#9b9b9b" href="https://www.zogorides.com/" target="_blank">www.zogorides.com</a> </p> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table><div></div><div> </div></div> </div></body>`
                }
                mailer.sendZogoSignupMail(mailOptions);
                return res.status(200).json({ "message": "Mobile Verified" });
              }
            });
          }
          else {
            res.status(500).json({ "message": "Didn't match otp" });
          }
        }
      })
    }
    else if (req.body.phone && req.body.email) {
      //console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
      Contact.findOne({ $or: [{ 'email': req.body.email }, { 'phone': req.body.phone }] }, function (err, user) {
        if (err) {
          console.error(err)
        }
        else if (user) {
          res.status(200).json({ "message": "Email ID or Mobile Number already exists" })
        }
        else {
          function randomString(length, chars) {
            var mask = '';
            if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
            if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            if (chars.indexOf('#') > -1) mask += '0123456789';
            if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
            var result = '';
            for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
            return result;
          }
          var otprand = randomString(4, '#');
          var randomemail = randomString(16, '#aA!');

          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
            if (req.body.dealer == true) {

              Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                // console.log("15");
                var newUserJson = {

                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  email: req.body.email.toLowerCase(),
                  phone: req.body.phone,
                  email_verfi: false,
                  phone_verfi: false,
                  otp: otprand,
                  status: req.body.status,
                  id_email_ver: randomemail,
                  isDealer: req.body.dealer,
                  dealerid: 'd_' + counter.seq,
                  custumerid: 'c_' + count.seq,
                  purpose: "zogo",
                  timezone: req.body.timezone
                };
                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();
                newUser.save(function (err, u) {
                  if (err) {
                    if (err.name === 'MongoError' && err.code === 11000) {
                      // Duplicate username
                      return res.status(200).send({ succes: false, message: 'User already exist!' });
                    }

                    // Some other error
                    return res.status(500).send(err);
                  }
                  if (u) {
                    //console.log("in uuuuu");
                    var newCode = {
                      "code": "FirstFree",
                      "isPercent": false,
                      "amount": "50",
                      "expireDate": new Date(req.body.expdate),
                      "isActive": true,
                      "countMax": "1",
                      "onOrder": [
                        "1"
                      ],
                      "maxDiscount": "50",
                      "minOrderAmount": "",
                      "type": "ONETIME"
                    }
                    newCode.user = u[0]._id
                    couponCode.addDiscountCodeOnSignup(newCode);
                    res.status(200).json({ "message": "OTP sent successfully" });
                    // request({


                    //   uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand,
                    //   method: "GET"
                    // }, function (error, response, body) {
                    //   /* var jsonObj = JSON.parse(response.body);
                    //   if(jsonObj.MsgStatus == 'Sent'){
                    //     email(req.body.first_name,req.body.email,randomemail);
                    //     res.status(200).json({"message" : "OTP sent successfully"})

                    //   }
                    //   else{
                    //     res.status(500).json({"message" : "OTP sent Failed"})
                    //     Contact.remove({"phone" :req.body.phone}).then(function(err){
                    //       if(err){
                    //         res.send(err);
                    //         return err;
                    //       }
                    //     });
                    //   } */
                    //   res.status(200).json({ "message": "OTP sent successfully" });

                    // });
                  }
                })

              })

            }
            else {
              // console.log("16");
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                email: req.body.email.toLowerCase(),
                phone: req.body.phone,
                email_verfi: false,
                phone_verfi: false,
                otp: otprand,
                id_email_ver: randomemail,
                isDealer: req.body.dealer,
                status: req.body.status,
                custumerid: 'c_' + count.seq,
                timezone: req.body.timezone,
                purpose: "zogo",
              };
              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();
              newUser.save(function (err, u) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }


                //console.log("in uuuuu", u);
                var newCode = {
                  "code": "FirstFree",
                  "isPercent": false,
                  "amount": "50",
                  "expireDate": new Date(req.body.expdate),
                  "isActive": true,
                  "countMax": "1",
                  "onOrder": [
                    "1"
                  ],
                  "maxDiscount": "50",
                  "minOrderAmount": "",
                  "type": "ONETIME"
                }
                newCode.user = u._id
                couponCode.addDiscountCodeOnSignup(newCode);
                email(req.body.first_name, req.body.email, randomemail);
                request({


                  uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.phone + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + otprand,
                  method: "GET"
                }, function (error, response, body) {
                  /* var jsonObj = JSON.parse(response.body);
                  if(jsonObj.MsgStatus == 'Sent'){
                    email(req.body.first_name,req.body.email,randomemail);
                    res.status(200).json({"message" : "OTP sent successfully"})
                    
                  }
                  else{
                    res.status(500).json({"message" : "OTP sent Failed"})
                    Contact.remove({"phone" :req.body.phone}).then(function(err){
                      if(err){
                        res.send(err);
                        return err;
                      }
                    });
                  } */

                  // res.status(200).json({ "message": "OTP sent successfully" });
                  res.status(200).json({ "message": "OTP sent successfully" })
                });

              })

            }



          })



        }
      })

    }


    else if (req.body.phone) {
      Contact.findOne({ "phone": req.body.phone }, function (err, ph) {
        if (err) {
          console.error(err);
        }
        else if (ph) {
          res.status(500).json({ "message": "Mobile Number already Exists" })
        }
        else {
          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
            if (req.body.dealer == true) {
              Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                //console.log("17");
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  phone: req.body.phone,
                  password: req.body.password,
                  isDealer: req.body.dealer,
                  dealerid: 'd_' + counter.seq,
                  custumerid: 'c_' + count.seq,
                  email: 'noEmail' + count.seq,
                  status: req.body.status,
                  purpose: "zogo",
                  timezone: req.body.timezone

                };
                let datastore = newUserJson;
                //  let a = otp(newUserJson);
                otp(newUserJson, function (final_data) {

                  if (final_data == true) {
                    res.status(200).json({ "message": "OTP Successfully Sent" });
                  }
                  else {
                    res.status(500).json({ "message": "OTP sent Failed" })
                    Contact.remove({ "phone": req.body.phone }).then(function (err) {
                      if (err) {
                        // res.send(err);
                        //  return err;
                      }
                    });

                  }

                })

              })


            }
            else {
              console.log("18");
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                phone: req.body.phone,
                password: req.body.password,
                isDealer: req.body.dealer,
                custumerid: 'c_' + count.seq,
                email: 'noEmail' + count.seq,
                status: req.body.status,
                purpose: "zogo",
                timezone: req.body.timezone

              };
              // otp(newUserJson);
              //  let a = otp(newUserJson);
              otp(newUserJson, function (final_data) {

                if (final_data == true) {
                  res.status(200).json({ "message": "OTP Successfully Sent" });
                }
                else {
                  res.status(500).json({ "message": "OTP sent Failed" })
                  Contact.remove({ "phone": req.body.phone }).then(function (err) {
                    if (err) {
                      // res.send(err);
                      // return err;
                    }
                  });
                }

              })
            }

          })
        }
      })


    }



    else if (req.body.email) {

      var randomemail = Math.floor((Math.random() * 100000000000000) + 54);
      Contact.findOne({ "email": req.body.email.toLowerCase() }, function (err, em) {
        if (err) {
          console.error(err);
        }
        else if (em) {
          res.status(500).json({ "message": "Email ID already Exists" })
        }
        else {
          Count.findByIdAndUpdate({ _id: 'custumer' }, { $inc: { seq: 1 } }, function (error, count) {
            if (req.body.dealer == true) {
              Count.findByIdAndUpdate({ _id: 'dealer' }, { $inc: { seq: 1 } }, function (error, counter) {
                console.log("19");
                var newUserJson = {
                  first_name: req.body.first_name,
                  last_name: req.body.last_name,
                  org_name: req.body.org_name,
                  org: req.body.org_id,
                  email: req.body.email.toLowerCase(),
                  email_verfi: false,
                  phone_verfi: false,
                  id_email_ver: randomemail,
                  isDealer: req.body.dealer,
                  dealerid: 'd_' + counter.seq,
                  custumerid: 'c_' + count.seq,
                  phone: 'noNumber' + count.seq,
                  status: req.body.status,
                  purpose: "zogo",
                  timezone: req.body.timezone
                };

                var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
                newUser.setPassword(req.body.password);
                newUser.setLastReportDate();

                newUser.save(function (err) {
                  if (err) {
                    res.status(500).json({ "message": "Something Is Wrong" } + err);
                  }
                  res.status(200).json({ "message": "Registered Sucessfully" });
                })
                email(req.body.first_name, req.body.email, randomemail);
              })

            }
            else {
              console.log("20");
              var newUserJson = {
                first_name: req.body.first_name,
                last_name: req.body.last_name,
                org_name: req.body.org_name,
                org: req.body.org_id,
                email: req.body.email.toLowerCase(),
                email_verfi: false,
                phone_verfi: false,
                id_email_ver: randomemail,
                isDealer: req.body.dealer,
                status: req.body.status,
                custumerid: 'c_' + count.seq,
                phone: 'noNumber' + count.seq,
                purpose: "zogo",
                timezone: req.body.timezone
              };

              var newUser = new Contact(JSON.parse(JSON.stringify(newUserJson)));
              newUser.setPassword(req.body.password);
              newUser.setLastReportDate();

              newUser.save(function (err) {
                if (err) {
                  res.status(500).json({ "message": "Something Is Wrong" } + err);
                }
                res.status(200).json({ "message": "Registered Sucessfully" });
              })
              email(req.body.first_name, req.body.email, randomemail);
            }
          })


        }
      })


    }
    else {
      res.status(500).json({ "message": "Something Is Missing Email id or Phone Number" });
    }

  }
}
// ==================================
function email(fname, emailid, verid) {

  var url = "http://" + Utilities.getConfig().webAppIp + ":" + Utilities.getConfig().EPort + "/users/emailverfi?id=" + encodeURIComponent(verid);

  var mailOptions = {
    from: Utilities.getConfig().mailUser, // sender address
    to: emailid.toLowerCase(), // list of receivers
    subject: Utilities.getConfig().orgName + "- Mail Verification", // Subject line
    text: "New Task", // plaintext body emailverfi
    html: 'Dear ' + fname + ',<br><br>Thank you for registering with us.<br>You are just one click away from using our services.Please verify your mail by clicking below button.<br><center><a href="' + url + '"><br><input type="button"  value="Click here to Verify Email" style="font-size:12pt;color:white;background-color:DodgerBlue  ;padding:11px" ></a></center><br>Thanks<br>Regards<br>Team AdnateIOT'// html body
  }
  mailer.sendMail(mailOptions);


}

module.exports.zogoUserUpdate = function (req, res) {
  if (req.body.phone) {
    Contact.findOne({ "phone": req.body.phone }, function (err, user) {
      if (err) {
        console.error(err);
      }
      if (user) {
        if (req.body.img_type == "adharCard") {
          user.aadharImg = req.body.image_path;
        }
        if (req.body.img_type == "drivingLicence") {
          user.dl_path = req.body.image_path;
        }
        if (req.body.img_type == "selfie") {
          user.userImg = req.body.image_path;
        }
        user.save(function (err) {
          if (err) {
            console.error("otp error :" + err);
            return err;
          }
          else {
            res.status(200).send({ "message": "image saved successfully" })
          }
        })
      }
      else {
        res.status(200).send({ "message": "user not found" })
      }
    })

  }

}



function otp(data, recur) {

  function randomString(length, chars) {
    var mask = '';
    if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
    if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (chars.indexOf('#') > -1) mask += '0123456789';
    if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
    var result = '';
    for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
    return result;
  }
  var randomotp = randomString(4, '#');
  if (data.dealerid) {
    var newOtpJson = {
      first_name: data.first_name,
      last_name: "",
      org_name: data.org_name,
      phone: data.phone,
      otp: randomotp,
      email_verfi: false,
      phone_verfi: false,
      isDealer: data.isDealer,
      dealerid: data.dealerid,
      custumerid: data.custumerid,
      email: 'noEmail' + data.custumerid,
      purpose: "zogo",
      status: false,
      timezone: req.body.timezone


    };
    var newOtp = new Contact(JSON.parse(JSON.stringify(newOtpJson)));
    newOtp.setPassword(data.password);
    newOtp.setLastReportDate();


    newOtp.save(function (err) {
      if (err) {
        console.error("otp error :" + err);
        return err;
      }

      request({


        uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + data.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp,
        method: "GET"
      }, function (error, response, body) {
        /* var jsonObj = JSON.parse(response.body);
        if(jsonObj.MsgStatus == 'Sent'){
          // email(req.body.first_name,req.body.email,randomemail);
          //  res.status(200).json({"message" : "OTP sent successfully"})
          
          recur(true);  
        }
        else{
          //   res.status(500).json({"message" : "OTP sent Failed"})
          recur(false); 
        } */
        recur(true);
      });

    });
  }
  else {
    var newOtpJson = {
      first_name: data.first_name,
      last_name: "",
      org_name: data.org_name,
      phone: data.phone,
      otp: randomotp,
      email_verfi: false,
      phone_verfi: false,
      isDealer: data.isDealer,
      custumerid: data.custumerid,
      email: 'noEmail' + data.custumerid,
      purpose: "zogo",
      status: false
      //  timezone: req.body.timezone

    };
    var newOtp = new Contact(JSON.parse(JSON.stringify(newOtpJson)));

    newOtp.setPassword(data.password);
    newOtp.setLastReportDate();

    // var newUser = new Contact(newUserJson);


    newOtp.save(function (err) {
      if (err) {
        console.error("otp error :" + err);
        return err;
      }

      request({


        uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + data.phone + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp,
        method: "GET"
      }, function (error, response, body) {
        /* var jsonObj = JSON.parse(response.body);
        if(jsonObj.MsgStatus == 'Sent'){
          //   email(data.first_name,data.email,randomemail);
          // res.status(200).json({"message" : "OTP sent successfully"})
          recur(true); 
        }
        else{
          //  res.status(500).json({"message" : "OTP sent Failed"})
          recur(false); 
        } */
        recur(true);
      });

    });
  }

}

module.exports.find = function (req, res) {
  req.body = evaluate(req.body);
  var qr = Contact.find(req.body._find);
  if (req.body._limit)
    qr.limit(req.body._limit);
  if (req.body._sort)
    qr.sort(req.body._sort);
  if (req.body._select)
    qr.select(req.body._select);
  if (req.body.school)
    qr.populate({ 'path': 'school', select: req.body.school })

  qr.exec(function (err, data) {
    if (err) return res.send(err);
    else
      res.send(data);
  })
}

module.exports.emailverfi = function (req, res) {

  Contact.findOne({ "id_email_ver": (req.query.id) }).exec(function (err, sd) {

    if (err) {
      return res.status(401).send("Error ::" + err)
      console.error(err);
    }
    else if (sd) {

      Contact.update({ _id: sd._id }, { $set: { email_verfi: true } }, function (err, result) {
        if (err) {
          console.error(err)
          return res.status(400).send(err);
        }
        else {

          return res.redirect(Utilities.getConfig().webAppDomain + '/login');

        }
      });


    }
    else {
      return res.status(401).send("Error ::" + err)
      console.error(err);
    }
  })
}

// module.exports.getAllUsersForSuperUser = function(req, res) {
//   Contact.findOne({_id : req.body.user, isSuperUser : true}, function(err, superUser){
//     if(err){
//       console.error(err);
//       res.send(500);
//       return;
//     }
//     else if(superUser){
//       Contact.find({isDealer : true},function(err, contacts){
//         if(err){
//           console.error(err);
//       res.send(500);
//       return;
//         }
//         res.status(200).send(contacts);

//       });
//     }
//   })

// }

//retreve data (signup/login)
module.exports.getAllUsers = function (req, res) {
  var id = "";
  if (req.query.dealer) {
    id = req.query.dealer
  } else if (req.query.user) {
    id = req.query.user
  }

  Contact.findOne({ _id: id }, function (err, dealer) {
    if (err) {
      console.error(err);
      res.send(500);
      return;
    }
    if (dealer) {
      var query = {};
      if (req.query.dealer) {
        query = { $or: [{ 'Dealer': req.query.dealer }, { group: { $in: dealer.group } }] }
      }
      if (req.query.user) {
        query = { $or: [{ $and: [{ 'Dealer': dealer.Dealer }, { '_id': { $nin: [req.query.user] } }] }, { '_id': dealer.Dealer }] }
      }
      Contact.find(query, function (err, contacts) {
        if (err) {
          console.error(err);
          return err;
        }
        if (contacts.length > 0) {
          res.status(200).send(contacts);
        }
        else {
          res.status(500).send("No records found");
        }
      });
    }

    else {
      res.send(400);
    }
  })

}
module.exports.datatable = function (req, res) {

  var qr = req.body;
  var dtop = {
    conditions: qr.find,
    select: qr.select
  };
  Contact.dataTable(qr, dtop, function (err, data) {
    if (err) {
      console.error(err);
      res.sendStatus(500);
      return;
    }
    res.send(data);
  })
}

module.exports.getAll = function (req, res) {
  Contact.find({ supAdmin: req.query.supadm }, function (err, contacts) {
    if (err) {
      console.error(err);
      return err;
    }
    if (contacts.length > 0) {
      res.status(200).send(contacts);
    }
    else {
      res.status(500).send("No records found");
    }
  });

}

//delete Data (NOT USED)
module.exports.DeleteUser = function (req, res) {
  Contact.remove({ _id: req.query.id }, function (err, del) {
    if (err) {
      console.error(err);
      return err;
    }
    res.status(200).json({ "message": "Deleted Successfully" })

  })
}

//saving phonenum with otp
module.exports.SendOtp = function (req, res) {
  function randomString(length, chars) {
    var mask = '';
    if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
    if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (chars.indexOf('#') > -1) mask += '0123456789';
    if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
    var result = '';
    for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
    return result;
  }
  var randomotp = randomString(6, '#');
  /* var randomotp=Math.floor((Math.random() * 100000) + 54); */
  var newOtpJson = {
    phone_number: req.body.ph_num,
    otp: randomotp
  };

  var newOtp = new Otp(JSON.parse(JSON.stringify(newOtpJson)));
  newOtp.save(function (err) {
    if (err) {
      console.error("otp error :" + err);
      return err;
    }
    //
    request({
      uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + req.body.ph_num + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp,
      method: "GET"
    }, function (error, response, body) {
      /* var jsonObj = JSON.parse(response.body);
      if(jsonObj.MsgStatus == 'Sent'){
        email(req.body.first_name,req.body.email,randomemail);
        res.status(200).json({"message" : "OTP sent successfully"})
        
      } */
      res.status(200).json({ "message": "OTP sent successfully" })
    });

  });
}


module.exports.SendOtpZOGO = function (req, res) {
  function randomString(length, chars) {
    var mask = '';
    if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
    if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (chars.indexOf('#') > -1) mask += '0123456789';
    if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
    var result = '';
    for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
    return result;
  }
  var randomotp = randomString(4, '#');
  /* var randomotp=Math.floor((Math.random() * 100000) + 54); */
  var newOtpJson = {
    phone_number: req.body.ph_num,
    otp: randomotp
  };

  var newOtp = new Otp(JSON.parse(JSON.stringify(newOtpJson)));
  newOtp.save(function (err) {
    if (err) {
      console.error("otp error :" + err);
      return err;
    }
    //req.body.ph_num
    Contact.findOne({ phone: req.body.ph_num }, function (err, mobileNum) {
      if (err) {
        res.status(500).json({ "Error": "Device Not Found" })
      }
      //console.log("Mobile Number", mobileNum);
      //console.log("randonOTP", randomotp);
      mobileNum.otp = randomotp;

      mobileNum.save(function (err) {
        if (err) {
          res.status(500).json({ "errMsg": "OTP not Updated" })
        } else {
          // console.log("updatedInfo=>", mobileNum);
          request({
            uri: Utilities.getConfig().smsUrl_zogo + Utilities.getConfig().smsApiMobileKeyzogo + req.body.ph_num + Utilities.getConfig().smsApiTextKeyzogo + 'Zogo%20Rides%20Your%20OTP%20is ' + randomotp,
            method: "GET"
          }, function (error, response, body) {
            res.status(200).json({ "message": "OTP sent successfully" })
          });
        }
      })
    })
  });
}


//checking otp with phonenumber

//saving phonenum with otp
//LOGIN
module.exports.LoginWithOtp = function (req, res) {
  var loginType = '';
  // console.log("header",JSON.stringify(req.headers));
  var user_agent = req.headers["user-agent"];
  //console.log("UUUUUUUUUUUUUUUUUUUUUUUU",user_agent);
  if (user_agent.includes("Android ") || user_agent.includes("iPhone") || user_agent.includes("blackberry")) {
    loginType = "MOBILE"
  }
  else if (user_agent.includes("Mozilla") || user_agent.includes("AppleWebKit") || user_agent.includes("Chrome") || user_agent.includes("Safari")) {
    loginType = "WEB";
  } else {
    loginType = "MOBILE"
  }
  var token;
  if (req.body.emailid) {

    Contact.findOne({ "email": req.body.emailid.toLowerCase() }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) {
      if (err) {
        console.error(err);
        return err;
      }
      if (user) {
        //checking user expiration date
        if (user.DeletedUser == true) {
          res.status(500).json({ "message": "Account Deleted" });
          return;
        }
        if (user.expire_date) {
          if (new Date() > user.expire_date) {
            res.status(500).json({ "message": "User account is expired" });
          }
        }
        //console.log(user);
        //
        //user is active or not
        if ((!user.status) && (user.purpose != 'zogo')) {
          res.status(500).json({ "message": "User account is InActive" });
        }
        //valid or not
        if (user.email_verfi == true) {
          //
          if (user.validPassword(req.body.psd)) {
            Contact.update({ _id: user._id }, { $set: { last_login: new Date, login_type: loginType, "user_agent": user_agent } }, function (err, re) {
              if (err) {
                console.log(err);
                return;
              }
              token = user.generateJwt();
              res.status(200);
              res.json({
                "token": token
              });
            })

          } else {
            res.status(500).json({ "message": "Password is Wrong" });
          }

          //res.status(200).json({"message":"LoggedIn Successfully"});
        }
        else {
          res.status(500).json({ "message": "Email ID Not Verified" });
        }
      }
      else {

        res.status(500).json({ "message": "User is not registered" });

      }
    });

  }
  else if (req.body.ph_num && req.body.psd) {

    Contact.findOne({ $or: [{ "phone": req.body.ph_num }, { "user_id": req.body.ph_num }] }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) {
      if (err) {
        console.error(err);
        return err;
      }
      if (user) {

        if (user.DeletedUser == true) {
          res.status(500).json({ "message": "Account Deleted" });
          return;
        }
        //checking user expiration date
        if (user.expire_date) {
          if (new Date() > user.expire_date) {
            res.status(500).json({ "message": "User account is expired" });
          }
        }
        //
        //user is active or not
        if (!user.phone_verfi) {
          res.status(500).json({ "message": "Mobile Phone Not Verified" });

        }
        if ((!user.status) && (user.purpose != 'zogo')) {
          res.status(500).json({ "message": "User account is InActive" });
        }
        //valid or not
        if (user.phone_verfi == true) {
          //
          if (user.validPassword(req.body.psd)) {
            Contact.update({ _id: user._id }, { $set: { last_login: new Date, login_type: loginType, "user_agent": user_agent } }, function (err, re) {
              if (err) {
                console.log(err);
                return;
              }
              token = user.generateJwt();
              res.status(200);
              res.json({
                "token": token
              });
            })
          } else {
            res.status(500).json({ "message": "Password is Wrong" });
          }

          //res.status(200).json({"message":"LoggedIn Successfully"});
        }
        else {
          res.status(500).json({ "message": "Mobile Phone Not Verified" });
        }
      }
      else {
        res.status(500).json({ "message": "User is not registered" });
      }
    });

  }

  else if (req.body.ph_num && req.body.otp) {

    Contact.findOne({ "phone": req.body.ph_num }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) {
      if (err) {
        console.error(err);
        return err;
      }
      if (user) {
        if (user.phone_verfi = true) {
          Otp.findOne({ "phone_number": req.body.ph_num }).sort({ "timestamp": -1 }).exec(function (err, otpres) {
            if (err) {
              console.error(err);
              return err;
            }
            if (otpres) {
              //
              var dbtime = new Date(otpres.timestamp);
              var curtime = new Date();
              var diffMs = (curtime - dbtime); // milliseconds between now & Christmas
              var diffDays = Math.floor(diffMs / 86400000); // days
              var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
              var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
              if (diffDays == 0 && diffHrs < 1 && diffMins <= 10) {
                if (otpres.otp == req.body.otp) {
                  token = user.generateJwt();
                  res.status(200);
                  res.json({
                    "token": token
                  });
                  //res.status(200).json({"message": "Successfully Logged In"});
                }
                else {
                  res.status(500).json({ "message": "Didn't match otp" });
                }

              }
              else {
                res.status(500).json({ "message": "Otp has been Expired" });
              }
              // 


            }
          })
        }
        else {
          res.status(500).json({ "message": "Mobile Number Not Verified" });
        }
      }
      else {
        res.status(500).json({ "message": "This number is not registered.Please SignUp" })
      }
    })


  }
  //checking userid with password
  else if (req.body.user_id && req.body.psd) {

    var userIDstring = req.body.user_id;
    var user_id_regex = new RegExp(["^", userIDstring, "$"].join(""), "i");

    Contact.findOne({ $or: [{ "user_id": user_id_regex }, { "phone": req.body.user_id }] }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, user) {
      if (err) {
        console.error(err);
        return err;
      }
      if (user) {
        //checking user expiration date
        if (user.DeletedUser == true) {
          res.status(500).json({ "message": "Account Deleted" });
          return;
        }

        if (user.expire_date) {
          if (new Date() > user.expire_date) {
            res.status(500).json({ "message": "User account is expired" });
          }
        }
        //
        //user is active or not
        if ((!user.status) && (user.purpose != 'zogo')) {
          res.status(500).json({ "message": "User account is InActive" });
        }
        if (user.validPassword(req.body.psd)) {
          Contact.update({ _id: user._id }, { $set: { last_login: new Date, login_type: loginType, "user_agent": user_agent } }, function (err, re) {
            if (err) {
              console.log(err);
              return;
            }
            token = user.generateJwt();
            res.status(200);
            res.json({
              "token": token
            });
          })
        } else {
          res.status(500).json({ "message": "Password is Wrong" });
        }
      }
      else {

        res.status(500).json({ "message": "User is not registered" });

      }
    });
  }
}

module.exports.SendOtpp = function (phonenumber) {
  return new Promise(function (resolve, reject) {
    function randomString(length, chars) {
      var mask = '';
      if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
      if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if (chars.indexOf('#') > -1) mask += '0123456789';
      if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
      var result = '';
      for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
      return result;
    }
    var randomotp = randomString(6, '#');
    //var randomotp=Math.floor((Math.random() * 100000) + 54);
    var newOtpJson = {
      phone_number: phonenumber,
      otp: randomotp
    };

    var newOtp = new Otp(JSON.parse(JSON.stringify(newOtpJson)));
    newOtp.save(function (err) {
      if (err) {
        console.error("otp error :" + err);
        return err;
      }
      request({


        uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + phonenumber + Utilities.getConfig().smsApiTextKey + 'Adnate%20IOT%20Your%20OTP%20is ' + randomotp,
        method: "GET"
      }, function (error, response, body) {
        /* var jsonObj = JSON.parse(response.body);
        if(jsonObj.MsgStatus == 'Sent'){
          email(req.body.first_name,req.body.email,randomemail);
          res.status(200).json({"message" : "OTP sent successfully"})
          
        } */
        res.status(200).json({ "message": "OTP sent successfully" })
      });
    });
  });
}
//

//reset password
module.exports.resetPassword = function (req, res) {
  if (req.body.dev == "Mobile") {
    Contact.findOne({ "phone": req.body.phone }, function (err, result) {
      if (err) {
        console.error(err);
        return err;
      }
      if (result) {
        Otp.findOne({ "phone_number": req.body.phone }).sort({ "timestamp": -1 }).exec(function (err, otpres) {
          if (err) {
            console.error(err);
            return err;
          }
          if (otpres) {
            if (otpres.otp == req.body.otp) {
              if (req.body.password) result.setPassword(req.body.password);
              result.save(function (err) {
                if (err) {
                  console.error("inside error :" + err);
                  return;
                }
                res.status(200).send(result._id);
              })
            }
          }
        })
        //
      }
      else {
        res.status(500).json({ "message": "This Number is not registered" });
      }
    })

  }

}

//mlogin send otp 

module.exports.LoginSendOtp = function (req, res) {
  try {
    Contact.findOne({ "phone": req.body.phone }, function (err, result) {
      if (err) {
        console.error(err);
        return;
      }
      if (result) {
        module.exports.SendOtpp(result.phone).then(function (success) {
          res.send(success);
        }, function (err) {
          res.send(err);
        });
      }
      else {
        res.status(500).json({ "message": "This Number is not registered" });
      }
    })
  }
  catch (e) {
    console.error(e);
  }
}
//userFeedback
//User Feedback
module.exports.userFeedback = function (req, res) {

  Contact.findOne({ "_id": req.body.uid }, function (err, validUser) {

    if (err) {
      console.error(err);
      return;
    }
    else if (validUser) {
      Contact.update({ _id: validUser._id }, { $addToSet: { "feedback": req.body.feedback }, $set: { "rating": req.body.rating } }, function (err, result) {
        if (err) {
          console.error(err);
          return;
        }
        else if (result) {



          var mailOptions = {
            from: Utilities.getConfig().mailUser, // sender address
            to: Utilities.getConfig().adminMailId, // gaurav.gupta@adnate.in list of receivers
            subject: Utilities.getConfig().orgName + " - Feedback", // Subject line
            text: "New Task", // plaintext body emailverfi
            html: 'Dear Sir,<br>We have recevied a new feedback from ' + Utilities.getConfig().orgName + ' GPS Tracker Mobile App <br><br> <b>From: </b>' + validUser.first_name + ' ' + validUser.last_name + '<br><b>Contact Details: </b>' + validUser.email + ' /  ' + validUser.phone + '<br> <b>Rating: </b>' + req.body.rating + ' Stars<br> <b>Feedback: </b>' + req.body.feedback + ' <br><br>Thanks<br>Regards<br>Team Adnate'// html body
          }
          mailer.sendMail(mailOptions);


          res.status(200).json({ "message": "Thanks for your feedback" });
        }
        else {
          res.status(500).json({ "message": "Invalid User" });
        }
      });

    }
  })

}

// Push Notificaion

module.exports.PushNotification = function (req, res) {

  Contact.update({ _id: req.body.uid }, {
    $addToSet: {
      "pushNotification": {
        token: req.body.token, "imei": req.body.imei, "os": req.body.os
      }
    }
  }, function (err, result) {
    if (err) {
      console.error(err)
      res.sendStatus(500);
      return;
    }
    res.status(200).json({ "message": "Notifcation Updated" });
  })

}


// Pull Notificaion on logout

module.exports.PullNotification = function (req, res) {

  Contact.update({ _id: req.body.uid }, {
    $pull: {
      "pushNotification": {
        token: req.body.token, "imei": req.body.imei, "os": req.body.os
      }
    }
  }, function (err, result) {
    if (err) {
      console.error(err)
      res.sendStatus(500);
      return;
    }
    res.status(200).json({ "message": "Notifcation Updated" });
  })

}
// Forgot Password

module.exports.forgotpwd = function (req, res) {

  if (req.query.cred == undefined || req.query.cred == null || req.query.cred == "undefined") {
    res.status(500).json({ "message": "Blank Entry" })

  }
  else {

    Contact.findOne({ $or: [{ 'email': req.query.cred }, { 'phone': req.query.cred }] }, function (err, user) {

      if (err) {
        console.error(err);
      }
      else if (user) {
        function randomString(length, chars) {
          var mask = '';
          if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
          if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
          if (chars.indexOf('#') > -1) mask += '0123456789';
          if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
          var result = '';
          for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
          return result;
        }
        var randomotp = randomString(6, '#');
        //  var randomotp=Math.floor((Math.random() * 100000) + 54);

        if (req.query.phone && req.query.otp) {

          Contact.findOne({ $or: [{ 'email': req.query.phone }, { 'phone': req.query.phone }] }, function (err, verify) {
            if (err) {
              console.error(err);
              res.status(500).json(err);
            }
            else if (verify) {
              if (verify.otp == req.query.otp) {

                this.salt = crypto.randomBytes(16).toString('hex');
                this.hash = crypto.pbkdf2Sync(req.query.newpwd, this.salt, 1000, 64, 'sha1').toString('hex');
                var changedPass = req.query.newpwd;

                Contact.update({ _id: verify._id }, { $set: { "hash": this.hash, "salt": this.salt, "pass": changedPass } }, function (err, succ) {
                  if (err) {
                    console.error(err);
                  }
                  res.status(200).json({ "message": "Password Sucessfully Changes" })
                })
              }
              else {
                res.status(500).json({ "message": "Wrong OTP try again" })
              }
            }
          })
        }
        else if (user.phone) {
          Contact.update({ _id: user._id }, { $set: { "otp": randomotp } }, function (err, result) {

            if (err) {
              console.error(err);
              res.status(500).json(err);
              return;
            }
            //  res.status(200).json({"message" : "OTP sent successfully"})

            request({


              uri: Utilities.getConfig().smsUrl + "&sender=OneQlk" + Utilities.getConfig().smsApiMobileKey + user.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20to%20reset%20your%20password ' + randomotp,
              method: "GET"
            }, function (error, response, body) {
              /* var jsonObj = JSON.parse(response.body);
              if(jsonObj.MsgStatus == 'Sent'){
                //  email(req.body.first_name,req.body.email,randomemail);
                res.status(200).json({"message" : "OTP sent successfully"})
                
              }
              else{
                res.status(500).json({"message" : "OTP sent failed"})
              } */
              res.status(200).json({ "message": "OTP sent successfully" })
            });

          })

        }
        else if (user.email) {
          Contact.update({ _id: user._id }, { $set: { "otp": randomotp } }, function (err, result) {

            if (err) {
              res.status(500).json(err);
              console.error(err);
            }
            var url = "http://" + Utilities.getConfig().webAppIp + ":" + Utilities.getConfig().EPort + "/users/foremailver?key=" + randomotp + '&uid=' + user._id;

            var mailOptions = {
              from: "", // sender address
              to: user.email, // gaurav.gupta@adnate.in list of receivers
              subject: Utilities.getConfig().orgName + " - Reset Passwod", // Subject line
              text: "New Task", // plaintext body emailverfi
              html: 'Dear Sir,<br>You can reset your password by clicking on following link<br><center><a href="' + url + '"><br><input type="button"  value="Click here to Reset Your Password" style="font-size:12pt;color:white;background-color:DodgerBlue  ;padding:11px" ></a></center><br><br>Thanks<br>Regards<br>Team Adnate'// html body
            }
            mailer.sendMail(mailOptions);


            res.status(200).json({ "message": "email sent" });
          })



        }
      }
      else {
        res.status(500).json({ "message": "Email ID / Mobile Number not found" })
      }
    })
  }

}


module.exports.foremailver = function (req, res) {

  Contact.findOne({ "_id": req.query.uid }, function (err, res) {
    if (err) {
      console.error(err)
    }
    else if (res) {
      if (req.query.key == res.otp) {
        return res.redirect(Utilities.getConfig().webAppDomain + '/forgotpwd');


      }
    }
    else {
    }
  })

}
module.exports.foremailpwdchg = function (req, res) {

  Contact.findOne({ $or: [{ 'email': req.query.cred.toLowerCase() }, { 'phone': req.query.cred }] }, function (err, verify) {

    this.salt = crypto.randomBytes(16).toString('hex');
    this.hash = crypto.pbkdf2Sync(req.query.newpwd, this.salt, 1000, 64).toString('hex');
    Contact.update({ _id: verify._id }, { $set: { "hash": this.hash, "salt": this.salt } }, function (err, succ) {
      if (err) {
        console.error(err);
      }
      res.status(200).json({ "message": "Password Sucessfully Changes" })
    })
  })

}

//Contact OUS
module.exports.contactous = function (req, res) {
  if (req.body.phone == null || req.body.phone == undefined || req.body.phone == "undefined") {
    req.body.phone == " "
  }
  var mailOptions = {
    from: Utilities.getConfig().mailUser, // sender address
    to: req.body.dealerid, // gaurav.gupta@adnate.in list of receivers
    subject: Utilities.getConfig().orgName + " - Contact Ous", // Subject line
    text: "New Task", // plaintext body emailverfi phone
    html: 'Dear Sir,<br>Someone Wanted to contact ous details are :-<br><br><b>Email ID-</b>' + req.body.email.toLowerCase() + '<br><b>Phone Number-</b>' + req.body.phone + '<br><b>Title-</b>' + req.body.title + '<br><b>Message-</b>' + req.body.msg + '<br><br>Thanks<br>Regards<br>Team Adnate'// html body
  }
  mailer.sendMail(mailOptions);


  res.status(200).json({ "message": "email sent" });
}

//Resend OTP 
module.exports.otpResend = function (req, res) {

  Contact.findOne({ 'phone': req.query.phone }, function (err, verify) {
    if (err) {
      console.error(err);
      res.status(500);
      return;
    }
    else if (verify) {
      function randomString(length, chars) {
        var mask = '';
        if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
        if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if (chars.indexOf('#') > -1) mask += '0123456789';
        if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*+-:";\'<>?,./|\\';
        var result = '';
        for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
        return result;
      }
      var randomotp = randomString(6, '#');
      Contact.update({ _id: verify._id }, { $set: { otp: randomotp } }, function (err, result) {
        if (err) {
          console.error(err)
          return res.status(400).send(err);
        }
        else {
          request({


            uri: Utilities.getConfig().smsUrl + Utilities.getConfig().smsApiMobileKey + verify.phone + Utilities.getConfig().smsApiTextKey + 'Use%20this%20One%20Time%20Password%20for%20SignUp%20 ' + randomotp,
            method: "GET"
          }, function (error, response, body) {

            /* var jsonObj = JSON.parse(response.body);
            if(jsonObj.MsgStatus == 'Sent'){
              res.status(200).json({"message" : "OTP sent successfully"})
            }
            else{
              res.status(500).json({"message" : "OTP sent failed"})
              
            } */
            res.status(200).json({ "message": "OTP sent successfully" })
          });

        }
      });

    }
    else {
      res.status(500).json({ "message": "User not Registered" })
    }
  })
}

//Account Edit
module.exports.Account_Edit = function (req, res) {
  var token;
  Contact.findOne({ '_id': req.body.uid }, function (err, verify) {
    if (err) {
      console.error(err);
    }
    else if (verify) {
      console.log("BODY",req.body)
     var accountUpdate={}
      if(req.body.reportSchedule){
      if(req.body.report_config){
        accountUpdate['report_config'] = req.body.report_config;
      }
      if(req.body.report_emailid){
        accountUpdate['report_emailid'] = req.body.report_emailid;
      }
      if(req.body.scheduled_excel_report){
        accountUpdate['scheduled_excel_report'] = req.body.scheduled_excel_report;
      }
      }
      else{
        // accountUpdate = {
          accountUpdate['first_name'] = req.body.fname;
          accountUpdate['last_name'] = req.body.lname;
          accountUpdate['org_name'] = req.body.org;
          accountUpdate['GET_notif'] = req.body.noti;
          accountUpdate['fuel_unit'] = req.body.fuel_unit;
          accountUpdate['show_announcement'] = req.body.show_announcement?req.body.show_announcement:false;
          accountUpdate['digital_input'] = req.body.digital_input?req.body.digital_input:1
          accountUpdate['label_setting']=req.body.label_setting?req.body.label_setting:false;

          if(req.body.immobilize_setting!=undefined){
	          accountUpdate['immobilize_setting']=req.body.immobilize_setting?req.body.immobilize_setting:false;
	        }
          if(req.body.tow_setting!=undefined){
	          accountUpdate['tow_setting']=req.body.tow_setting?req.body.immobilize_setting:false;
	        }
          if(req.body.parking_setting!=undefined){
	          accountUpdate['parking_setting']=req.body.parking_setting?req.body.immobilize_setting:false;
	        }
  //          show_announcement:req.body.show_announcement?req.body.show_announcement:false,
	// digital_input:req.body.digital_input?req.body.digital_input:1,
        //  first_name: req.body.fname,
        //  last_name: req.body.lname,
        //  org_name: req.body.org,
        //  GET_notif: req.body.noti,
        //  fuel_unit: req.body.fuel_unit,
       }

      
     
      
      if (req.body.timezone) {
        accountUpdate['timezone'] = req.body.timezone;
      }
      Contact.update({ _id: verify._id }, { $set: accountUpdate }, function (err, result) {
        if (err) {
          console.error(err)
          res.status(500);
          return;
        }
        else {
          Contact.findOne({ '_id': req.body.uid }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, verifyy) {
            if (err) {
              console.error(err);
            }
            else if (verify) {

              if (result.nModified == 1) {
                token = verifyy.generateJwt();
                res.status(200);
                res.json({
                  "token": token
                });
              }
              else {
                token = verify.generateJwt();
                res.status(200);
                res.json({
                  "token": token
                });
              }
            }
          })

        }
      })


    }
    else {
      res.status(500).json({ "message": "User not Registered" });
    }
  })
}

module.exports.set_user_setting = function (req, res) {
 if (!req.body.uid) {
    res.status(200).send({ "message": "uid is mandatory" });
    return;
  }

  Contact.findOne({ '_id': req.body.uid }, function (err, user) {
    if (err) {
      console.error(err);
    }
    else if (user) {
      if (req.body.lang) user.language_code = req.body.lang;
      if (req.body.currency_code) user.currency_code = req.body.currency_code;
      if (req.body.fuelUnit) user.fuel_unit = req.body.fuelUnit;
      if (req.body.notifSound) user.notification_sound = req.body.notifSound;
      if (req.body.engine_cut_psd) user.engine_cut_psd = req.body.engine_cut_psd;
      if (req.body.tripGeneration) user.tripGeneration = req.body.tripGeneration;
      if (req.body.unit_measurement) user.unit_measurement = req.body.unit_measurement;
      if (req.body.adminAlert == true || req.body.adminAlert == false) user.adminAlert = req.body.adminAlert;
      if (req.body.tripGeneration) user.tripGeneration = req.body.tripGeneration;
      if (req.body.voice_alert == true || req.body.voice_alert == false) user.voice_alert = req.body.voice_alert;
      if (req.body.announcement) user.announcement = req.body.announcement;
      user.save(function (err, result) {
        if (err) {
          console.error(err)
          res.status(500);
          return;
        }
        else if (result) {
         if (req.body.lang) res.status(200).send({ "message": "language updated sucessfully" })
	 else res.status(200).send({ "message": "announcement updated sucessfully" })
        }
      })


    }
    else {
      res.status(500).json({ "message": "User not Registered" });
    }
  })


 }
/*
module.exports.get_user_setting = function (req, res) {

  if (!req.body.uid) {
    res.status(200).send({ "message": "uid is mandatory" });
    return;
  }

  Contact.findOne({ '_id': ObjectId(req.body.uid) })

    .select('language_code fuel_unit notification_sound engine_cut_psd voice_alert currency_code unit_measurement timezone adminAlert')
    .lean()
    .exec(function (err, user) {
      if (err) {
        console.error(err);
      }
      else if (user) {
        res.status(200).send(user);

      }
      else {
        res.status(500).json({ "message": "User not Registered" });
      }
    })
}
*/

module.exports.get_user_setting = function (req, res) {

  if (!req.body.uid) {
    res.status(200).send({ "message": "uid is mandatory" });
    return;
  }

  Contact.findOne({ '_id': ObjectId(req.body.uid) })
   .select('language_code fuel_unit notification_sound engine_cut_psd voice_alert currency_code unit_measurement timezone adminAlert announcement show_announcement isSuperAdmin isDealer supAdmin')
    .lean()
    .exec(function (err, user) {
      if (err) {
        console.error(err);
      }
      else if (user) {
        if(user.isSuperAdmin){
          res.status(200).send(user);
		
        }else{
          Contact.find({_id: ObjectId(user.supAdmin) }).exec(function (err, result) {
		console.log("Result--->",result)
    console.log("User---",user);
    if(result[0].announcement){
	    console.log("In If Condition");
		var data={
 	     "language_code":user.language_code, 
      	"fuel_unit":user.fuel_unit,
   	    "notification_sound":user.notification_sound,
      	"engine_cut_psd":user.engine_cut_psd,
      	"voice_alert":user.voice_alert,
    	  "currency_code":user.currency_code,
    	  "unit_measurement":user.unit_measurement,
    	  "timezone":user.timezone,
    	  "adminAlert":user.adminAlert,
    	  "announcement":result[0].announcement,
	  "show_announcement":user.show_announcement?user.show_announcement:false,
    	  "isSuperAdmin":user.isSuperAdmin,
    	  "isDealer":user.isDealer,
	   "digital_input":user.digital_input?user.digital_input:1
		}            
	    	console.log("Data-=---",data);
        res.status(200).send(data);
  }else{
	console.log("In else Condition");

    var data={
 	     "language_code":user.language_code, 
      	"fuel_unit":user.fuel_unit,
   	    "notification_sound":user.notification_sound,
      	"engine_cut_psd":user.engine_cut_psd,
      	"voice_alert":user.voice_alert,
    	  "currency_code":user.currency_code,
    	  "unit_measurement":user.unit_measurement,
    	  "timezone":user.timezone,
    	  "adminAlert":user.adminAlert,
    	  "isSuperAdmin":user.isSuperAdmin,
	  "show_announcement":user.show_announcement?user.show_announcement:false,
    	  "isDealer":user.isDealer,
	   "digital_input":user.digital_input?user.digital_input:1
	}            
	    	console.log("Data-=---",data);
        res.status(200).send(data);

  }
  })
  }
  }
      else {
        res.status(500).json({ "message": "User not Registered" });
      }
    })
}


module.exports.verify_EngineCut_Password = function (req, res) {

  if (!req.body.uid) {
    res.status(200).send({ "message": "uid is mandatory" });
    return;
  }

  Contact.findOne({ '_id': ObjectId(req.body.uid) })

    .exec(function (err, user) {
      if (err) {
        console.error(err);
      }
      else if (user) {
        if (user.engine_cut_psd == null || user.engine_cut_psd == undefined || user.engine_cut_psd == "") {
          res.status(200).send({ message: "password not set for user" });
        } else if (user.engine_cut_psd) {
          if (req.body.psd == user.engine_cut_psd) {
            res.status(200).send({ message: "password verified" });
          }
          else {
            res.status(200).send({ message: "password not matched" });
          }
        }
        // res.status(200).send(user);

      }
      else {
        res.status(500).json({ "message": "User not Registered" });
      }
    })
}


module.exports.cancel_signup = function (req, res) {
  Contact.remove({ "phone": req.query.phone }).then(function (err) {
    if (err) {
      res.send(err);
      return err;
    }
    res.status(200).json({ "message": "Sign_Canceled" })
  });
}

module.exports.demo = function (req, res) {

  var mailOptions = {
    from: Utilities.getConfig().mailUser, // sender address
    to: req.query.dealeID, //  dealeID gaurav.gupta@adnate.in list of receivers
    subject: "Oneqlik - Demo Request", // Subject line
    text: "New Task", // plaintext body emailverfi
    html: 'Dear Sir,<br>Someone Wanted a demo details are :-<br><br><b>First Name-</b>' + req.query.fname + '<br><b>Last Name-</b>' + req.query.lname + '<br><b>Email-</b>' + req.query.email + '<br><b>Mobile Number-</b>' + req.query.mobile + '<br><br>Thanks<br>Regards<br>Team Adnate'// html body
  }
  mailer.sendMail(mailOptions);


  res.status(200).json({ "message": "email sent" });
}

//Get Custumer
module.exports.getCust = function (req, res) {
  var query = {};
  query = { 'Dealer': req.query.uid, isDealer: false };
  var pageNo = parseInt(req.query.pageNo);
  var size = parseInt(req.query.size);
  if (pageNo < 0 || pageNo === 0) {
    response = { "error": true, "message": "invalid page number, should start with 1" };
    return res.json(response)
  }
  // query = { isDealer: false };

  query['$and'] = [];
  if (req.query.search) {
    query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] })
  }

  var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] };
  query['$and'].push(queryNew);

  Contact.find(query)
    .populate({ path: 'Dealer', select: 'first_name last_name' })
    .sort({ first_name: 1, last_name: 1 })
    .skip(size * (pageNo - 1))
    .limit(size)
    .exec(function (err, custumer) {

      if (err) {
        console.error(err);
        res.status(500).json({ "message": "Error Occured" } + err);
      }
      else if (custumer.length > 0) {
        // res.status(200).json(custumer)
        var pointer = 0;
        var trac_pointer = 0;
        let final_data = [];
        for (let k = 0; k < custumer.length; k++) {
          trac_pointer++;
          module.exports.calDevice(custumer[k], function (id) {
            final_data.push(id)
            pointer++
            if (trac_pointer == pointer) {
              res.send(final_data);
            }
          })
        }
      }
      else {
        res.status(500).json({ "message": "No custumer Found" });
      }
    })
}

module.exports.calDevice = function (uid, cb) {


  Device.find({ "user": uid._id }, function (err, data) {

    if (err) {
      console.error(err);
    }
    else if (data.length > 0) {

      if (uid.phone.charAt(0) == "n") {
        let r = {
          "_id": uid._id,
          "first_name": uid.first_name,
          "last_name": uid.last_name,
          "email": uid.email,
          "phone": "",
          "total_vehicle": data.length,
          "custumerid": uid.custumerid,
          "status": uid.status,
          "created_on": uid.created_on,
          "pass": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "dealer_firstname": uid.Dealer.first_name,
          "dealer_lastname": uid.Dealer.last_name,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on

        }
        cb(r);
      }
      else if (uid.email.charAt(0) == "n" && uid.email.charAt(2) == "E") {
        let r = {
          "_id": uid._id,
          "first_name": uid.first_name,
          "last_name": uid.last_name,
          "email": "",
          "phone": uid.phone,
          "total_vehicle": data.length,
          "custumerid": uid.custumerid,
          "status": uid.status,
          "created_on": uid.created_on,
          "pass": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "dealer_firstname": uid.Dealer.first_name,
          "dealer_lastname": uid.Dealer.last_name,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on
        }
        cb(r);
      }
      else {
        let r = {
          "_id": uid._id,
          "first_name": uid.first_name,
          "last_name": uid.last_name,
          "email": uid.email,
          "phone": uid.phone,
          "total_vehicle": data.length,
          "custumerid": uid.custumerid,
          "status": uid.status,
          "created_on": uid.created_on,
          "pass": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "dealer_firstname": uid.Dealer.first_name,
          "dealer_lastname": uid.Dealer.last_name,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on
        }
        cb(r);
      }



    }
    else {

      if (uid.phone.charAt(0) == "n") {
        let r = {
          "_id": uid._id,
          "first_name": uid.first_name,
          "last_name": uid.last_name,
          "email": uid.email,
          "phone": "",
          "total_vehicle": 0,
          "custumerid": uid.custumerid,
          "status": uid.status,
          "created_on": uid.created_on,
          "pass": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "dealer_firstname": uid.Dealer.first_name,
          "dealer_lastname": uid.Dealer.last_name,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on
        }
        cb(r)
      }
      else if (uid.email.charAt(0) == "n" && uid.email.charAt(2) == "E") {
        let r = {
          "_id": uid._id,
          "first_name": uid.first_name,
          "last_name": uid.last_name,
          "email": "",
          "phone": uid.phone,
          "total_vehicle": 0,
          "custumerid": uid.custumerid,
          "status": uid.status,
          "created_on": uid.created_on,
          "pass": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "dealer_firstname": uid.Dealer.first_name,
          "dealer_lastname": uid.Dealer.last_name,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on
        }
        cb(r)
      }
      else {
        let r = {
          "_id": uid._id,
          "first_name": uid.first_name,
          "last_name": uid.last_name,
          "email": uid.email,
          "phone": uid.phone,
          "total_vehicle": 0,
          "custumerid": uid.custumerid,
          "status": uid.status,
          "created_on": uid.created_on,
          "pass": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "dealer_firstname": uid.Dealer.first_name,
          "dealer_lastname": uid.Dealer.last_name,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on
        }
        cb(r)
      }

    }
  })

}


//Get Custumer Token
module.exports.getCustumerDetail = function (req, res) {

  Contact.findOne({ '_id': req.query.uid }).populate({ "path": "Dealer", select: "first_name last_name phone email address" }).exec(function (err, custumer) {

    if (err) {
      console.error(err);
      res.status(500).json({ "message": "Error Occured" } + err);
    }
    else if (custumer) {


      if (custumer.image_path) {
        token = custumer.generateJwt();
        img = Utilities.getImage(custumer.image_path)
        res.status(200);
        res.json({
          "img": img,
          "cust": custumer,
          "custumer_token": token,
        });
      }
      else {
        token = custumer.generateJwt();
        res.status(200);
        res.json({
          "cust": custumer,
          "custumer_token": token,
        });
      }


    }
    else {
      res.status(500).json({ "message": "Custumer not found" });
    }
  })

}

//Get Support
module.exports.getSupport = function (req, res) {
  let support = {
    "number": "020-65103106",
    "email": "poonam.g@processfactory.in"
  }
  res.status(200).json(support);
}

//Getabout
module.exports.Getabout = function (req, res) {
  let about = {
    "org": Utilities.getConfig().orgName,
    "address": "404,purple pride square,kalewadi phata Kalewadi, Pune, Maharashtra 411057",
    "Contact_Person": "Gaurav Gupta",
    "Contact_per_phone": "7507500582",
    "Contact_per_email": "info@processfactory.in",
    "website": "https://www.oneqlik.in/home"
  }
  res.status(200).json(about);
}

//Dealer Information Anshul Saxena 04/02/2018

module.exports.getDealerInfo = function (req, res) {

  var json = JSON.parse(require('fs').readFileSync('app_api/dealerConfig/' + req.query.url + '.json', 'utf8'));

  res.status(200).json(json);
}

module.exports.dealer_status = function (req, res) {
  //  res.status(500).send({"message":"restricted"});
  Contact.findOne({ _id: ObjectId(req.body.uId) }, function (err, response) {

    if (err) {
      console.error(err);
    } else {
      if (req.body.status == false) {
        response.status = false
        response.deactivated_by = req.body.loggedIn_id
        response.deactivated_on = new Date();
        response.save(function (err) {
          if (err) {
            console.error(err);
          } else {
            res.sendStatus(200);
          }
        })
      } else if (req.body.status == true) {
        response.status = true
        response.activated_by = req.body.loggedIn_id
        response.activated_on = new Date();
        response.save(function (err) {
          if (err) {
            console.error(err)
          } else {
            res.sendStatus(200);
          }
        })
      }
    }
  })

}


//get all dealer vehicles added by m.hemanth@12/06/2018

module.exports.calDevices = function (uid, cb) {
  var pushArray = [];
  var summation = 0;
  Contact.find({ 'Dealer': uid._id }, function (err, customer) {
    if (err) {
      console.error(err);
      res.sendStatus(500);
      return;
    }
    if (customer.length > 0) {
      function syncCustomers(index) {
        if (index < customer.length) {
          var t = customer[index];
          Device.find({ "user": t._id }, function (err, data) {
            if (err) {
              console.error(err);
              res.sendStatus(500);
              return;
            }
            if (data.length > 0) {
              summation = summation + data.length;
            }
            else {
              summation = summation;
            }
            syncCustomers(index + 1);
          }
          );
        }
        else {
          var obj = {
            "dealer_id": uid._id,
            "dealer_firstname": uid.first_name,
            "dealer_lastname": uid.last_name,
            "email": uid.email,
            "phone": uid.phone,
            "vehicleCount": summation,
            "status": uid.status,
            "created_on": uid.created_on,
            "password": uid.pass,
            "expiration_date": uid.expire_date,
            "userid": uid.user_id,
            "address": uid.address,
            "docObject": uid.imageDoc,
            "login_type": uid.login_type,
            "last_login": uid.last_login,
            "last_activity_on": uid.last_activity_on
          }
          cb(obj);
        }
      }
      syncCustomers(0)
    }
    else {
      Device.find({ "user": uid._id }, function (err, dealerdev) {
        if (err) {
          console.error(err);
          res.status(500).send(err);
          return;
        }
        var obj = {
          "dealer_id": uid._id,
          "dealer_firstname": uid.first_name,
          "dealer_lastname": uid.last_name,
          "email": uid.email,
          "phone": uid.phone,
          "vehicleCount": dealerdev.length,
          "status": uid.status,
          "created_on": uid.created_on,
          "password": uid.pass,
          "expiration_date": uid.expire_date,
          "userid": uid.user_id,
          "address": uid.address,
          "docObject": uid.imageDoc,
          "login_type": uid.login_type,
          "last_login": uid.last_login,
          "last_activity_on": uid.last_activity_on
        }
        cb(obj);
      })
    }
  });

}

module.exports.getAllDealerVehicles = function (req, res) {
  var final_result = [];
  var query = {};
  var pageNo = parseInt(req.query.pageNo);
  var size = parseInt(req.query.size);
  if (pageNo < 0 || pageNo === 0) {
    response = { "error": true, "message": "invalid page number, should start with 1" };
    return res.json(response)
  }

  if (req.query.supAdmin) {
    query = { $and: [{ isDealer: true }, { supAdmin: req.query.supAdmin }] };
  }

  else {
    query = { $and: [{ isDealer: true }] };
  }

  var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] };
  // console.log(queryNew)
  query['$and'].push(queryNew);

  if (req.query.search) {
    query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] })
  }
  // console.log("queryforget Dealer", query)
  Contact.find(query)
    .sort({ first_name: 1, last_name: 1 })
    .skip(size * (pageNo - 1))
    .limit(size)
    .exec(function (err, dealers) {
      if (err) {
        console.error(err);
        res.status(500).send(err);
        return;
      }
      if (dealers.length > 0) {
        var pointer = 0;
        var trac_pointer = 0;
        let final_data = [];
        for (var k = 0; k < dealers.length; k++) {
          trac_pointer++;
          module.exports.calDevices(dealers[k], function (id) {
            final_data.push(id)
            pointer++
            if (trac_pointer == pointer) {
              res.send(final_data);
            }
          })
        }
      }
      else {
        res.status(500).json({ "message": "No customer Found" });
      }
    })
}



//update user details

module.exports.editUserDetails = function (req, res) {
 Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.contactid) }, function (err, contact) {
    if (err) {
      console.error(err);
      res.status(500).send(err);
      return;
    }

    if (contact) {
      var tempUser = JSON.parse(JSON.stringify(contact));
      if (req.body.first_name) tempUser.first_name = req.body.first_name;
      if (req.body.last_name) tempUser.last_name = req.body.last_name;
      if (req.body.email) tempUser.email = req.body.email;
      if (req.body.phone) tempUser.phone = req.body.phone;
       if (req.body.emergencyContact) tempUser.emergency_contact= req.body.emergencyContact;

      // if (typeof (req.body.status) != null) tempUser.status = req.body.status;
      if (req.body.expire_date) tempUser.expire_date = req.body.expire_date;
      if (req.body.address) tempUser.address = req.body.address;
      if (req.body.user_id) tempUser.user_id = req.body.user_id;
      if (req.body.alert) tempUser.alert = req.body.alert;
      if (req.body.role) tempUser.role = req.body.role;
      // if (req.body.role) tempUser.role = req.body.role;
      if (req.body.group) tempUser.group = req.body.group;
      if (req.body.status) tempUser.status = req.body.status;

      Contact.update({ _id: req.body.contactid }, { $set: tempUser }, function (err, data) {
        if (err) {
          res.status(400).send({ "message": err.errmsg });
          return;
        }
        res.status(200).send({ "message": "Saved" });
      });
    }
    else {
      res.status(500).send("No User Found");
    }
  })

}

module.exports.deleteuserDetails = function (req, res) {
  //console.log(req.body.userId);
  Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.userId) }, function (err, delcontact) {
    console.log(delcontact);
    if (err) {
      console.error(err);
      res.status(500).send(err);
      return;
    }
    if (delcontact) {

      delcontact.DeletedUser = req.body.deleteuser;
      delcontact.save(function (err) {
        if (err) {
          console.error("inside error :" + err);
          return;
        }
        res.status(200).send(delcontact._id);
      });
    }
    else {
      res.status(500).send("No User Found");
    }

  })
}




//get all customer vehicles under dealer

module.exports.getAllCustomerVehiclesUnderDealer = function (req, res) {
  var final_result = [];
  Contact.find({ isDealer: true }, function (err, dealers) {
    if (err) {
      console.error(err);
      res.status(500).send(err);
      return;
    }
    if (dealers.length > 0) {
      var pointer = 0;
      var trac_pointer = 0;
      let final_data = [];
      for (var k = 0; k < dealers.length; k++) {
        trac_pointer++;
        module.exports.callCustomerVehicles(dealers[k], function (id) {
          final_data.push(id)
          pointer++
          if (trac_pointer == pointer) {
            res.send(final_data);
          }
        })
      }
    }
    else {
      res.status(500).json({ "message": "No customer Found" });
    }
  })
}

module.exports.callCustomerVehicles = function (uid, cb) {
  var pushArray = [];
  Contact.find({ 'Dealer': uid._id }, function (err, customer) {
    if (err) {
      console.error(err);
      res.sendStatus(500);
      return;
    }
    if (customer.length > 0) {
      function syncCustomers(index) {
        if (index < customer.length) {
          var t = customer[index];
          Device.find({ "user": t._id }, function (err, data) {
            if (err) {
              console.error(err);
              res.sendStatus(500);
              return;
            }
            if (data.length > 0) {
              var cusObj = {
                "customerName": t.first_name,
                "customerId": t._id,
                "vehicleDetails": data
              }
              pushArray = pushArray.concat(cusObj);
            }
            else {
              var cusObj = {
                "customerName": t.first_name,
                "customerId": t._id,
                "vehicleDetails": []
              }
              pushArray = pushArray.concat(cusObj);
            }
            syncCustomers(index + 1);
          }
          );
        }
        else {
          var obj = {
            "dealer_id": uid._id,
            "dealer_firstname": uid.first_name,
            "dealer_lastname": uid.last_name,
            "email": uid.email,
            "CustomerDetails": pushArray
          }
          cb(obj);
        }

      }
      syncCustomers(0)
    }
    else {
      Device.find({ "user": uid._id }, function (err, dealerdev) {
        if (err) {
          console.error(err);
          res.status(500).send(err);
          return;
        }
        var obj = {
          "dealer_id": uid._id,
          "dealer_firstname": uid.first_name,
          "dealer_lastname": uid.last_name,
          "email": uid.email,
          "phone": uid.phone,
        }
        cb(obj);

      })
    }
  });

}

function evaluate(object) {
  if (object && object.constructor === Array) {
    for (var i = 0; i < object.length; i++) {
      object[i] = evaluate(object[i]);
    }
  } else if (object && typeof object == 'object' && Object.keys(object).length > 0) {
    if (Object.keys(object).indexOf('_eval') < 0) {
      for (var key in object) {
        object[key] = evaluate(object[key]);
      }
    } else switch (object['_eval']) {
      case 'Id':
        {
          object = mongoose.Types.ObjectId(object['value']);
          break;
        }
      case 'regex':
        {
          object = new RegExp(object['value'], 'i');
          break;
        }
      case 'date':
        {
          object = new Date(object['value']).getTime();
          break;
        }
    }
  }
  return object;
}



module.exports.datatable = function (req, res) {
  var dtop = {
    conditions: evaluate(req.body.find),
    select: req.body.select
  };
  //console.log(JSON.stringify(dtop.conditions, null, 4));

  Contact.dataTable(req.body, dtop, function (err, data) {
    if (err) {
      console.error(err);
      res.sendStatus(500);
      return;
    }
    res.send(data);
  })
}


module.exports.editUserMaster = function (req, res) {
  Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.contactid) }, function (err, data) {

    if (err) {
      res.status(500).send(err);
      return;
    } else {
      if (data) {
        if (req.body.first_name) data.first_name = req.body.first_name;
        if (req.body.last_name) data.last_name = req.body.last_name;
        if (req.body.email) data.email = req.body.email;
        if (req.body.organisation_name) data.organisation_name = req.body.organisation_name;
        if (req.body.welcome_msg == true) data.welcome_msg = req.body.welcome_msg;
        if (req.body.welcome_msg == false) data.welcome_msg = req.body.welcome_msg;
        if (req.body.phone) data.phone = req.body.phone;
        if (req.body.isDealer == false || req.body.isDealer) data.isDealer = req.body.isDealer;
        if (req.body.isSuperAdmin == false || req.body.isSuperAdmin) data.isSuperAdmin = req.body.isSuperAdmin;
        if (req.body.Dealer) data.Dealer = req.body.Dealer;
        if (req.body.createdOn) data.createdOn = req.body.createdOn;
        if (req.body.user_id) data.user_id = req.body.user_id;
        if ((req.body.status == false) || req.body.status) data.status = req.body.status;


        var tempData = JSON.parse(JSON.stringify(data));

        if ((req.body.isDealer == true) && (req.body.isDealer != undefined)) {

          tempData.isDealer == true;
          delete tempData['Dealer'];
          var uId = tempData._id;
          var updateFlag = 'dealerUpdate';

          saveUser(uId, updateFlag);
        }



        else if ((req.body.isSuperAdmin == true) && (req.body.isSuperAdmin != undefined)) {

          if (tempData.supAdmin) {
            tempData.organisation = tempData.supAdmin;



          }
          tempData.isSuperAdmin == true;
          tempData.isDealer = false;
          delete tempData['Dealer'];
          delete tempData['supAdmin'];
          var uId = tempData._id;
          var updateFlag = 'adminUpdate';
          saveUser(uId, updateFlag);

        } else {
          var uId = tempData._id;
          var updateFlag = 'null';
          saveUser(uId, updateFlag);
        }


        function saveUser(uId, updateFlag) {

          var updatesupAdmin = false;
          var updateId = uId;
          // var newObject = new Contact(JSON.parse(JSON.stringify(tempData)));


          if (updateFlag == 'adminUpdate') {
            var unsetKey = { $unset: { supAdmin: "" }, $set: tempData };
          }
          if (updateFlag == 'dealerUpdate') {
            var unsetKey = { $set: tempData }
          }


          if (updateFlag == 'null') {
            var unsetKey = { $set: tempData }
          }


          Contact.update({ _id: tempData._id }, unsetKey, function (err, changedObject) {
            if (err) {
              res.status(400).send(err);
            } else {

              if (updateFlag != undefined) {

                var query = {
                  $or: [{ user: updateId }, { Dealer: updateId }]
                };
                if (updateFlag == 'dealerUpdate') {
                  var setDevice = {
                    "Dealer": updateId
                  };

                }
                if (updateFlag == 'adminUpdate') {
                  var setDevice = {
                    "Dealer": updateId,
                    "supAdmin": updateId
                  };



                  updatesupAdmin = true;

                }

                if (updateFlag == 'null') {
                  var changeDealer = changedObject.Dealer;
                  var setDevice = {
                    "Dealer": changeDealer,
                  };

                }



                if (updatesupAdmin == true) {
                  Contact.update({ Dealer: updateId }, { $set: { supAdmin: updateId } }, { multi: true }, function (err, updated) {
                    if (err) {
                      res.status(400).send({ "message": "err during supadmin update" })
                    }
                    Device.update(query, { $set: setDevice }, { multi: true }, function (err, deviceUpdate) {
                      if (err) {
                        res.status(400).send({ "message": "error during device update" });
                      }
                      res.status(200).send({ "message": "Role changed and devices updated" });

                    })

                  })
                } else {
                  Device.update(query, { $set: setDevice }, { multi: true }, function (err, deviceUpdate) {
                    if (err) {
                      res.status(400).send({ "message": "error during device update" });
                    }
                    res.status(200).send({ "message": "Role changed and devices updated" });

                  })
                }

              } else {
                res.status(200).send("Edited Successfully!!!");
              }
            }
          })
        }

      } else {
        res.status(500).send("No user Found !!!");
      }

    }
  })
}
module.exports.tokenCheck = function (req, res, next) {

  if (req.method == "GET") next();
  if (req.method == "POST" || req.method == "PUT") {
    var token = req.header('Authorization');
    if (token != "bearer") {
      req.user = jwt.decode(token);
      next();
      // res.send({res:jwt.decode(token)});
      // jwt.verify(token, 'MY_SECRET', function (err, data) {
      //   req.user = data;
      //   if (err) return res.send({ msg: "forbidden" });
      //   next();
      // });
    }
    else
      res.send({ msg: "forbidden" });
  }

}

// module.exports.updatePassword = function (req,res){
//   console.log(req.body);
//   Contact.find({ "_id": mongoose.Types.ObjectId(req.body.ID) }-, function (err, user) {
//     if(err){
//       res.status(400).send(err);
//   }
//   if(user){
//     console.log(user);
//     res.status(200).send({"success":"Password updated"});
//   } 
//   else{
//     res.status(200).send({"success":"UserNot found"});
//   }  
// })

// }

module.exports.updatePassword = function (req, res) {
  Contact.findOne({ "_id": mongoose.Types.ObjectId(req.body.ID) }, function (err, result) {
    if (err) {
      console.error(err);
      res.status(400).send(err);
      return err;
    }
    if (result) {
      //console.log(result);
      if (result.validPassword(req.body.OLD_PASS)) {
        console.log("old pass found !!!!");
        result.setPassword(req.body.NEW_PASS);
        result.save(function (err) {
          if (err) {
            console.error("inside error :" + err);
            return;
          }
          //console.log(result);
          res.status(200).send({ "message": "Password updated !!!" });
        })
      } else {
        res.status(400).send({ "message": "Old password not matched" });
      }
    }
    else {
      res.status(500).json({ "message": "USER NOT FOUND !!!" });
    }
  })
}


module.exports.getCostumer = function (req, res) {
  var query = {};
  if (req.query.all == 'true') {
    query = { 'supAdmin': ObjectId(req.query.uid), isDealer: false };
  } else {
    query = { 'Dealer': ObjectId(req.query.uid), isDealer: false };
  }
  console.log('query', query);

  var pageNo = parseInt(req.query.pageNo);
  var size = parseInt(req.query.size);
  if (pageNo < 0 || pageNo === 0) {
    response = { "error": true, "message": "invalid page number, should start with 1" };
    return res.json(response)
  }
  // query = { isDealer: false };

  query['$and'] = [];
  if (req.query.search) {
    query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] })
  }

  var queryNew = { $or: [{ DeletedUser: { $exists: false } }, { $and: [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] };
  query['$and'].push(queryNew);
  Contact.aggregate([

    {
      $match: query
    },
    {
      $project: {
        "user_id": 1, "first_name": 1, "last_name": 1, "Dealer": 1, "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "point_Allocated": 1,
        "login_type": 1, "last_login": 1, "last_activity_on": 1, "_id": -1, "status": 1, "imageDoc": 1, "pushNotification": 1, "address": 1, "std_code": 1, "accountSuspended": 1,"emergency_contact":1, "adminAlert": 1
      }
    },
    {
      $sort: { _id: -1 }
    },
    {
      $lookup: {
        from: "devInfo",
        localField: "_id",
        foreignField: "user",
        as: "total_vehicle"
      }
    },
    {
      $lookup: {
        from: "client_master",
        localField: "Dealer",
        foreignField: "_id",
        as: "DealerDetails"
      }
    },
    {
      $project: {
        "DealerDetails.first_name": 1, "DealerDetails.last_name": 1, "total_vehicle": { $size: "$total_vehicle" }, "delDevices": { $size: "$total_vehicle.deletedDevice" }, "user_id": 1, "first_name": 1, "last_name": 1, "address": 1, "std_code": 1, "accountSuspended": 1,
        "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "point_Allocated": 1, "login_type": 1, "last_login": 1, "last_activity_on": 1, "_id": -1, "status": 1,"emergency_contact":1, "imageDoc": 1, "notificationTokenCount": { $size: "$pushNotification" }, "adminAlert": 1
      }
    },
    {
      "$skip": (size * (pageNo - 1))
    },
    {
      "$limit": size
    }
  ]).exec(function (err, customers) {
    if (err) {
      res.status(400).send(err);
    }
    res.status(200).send(customers);
  })

}



module.exports.getAllDealerDetails = function (req, res) {
  var final_result = [];
  var query = {};
  var pageNo = parseInt(req.query.pageNo);
  var size = parseInt(req.query.size);
  if (pageNo < 0 || pageNo === 0) {
    response = { "error": true, "message": "invalid page number, should start with 1" };
    return res.json(response)
  }

  if (req.query.supAdmin) {
    query = { $and: [{ isDealer: true }, { supAdmin: ObjectId(req.query.supAdmin) }] };
  }

  else {
    query = { $and: [{ isDealer: true }] };
  }

  if (req.query.customer_role) {
    query = { $and: [{ customer_role: 'subadmin' }] };
  }

  var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] };
  //console.log(queryNew)
  query['$and'].push(queryNew);

  if (req.query.search) {
    query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] })
  }
  console.log("queryforget Dealer", query);

  Contact.aggregate([
    {
      $match: query
    },
    {
      "$skip": (size * (pageNo - 1))
    },
    {
      "$limit": size
    },
    {
      $project: {
        "phone": 1, "status": 1, "created_on": 1, "pass": 1, "expire_date": 1, "user_id": 1, "address": 1, "imageDoc": 1, "login_type": 1, "std_code": 1, "accountSuspended": 1,
        "last_login": 1, "last_activity_on": 1, "_id": 1, "first_name": 1, "last_name": 1, "email": 1, "pushNotification": 1, "cust_add_permission": 1, "device_add_permission": 1, "point_Allocated": 1, "point_Shared_Other": 1
      }
    },
    {
      $sort: { _id: -1 }
    },
    {
      $lookup: {
        from: "devInfo",
        localField: "_id",
        foreignField: "Dealer",
        as: "total_vehicle"
      }
    },
    {
      $project: {
        "total_vehicle": { $size: "$total_vehicle" }, "delDevices": { $size: "$total_vehicle.deletedDevice" }, "user_id": 1, "first_name": 1, "last_name": 1, "address": 1, "cust_add_permission": 1, "device_add_permission": 1, "point_Allocated": 1, "point_Shared_Other": 1, "std_code": 1,
        "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "login_type": 1, "last_login": 1, "last_activity_on": 1, "_id": -1, "status": 1, "imageDoc": 1, "notificationTokenCount": { $size: "$pushNotification" }, "accountSuspended": 1
      }
    }

  ]).exec(function (err, Dealers) {
    if (err) {
      res.status(400).send(err);
    }
    res.status(200).send(Dealers);
  })

}

module.exports.getAllDealerDetailsMobile = function (req, res) {
  var final_result = [];
  var query = {};
  var pageNo = parseInt(req.query.pageNo);
  var size = parseInt(req.query.size);
  if (pageNo < 0 || pageNo === 0) {
    response = { "error": true, "message": "invalid page number, should start with 1" };
    return res.json(response)
  }

  if (req.query.supAdmin) {
    query = { $and: [{ isDealer: true }, { supAdmin: ObjectId(req.query.supAdmin) }] };
  }

  else {
    query = { $and: [{ isDealer: true }] };
  }

  if (req.query.customer_role) {
    query = { $and: [{ customer_role: 'subadmin' }] };
  }

  var queryNew = { "$or": [{ DeletedUser: { $exists: false } }, { "$and": [{ DeletedUser: { $exists: true } }, { DeletedUser: false }] }] };
  //console.log(queryNew)
  query['$and'].push(queryNew);

  if (req.query.search) {
    query['$and'].push({ $or: [{ "first_name": new RegExp(req.query.search, 'i') }, { "last_name": new RegExp(req.query.search, 'i') }, { "phone": new RegExp(req.query.search, 'i') }] })
  }
  //console.log("queryforget Dealer", query);

  Contact.aggregate([
    {
      $match: query
    },
    {
      "$skip": (size * (pageNo - 1))
    },
    {
      "$limit": size
    },
    {
      $project: {
        "phone": 1, "status": 1, "created_on": 1, "pass": 1, "expire_date": 1, "user_id": 1, "address": 1, "imageDoc": 1, "login_type": 1, "std_code": 1, "accountSuspended": 1,
        "last_login": 1, "last_activity_on": 1, "_id": 1, "first_name": 1, "last_name": 1, "email": 1, "pushNotification": 1, "cust_add_permission": 1, "device_add_permission": 1, "point_Allocated": 1, "point_Shared_Other": 1
      }
    },
    {
      $sort: { _id: -1 }
    },
    {
      $lookup: {
        from: "devInfo",
        localField: "_id",
        foreignField: "Dealer",
        as: "total_vehicle"
      }
    },
    {
      $project: {
        "total_vehicle": { $size: "$total_vehicle" }, "user_id": 1, "first_name": 1, "last_name": 1, "point_Allocated": 1, "point_Shared_Other": 1,
        "email": 1, "phone": 1, "pass": 1, "created_on": 1, "expire_date": 1, "_id": -1, "status": 1, "accountSuspended": 1, "address": 1
      }
    }
    // _id, first_name, last_name, email, phone, pass, created_on, total_vehicle, status, expire_date, user_id, address, point_Allocated

  ]).exec(function (err, Dealers) {
    if (err) {
      res.status(400).send(err);
    }
    res.status(200).send(Dealers);
  })

}
module.exports.zogogetDocument = function (req, res) {
  Contact.findOne({ _id: req.query.id }, function (err, data) {
    if (err) {
      res.status(400).send('something went wrong');
    }
    res.status(200).send({ 'userdata': data });
  })


}


module.exports.restoreUsers = function (req, res) {
  Contact.findOneAndUpdate(
    { _id: req.query.id },
    { $unset: { DeletedUser: "" } },
    function (err, user) {
      if (err) {
        res.status(400).send({ message: "no user found" });
      }
      res.status(200).send(user);
    }
  );
};


module.exports.reportPrefrence = function (req, res) {
 //console.log('req.body', req.body);
  var setObject = {}

  if (req.body.reportsArr) {
    setObject['report_preference'] = req.body.reportsArr;
  }
  if(req.body.userSetting){
  setObject['user_settings'] = req.body.userSetting;
  }


  Contact.update(
    { _id: req.body.id },
    { $set: setObject }, function (err, user) {
      if (err) {
        req.status(400).send({ err })
      }
      res.status(200).send({ "message": "Report preference updated" });
    }
  )
}

module.exports.dashboardContent = function (req, res) {
  //console.log('req.body', req.body);
  var setObject = {}

  if (req.body.dashboard_column) {
    setObject['dashboard_column'] = req.body.dashboard_column;
  }


  Contact.update(
    { _id: req.body.user },
    { $set: setObject }, function (err, user) {
      if (err) {
        req.status(400).send({ err })
      }
      res.status(200).send({ "message": "Dashboard Content updated" });
    }
  )
}


module.exports.shareUserDetails = function (req, res) {
  Contact.findOne({ _id: req.query.user })
    .populate('supAdmin')
    .exec(function (err, data) {
      if (err) {
        res.status(400).send('something went wrong');
      }
      var userdata = data;
      var SMSURL = Utilities.getConfig().smsUrl;
      var organisation_name = data.supAdmin.organisation_name;
      var tracktiveAndroidLink = 'https://play.google.com/store/apps/details?id=com.trackTive.ionic';
      var tracktiveIOSlink = 'https://apps.apple.com/us/app/tracktive/id1467327906?ls=1';
      var userCred1 = 'Dear%20' + userdata.first_name + "%20Your%20credentials%20of%20" + organisation_name + "%20are%20userId%20" + userdata.user_id + '%20Password%20' + userdata.pass;
      var mobile_key = Utilities.getConfig().smsApiMobileKey;
      var txt_key = Utilities.getConfig().smsApiTextKey;

      if (organisation_name == 'Tractive VTS') {
        SMSURL += '&sender=TRACTV';
        userCred1 = 'Dear%20' + userdata.first_name + "%20Welcome%20to%20" + organisation_name + "%20Platform%20%2C%20Your%20Login%20credentials%20are%20UserId%20" + userdata.user_id + '%20Password%20' + userdata.pass + "%20App%20%Download%20link%20Android%20" + tracktiveAndroidLink + '%20IOS%20' + tracktiveIOSlink + '%20WEB%20LOGIN%20' + 'https://www.tracktive.in/login';
      } else if (organisation_name === 'IConnect Technologies') {
        SMSURL = Utilities.getConfig().smsUrl_iconnect;
        SMSURL += '&senderid=AMASEC';
        mobile_key = Utilities.getConfig().smsApiMobileKey_iconnect;
        txt_key = Utilities.getConfig().smsApiTextKey_iconnect;
        var userCred1 = 'Dear%20' + userdata.first_name + "%20Welcome%20to%20" + organisation_name + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + userdata.user_id + '%20Password%20' + userdata.pass + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in';
      } else if (organisation_name === 'Saanvi Security Solution') {
        SMSURL = Utilities.getConfig().smsUrl_saanvi;
        mobile_key = Utilities.getConfig().smsApiMobileKey_saanvi;
        txt_key = Utilities.getConfig().smsApiTextKey_saanvi;
        var userCred1 = 'Dear%20' + userdata.first_name + "%20Welcome%20to%20" + organisation_name + "%20platform%20%2C%20Your%20credentials%20are%20userId%20" + userdata.user_id + '%20Password%20' + userdata.pass + '%20WEB%20LOGIN%20' + 'http://www.iconnectindia.in';
      } else {
        SMSURL += '&sender=OneQlk';
      }



      console.log(SMSURL + mobile_key + userdata.phone + txt_key + userCred1);

      request({
        uri: SMSURL + mobile_key + userdata.phone + txt_key + userCred1,
        method: "GET"
      }, function (error, response, body) {
        res.status(200).json({ "message": "Login Information Sent" })
      });
    })

}

module.exports.hardresetPassword = function (req, res) {
  console.log('inside function');
  Contact.findOne({ _id: req.body.id }, function (err, user) {
    if (err) {
      res.status(500).send({ "message": "No user found" })
    }
    console.log('useruseruseruseruseruseruser',user);
    var newUser = new Contact(user);
    newUser.setPassword(req.body.pass);
    newUser.save(function (err) {
      if (err) {
        res.status(500).send(err)
      } else {
        res.status(200).send({ "message": "Password updated !!!" });
      }
    })
  })

}



module.exports.setDealerPermission = function (req, res) {
  Contact.findOne({ _id: req.body.uid }, function (err, user) {
    if (err) {
      res.status(500).send({ "message": "No user found" })
    }

    var newUser = new Contact(user);
    newUser.cust_add_permission = req.body.cust_add_permission;
    newUser.device_add_permission = req.body.device_add_permission;
    newUser.save(function (err) {
      if (err) {
        res.status(500).send({ "message": "Internal Server Error" })
      } else {
        res.status(200).send({ "message": "Permission updated !!!" });
      }
    })
  })
}


module.exports.getuserDetail = function (req, res) {
  Contact.findOne({ _id: req.query.uid }, function (err, user) {
    if (err) {
      res.status(500).send({ "message": "No user found" })
    }
    res.status(200).send(user)

  })


}

module.exports.getuserDetailBySchhol = function (req, res) {
  Contact.findOne({ school: req.query.uid }, function (err, user) {
    if (err) {
      res.status(500).send({ "message": "No user found" })
    }
    res.status(200).send(user)

  })

}



module.exports.DemoRequest = function (req, res) {
  console.log("Inside function");

  var parseJson = req.body.url;

  var parse1 = parseJson.split('.');
  var parse2 = parse1[1];
  console.log("ParsedUrl", parse2);

  var Dealerjson = JSON.parse(require('fs').readFileSync('app_api/dealerConfig/' + parse2 + '.json', 'utf8'));
  console.log('Dealerjson', Dealerjson);
  if (Dealerjson == undefined) {
    return res.status(500).send({ 'message': 'Url is not valid' });
  }
  console.log(Dealerjson);
  var DealerEmail = (Dealerjson.email != '') ? Dealerjson.email : res.status(500).send({ 'message': 'Update Email in DealerConfig' });
  console.log('DealerEmail', DealerEmail);
  var DealerName = Dealerjson.dealerName;

  var client_fName = req.body.first_name;
  var client_lName = req.body.last_name ? req.body.last_name : '';
  var client_phone = req.body.phone ? req.body.phone : '';
  var client_email = req.body.email;

  var htmlBody = '<div>' +
    '<div>' +
    '<p>' + 'Dear ' + DealerName + '</p>' +
    '<p>' + 'Someone has requested for demo.Please find details below.' + '</p>' +
    '<p>' + 'First Name : ' + client_fName + '</p>' +
    '<p>' + 'Last Name : ' + client_lName + '</p>' +
    '<p>' + 'Eamil : ' + client_email + '</p>' +
    '<p>' + 'Phone Number :' + client_phone + '</p>' +
    '<p>' + 'Thank You' + '</p>'
  '</div>' +
    '</div>';

  var mainEmail = 'reports@oneqlik.in'
  var mailOptions = {
    from: mainEmail, // sender address
    to: DealerEmail, // list of receivers
    subject: 'Demo Request', // Subject line
    // text: 'Switch Status', // plaintext body
    html: htmlBody
  };
  console.log(mailOptions);
  mailer.sendMail(mailOptions);
  res.status(200).send({ 'message': 'Demo request sent' })


}

module.exports.checkPointAvailablity = function (req, res) {
  console.log('req.body', req.query);
  if (!req.query.u_id) {
    res.status(200).send({ message: "user_id is mandatory" });
    return;
  }
  if (!req.query.demanded_points) {
    res.status(200).send({ message: "demanded_points is mandatory" })
    return;
  }


  Contact.findOne({ _id: req.query.u_id }, function (err, con) {
    if (err) {
      console.log(err);
      res.send(err)
      return;
    }
    if (con) {
      //console.log(con);
      if (con.isSuperAdmin) {
        Device.find({ $or: [{ user: req.query.u_id }, { Dealer: req.query.u_id }] }).count().exec(function (err, count) {
          if (err) {
            console.log(err);
            res.send(err)
            return;
          }
          if (count >= 0) {
            console.log(count);
            if (con.point_Allocated > (count + con.point_Shared_Other)) {

              if (con.point_Allocated - (count + con.point_Shared_Other) > req.query.demanded_points) {
                res.status(200).send({ available: true, available_points: con.point_Allocated - (count + con.point_Shared_Other) })

              }
              else {
                res.status(200).send({ available: true, message: "only " + con.point_Allocated - (count + con.point_Shared_Other) + " points available" })
              }
            } else {
              res.status(200).send({ available: false, available_points: con.point_Allocated - (count + con.point_Shared_Other) })

            }

          }

        })
      }
      else if (con.isDealer) {
        Device.find({ Dealer: req.query.u_id }).count().exec(function (err, count) {
          if (err) {
            console.log(err);
            res.send(err)
            return;
          }
          if (count >= 0) {
            console.log(count);
            if (con.point_Allocated > (count + con.point_Shared_Other)) {

              if (con.point_Allocated - (count + con.point_Shared_Other) > req.query.demanded_points) {
                res.status(200).send({ available: true, available_points: con.point_Allocated - (count + con.point_Shared_Other) })

              }
              else {
                res.status(200).send({ available: true, message: "only " + con.point_Allocated - (count + con.point_Shared_Other) + " points available" })
              }
            } else {
              res.status(200).send({ available: false, available_points: con.point_Allocated - (count + con.point_Shared_Other) })

            }

          }

        })
      } else {
        Contact.findOne({ _id: con.Dealer }, function (err, con1) {
          if (err) {
            console.log(err);
            res.send(err)
            return;
          }
          if (con1) {
            Device.find({ Dealer: con.Dealer }).count().exec(function (err, count) {
              if (err) {
                console.log(err);
                res.send(err)
                return;
              }
              if (count >= 0) {
                con = con1
                console.log(count);
                if (con.point_Allocated > (count + con.point_Shared_Other)) {

                  if (con.point_Allocated - (count + con.point_Shared_Other) > req.query.demanded_points) {
                    res.status(200).send({ available: true, available_points: con.point_Allocated - (count + con.point_Shared_Other) })

                  }
                  else {
                    res.status(200).send({ available: true, message: "only " + con.point_Allocated - (count + con.point_Shared_Other) + " points available" })
                  }
                } else {
                  res.status(200).send({ available: false, available_points: con.point_Allocated - (count + con.point_Shared_Other) })

                }

              }

            })
          }
        })


      }


    } else {

      res.status(200).send({ "message": "user not found" })
    }
  })
}
module.exports.getColumnSetting = function (req, res) {

  if (!req.query.u_id) {
    res.status(200).send({ message: "user_id is mandatory" });
    return;
  }



  Contact.findOne({ _id: req.query.u_id }, function (err, con) {
    if (err) {
      console.log(err);
      res.send(err)
      return;
    }
    if (con) {
      if (con.dashboard_column) {
        res.status(200).send({ "dashboard_column": con.dashboard_column })
      } else {
        res.status(200).send({ "message": "dashboard_column not found" })
      }



    } else {

      res.status(200).send({ "message": "user not found" })
    }
  })
}

module.exports.setApiKey = function (req, res) {

  if (!req.body.u_id) {
    res.status(200).send({ message: "user_id is mandatory" });
    return;
  }
  if (!req.body.dashboard_column) {
    res.status(200).send({ message: "dashboard_column is mandatory" })
    return;
  }


  Contact.findOne({ _id: req.body.u_id }, function (err, con) {
    if (err) {
      console.log(err);
      res.send(err)
      return;
    }
    if (con) {
      Contact.update({ _id: req.body.u_id }, { $set: { dashboard_column: req.body.dashboard_column } }, function (err, upd) {
        if (err) {
          console.log(err);
        }
        if (upd) {
          res.status(200).send("saved successfully");
        }
      })




    } else {

      res.status(200).send({ "message": "user not found" })
    }
  })
}
module.exports.setApiKey = function (req, res) {

  if (!req.query.u_id) {
    res.status(200).send({ message: "user_id is mandatory" });
    return;
  }
  if (!req.query.api_key) {
    res.status(200).send({ message: "api key is mandatory" })
    return;
  }


  Contact.findOne({ _id: req.query.u_id }, function (err, con) {
    if (err) {
      console.log(err);
      res.send(err)
      return;
    }
    if (con) {
      Contact.update({ _id: req.query.u_id }, { $set: { api_key: req.query.api_key } }, function (err, upd) {
        if (err) {
          console.log(err);
        }
        if (upd) {
          res.status(200).send("saved successfully");
        }
      })




    } else {

      res.status(200).send({ "message": "user not found" })
    }
  })
}


module.exports.getApiKey = function (req, res) {

  if (!req.query.u_id) {
    res.status(200).send({ message: "user_id is mandatory" });
    return;
  }



  Contact.findOne({ _id: req.query.u_id }, function (err, con) {
    if (err) {
      console.log(err);
      res.send(err)
      return;
    }
    if (con) {
      if (con.api_key) {
        res.status(200).send({ "api_key": con.api_key })
      } else {
        res.status(200).send({ "message": "api key not found" })
      }



    } else {

      res.status(200).send({ "message": "user not found" })
    }
  })
}
module.exports.accountSuspension = function (req, res) {
  if ((req.body.accountSuspended === undefined) || (req.body.acoountId === undefined) || (req.body.suspendedBy === undefined)) {
    res.status(500).send({ "message": "missing Parameters" });
  } else {
    var query = {};

    if (req.body.suspendedBy === 'org') {
      query = { $or: [{ supAdmin: req.body.acoountId }, { _id: req.body.acoountId }] };
      Contact.update(query, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err1, contactObj) {
        if (err1) {
          res.status(400).send({ "message": "contact noot updated" });
        }
        Device.update({ supAdmin: req.body.acoountId }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err2, deviceObj) {
          if (err2) {
            res.status(400).send({ "message": "device noot updated" });
          }
          res.status(200).send({ "messsage": "Contact and device status updated" });
        })
      })
    } else if (req.body.suspendedBy === 'distributer') {
      Contact.update({ $or: [{ Dealer: req.body.acoountId }, { _id: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err1, contactObj) {
        if (err1) {
          res.status(400).send({ "message": "contact noot updated" });
        }
        Device.update({ $or: [{ Dealer: req.body.acoountId }, { user: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err2, deviceObj) {
          if (err2) {
            res.status(400).send({ "message": "device noot updated" });
          }
          res.status(200).send({ "messsage": "Contact and device status updated" });
        })
      })
    } else if (req.body.suspendedBy === 'dealer') {
      Contact.update({ $or: [{ _id: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err1, contactObj) {
        if (err1) {
          res.status(400).send({ "message": "contact noot updated" });
        }
        Device.update({ $or: [{ user: req.body.acoountId }] }, { $set: { accountSuspended: req.body.accountSuspended } }, { multi: true }, function (err2, deviceObj) {
          if (err2) {
            res.status(400).send({ "message": "device noot updated" });
          }
          res.status(200).send({ "messsage": "Contact and device status updated" });
        })
      })

    } else {
      res.status(500).send({ "message": "missing parameters" })

    }

  }

}


module.exports.getsupAdmin = function (req, res) {
  Contact.find({ organisation: req.query.supAdmin }, function (err, distributers) {
    if (err) {
      res.status(500).send({ "message": "no distributers found" });
    }
    res.status(200).send(distributers);
  })
}

module.exports.getDealerAndcust = function (req, res) {
  Contact.find({ $or: [{ supAdmin: req.query.supAdmin }, { Dealer: req.query.supAdmin }] }, function (err, distributers) {
    if (err) {
      res.status(500).send({ "message": "no data found" });
    }
    res.status(200).send(distributers);
  })

}

