public ActionResult UserDashBoard()
        {
            ViewBag.login = false;

            var id = userData.UserId;

            var dashBoardModel = new Models.DashBoard();

            var newDashDAL = new DashBoardAccess();

            if (id > 0)
            {

                ///get level id by userid
                int userLevelId = newDashDAL.GetUserLevelByUserId(id);

                dashBoardModel.userId = id;
                dashBoardModel.userName = userData.UserName;
                dashBoardModel.roleName = (new UserManageAccess()).getUserRoleName(id);
                if (userLevelId == 1)
                {

                    dashBoardModel.levelId = 1;
                    return PartialView("~/Views/Shared/_UserDetail.cshtml", dashBoardModel);

                }
                else if (userLevelId == 2)
                {

                    dashBoardModel.levelId = 2;
                    return PartialView("~/Views/Shared/_UserDetail.cshtml", dashBoardModel);

                }
                else if (userLevelId == 3)
                {

                    dashBoardModel.levelId = 3;
                    return PartialView("~/Views/Shared/_UserDetail.cshtml", dashBoardModel);
                }
                else {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else {
                return RedirectToAction("UserLogin", "Login");
            }
        }
        /*

            Frontend page: Report page
            Title: Get active loans of user for grid
            Designed: Kanishka SHM
            User story: 
            Developed: Kanishka SHM
            Date created: 

            Edited By: Irfan MAM
            Purpose: Grid Functionality and user right access

        */
        public ActionResult ReportIndex()
        {
            DashBoardAccess da = new DashBoardAccess();
           int loanCount = 0; 


            ViewBag.RoleId = _userData.RoleId; //user role
            ViewBag.BranchId = _userData.BranchId; // branch

            // if user is a super admin
            if (_userData.RoleId == 1)
            {
                // get total number of active loans which belong to his company
                loanCount = da.GetLoanCount(_userData.Company_Id, _userData.RoleId);
                
                ViewBag.ComId = _userData.Company_Id;
                //branch list
                List<Branch> branchList = (new BranchAccess()).GetLoansBranches(_userData.Company_Id);

                var slectListBranches = new List<SelectListItem>();

                foreach (var br in branchList) {
                    slectListBranches.Add(new SelectListItem {
                        Text = br.BranchName,
                        Value = br.BranchId.ToString()
                    });
                }
                ViewBag.BranchSelectList = slectListBranches;
                // if there is no active loan then redirect to login -- wrong access
                if (loanCount < 1)
                {
                    return RedirectToAction("UserLogin", "Login");
            }
            }
            // if user is a admin
            else if (_userData.RoleId == 2)
            {
                // get total number of active loans which belong to his branch
                loanCount = da.GetLoanCount(_userData.BranchId, _userData.RoleId);
                ViewBag.BranchName = _userData.BranchName;
                // if there is no active loan then redirect to login -- wrong access
                if (loanCount < 1)
                {
                    return RedirectToAction("UserLogin", "Login");
                }

            }
            // if user is a user
            else if (_userData.RoleId == 3)
            {
                // get total number of autorized loans which belong to him
                loanCount = (new ReportAccess()).GetLoanCountAccountDetailsForUser(_userData.UserId);

                // if there is no authorized loan then redirect to login -- wrong access
                if (loanCount < 1)
                {
                    return RedirectToAction("UserLogin", "Login");
                }
                //  if user selected the authorized loan from dashboard
                else if(Session["CurrentLoanRights"] != null && Session["CurrentLoanRights"].ToString().Contains("U06"))
                {
                    // if loan count is equal to 1
                    if (loanCount == 1)
                    {
                        // get loan details of perticular loan
                        // pass it to view
                        ViewBag.loan = (new ReportAccess()).GetAccountDetailsForUser(_userData.UserId);

                    }



                }
                // if user selected the non authorized loan from dashboard
                else if (Session["CurrentLoanRights"] != null && !Session["CurrentLoanRights"].ToString().Contains("U06"))
                {


                    // clear the session of selected loan
                    Session["loanCode"] = null;
                    Session["loanDashboard"] = null;


                    // if loan count is equal to 1
                    if (loanCount== 1) {
                        // get that loan detail and report rights
                       List<Account> accounts = (new ReportAccess()).GetAccountDetailsForUser(_userData.UserId);

                        // if there is no other loan which has report rights -> redirect to login 
                        if(accounts == null || accounts.Count < 1)
                        {
                            return RedirectToAction("UserLogin", "Login");
                        }
                        ViewBag.loan = accounts;
                       // set the session of selected loan
                       Session["loanCode"] = accounts[0].LoanCode;
                    }

                   
                }
                // if user doesn't select the loan from the dashboard
                else
                {
                    if (loanCount == 1)
                    {
                        // get that loan detail and report rights
                        List<Account> accounts = (new ReportAccess()).GetAccountDetailsForUser(_userData.UserId);
                        ViewBag.loan = accounts;
                        // set the session of selected loan
                        Session["loanCode"] = accounts[0].LoanCode;

                    }
                }



            }
            // if user is a dealer
            else if ( _userData.RoleId == 4)
            {
                loanCount = (new ReportAccess()).GetLoanCountAccountDetailsForUser(_userData.UserId);
                
                // dealer user can have only one account
                if (loanCount != 1)
                {
                    return RedirectToAction("UserLogin", "Login");
                }
                else
                {
                    // get that loan detail and report rights
                    List<Account> accounts = (new ReportAccess()).GetAccountDetailsForUser(_userData.UserId);
                    ViewBag.loan = accounts;
                }
                
            }
            ViewBag.getReportRights = (new UserRightsAccess()).getReportRights();
                ViewBag.loanCount = loanCount;
            return View();
        }
        /// <summary>
        /// CreatedBy : Piyumi
        /// CreatedDate: 2016/01/18
        /// 
        /// delete selected user
        /// 
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult Delete()
        {
            int id = (int)TempData["delRowId"];

            DashBoardAccess db = new DashBoardAccess();

            UserManageAccess obj1 = new UserManageAccess();
            if (id != 0)
            {
                bool ret = obj1.deleteUser(id);
                if (ret)
                {
                    ViewBag.SuccessMsg = "User is successfully deleted";

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

            }

            return RedirectToAction("UserList", "UserManagement");


        }
        /// <summary>
        /// CreatedBy : Irfan
        /// CreatedDate: 2016/01/13
        /// 
        /// Showing details of selected user
        /// EditedBy: Piyumi
        /// EditedDate:2016/03/30
        /// Edited for new dashboard
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult UserDetails()
        {
            Session["rowId"] = userData.UserId;
            Session["loanStep"] = null;
            Loan loan = new Loan();

            if (Session["loanDashboardJoinDealer"] != null)
            {
                Session.Remove("loanDashboardJoinDealer");
            }
            if (Session["loanDashboardAssignUser"] != null)
            {
                Session.Remove("loanDashboardAssignUser");
            }

            if (Session["AuthenticatedUser"] != null)
            {
                DashBoardAccess da = new DashBoardAccess();
                ViewBag.Username = userData.UserName;
                ViewBag.Userid = userData.UserId;
                ViewBag.Company = userData.CompanyName;
                ViewBag.roleId = userData.RoleId;
                if (Session["loanDashboard"] != null)
                {
                    ViewBag.LoanCount = 1;
                    ViewBag.loanSelected = 1;
                    Loan loanSelected = (Loan)Session["loanDashboard"];

                    if (loanSelected != null)
                    {
                        if (userData.RoleId == 1)
                        {
                            ViewBag.PartnerType = 2;
                        }
                        else if (userData.RoleId == 2)
                        {
                            ViewBag.PartnerType = 1;
                        }
                        else {
                            ViewBag.PartnerType = 0;
                        }
                        ViewBag.PartnerName = loanSelected.PartnerName;

                        ViewBag.Branch = loanSelected.BranchName;
                        ViewBag.LoanNum = loanSelected.LoanNumber;
                        ViewBag.LoanCode = loanSelected.LoanCode;
                        ViewBag.IsTitleTrack = loanSelected.IsTitleTrack;

                        Session["IsTitleTrack"] = loanSelected.IsTitleTrack;
                        if ((loanSelected.AdvanceFee == 1) || (loanSelected.LotInspectionFee == 1) || (loanSelected.MonthlyLoanFee == 1))
                        {
                            ViewBag.Fee = 1;
                        }
                        else
                        {
                            ViewBag.Fee = 0;
                        }
                        Session["loanCode"] = loanSelected.LoanCode;

                        if (userData.RoleId == 3)
                        {
                            if ((string)Session["CurrentLoanRights"] != "")
                            {
                                //string[] charactors = loanSelected.Rights.Split(',');

                                string rgts = (string)(Session["CurrentLoanRights"]);
                                string[] rightsStringList = rgts.Split(',');

                                List<string> rightList = new List<string>();
                                for (int i = 0; i < rightsStringList.Length; i++) {
                                    rightList.Add(rightsStringList[i]);
                                }

                                //List<string> rightList = new List<string>(charactors);
                                ViewBag.RightList = rightList;
                            }

                        }
                        else
                        {
                            ViewBag.AdvanceUnits = 1;
                            ViewBag.AddUnits = 1;
                            ViewBag.ViewReports = 1;
                            ViewBag.PayoffUnits = 1;
                            ViewBag.Curtailment = 1;
                            ViewBag.TitleAdd = 1;
                            ViewBag.PayFees = 1;
                        }


                        
                        return View();
                    }
                    else
                    {
                        return View();
                    }

                }

                if (userData.RoleId == 2)
                {
                    //ViewBag.Branch = (ba.getBranchByBranchId(user.BranchId)).BranchName;
                    ViewBag.LoanCount = da.GetLoanCount(userData.BranchId, 2);
                    ViewBag.Branch = userData.BranchName;
                    ViewBag.Position = "Admin";

                }
                else if (userData.RoleId == 1)
                {
                    ViewBag.LoanCount = da.GetLoanCount(userData.Company_Id, 1);
                    ViewBag.Branch = "";
                    ViewBag.Position = "Super Admin";

                }
                else if (userData.RoleId == 3 || userData.RoleId == 4)
                {
                    ViewBag.LoanCount = da.GetLoanCount(userData.UserId, 3);
                    ViewBag.Branch = userData.BranchName;
                    ViewBag.Position = "User";

                }

                if (ViewBag.LoanCount == 1)
                {

                    if (userData.RoleId == 2)
                    {
                        loan = da.GetLoanDetails(userData.BranchId, 2);

                    }
                    else if (userData.RoleId == 1)
                    {
                        loan = da.GetLoanDetails(userData.Company_Id, 1);

                    }
                    else if (userData.RoleId == 3)
                    {
                        loan = da.GetLoanDetails(userData.UserId, 3);

                    }
                    else if (userData.RoleId == 4)
                    {
                        loan = da.GetLoanDetails(userData.UserId, 4);

                    }
                    if (loan != null)
                    {
                        Session["LoanOne"] = loan;
                        if (userData.RoleId == 3)
                        {
                            Session["CurrentLoanRights"] = loan.Rights;
                        }
                        ViewBag.PartnerName = ((Loan)Session["LoanOne"]).PartnerName;
                        ViewBag.PartnerType = loan.PartnerType;
                        ViewBag.Branch = ((Loan)Session["LoanOne"]).BranchName;
                        ViewBag.LoanNum = loan.LoanNumber;
                        ViewBag.LoanCode = loan.LoanCode;
                        ViewBag.IsTitleTrack = loan.IsTitleTrack;
                        Session["IsTitleTrack"] = loan.IsTitleTrack;
                        if ((loan.AdvanceFee == 1) || (loan.LotInspectionFee == 1) || (loan.MonthlyLoanFee == 1))
                        {
                            ViewBag.Fee = 1;
                        }
                        else
                        {
                            ViewBag.Fee = 0;
                        }

                        // 
                        Session["loanCode"] = loan.LoanCode;
                        if (userData.RoleId == 3)
                        {

                            if ((loan.Rights.Length > 0) && (loan.Rights != null))
                            {
                                string[] charactors = { };
                                if (loan.Rights != "")
                                {
                                    charactors = loan.Rights.Split(',');
                                }
                                List<string> rightLst = new List<string>(charactors);

                                ViewBag.RightList = rightLst;

                            }


                        }
                        else if ((userData.RoleId == 1) || (userData.RoleId == 2))
                        {
                            ViewBag.AdvanceUnits = 1;
                            ViewBag.AddUnits = 1;
                            ViewBag.ViewReports = 1;
                            ViewBag.PayoffUnits = 1;
                            ViewBag.Curtailment = 1;
                            ViewBag.TitleAdd = 1;
                            ViewBag.PayFees = 1;
                        }


                        //ViewBag.CompType = (new BranchAccess()).getCompanyTypeByUserId(userData.UserId);
                        //ViewBag.CompType
                        Session["oneLoanDashboard"] = loan;
                        return View();
                    }
                    else
                    {
                        return View();
                    }

                }
                else
                {
                    ViewBag.PartnerType = (userData.CompanyType == 1) ? 2 : 1;
                    return View();
                }


            }
            else
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }



        }
        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 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();
            }

        }