//protected override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    try
        //    {
        //        if (Session["AuthenticatedUser"] != null)
        //        {
        //            userData = ((User)Session["AuthenticatedUser"]);
        //        }
        //        else
        //        {
        //            //return RedirectToAction("UserLogin", "Login", new { lbl = "Your Session Expired" });
        //            filterContext.Controller.TempData.Add("UserLogin", "Login");
        //        }
        //    }
        //    catch
        //    {
        //        //filterContext.Result = new RedirectResult("~/Login/UserLogin");
        //        filterContext.Controller.TempData.Add("UserLogin", "Login");
        //    }
        //}

        /// <summary>
        /// CreatedBy : Kanishka SHM
        /// CreatedDate: 2016/01/16
        /// 
        /// Inserting user details
        /// 
        /// argument: None
        /// 
        /// </summary>
        /// <returns>Return view</returns>

        // GET: CreateUser
        public ActionResult Create(string lbls)
        {
            
            int.Parse(Session["userId"].ToString());

            if (lbls != null)
            {
                ViewBag.SuccessMsg = "User Successfully Created";
            }
            //int id = (int)Session["userId"];
            int id = Convert.ToInt32(Session["userId"].ToString());
            UserAccess ua = new UserAccess();
            User curUser = ua.retreiveUserByUserId(id);
            ViewBag.CurrUserRoleType = curUser.RoleId;

            //Restrict to create above user role 
            RoleAccess ra = new RoleAccess();
            List<UserRole> roleList = ra.GetAllUserRoles();
            List<UserRole> tempRoleList = new List<UserRole>();

            //if current user is first super admin he can create aditional super admin
            if (curUser.UserId == curUser.CreatedBy)
            {
                //ViewBag.RoleId = new SelectList(roleList, "RoleId", "RoleName");
                tempRoleList = roleList;
            }
            else
            {
                for (int i = 1; i < roleList.Count && ViewBag.CurrUserRoleType != 3; i++)
                {
                    UserRole tempRole = new UserRole()
                    {
                        RoleId = roleList[i].RoleId,
                        RoleName = roleList[i].RoleName
                    };
                    tempRoleList.Add(tempRole);
                }
            }
            _createById = curUser.UserId;
            _companyId = curUser.Company_Id;
            _curUserRoleId = curUser.RoleId;
            ViewBag.RoleId = new SelectList(tempRoleList, "RoleId", "RoleName");
            _curBranchId = curUser.BranchId;

            // get all branches
            List<Branch> branchesLists = (new BranchAccess()).getBranches(curUser.Company_Id);

            //if current user is admin restrict to creat user for another branch
            if (ViewBag.CurrUserRoleType == 2)
            {
                //ViewBag.BranchId = new SelectList(branchesLists, "BranchId", "BranchName", curUser.BranchId);
                _curBranchId = curUser.BranchId;
            }
            else
            {
                ViewBag.BranchId = new SelectList(branchesLists, "BranchId", "BranchName");
            }

            return PartialView("Create"); 
        }
        public ActionResult SignUp(User user)
        {
            if (this.Session["CaptchaImageText"].ToString() == user.SecurityCode)
            {

                string newSalt = PasswordEncryption.RandomString();
                user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
                user.Email = user.NewEmail;
                user.RoleId = 1;
                user.Status = true;
                user.step_status = 0;

                UserAccess ua = new UserAccess();
                if (ua.InsertUser(user) >= 1)
                {
                    //ViewBag.SuccessMsg = "Your profile Successfully created.";
                    TempData["status"] = "success";
                    //If succeed update step table to step2 
                    StepAccess sa = new StepAccess();
                    //if (sa.updateStepNumberByUserId(ua.getUserId(user.Email), 1))
                    return RedirectToAction("UserLogin", "Login");
                }
                TempData["status"] = "fail";
                //ViewBag.ErrorMsg = "Failed to Sign up try again!";
            }
            else
            {
                TempData["status"] = "captchaFail";
                //ViewBag.ErrorMsg = "Entered Security Code is Not Correct!";
                TempData["ErrorModel"] = user;
            }


            //return View();
            return RedirectToAction("SignUp");
        }
        public ActionResult Create(User user)
        {


            int currentUser =0;
            try
            {
                currentUser = int.Parse(Session["userId"].ToString());
            }
            catch (Exception) {
                return RedirectToAction("UserLogin", "Login");
            }

            user.CreatedBy = _createById;
            user.IsDelete = false;
            user.Status = false;

            //Set admin branch to new user 
            if (_curUserRoleId == 2)
            {
                user.BranchId = _curBranchId;
            }

            //Check role is selected
            if (user.RoleId == 0)
                user.RoleId = 2;

            //Check branch is selected
            if (_curUserRoleId == 1 && user.BranchId == 0)
            {
                user.BranchId = _curBranchId;
            }
            string passwordTemp = user.Password;

            UserAccess ua = new UserAccess();

            string newSalt = PasswordEncryption.RandomString();
            user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
            user.Email = user.NewEmail;

            //Check this
            CompanyAccess ca = new CompanyAccess();
            Company company = new Company();//ca.GetCompanyDetailsByFirstSpUserId(currentUser);
            //Insert user
            user.Company_Id = company.CompanyId;
            int res = ua.InsertUser(user);

            //Insert new user to user activation table
            string activationCode = Guid.NewGuid().ToString();
            int userId = (new UserAccess()).getUserId(user.Email);
            res = ua.InsertUserActivation(userId, activationCode);
            if (res == 1)
            {
                ViewBag.SuccessMsg = "Data Successfully inserted!";
                
                string body = "Hi " + user.FirstName + "! <br /><br /> Your account has been successfully created. Below in your account detail." +
                              "<br /><br /> User name: " + user.UserName +
                                    "<br /> Password : <b>" + passwordTemp +
                              "<br />Click <a href='http://localhost:57318/CreateUser/ConfirmAccount?userId=" + userId + "&activationCode=" + activationCode + "'>here</a> to activate your account." +
                              "<br /><br/> Thanks,<br /> Admin.";

                Email email = new Email(user.Email);
                email.SendMail(body, "Account details");

                
                // check the user as superadmin or admin..
                if (user.RoleId == 1 || user.RoleId == 2)
                {
                    ViewBag.SuccessMsg = "User Successfully Created";
                    

                   
                    return RedirectToAction("create",new { lbls = ViewBag.SuccessMsg });
                }

                Session["editUserIds"] = userId;


                return RedirectToAction("SetRights", "EditRights", new {@lbl1 = ViewBag.SuccessMsg });
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to create user!";

                //Restrict to create above user role 
                RoleAccess ra = new RoleAccess();
                List<UserRole> roleList = ra.GetAllUserRoles();
                List<UserRole> tempRoleList = new List<UserRole>();

                for (int i = roleList[_curUserRoleId - 1].RoleId; i <= roleList.Count && _curUserRoleId != 3; i++)
                {
                    UserRole tempRole = new UserRole()
                    {
                        RoleId = roleList[i - 1].RoleId,
                        RoleName = roleList[i - 1].RoleName
                    };
                    tempRoleList.Add(tempRole);
                }

                ViewBag.RoleId = new SelectList(tempRoleList, "RoleId", "RoleName");

                // get all branches
                List<Branch> branchesLists = (new BranchAccess()).getBranches(_companyId);
                ViewBag.BranchId = new SelectList(branchesLists, "BranchId", "BranchName");


                return PartialView("Create");
            }
        }
        public ActionResult Selectloan(string type)
        {



            LoanSelection detail = new LoanSelection();
            //if edit loan
            if (!string.IsNullOrEmpty(type) && type.Contains("tidenaol"))
            {
                detail = (new UnitAccess()).GetInActiveLoans(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail != null)
                {
                    Session["detail"] = detail;
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else if (!string.IsNullOrEmpty(type) && type.Contains("aticno"))
            {
                detail = (new UnitAccess()).GetPermisssionGivenLoanwithBranchDeatils(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail != null)
                {
                    Session["detail"] = detail;
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else if(!string.IsNullOrEmpty(type) && type.Contains("tcaninaol"))
            {
                detail = (new UnitAccess()).GetActiveLoanforInactive(userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail != null)
                {
                    Session["detail"] = detail;
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else if (!string.IsNullOrEmpty(type))
            {
                detail = (new UnitAccess()).GetPermisssionGivenLoanwithBranchDeatils(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail == null)
                {
                    ViewBag.type = "return";
                    return PartialView();
                }
                else if (detail != null) {
                    Session["detail"] = detail;
                }


            }



            int userId = userData.UserId;
            // if Session is expired throw an error


            loanSelection.RegBranches = new List<Branch>();
            loanSelection.NonRegBranchList = new List<NonRegBranch>();
            loanSelection.LoanList = new List<LoanSetupStep1>();


            //getting user role
            UserAccess ua = new UserAccess();



            // curUser.Company_Id   asanka 8/3/2016
            //create list for nonRegisterCompaniers

            List<NonRegBranch> NonRegisteredBranchLists = detail.NonRegBranchList; //(new BranchAccess()).getNonRegBranches(userData.Company_Id);

            if (userData.RoleId == 1)
            {

                loanSelection.RegBranches = detail.RegBranches; //(new BranchAccess()).getBranches(userData.Company_Id);

                if (loanSelection.RegBranches != null && loanSelection.RegBranches.Count() == 1)
                {



                    // the get non registered branches details for perticular branch  from the non registeres branches list
                    foreach (NonRegBranch branch in NonRegisteredBranchLists)
                    {
                        if (branch.BranchId == loanSelection.RegBranches[0].BranchId)
                        {
                            loanSelection.NonRegBranchList.Add(branch);
                        }
                    }

                    if (loanSelection.NonRegBranchList.Count() == 1)
                    {

                        List<LoanSetupStep1> loanLists = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);
                        loanSelection.LoanList = new List<LoanSetupStep1>();
                        foreach (LoanSetupStep1 loan in loanLists) {
                            // if(loan.LoanStatus == true)
                            //  {
                            loanSelection.LoanList.Add(loan);
                            //  }
                        }

                        //if loans count is one redirect to add unit page
                    }
                }

            } else if (userData.RoleId == 2)
            {

                //loanSelection.RegBranches.Add((new BranchAccess()).getBranchByBranchId(userData.BranchId));
                if (detail.RegBranches != null && detail.RegBranches.Count > 0)
                {
                    loanSelection.RegBranches.Add(detail.RegBranches[0]);
                }



                // the get non registered branches details for perticular branch  from the non registeres branches list
                foreach (NonRegBranch branch in NonRegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {

                        loanSelection.NonRegBranchList.Add(branch);


                    }
                }
                if (loanSelection.NonRegBranchList.Count() == 1)
                {
                    loanSelection.LoanList = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);

                }
            }
            else if (userData.RoleId == 3)
            {

                //loanSelection.RegBranches.Add((new BranchAccess()).getBranchByBranchId(userData.BranchId));

                loanSelection.RegBranches.Add(detail.RegBranches[0]);


                // the get non registered branches details for perticular branch  from the non registeres branches list
                foreach (NonRegBranch branch in NonRegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {
                        loanSelection.NonRegBranchList.Add(branch);
                    }
                }
                if (loanSelection.NonRegBranchList.Count() == 1)
                {
                    loanSelection.LoanList = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);

                }
            }


            Session["popUpSelectionType"] = type;
            if (type == "asderruy") // for add unit page
            {
                ViewBag.type = "AddUnit";
                return PartialView(loanSelection);
            }

            else if (type == "tyuirede") // for add unit page
            {
                ViewBag.type = "Advance";
                return PartialView(loanSelection);
            }

            else if (type == "sedretyt")
            {
                ViewBag.type = "Curtailment";
                return PartialView(loanSelection);
            }

            else if (type == "wsedtgio")
            {
                ViewBag.type = "PayOff";
                return PartialView(loanSelection);
            }

            else if (type == "frtgcvfd")
            {
                ViewBag.type = "Title";
                return PartialView(loanSelection);
            }
            else if (type == "dashboard")
            {
                ViewBag.type = "DashBoard";
                return PartialView(loanSelection);
            }
            else if (type == "linkDealer")
            {
                ViewBag.type = "linkDealer";
                return PartialView(loanSelection);
            }
            else if (type == "assignRights")
            {
                ViewBag.type = "assignRights";
                return PartialView(loanSelection);
            }

            else if (type == "tidenaol") // for add unit page
            {
                ViewBag.type = "EditLoan";
                return PartialView(loanSelection);
            }
            else if (type == "tcaninaol") 
            {
                ViewBag.type = "InactiveLoan";
                return PartialView(loanSelection);
            }
            else if (type == "aticno")
            {
                ViewBag.type = "RenewLoan";
                return PartialView(loanSelection);
            }
            return PartialView(loanSelection);
        }
        public ActionResult EditProfile(User model)
        {
            if (model != null)
            {
                if ((!string.IsNullOrEmpty(model.CurrentPassword)) && (!string.IsNullOrEmpty(model.Password)) && (!string.IsNullOrEmpty(model.ConfirmPassword)))
                {
                    User userObj = new User();
                    userObj = (new UserAccess()).retreiveUserByUserId(userData.UserId);
                    string passwordFromDB = userObj.Password;
                    //user.Password = userObj.Password;
                    char[] delimiter = { ':' };

                    string[] split = passwordFromDB.Split(delimiter);

                    var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');

                    if (passwordFromDB == null || (checkCharHave == false))
                    {
                        return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username or Password, please confirm and submit." });
                    }

                    string passwordEncripted = PasswordEncryption.encryptPassword(model.CurrentPassword, split[1]);

                    if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                    {
                        string passwordEncripted1 = PasswordEncryption.encryptPassword(model.Password, split[1]);
                        model.Password = passwordEncripted1;
                        model.CurrentPassword = passwordFromDB;

                    }
                    else
                    {

                        TempData["UpdteReslt"] = -1;
                        return RedirectToAction("EditProfile");
                        //return View();
                    }
                    //string newSalt = PasswordEncryption.RandomString();
                    //user.CurrentPassword = PasswordEncryption.encryptPassword(user.CurrentPassword, newSalt);
                    //user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
                }
                model.UserId = userData.UserId;
                model.Status = true;
                UserAccess usrAcc = new UserAccess();
                int reslt = usrAcc.UpdateUser(model, userData.UserId);
                if ((reslt == 1) || (reslt == 2))
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, model.BranchId, 0, "Edit User", "Edit User : "******"UpdteReslt"] = 1;
                }
                else
                {
                    TempData["UpdteReslt"] = 0;
                }
                return RedirectToAction("EditProfile");
            }

            return RedirectToAction("UserLogin", "Login");

            
        }
        public ActionResult EditProfile()
        {
            User userObj = new User();
            UserAccess uas = new UserAccess();
            userObj = uas.retreiveUserByUserId(userData.UserId);

            string roleName = "";

            if (userData.RoleId == 1)
                roleName = "Super Admin";
            else if (userData.RoleId == 2)
                roleName = "Admin";
            else if (userData.RoleId == 3)
                roleName = "User";
            else if (userData.RoleId == 4)
                roleName = "Dealer User";

            ViewBag.RoleName = roleName;

            if (TempData["UpdteReslt"] != null)
            {
                if (int.Parse(TempData["UpdteReslt"].ToString()) == 1)
                {
                    ViewBag.SuccessMsg = "Profile is successfully updated";
                }
                else if (int.Parse(TempData["UpdteReslt"].ToString()) == 0)
                {
                    ViewBag.ErrorMsg = "Failed to update Profile";
                }
                else if (int.Parse(TempData["UpdteReslt"].ToString()) == -1)
                {
                    ViewBag.ErrorMsg = "Failed to update Profile";
                }
            }
            userObj.PhoneNumber2 = userObj.PhoneNumber;
            return View(userObj);
        }
        public ActionResult EditUserAtDashboard(User user)
        {
        if(user!=null) 
        {
                if ((!string.IsNullOrEmpty(user.CurrentPassword)) && (!string.IsNullOrEmpty(user.Password)) && (!string.IsNullOrEmpty(user.ConfirmPassword)))
                {
                    User userObj = new User();
                    userObj = (new UserAccess()).retreiveUserByUserId(user.UserId);
                    string passwordFromDB = userObj.Password;
                    //user.Password = userObj.Password;
                    char[] delimiter = { ':' };

                    string[] split = passwordFromDB.Split(delimiter);

                    var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');

                    if (passwordFromDB == null || (checkCharHave == false))
                    {
                        return RedirectToAction("UserLogin", "Login");
                    }

                    string passwordEncripted = PasswordEncryption.encryptPassword(user.CurrentPassword, split[1]);

                    if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                    {
                        string passwordEncripted1 = PasswordEncryption.encryptPassword(user.Password, split[1]);
                        user.Password = passwordEncripted1;
                        user.CurrentPassword = passwordFromDB;

                    }
                    else
                    {

                        TempData["UpdteReslt"] = -1;
                        return RedirectToAction("EditUserAtDashboard");
                        //return View();
                    }
                    //string newSalt = PasswordEncryption.RandomString();
                    //user.CurrentPassword = PasswordEncryption.encryptPassword(user.CurrentPassword, newSalt);
                    //user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
                }

                UserAccess usrAcc = new UserAccess();
                int reslt = usrAcc.UpdateUser(user,userData.UserId);
                if((reslt==1)||(reslt == 2)) 
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, user.BranchId, 0, "Edit User", "Edit User : "******"AuthenticatedUser"] = null;
                    }
                    else
                    {
                        TempData["UpdteReslt"] = 1;
                    }
                    


                }
                else 
                {
                    TempData["UpdteReslt"] = 0;
                }
               
                return RedirectToAction("EditUserAtDashboard");
            }
        else 
        {
                return RedirectToAction("UserLogin", "Login");
        }
            
        }
        public ActionResult Step3(User user)
        {
            
                user.PhoneNumber = user.PhoneNumber2;
            
            int currentUser = userData.UserId;

            // check he is a super admin or admin
            int roleId = userData.RoleId;

            if (roleId > 2)
            {
                return new HttpStatusCodeResult(404,"You are not allowed");
            }

            // check if   step is 3...
            if (Convert.ToInt32(Session["companyStep"]) < 3)
            {
                return new HttpStatusCodeResult(404, "You are not allowed");
            }

            user.CreatedBy = currentUser;
            user.IsDelete = false;
           // user.Status = false;

            string passwordTemp = user.Password;

            UserAccess ua = new UserAccess();

            string newSalt = PasswordEncryption.RandomString();
            user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);

            user.Email = user.NewEmail;

            //CompanyAccess ca = new CompanyAccess();
            //Company company = ca.GetCompanyDetailsByFirstSpUserId(currentUser);
            user.Company_Id = userData.Company_Id;//  company.CompanyId;  - asanka

            //Set admin branch to new user 
            if (roleId == 2)
            {
                user.BranchId = userData.BranchId;
            }
            user.step_status = userData.step_status;
            //Insert user
            int res = ua.InsertUser(user);

            if (res > 0)
            {
                //insert to log 
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId,0, "Create User in Company setup", "created "+(user.RoleId == 1 ? "Super Admin" : "Admin") + ", Username : "******"Hi " + user.FirstName + "! <br /><br /> Your account has been successfully created. Below in your account detail." +
                             "<br /><br /> User name: " + user.UserName +
                                   "<br /> Password : <b>" + passwordTemp +
                             //"<br />Click <a href='http://localhost:57318/CreateUser/ConfirmAccount?userId=" + userId + "&activationCode=" + activationCode + "'>here</a> to activate your account." +
                             "<br /><br/> Thanks,<br /> Admin.";

                    Email email = new Email(user.Email);
                    email.SendMail(body, "Account details");
                }

                Session["abcRol"] = user.RoleId;
                Session["abcBrnc"] = user.BranchId;
                



                ViewBag.SuccessMsg = "User Successfully Created";

                //additional page ----> Add User Rights
                //if()

                return RedirectToAction("Step3", new { lbls = ViewBag.SuccessMsg });

            }
            else
            {
                ViewBag.ErrorMsg = "Failed to create user!";

                //Restrict to create above user role 
                RoleAccess ra = new RoleAccess();
                List<UserRole> roleList = ra.GetAllUserRoles();



                ViewBag.RoleId = new SelectList(roleList, "RoleId", "RoleName");



               // User curUser = ua.retreiveUserByUserId(userId);
                // get all branches
                List<Branch> branchesLists = (new BranchAccess()).getBranches(userData.Company_Id);
                ViewBag.BranchId = new SelectList(branchesLists, "BranchId", "BranchName");


                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return RedirectToAction("Step3", new { lbls = ViewBag.ErrorMsg });
                }
                else
                {

                    return RedirectToAction("Step3", new { lbls = ViewBag.ErrorMsg });
                }
            }
        }
 public ActionResult GetUserByUserId(int userId)
 {
     if (userId > 0)
     {
         User userObj = new User();
         UserAccess uas = new UserAccess();
         userObj = uas.retreiveUserByUserId(userId);
         if (userObj.UserId > 1)
         {
             userObj.PhoneNumber2 = userObj.PhoneNumber;
         }
         //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
         return Json(userObj);
     }
     else
     {
         return RedirectToAction("UserLogin", "Login");
     }
 }
 public ActionResult GetSuperAdminsDetails(int roleId)
 {
     if (roleId == 1)
     {
         User eum = new User();
         UserAccess uas = new UserAccess();
         eum.UserList = uas.GetSuperAdminsByCompanyId(userData.Company_Id);
         //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
         //return Json(UserList1);
        if (eum.UserList != null)
         {
             //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
             return Json(eum);
         }
         else
         {
             return RedirectToAction("UserLogin", "Login");
         }
     }
     else
     {
         return RedirectToAction("UserLogin", "Login");
     }
 }
        public ActionResult GetUsersByBranchId(int roleId,int branchId)
        {
        if(branchId==0) 
        {
            if(userData.BranchId>0) 
            {
                        branchId = userData.BranchId;
            }
        }
            if ((branchId > 0)&&(roleId>1))
            {
                User eum = new User();
                UserAccess uas = new UserAccess();
                eum.UserList = uas.GetAllUsersByBranchId(roleId,branchId);
                 if(eum.UserList != null) 
                {
                    //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
                    return Json(eum);
                }
               else 
               {
                    return RedirectToAction("UserLogin", "Login");
                }
            }

            else
            {
                return RedirectToAction("UserLogin", "Login");
            }
        }
        /// <summary>
        /// CreatedBy : Piyumi
        /// CreatedDate: 2016/04/22
        /// 
        /// edit user(not include edit rights)
        /// 
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult EditUserAtDashboard()
        {
            if (Session["AuthenticatedUser"] != null)
            {
                ViewBag.UserRole = userData.RoleId;

                if(TempData["UpdteReslt"]!=null) 
                {
                if(int.Parse(TempData["UpdteReslt"].ToString())==1) 
                {
                        ViewBag.SuccessMsg = "User is successfully updated";
                }
                   else if (int.Parse(TempData["UpdteReslt"].ToString()) == 0)
                    {
                        ViewBag.ErrorMsg = "Failed to update user";
                    }
                    else if (int.Parse(TempData["UpdteReslt"].ToString()) == -1)
                    {
                        ViewBag.ErrorMsg = "Failed to update user";
                    }
                }

                RoleAccess ra = new RoleAccess();
                List<UserRole> roleList = ra.GetAllUserRoles(userData.Company_Id);
                List<UserRole> tempRoleList = new List<UserRole>();

                for (int i = 0; i < roleList.Count; i++)
                {
                    if ((userData.RoleId == 2) && (roleList[i].RoleId == 1))
                    {
                        continue;
                    }
                    //if (roleList[i].RoleId == 4)
                    //{
                    //    continue;
                    //}
                    UserRole tempRole = new UserRole()
                    {
                        RoleId = roleList[i].RoleId,
                        RoleName = roleList[i].RoleName
                    };
                    tempRoleList.Add(tempRole);
                }

                ViewBag.RoleId = new SelectList(tempRoleList, "RoleId", "RoleName");
                if ((userData.RoleId == 1) ||(userData.RoleId == 2))
                {
                    User eum = new User();
                    List<User> usrList = new List<User>();
                    List<Branch> brList = new List<Branch>();
                    UserAccess uas = new UserAccess();
                    //usrList = uas.GetAllUsersByCompanyId(userData.Company_Id);

                    if (userData.RoleId == 1)
                    {
                        //get all branches for the company
                        BranchAccess ba = new BranchAccess();

                        eum.BranchList = ba.GetBranchesByCompanyId(userData.Company_Id);

                        if (eum.BranchList == null)
                        {
                            eum.BranchList = new List<Branch>();
                        }
                        eum.UserList = new List<User>();

                        ViewBag.BranchId = new SelectList(eum.BranchList, "BranchId", "BranchNameAddress");
                        ViewBag.UserId = new SelectList(eum.UserList, "UserId", "UserName");

                        //return View(eum);
                    }
                    else if (userData.RoleId == 2)
                    {
                        eum.BranchList = new List<Branch>();
                        eum.UserList = new List<User>();
                        ViewBag.BranchId = new SelectList(eum.BranchList, "BranchId", "BranchNameAddress");
                        ViewBag.UserId = new SelectList(eum.UserList, "UserId", "UserName");
                    }


                    return View(eum);
                }
               
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else
            {
                return RedirectToAction("UserLogin", "Login");
            }
            //return View();
        }
        /// <summary>
        /// CreatedBy : Piyumi
        /// CreatedDate: 2016/04/20
        /// 
        /// edit loan
        /// 
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult SelectInActiveLoan(string type)
        {
            if ((userData.RoleId == 1) || (userData.RoleId == 2))
            {
                LoanSelection detail = (new UnitAccess()).GetInActiveLoans(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);

                if (detail != null)
                {
                    Session["InActiveLoanDetails"] = detail;
                }

                //Session["detail"] = detail;

                int userId = userData.UserId; 
                // if Session is expired throw an error


                loanSelection.RegBranches = new List<Branch>();
                loanSelection.NonRegBranchList = new List<NonRegBranch>();
                loanSelection.LoanList = new List<LoanSetupStep1>();


                //getting user role
                UserAccess ua = new UserAccess();



                // curUser.Company_Id   asanka 8/3/2016
                //create list for nonRegisterCompaniers

                List<NonRegBranch> NonRegisteredBranchLists = detail.NonRegBranchList; //(new BranchAccess()).getNonRegBranches(userData.Company_Id);

                if (userData.RoleId == 1)
                {

                    loanSelection.RegBranches = detail.RegBranches; //(new BranchAccess()).getBranches(userData.Company_Id);

                    if (loanSelection.RegBranches.Count() == 1)
                    {



                        // the get non registered branches details for perticular branch  from the non registeres branches list
                        foreach (NonRegBranch branch in NonRegisteredBranchLists)
                        {
                            if (branch.BranchId == loanSelection.RegBranches[0].BranchId)
                            {

                                loanSelection.NonRegBranchList.Add(branch);


                            }
                        }



                        if (loanSelection.NonRegBranchList.Count() == 1)
                        {

                            List<LoanSetupStep1> loanLists = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);
                            loanSelection.LoanList = new List<LoanSetupStep1>();
                            foreach (LoanSetupStep1 loan in loanLists)
                            {
                                // if(loan.LoanStatus == true)
                                //  {
                                loanSelection.LoanList.Add(loan);
                                //  }
                            }

                            //if loans count is one redirect to add unit page
                        }
                    }

                }
                else if (userData.RoleId == 2)
                {

                    //loanSelection.RegBranches.Add((new BranchAccess()).getBranchByBranchId(userData.BranchId));

                    loanSelection.RegBranches.Add(detail.RegBranches[0]);


                    // the get non registered branches details for perticular branch  from the non registeres branches list
                    foreach (NonRegBranch branch in NonRegisteredBranchLists)
                    {
                        if (branch.BranchId == userData.BranchId)
                        {

                            loanSelection.NonRegBranchList.Add(branch);


                        }
                    }
                    if (loanSelection.NonRegBranchList.Count() == 1)
                    {
                        loanSelection.LoanList = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);

                    }
                }
                Session["popUpType"] = type;
                if (type == "tidenaol") // for add unit page
                {
                    ViewBag.type = "EditLoan";
                    return PartialView(loanSelection);
                }

                else
                {
                    return View();
                }


                //return PartialView(loanSelection);


                //return View();
            }

            else
            {
                return RedirectToAction("UserLogin", "Login");
            }
        }
        public ActionResult CreateDashboardUser(User userObj)
        {
            //assign phone number to object property
            userObj.PhoneNumber = userObj.PhoneNumber2;
            //assign user id to variable
            int currentUser = userData.UserId;

            // assign role to variable
            int roleId = userData.RoleId;
            //assign current user id to created by property
            userObj.CreatedBy = currentUser;
            //is delete property as false
            userObj.IsDelete = false;
            //encrypt password
            string passwordTemp = userObj.Password;

            UserAccess ua = new UserAccess();
           DashBoardAccess da = new DashBoardAccess();
            string newSalt = PasswordEncryption.RandomString();
            userObj.Password = PasswordEncryption.encryptPassword(userObj.Password, newSalt);

            userObj.Email = userObj.NewEmail;

            //assign logged user's company id to created user's company id
            userObj.Company_Id = userData.Company_Id;
            //check user role is admin
            if (roleId == 2)
            {
                //assign logged user's branch id to created user's branch id
                userObj.BranchId = userData.BranchId;
            }
            //check created user is super admin and logged user is super admin
            if ((userObj.RoleId == 1)&&(userData.RoleId==1))
            {
                //assign logged user's step status to created user's step status
                userObj.step_status = userData.step_status;
            }
            //check created user is admin
            else if (userObj.RoleId == 2)
            {
                //get step status for given branch id
            int step= ua.GetStepStatusByUserBranchId(userObj.BranchId);
                //check step is 0 or greater than 0
            if(step>=0) 
            {
                    //assign step to created user's step status
                    userObj.step_status = step;
            }
                
            }
            //check created user is user
            else if (userObj.RoleId == 3)
            {
                //check Session["LoanTitle"] is not null
                if (Session["LoanTitle"] != null)
                {
                    //convert session to list
                    List<Branch> loanList = (List<Branch>)Session["LoanTitle"];
                    for (var j = 0; j < loanList.Count; j++)
                    {
                        //check created user's loan id
                        if (loanList[j].LoanId == userObj.LoanId)
                        {
                            foreach (Right rgt1 in userObj.UserRightsList)
                            {
                                //check title is needed to be tracked for created user's loan
                                if (!loanList[j].IsTitleTrack && rgt1.rightId == "U02")
                                {
                                    //assign title page rights as false if title is not needed to be tracked
                                    rgt1.active = false;
                                }
                                //check if there is atleast one fee for created user's loan
                                if (!loanList[j].HasFee && rgt1.rightId == "U07")
                                {
                                    //assign fee page rights as false if there is no atleast one fee
                                    rgt1.active = false;
                                }
                            }
                               
                            //check report rights according to the loan setup details
                            foreach(Right rgt in userObj.ReportRightsList)
                            {
                                //check title need to be tracked and related right id
                                if(!loanList[j].IsTitleTrack && rgt.rightId== "R04")
                                {
                                    rgt.active = false;
                                }
                                //check loan has advance fee and related right id for advance fee invoice
                                if (!loanList[j].HasAdvanceFee && rgt.rightId == "R07")
                                {
                                    rgt.active = false;
                                }
                                //check loan has advance fee and related right id for advance fee receipt
                                if (!loanList[j].HasAdvanceFee && rgt.rightId == "R08")
                                {
                                    rgt.active = false;
                                }
                                //check loan has monthly fee and related right id for monthly fee invoice
                                if (!loanList[j].HasMonthlyFee && rgt.rightId == "R09")
                                {
                                    rgt.active = false;
                                }
                                //check loan has monthly fee and related right id for monthly fee receipt
                                if (!loanList[j].HasMonthlyFee && rgt.rightId == "R10")
                                {
                                    rgt.active = false;
                                }
                                //check loan has lot inspection fee and related right id for lot inspection fee invoice
                                if (!loanList[j].HasLotFee && rgt.rightId == "R11")
                                {
                                    rgt.active = false;
                                }
                                //check loan has lot inspection fee and related right id for lot inspection fee receipt
                                if (!loanList[j].HasLotFee && rgt.rightId == "R12")
                                {
                                    rgt.active = false;
                                }
                            }
                        }
                    }
                }
                //assign 1 for created user's step status
                userObj.step_status= 1;
                //assign selected branch id for created user's branch id
                userObj.BranchId = userObj.BranchIdUser;
                string[] arrList = new string[userObj.UserRightsList.Count];
                string[] arrList2 = new string[userObj.ReportRightsList.Count];
                int i = 0;
                int k = 0;
                //create user right list string by checking each right in right list active status
                foreach (var x in userObj.UserRightsList)
                {
                    if (x.active)
                    {
                        arrList[i] = x.rightId;
                        i++;
                    }
                }
                //create user report right list string by checking each right in report right list active status
                foreach (var y in userObj.ReportRightsList)
                {
                    if (y.active)
                    {
                        arrList2[k] = y.rightId;
                        k++;
                    }
                }
                arrList = arrList.Where(x => !string.IsNullOrEmpty(x)).ToArray();
                
                userObj.UserRights = string.Join(",", arrList);
                //add report rights
                arrList2 = arrList2.Where(x => !string.IsNullOrEmpty(x)).ToArray();
                userObj.ReportRights = string.Join(",", arrList2);
            }
         
            //Insert user details
            int res = da.InsertUserInDashboard(userObj);

            //check result of insert user function
            if (res > 0)
            {
                //update Companay Step States in incomplete Branches continued in dashboard
                StepAccess sa = new StepAccess();
                sa.UpdateCompanySetupStep(userData.Company_Id, userObj.BranchId, 4);

                //if created user's status is active send email to inform his username and password
                if (userObj.Status)
                {

                string body = "Hi " + userObj.FirstName + "! <br /><br /> Your account has been successfully created. Below in your account detail." +
                              "<br /><br /> User name: " + userObj.UserName +
                                    "<br /> Password : <b>" + passwordTemp +
                                 
                              "<br /><br/> Thanks,<br /> Admin.";

                Email email = new Email(userObj.Email);

              
                email.SendMail(body, "Account details");

                }

                string roleName = "";
                //check created user is super admin
                if (userObj.RoleId == 1)
                {
                    //assign role name as super admin
                    roleName = "Super Admin";
                }
                //check created user is admin
                else if (userObj.RoleId == 2)
                {
                    //assign role name as admin
                    roleName = "Admin";
                }
                //check created user is user
                else if (userObj.RoleId == 3)
                {
                    //assign role name as user
                    roleName = "User";
                }
                //insert log record
                Log log = new Log(userData.UserId, userData.Company_Id, userObj.BranchId, 0, "Create User", "Create "+roleName+" ,Username:"******"createUserResult"] = 1;
                //return RedirectToAction("CreateDashboardUser");
                Session["LoanTitle"] = null;

            }
            else
            {
                TempData["createUserResult"] = 0;
                //return View();
            }
            return RedirectToAction("CreateDashboardUser");
        }
        public ActionResult LinkDealer(DealerUserModel user)
        {
            //initialize properties of user object
            user.PhoneNumber = user.PhoneNumber2;
            user.CreatedBy = userData.UserId;
            user.IsDelete = false;
            user.Status = true;
            user.Company_Id = userData.Company_Id;
            user.BranchId = userData.BranchId;
            user.RoleId = 4;
            user.Email = user.NewEmail;

            BranchAccess ba = new BranchAccess();
            Loan loan = new Loan();
            //Check Session["oneLoanDashboard"] is not null
            if (Session["oneLoanDashboard"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["oneLoanDashboard"];
                
            }
            //Check Session["loanDashboardJoinDealer"] is not null
            if (Session["loanDashboardJoinDealer"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["loanDashboardJoinDealer"];
            }
            //initialize non registered branch id
            user.NonRegBranchId = loan.NonRegBranchId;
            //initialize loan id
            user.LoanId = loan.LoanId;
            //encrypt given password
            string passwordTemp = user.Password;

            UserAccess ua = new UserAccess();

            string newSalt = PasswordEncryption.RandomString();
            user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
            user.ActivationCode = Guid.NewGuid().ToString();
            //report rights
            string[] arrList = new string[user.ReportRightsList.Count];
            int k = 0;
            foreach (var y in user.ReportRightsList)
            {
         
                //Check whether a particular report right is given to user
                if (y.active)
                {
                   
                    arrList[k] = y.rightId;
                    k++;
                }
            }
            arrList = arrList.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            user.ReportRights = string.Join(",", arrList);
            //Insert dealer user details and retrieve user id of inserted user
            int newUserId = ua.InsertDealerUser(user);
           //Check user id is not 0
            if (newUserId != 0)
            {
                //Generate email to send username and password to created dealer user                                        
                string body = "Hi " + user.FirstName + "! <br /><br /> Your account has been successfully created. Below in your account detail." +
                              "<br /><br /> User name: " + user.UserName +
                                    "<br /> Password : <b>" + passwordTemp +
                              "<br />Click <a href='www.dfpso.com'>here</a> to activate your account." +
                              "<br /><br/> Thanks,<br /> Admin.";

                Email email = new Email(user.Email);

                Session["abcRol"] = user.RoleId;
                Session["abcBrnc"] = user.BranchId;
                email.SendMail(body, "Account details");
                //insert log record after user is created
                Log log = new Log(userData.UserId, userData.Company_Id, user.BranchId, user.LoanId, "Create Dealer Account", "Inserted Dealer : " + user.UserName, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);

                TempData["msg"] = 1;
                return RedirectToAction("LinkDealer");               

            }
            else
            {
                TempData["msg"] = 2;
                return RedirectToAction("LinkDealer");                
            }
        }
 ///// <summary>
 ///// CreatedBy :  Kanishka SHM
 ///// CreatedDate: 2016/01/19
 ///// activated account
 /// 
 /// <param name="userId"></param>
 /// <param name="activationCode"></param>
 /// <returns>Return to view create first super admin</returns>
 public ActionResult ConfirmAccount(int userId, string activationCode)
 {
     UserAccess ua = new UserAccess();
     if (ua.UpdateUserSatus(userId, activationCode) == 1)
     {
         return View();
     }
     else
     {
         ViewBag.IsError = 1;
         ViewBag.SuccessMsg = "You have already activated your acount.";
         return View();
     }
 }
        public int CheckPasswd(int userId,string Cpwd)
        {
            if (userId > 0)
            {
                User userObj = new User();
                UserAccess uas = new UserAccess();
                userObj = uas.retreiveUserByUserId(userId);
                string passwordFromDB = userObj.Password;
                //user.Password = userObj.Password;
                char[] delimiter = { ':' };

                string[] split = passwordFromDB.Split(delimiter);

                var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');

                if (passwordFromDB == null || (checkCharHave == false))
                {
                   // return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username or Password, please confirm and submit." });
                }

                string passwordEncripted = PasswordEncryption.encryptPassword(Cpwd, split[1]);
                int reslt = 0;
                if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                {
                    reslt = 1;

                }
                else
                {
                    reslt = 0;
                    
                }
                return reslt;
            }
            else
            {
                return 0;
            }
        }
        public ActionResult getNonRegBranchesByRegBranchId(int regBranchId)
        {
            int userId;
            try
            {
                userId = userData.UserId;
            }
            catch (Exception)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }
            UserAccess ua = new UserAccess();
            //User curUser = ua.retreiveUserByUserId(userId);
            List<NonRegBranch> NonRegisteredBranchLists = (new BranchAccess()).getNonRegBranches(userData.Company_Id);
            List<NonRegBranch> newNonRegList = new List<NonRegBranch>();

            foreach (NonRegBranch nonRegBranch in NonRegisteredBranchLists)
            {
                if (nonRegBranch.BranchId == regBranchId)
                {
                    newNonRegList.Add(nonRegBranch);
                }
            }
            SelectList NonRegisteredBranches = new SelectList(newNonRegList, "NonRegBranchId", "BranchName");

            return Json(NonRegisteredBranches);
        }