//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 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");
            }
        }
        /// <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();
        }
        public ActionResult CreateDashboardUser(string lbls)
        {

            // take firstsuperadmin userid....
            int userId = userData.UserId;
            StepAccess sa = new StepAccess();
            DashBoardAccess da = new DashBoardAccess();
            User us = new User();
            // check he is a super admin or admin

            int roleId = userData.RoleId;
            //Check user role is user or dealer user
            if ((roleId == 3)||(roleId == 4))
            {
                //return to login page
                return RedirectToAction("UserLogin", "Login");
            }
            //Check result of insert user details
            if (TempData["createUserResult"] != null)
            {
                //result is 1 = success
            if(int.Parse(TempData["createUserResult"].ToString()) == 1) {
                    ViewBag.SuccessMsg = "User Successfully Created";
                }
                //result is 0 = failure
                else if (int.Parse(TempData["createUserResult"].ToString()) == 0)
                {
                    ViewBag.ErrorMsg = "Failed To Create User";
                }
            }
            

            ViewBag.CurrUserRoleType = roleId;
            int loanCount = -1;
            //Check user role is admin
            if (userData.RoleId == 2)
            {
                //get loan count for branch which admin is assigned to
                loanCount = da.GetLoanCount(userData.BranchId, 2);
                

            }
            //Check user role is super admin
            else if (userData.RoleId == 1)
            {
                //get loan count for company which super admin is assigned to
                loanCount = da.GetLoanCount(userData.Company_Id, 1);
                
            }
            RoleAccess ra = new RoleAccess();
            List<UserRole> roleList = ra.GetAllUserRoles();
            List<UserRole> tempRoleList = new List<UserRole>();
            // filter user roles for page user role drop down compairing with role of user who logged in
            for (int i = roleId - 1; i < roleList.Count && ViewBag.CurrUserRoleType != 3; i++)
            {
                //Check role is dealer user 
                if (roleList[i].RoleId == 4)
                {
                    continue;
                }
                //Check role is user and loan count is 0
                else if ((roleList[i].RoleId == 3) &&(loanCount==0)) 
                {
                    continue;
                }
                //Check role is super admin and logged user role is admin
                else if ((userData.RoleId==2)&&(roleList[i].RoleId == 1)) {
                    continue;
                }
                UserRole tempRole = new UserRole()
                {
                    RoleId = roleList[i].RoleId,
                    RoleName = roleList[i].RoleName
                };
                tempRoleList.Add(tempRole);
            }

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

            // get all branches which belong to company
            List<Branch> branchesLists = (new BranchAccess()).getBranches(userData.Company_Id);
            List<Branch> branchesListAdmin = new List<Branch>();
            //Check user is super admin
            if (userData.RoleId == 1) {
                ViewBag.BranchId = new SelectList(branchesLists, "BranchId", "BranchName");
            }
            else {
                //filter retrieved branch list for admin
                branchesListAdmin = branchesLists.FindAll(t => t.BranchId == userData.BranchId);
                ViewBag.BranchId = new SelectList(branchesListAdmin, "BranchId", "BranchName");
            }
           

            List<Branch> branchesListsLoan =  new List<Branch>();
            List<Branch> branchesListsLoanAd = new List<Branch>();
            //get list of branches which has atleast one loan 
            branchesListsLoan = (new BranchAccess()).GetLoansBranches(userData.Company_Id);
           //check user is super admin
            if (userData.RoleId == 1)
            {
                //convert branch list to select list
                ViewBag.BranchIdUser = new SelectList(branchesListsLoan, "BranchId", "BranchName");
            }
            else {
                //filter branch which admin is assigned
                branchesListsLoanAd = branchesListsLoan.FindAll(t => t.BranchId == userData.BranchId);
                //convert branch list to select list
                ViewBag.BranchIdUser = new SelectList(branchesListsLoanAd, "BranchId", "BranchName");
            }
           //check request is ajax request
            if (HttpContext.Request.IsAjaxRequest())
            {
                ViewBag.AjaxRequest = 1;
                return PartialView();
            }
            else
            {

                return View();
            }

        }
        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 Step3(string lbls)
        {

            // if there is no session exist - redirect to login -- wrong access
            if (Session["companyStep"] == null)
            {
                if (HttpContext.Request.IsAjaxRequest())
                {

                    return new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
                }
                else
                {

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

            
            int userId = userData.UserId; // current user id
            StepAccess sa = new StepAccess();

           

            int roleId = userData.RoleId; // current user's role

            // if he is not a super admin or admin , not allowed -- wrong access
            if (roleId > 2)
            {
                return RedirectToAction("UserLogin", "Login");
            }


            // check if the user completed the step 1 and 2, if not redirect to login -- wrong access
            if (Convert.ToInt32(Session["companyStep"]) < 3)
            {
                return RedirectToAction("UserLogin", "Login");
            }

            // after user created 
            // if user scussefully created
            if (lbls != null && lbls.Equals("User Successfully Created"))
            {

                // pass the sucessfull message to view
                ViewBag.SuccessMsg = "User Successfully Created";
               
                int rol = int.Parse(Session["abcRol"].ToString());
                int br = int.Parse(Session["abcBrnc"].ToString());
                if ((rol == 1) && (br == 0))
                {
                    sa.UpdateCompanySetupStep(userData.Company_Id, userData.BranchId, 4);
                }
                else if ((rol == 2) && (br != 0))
                {
                    sa.UpdateCompanySetupStep(userData.Company_Id, br, 4);
                }
                Session["abcRol"] = "";
                Session["abcBrnc"] = "";

                if (Convert.ToInt32(Session["companyStep"].ToString()) < 4)
                {
                    Session["companyStep"] = 4;
                }

                

                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView();
                }
                else
                {

                    return View();
                }
            }

            // if error occurs while creating the user
            else if (lbls != null && lbls.Equals("Failed to create user!"))
            {


                ViewBag.ErrorMsg = "Failed to create user";

                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView();
                }
                else
                {

                    return View();
                }
            }

            ViewBag.CurrUserRoleType = roleId;

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

            for (int i = roleId - 1; i < roleList.Count && ViewBag.CurrUserRoleType != 3; i++)
            {
                if ((roleList[i].RoleId == 3)||(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");

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


            ViewBag.BranchId = new SelectList(branchesLists, "BranchId", "BranchName");

            //return PartialView(userViewModel);

            if (HttpContext.Request.IsAjaxRequest())
            {
                ViewBag.AjaxRequest = 1;
                return PartialView();
            }
            else
            {

                return View();
            }

        }