public ActionResult Delete(string id = "")
        {
            Logger.Debug("Inside User Controller- Delete");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    AspUser user = new AspUser();
                    user.Id = id;
                    _IMarketRepository.DeleteMarketByUserGUID(new Guid(id));

                    _IOrganizationRepository.DeleteOrganizationUserMapByUserGUID(new Guid(id));
                    _IUserSubscriptionRepository.DeleteUserSubscriptionByUserGUID(new Guid(id));
                    _IGlobalUserRepository.DeleteGlobalUser(new Guid(id));
                    //_IGlobalUserRepository.Save();
                    _IUserProfileRepository.DeleteUserProfile(new Guid(id));
                    // _IUserProfileRepository.Save();
                    _IUserRepository.DeleteUser(user.Id);
                    //_IUserRepository.Save();



                    OrganizationSubscription orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                    orgSubscription.SubscriptionConsumed = orgSubscription.SubscriptionConsumed - 1;
                    _IOrganizationSubscriptionRepository.UpdateOrganizationSubscription(orgSubscription);
                    //_IOrganizationSubscriptionRepository.Save();
                    return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                }
                else
                {
                    //TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Session Expired');</script>";
                    //return RedirectToAction("../User/Login");
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Index");
            }
        }
        public ActionResult Edit(AspUser user, string GroupGUID, string RegionGUID, string TerritoryGUID, string RoleGUID)
        {
            Logger.Debug("Inside User Controller- Edit HttpPost");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    DropdownValues();
                    ViewBag.UserName = user.UserName;
                    string oldpassword = _IUserRepository.DecodeFrom64(_IGlobalUserRepository.GetPassword(new Guid(user.UserGUID)));
                    if (ModelState.IsValid)
                    {
                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(user.AddressLine1, user.AddressLine2, user.City, user.State, user.Country, user.ZipCode);
                        GlobalUser globalUser = new GlobalUser();
                        globalUser.UserGUID = new Guid(user.UserGUID);
                        globalUser.USERID = !string.IsNullOrEmpty(user.UserID) ? user.UserID.Trim() : "";
                        globalUser.Role_Id = RoleGUID;
                        globalUser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                        globalUser.Password = _IUserRepository.EncodeTo64(user.PasswordHash);
                        globalUser.IsActive = true;
                        globalUser.IsDelete = false;
                        globalUser.Latitude = latLong.Latitude;
                        globalUser.Longitude = latLong.Longitude;
                        globalUser.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());




                        if (_IGlobalUserRepository.GetRole(globalUser.Role_Id).UserType == "ENT_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "WIM_A" && r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        else if (_IGlobalUserRepository.GetRole(globalUser.Role_Id).UserType == "WIM_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }

                        UserProfile userprofile = new UserProfile();
                        userprofile.ProfileGUID = new Guid(user.ProfileGUID);
                        userprofile.UserGUID = new Guid(user.UserGUID);
                        userprofile.CompanyName = user.CompanyName;
                        userprofile.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                        userprofile.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                        userprofile.MobilePhone = user.MobilePhone;
                        userprofile.BusinessPhone = user.BusinessPhone;
                        userprofile.HomePhone = user.HomePhone;
                        userprofile.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                        userprofile.AddressLine1 = user.AddressLine1;
                        userprofile.AddressLine2 = user.AddressLine2;
                        userprofile.City = user.City;
                        userprofile.State = user.State;
                        userprofile.Country = user.Country;
                        userprofile.Latitude = latLong.Latitude;
                        userprofile.Longitude = latLong.Longitude;
                        userprofile.ZipCode = user.ZipCode;
                        userprofile.IsDeleted = false;
                        userprofile.PicFileURL = user.ImageURL;
                        userprofile.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        AspNetUser aspnetuser = new AspNetUser();
                        aspnetuser.Id = user.UserGUID;
                        aspnetuser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                        aspnetuser.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                        aspnetuser.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                        aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(user.PasswordHash);
                        aspnetuser.PhoneNumber = user.MobilePhone;
                        aspnetuser.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                        aspnetuser.OrganizationGUID = new Guid(user.OrganizationGUID);
                        aspnetuser.SecurityStamp = "";
                        aspnetuser.Discriminator = "";

                        OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                        organizationUserMap.OrganizationUserMapGUID = new Guid(user.OrganizationUserMapGUID);
                        organizationUserMap.OrganizationGUID = new Guid(user.OrganizationGUID);
                        organizationUserMap.UserGUID = globalUser.UserGUID;
                        organizationUserMap.IsContractor = false;
                        organizationUserMap.IsActive = true;
                        organizationUserMap.Status = 0;
                        if (!string.IsNullOrEmpty(user.RegionGUID) && user.RegionGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.RegionGUID = new Guid(user.RegionGUID);
                        }
                        else
                        {
                            organizationUserMap.RegionGUID = null;
                        }
                        if (!string.IsNullOrEmpty(user.TerritoryGUID) && user.TerritoryGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.TerritoryGUID = new Guid(user.TerritoryGUID);
                        }
                        else
                        {
                            organizationUserMap.TerritoryGUID = null;
                        }

                        organizationUserMap.UserType = "ENT_A";
                        organizationUserMap.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                        organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());



                        int userresult = _IUserRepository.UpdateUser(aspnetuser);
                        //int userresult = _IUserRepository.Save();
                        if (userresult > 0)
                        {
                            int guresult = _IGlobalUserRepository.UpdateGlobalUser(globalUser);
                            //int guresult = _IGlobalUserRepository.Save();
                            if (guresult > 0)
                            {
                                int usrresult = _IUserProfileRepository.UpdateUserProfile(userprofile);
                                //int usrresult = _IUserProfileRepository.Save();
                                if (usrresult > 0)
                                {

                                    if (_IOrganizationRepository.UpdateOrganizationUserMap(organizationUserMap) > 0)
                                    {
                                        if (oldpassword != user.PasswordHash)
                                        {
                                            TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Password Changed Successfully');</script>";
                                            if (user.UserGUID == Session["UserGUID"].ToString())
                                                return RedirectToAction("../User/Login");
                                            else
                                                return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                                        }
                                        else if (Session["UserType"] != null && Session["UserType"].ToString() == "SFT_A")
                                        {
                                            return RedirectToAction("Index", "Organization");
                                        }
                                        else if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_A")
                                        {
                                            return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                                        }
                                        else
                                        {
                                            return RedirectToAction("Dashboard", "User");
                                        }
                                    }

                                }
                            }
                        }
                    }
                    else
                    {

                        if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "WIM_A" && r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        else if (Session["UserType"] != null && Session["UserType"].ToString() == "WIM_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        var TerritoryDetails = _ITerritoryRepository.GetTerritoryByRegionGUID(new Guid(RegionGUID)).ToList().OrderBy(r => r.Name).Select(r => new SelectListItem
                        {
                            Value = r.TerritoryGUID.ToString(),
                            Text = r.Name
                        });
                        ViewBag.TerritoryDetails = new SelectList(TerritoryDetails, "Value", "Text");
                    }
                    return View(user);

                }
                else
                {
                    //TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Session Expired');</script>";
                    //return RedirectToAction("../User/Login");
                    return RedirectToAction("SessionTimeOut", "User");
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(user);
            }
        }
        public ActionResult Edit(string id = "", string Account = "")
        {

            Logger.Debug("Inside User Controller- Edit");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    DropdownValues();

                    AspUser user = new AspUser();
                    user.Id = id;
                    AspNetUser aspuser = _IUserRepository.GetUserByID(user.Id);
                    GlobalUser globaluser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(id));
                    UserProfile userprofile = _IUserProfileRepository.GetUserProfileByUserID(new Guid(id), new Guid(Session["OrganizationGUID"].ToString()));
                    OrganizationUsersMap organizationuserMap = _IOrganizationRepository.GetOrganizationUserMapByUserGUID(new Guid(id));
                    if (user == null)
                    {
                        return HttpNotFound();
                    }
                    else
                    {
                        user.Id = globaluser.UserGUID.ToString();
                        user.UserID = globaluser.USERID;
                        user.RegionGUID = organizationuserMap.RegionGUID != null ? organizationuserMap.RegionGUID.ToString() : Guid.Empty.ToString();
                        user.TerritoryGUID = organizationuserMap.TerritoryGUID != null ? organizationuserMap.TerritoryGUID.ToString() : Guid.Empty.ToString();
                        // user.GroupGUID = globaluser.GroupGUID.ToString();
                        user.UserName = globaluser.UserName;
                        ViewBag.UserName = globaluser.UserName;
                        user.CompanyName = userprofile.CompanyName;
                        if (string.IsNullOrEmpty(Account))
                            ViewBag.BreadCrumbUserName = globaluser.UserName;

                        user.PasswordHash = _IUserRepository.DecodeFrom64(globaluser.Password);
                        user.ConfirmPassword = _IUserRepository.DecodeFrom64(globaluser.Password);
                        user.OrganizationGUID = organizationuserMap.OrganizationGUID.ToString();
                        user.OrganizationUserMapGUID = organizationuserMap.OrganizationUserMapGUID.ToString();
                        user.RoleGUID = globaluser.Role_Id;

                        string UserType = _IGlobalUserRepository.GetUserTypeByRoleID(user.RoleGUID);

                        if (UserType == "ENT_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "WIM_A" && r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        else if (UserType == "WIM_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }

                        user.ProfileGUID = userprofile.ProfileGUID.ToString();
                        user.FirstName = userprofile.FirstName;
                        user.LastName = userprofile.LastName;
                        user.MobilePhone = userprofile.MobilePhone;
                        user.AddressLine1 = userprofile.AddressLine1;
                        user.AddressLine2 = userprofile.AddressLine2;
                        user.City = userprofile.City;
                        user.State = userprofile.State;
                        user.Country = userprofile.Country;
                        user.EmailID = userprofile.EmailID;
                        user.BusinessPhone = userprofile.BusinessPhone;
                        user.HomePhone = userprofile.HomePhone;
                        user.UserGUID = userprofile.UserGUID.ToString();
                        user.ZipCode = userprofile.ZipCode;

                        user.SecurityStamp = aspuser.SecurityStamp;
                        user.Discriminator = aspuser.Discriminator;

                        var TerritoryDetails = _ITerritoryRepository.GetTerritoryByRegionGUID(new Guid(user.RegionGUID)).ToList().OrderBy(r => r.Name).Select(r => new SelectListItem
                        {
                            Value = r.TerritoryGUID.ToString(),
                            Text = r.Name
                        });
                        ViewBag.TerritoryDetails = new SelectList(TerritoryDetails, "Value", "Text");
                    }

                    return View(user);
                }
                else
                {
                    //TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Session Expired');</script>";
                    //return RedirectToAction("../User/Login");
                    return RedirectToAction("Login", "User");
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View();
            }
        }
        public ActionResult Create(AspUser user, string GroupGUID, string RegionGUID, string TerritoryGUID, string RoleGUID)
        {
            Logger.Debug("Inside User Controller- Create HttpPost");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    DropdownValues();
                    ViewBag.OrganizationName = _IOrganizationRepository.GetOrganizationByID(new Guid(Session["OrganizationGUID"].ToString())).OrganizationFullName;
                    if (ModelState.IsValid)
                    {
                        OrganizationSubscription orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                        // if (orgSubscription.SubscriptionPurchased > orgSubscription.SubscriptionConsumed)
                        {
                            GlobalUser aspuser = _IUserRepository.GlobalUserLogin(user.UserName, Session["OrganizationGUID"].ToString());
                            GlobalUser aUser = _IGlobalUserRepository.GetGlobalUserByUserID(user.UserID, Session["OrganizationGUID"].ToString());
                            if (aspuser == null && aUser == null)
                            {
                                LatLong latLong = new LatLong();
                                latLong = GetLatLngCode(user.AddressLine1, user.AddressLine2, user.City, user.State, user.Country, user.ZipCode);
                                GlobalUser globalUser = new GlobalUser();
                                globalUser.UserGUID = Guid.NewGuid();
                                globalUser.USERID = user.UserID;
                                globalUser.Role_Id = RoleGUID;
                                globalUser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                                globalUser.Password = _IUserRepository.EncodeTo64(user.PasswordHash);
                                globalUser.IsActive = true;
                                globalUser.IsDelete = false;
                                globalUser.Latitude = latLong.Latitude;
                                globalUser.Longitude = latLong.Longitude;
                                globalUser.CreateDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    globalUser.CreateBy = new Guid(Session["UserGUID"].ToString());
                                globalUser.LastModifiedDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                                OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                                organizationUserMap.OrganizationUserMapGUID = Guid.NewGuid();
                                organizationUserMap.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                organizationUserMap.UserGUID = globalUser.UserGUID;
                                organizationUserMap.IsContractor = false;
                                organizationUserMap.IsActive = true;
                                organizationUserMap.Status = 0;

                                if (!string.IsNullOrEmpty(RegionGUID) && RegionGUID != Guid.Empty.ToString())
                                {
                                    organizationUserMap.RegionGUID = new Guid(RegionGUID);
                                }
                                else
                                {
                                    organizationUserMap.RegionGUID = null;
                                }
                                if (!string.IsNullOrEmpty(TerritoryGUID) && TerritoryGUID != Guid.Empty.ToString())
                                {
                                    organizationUserMap.TerritoryGUID = new Guid(TerritoryGUID);
                                }
                                else
                                {
                                    organizationUserMap.TerritoryGUID = null;
                                }


                                organizationUserMap.UserType = "ENT_A";
                                organizationUserMap.CreateDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                                organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                                UserProfile userprofile = new UserProfile();
                                userprofile.ProfileGUID = Guid.NewGuid();
                                userprofile.UserGUID = globalUser.UserGUID;
                                userprofile.CompanyName = _IOrganizationRepository.GetOrganizationByID(new Guid(Session["OrganizationGUID"].ToString())).OrganizationFullName;
                                userprofile.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                                userprofile.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                                userprofile.MobilePhone = user.MobilePhone;
                                userprofile.BusinessPhone = user.BusinessPhone;
                                userprofile.HomePhone = user.HomePhone;
                                userprofile.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                                userprofile.AddressLine1 = user.AddressLine1;
                                userprofile.AddressLine2 = user.AddressLine2;
                                userprofile.City = user.City;
                                userprofile.State = user.State;
                                userprofile.Country = user.Country;
                                userprofile.Latitude = latLong.Latitude;
                                userprofile.Longitude = latLong.Longitude;
                                userprofile.ZipCode = user.ZipCode;
                                userprofile.IsDeleted = false;
                                userprofile.PicFileURL = user.ImageURL;
                                userprofile.LastModifiedDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                                AspNetUser aspnetuser = new AspNetUser();
                                aspnetuser.Id = globalUser.UserGUID.ToString();
                                aspnetuser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                                aspnetuser.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                                aspnetuser.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                                aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(user.PasswordHash);
                                aspnetuser.PhoneNumber = user.MobilePhone;
                                aspnetuser.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                                aspnetuser.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                aspnetuser.SecurityStamp = "";
                                aspnetuser.Discriminator = "";


                                UserSubscription userSubscription = new UserSubscription();
                                if (orgSubscription != null)
                                {

                                    userSubscription.UserSubscriptionGUID = Guid.NewGuid();
                                    userSubscription.UserGUID = globalUser.UserGUID;
                                    userSubscription.OrganizationSubscriptionGUID = orgSubscription.OrganizationSubscriptionGUID;
                                    userSubscription.IsActive = true;
                                    userSubscription.CreatedDate = DateTime.UtcNow;
                                }

                                int userresult = _IUserRepository.InsertUser(aspnetuser);
                                //int userresult = _IUserRepository.Save();
                                if (userresult > 0)
                                {
                                    int guresult = _IGlobalUserRepository.InsertGlobalUser(globalUser);
                                    //int guresult = _IGlobalUserRepository.Save();
                                    if (guresult > 0)
                                    {
                                        int usrresult = _IUserProfileRepository.InsertUserProfile(userprofile);
                                        //int usrresult = _IUserProfileRepository.Save();
                                        if (usrresult > 0)
                                        {
                                            int uSubscriptionResult = _IUserSubscriptionRepository.InsertUserSubscription(userSubscription);
                                            //int uSubscriptionResult = _IUserSubscriptionRepository.Save();
                                            if (uSubscriptionResult > 0)
                                            {
                                                int orgusermap = _IOrganizationRepository.InsertOrganizationUserMap(organizationUserMap);
                                                //int orgusermap = _IOrganizationRepository.Save();
                                                if (orgusermap > 0)
                                                {
                                                    orgSubscription.SubscriptionConsumed = orgSubscription.SubscriptionConsumed + 1;
                                                    _IOrganizationSubscriptionRepository.UpdateOrganizationSubscription(orgSubscription);
                                                    //_IOrganizationSubscriptionRepository.Save();
                                                    return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                                                }
                                                else
                                                {
                                                    _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                                    //_IUserSubscriptionRepository.Save();
                                                    _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                                    // _IUserProfileRepository.Save();
                                                    _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                                    //_IGlobalUserRepository.Save();
                                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                                    //_IUserRepository.Save();
                                                }
                                            }
                                            else
                                            {
                                                _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                                // _IUserProfileRepository.Save();
                                                _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                                //_IGlobalUserRepository.Save();
                                                _IUserRepository.DeleteUser(aspnetuser.Id);
                                                // _IUserRepository.Save();
                                            }

                                        }
                                        else
                                        {
                                            _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                            //_IGlobalUserRepository.Save();
                                            _IUserRepository.DeleteUser(aspnetuser.Id);
                                            //_IUserRepository.Save();
                                        }
                                    }
                                    else
                                    {
                                        _IUserRepository.DeleteUser(aspnetuser.Id);
                                        // _IUserRepository.Save();
                                    }
                                }
                                else
                                {
                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                    // _IUserRepository.Save();
                                }
                            }
                            else if (aspuser != null)
                            {
                                //UserName already exists for this Organization
                                TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','User Aleady Exists');</script>";
                            }
                            else if (aUser != null)
                            {
                                //UserID already exists for this Organization
                                TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','UserID is Aleady Exists');</script>";
                            }
                        }
                    }
                    else
                    {
                        var TerritoryDetails = _ITerritoryRepository.GetTerritoryByRegionGUID(new Guid(RegionGUID)).ToList().OrderBy(r => r.Name).Select(r => new SelectListItem
                        {
                            Value = r.TerritoryGUID.ToString(),
                            Text = r.Name
                        });
                        ViewBag.TerritoryDetails = new SelectList(TerritoryDetails, "Value", "Text");

                    }

                    return View(user);
                }
                else
                {
                    //TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Session Expired');</script>";
                    //return RedirectToAction("../User/Login");
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(user);
            }
        }
        public int UserCreate(AspUser user)
        {
            Logger.Debug("Inside CustomerView Controller- UserCreate");
            int result = 0;
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    OrganizationSubscription orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                    //if (orgSubscription.SubscriptionPurchased > orgSubscription.SubscriptionConsumed)
                    GlobalUser aspuser = _IUserRepository.GlobalUserLogin(user.UserName, Session["OrganizationGUID"].ToString());
                    if (aspuser == null)
                    {
                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(user.AddressLine1, user.AddressLine2, user.City, user.State, user.Country, user.ZipCode);
                        GlobalUser globalUser = new GlobalUser();
                        globalUser.UserGUID = Guid.NewGuid();
                        globalUser.USERID = user.UserID;
                        globalUser.Role_Id = user.RoleGUID;
                        globalUser.UserName = user.UserName;
                        globalUser.Password = _IUserRepository.EncodeTo64(user.PasswordHash);
                        globalUser.IsActive = true;
                        globalUser.IsDelete = false;
                        globalUser.Latitude = latLong.Latitude;
                        globalUser.Longitude = latLong.Longitude;
                        globalUser.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.CreateBy = new Guid(Session["UserGUID"].ToString());
                        globalUser.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                        organizationUserMap.OrganizationUserMapGUID = Guid.NewGuid();
                        organizationUserMap.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                        organizationUserMap.UserGUID = globalUser.UserGUID;
                        organizationUserMap.IsContractor = false;
                        organizationUserMap.IsActive = true;
                        organizationUserMap.Status = 0;

                        if (!string.IsNullOrEmpty(user.RegionGUID) && user.RegionGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.RegionGUID = new Guid(user.RegionGUID);
                        }
                        else
                        {
                            organizationUserMap.RegionGUID = null;
                        }
                        if (!string.IsNullOrEmpty(user.TerritoryGUID) && user.TerritoryGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.TerritoryGUID = new Guid(user.TerritoryGUID);
                        }
                        else
                        {
                            organizationUserMap.TerritoryGUID = null;
                        }


                        organizationUserMap.UserType = "ENT_A";
                        organizationUserMap.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                        organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                        UserProfile userprofile = new UserProfile();
                        userprofile.ProfileGUID = Guid.NewGuid();
                        userprofile.UserGUID = globalUser.UserGUID;
                        userprofile.CompanyName = _IOrganizationRepository.GetOrganizationByID(new Guid(Session["OrganizationGUID"].ToString())).OrganizationFullName;
                        userprofile.FirstName = user.FirstName;
                        userprofile.LastName = user.LastName;
                        userprofile.MobilePhone = user.MobilePhone;
                        userprofile.BusinessPhone = user.BusinessPhone;
                        userprofile.HomePhone = user.HomePhone;
                        userprofile.EmailID = user.EmailID;
                        userprofile.AddressLine1 = user.AddressLine1;
                        userprofile.AddressLine2 = user.AddressLine2;
                        userprofile.City = user.City;
                        userprofile.State = user.State;
                        userprofile.Country = user.Country;
                        userprofile.Latitude = latLong.Latitude;
                        userprofile.Longitude = latLong.Longitude;
                        userprofile.ZipCode = user.ZipCode;
                        userprofile.IsDeleted = false;
                        userprofile.PicFileURL = user.ImageURL;
                        userprofile.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        AspNetUser aspnetuser = new AspNetUser();
                        aspnetuser.Id = globalUser.UserGUID.ToString();
                        aspnetuser.UserName = user.UserName;
                        aspnetuser.FirstName = user.FirstName;
                        aspnetuser.LastName = user.LastName;
                        aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(user.PasswordHash);
                        aspnetuser.PhoneNumber = user.MobilePhone;
                        aspnetuser.EmailID = user.EmailID;
                        aspnetuser.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                        aspnetuser.SecurityStamp = "";
                        aspnetuser.Discriminator = "";


                        UserSubscription userSubscription = new UserSubscription();
                        if (orgSubscription != null)
                        {

                            userSubscription.UserSubscriptionGUID = Guid.NewGuid();
                            userSubscription.UserGUID = globalUser.UserGUID;
                            userSubscription.OrganizationSubscriptionGUID = orgSubscription.OrganizationSubscriptionGUID;
                            userSubscription.IsActive = true;
                            userSubscription.CreatedDate = DateTime.UtcNow;
                        }

                        int userresult = _IUserRepository.InsertUser(aspnetuser);
                        //int userresult = _IUserRepository.Save();
                        if (userresult > 0)
                        {
                            int guresult = _IGlobalUserRepository.InsertGlobalUser(globalUser);
                            //int guresult = _IGlobalUserRepository.Save();
                            if (guresult > 0)
                            {
                                int usrresult = _IUserProfileRepository.InsertUserProfile(userprofile);
                                // int usrresult = _IUserProfileRepository.Save();
                                if (usrresult > 0)
                                {
                                    int uSubscriptionResult = _IUserSubscriptionRepository.InsertUserSubscription(userSubscription);
                                    //int uSubscriptionResult = _IUserSubscriptionRepository.Save();
                                    if (uSubscriptionResult > 0)
                                    {
                                        int orgusermap = _IOrganizationRepository.InsertOrganizationUserMap(organizationUserMap);
                                        //int orgusermap = _IOrganizationRepository.Save();
                                        if (orgusermap > 0)
                                        {
                                            orgSubscription.SubscriptionConsumed = orgSubscription.SubscriptionConsumed + 1;
                                            result = _IOrganizationSubscriptionRepository.UpdateOrganizationSubscriptionCount(orgSubscription);
                                        }
                                        else
                                        {
                                            _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                            //_IUserSubscriptionRepository.Save();
                                            _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                            //_IUserProfileRepository.Save();
                                            _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                            //_IGlobalUserRepository.Save();
                                            _IUserRepository.DeleteUser(aspnetuser.Id);
                                            // _IUserRepository.Save();
                                        }
                                    }
                                    else
                                    {
                                        _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                        // _IUserProfileRepository.Save();
                                        _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                        //_IGlobalUserRepository.Save();
                                        _IUserRepository.DeleteUser(aspnetuser.Id);
                                        // _IUserRepository.Save();
                                    }

                                }
                                else
                                {
                                    _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                    //_IGlobalUserRepository.Save();
                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                    //_IUserRepository.Save();
                                }
                            }
                            else
                            {
                                _IUserRepository.DeleteUser(aspnetuser.Id);
                                // _IUserRepository.Save();
                            }
                        }
                        else
                        {
                            _IUserRepository.DeleteUser(aspnetuser.Id);
                            //_IUserRepository.Save();
                        }
                    }
                    return result;
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return 0;
            }
        }
        public bool CreateUserByStoreJson(S_POSStoreResponse lObjPOSResp, Guid? RegionGUID, Guid? TerritoryGUID)
        {
            Logger.Debug("Inside CustomerView Controller- CreateUserByStoreJson");
            try
            {

                bool result = false;
                int userCount = 0, resultCount = 0;
                if (Session["OrganizationGUID"] != null)
                {
                    if (lObjPOSResp.store.fieldmanager != null)
                    {
                        GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByUserID(lObjPOSResp.store.fieldmanager.userid, Session["OrganizationGUID"].ToString());
                        if (_globalUser == null)
                        {
                            userCount = userCount + 1;
                            AspUser user = new AspUser();
                            user.UserName = lObjPOSResp.store.fieldmanager.name;
                            user.PasswordHash = "Password";
                            user.ConfirmPassword = "******";
                            user.SecurityStamp = "";
                            user.Discriminator = "";
                            string[] names = lObjPOSResp.store.fieldmanager.name.ToString().Split(' ');
                            if (names.Length > 1)
                            {
                                user.FirstName = names[0].ToString();
                                user.LastName = names[1].ToString();
                            }
                            else
                            {
                                user.FirstName = "";
                                user.LastName = "";
                            }

                            user.EmailID = lObjPOSResp.store.fieldmanager.email;
                            user.UserID = lObjPOSResp.store.fieldmanager.userid;
                            user.BusinessPhone = lObjPOSResp.store.fieldmanager.phone;
                            user.HomePhone = lObjPOSResp.store.fieldmanager.phone;
                            user.MobilePhone = lObjPOSResp.store.fieldmanager.phone;
                            user.RegionGUID = RegionGUID != null ? RegionGUID.ToString() : "";
                            user.TerritoryGUID = TerritoryGUID != null ? TerritoryGUID.ToString() : "";
                            user.OrganizationGUID = Session["OrganizationGUID"] != null ? Session["OrganizationGUID"].ToString() : "";
                            AspNetRole Role = _IUserRepository.GetRolebyUserType("ENT_U");
                            if (Role != null)
                            {
                                user.RoleGUID = Role.Id;
                            }
                            user.AddressLine1 = lObjPOSResp.store.addr1;
                            user.AddressLine2 = lObjPOSResp.store.addr2;
                            user.City = lObjPOSResp.store.addr2;
                            user.State = lObjPOSResp.store.state;
                            user.Country = lObjPOSResp.store.country;
                            user.ZipCode = lObjPOSResp.store.postalcode;
                            user.IsActive = true;
                            if (UserCreate(user) > 0)
                            {
                                resultCount = resultCount + 1;
                            }
                        }
                    }
                    if (lObjPOSResp.store.regionalmanager != null)
                    {

                        GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByUserID(lObjPOSResp.store.regionalmanager.userid, Session["OrganizationGUID"].ToString());
                        if (_globalUser == null)
                        {
                            userCount = userCount + 1;
                            AspUser user = new AspUser();
                            user.UserName = lObjPOSResp.store.regionalmanager.name;
                            user.PasswordHash = "Password";
                            user.ConfirmPassword = "******";
                            user.SecurityStamp = "";
                            user.Discriminator = "";
                            string[] names = lObjPOSResp.store.regionalmanager.name.ToString().Split(' ');
                            if (names.Length > 1)
                            {
                                user.FirstName = names[0].ToString();
                                user.LastName = names[1].ToString();
                            }
                            else
                            {
                                user.FirstName = "";
                                user.LastName = "";
                            }

                            user.EmailID = lObjPOSResp.store.regionalmanager.email;
                            user.UserID = lObjPOSResp.store.regionalmanager.userid;
                            user.BusinessPhone = lObjPOSResp.store.regionalmanager.phone;
                            user.HomePhone = lObjPOSResp.store.regionalmanager.phone;
                            user.MobilePhone = lObjPOSResp.store.regionalmanager.phone;
                            user.RegionGUID = RegionGUID != null ? RegionGUID.ToString() : "";
                            user.TerritoryGUID = TerritoryGUID != null ? TerritoryGUID.ToString() : "";
                            user.OrganizationGUID = Session["OrganizationGUID"] != null ? Session["OrganizationGUID"].ToString() : "";
                            AspNetRole Role = _IUserRepository.GetRolebyUserType("ENT_U_RM");
                            if (Role != null)
                            {
                                user.RoleGUID = Role.Id;
                            }
                            user.AddressLine1 = lObjPOSResp.store.addr1;
                            user.AddressLine2 = lObjPOSResp.store.addr2;
                            user.City = lObjPOSResp.store.addr2;
                            user.State = lObjPOSResp.store.state;
                            user.Country = lObjPOSResp.store.country;
                            user.ZipCode = lObjPOSResp.store.postalcode;
                            user.IsActive = true;
                            if (UserCreate(user) > 0)
                            {
                                resultCount = resultCount + 1;
                            }
                        }
                    }
                    if (lObjPOSResp.store.managers != null && lObjPOSResp.store.managers.Count > 0)
                    {
                        foreach (S_POSResponseManagers manager in lObjPOSResp.store.managers)
                        {

                            GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByUserID(manager.userid, Session["OrganizationGUID"].ToString());
                            if (_globalUser == null)
                            {
                                userCount = userCount + 1;
                                AspUser user = new AspUser();
                                user.UserName = manager.name;
                                user.PasswordHash = "Password";
                                user.ConfirmPassword = "******";
                                user.SecurityStamp = "";
                                user.Discriminator = "";
                                string[] names = manager.name.ToString().Split(' ');
                                if (names.Length > 1)
                                {
                                    user.FirstName = names[0].ToString();
                                    user.LastName = names[1].ToString();
                                }
                                else
                                {
                                    user.FirstName = "";
                                    user.LastName = "";
                                }

                                user.EmailID = manager.email;
                                user.UserID = manager.userid;
                                user.BusinessPhone = manager.phone;
                                user.HomePhone = manager.phone;
                                user.MobilePhone = manager.phone;
                                user.RegionGUID = RegionGUID != null ? RegionGUID.ToString() : "";
                                user.TerritoryGUID = TerritoryGUID != null ? TerritoryGUID.ToString() : "";
                                user.OrganizationGUID = Session["OrganizationGUID"] != null ? Session["OrganizationGUID"].ToString() : "";
                                AspNetRole Role = _IUserRepository.GetRolebyUserType("ENT_U");
                                if (Role != null)
                                {
                                    user.RoleGUID = Role.Id;
                                }
                                user.AddressLine1 = lObjPOSResp.store.addr1;
                                user.AddressLine2 = lObjPOSResp.store.addr2;
                                user.City = lObjPOSResp.store.addr2;
                                user.State = lObjPOSResp.store.state;
                                user.Country = lObjPOSResp.store.country;
                                user.ZipCode = lObjPOSResp.store.postalcode;
                                user.IsActive = true;
                                if (UserCreate(user) > 0)
                                {
                                    resultCount = resultCount + 1;
                                }
                            }
                        }
                    }
                    if (resultCount == userCount)
                        result = true;
                    else
                        result = false;
                }
                return result;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return false;
            }
        }