/// <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>
        /// Frontend page: Assign rights
        /// Title: Assign new rights for a loan for users and edit rights
        /// Designed : Kasun Samarawickrama
        /// User story: 
        /// Developed: Kasun Samarawickrama
        /// Date created: 
        /// </summary>
        /// <returns></returns>
        public ActionResult AssignRights()
        {
            Session.Remove("popUpSelectionType");
            Loan loan = new Loan();
            // get loan details from session
            if (Session["oneLoanDashboard"] != null)
            {
                loan = (Loan)Session["oneLoanDashboard"];
                //Session.Remove("oneLoanDashboard");
            }
            if (Session["loanDashboardAssignUser"] != null)
            {
                loan = (Loan)Session["loanDashboardAssignUser"];
            }
            //check from submission 
            if (TempData["submit"] != null) {
                if ((string)TempData["submit"] == "success") {
                    ViewBag.SuccessMsg = "User Rights Successfully Updated";
                }
                else if ((string)TempData["submit"] == "failed")
                {
                    ViewBag.ErrorMsg = "Failed To Update User Rights";
                }
            }
            // check loan null or not
            if (Session["oneLoanDashboard"] != null || Session["loanDashboardAssignUser"] != null)
            {
                ViewBag.LoanId = loan.LoanId;
                ViewBag.LoanNumber = loan.LoanNumber;
                UserManageAccess ua = new UserManageAccess();

                // get user list for that branch
                List<User> userList = ua.getUsersByRoleBranch(3, loan.BranchId);
                List<User> tempRoleList = new List<User>();

                // add users to select list for front end 
                for (int i = 0; i < userList.Count; i++)
                {
                    User tempRole = new User()
                    {
                        UserId = userList[i].UserId,
                        UserName = userList[i].UserName
                    };
                    tempRoleList.Add(tempRole);
                }
                ViewBag.userSelectList = tempRoleList;

                User user = new Models.User();
                List<Right> list = new List<Right>();

                user.UserRightsList = new List<Right>();

                // retrive all rights from table
                list = (new UserRightsAccess()).getRights();

                // check title track yes or no.
                if ( loan.IsTitleTrack !=  1)
                {
                    foreach (var x in list)
                    {
                        // title page right
                        if (x.rightId != "U02")
                        {
                            user.UserRightsList.Add(x);
                        }
                    }
                }

                else {
                    user.UserRightsList = list;
                }

                //get all report list
                
                List<Right> ReportRightsList = (new UserRightsAccess()).getReportRights();
                user.ReportRightsList = new List<Right>();
                // filter report rights according to the loan
                if (ReportRightsList != null && ReportRightsList.Count > 0)
                {
                    foreach (Right rgt in ReportRightsList)
                    {
                        //Check dealer user can view the report
                        if (!rgt.UserView)
                        {
                            continue;
                        }
                        else
                        {
                            //check title need not to be tracked for selected loan and report right for Title Status
                            if ((loan.IsTitleTrack == 0) && (rgt.rightId == "R04"))
                            {
                                //if title need not to be tracked report right for Title Status is not added to right list
                                continue;
                            }
                            //check there is no advance fee for selected loan and report right for advance fee invoice and advance fee receipt
                            if ((loan.AdvanceFee == 0) && ((rgt.rightId == "R07") || (rgt.rightId == "R08")))
                            {
                                //if there is no advance fee, report right for advance fee invoice and advance fee receipt are not added to right list
                                continue;
                            }
                            //check there is no monthly loan fee for selected loan and report right for monthly loan fee invoice and monthly loan fee receipt
                            if ((loan.MonthlyLoanFee == 0) && ((rgt.rightId == "R09") || (rgt.rightId == "R10")))
                            {
                                //if there is no monthly loan fee, report right for monthly loan fee invoice and monthly loan fee receipt are not added to right list
                                continue;
                            }
                            //check there is no lot inspection fee for selected loan and report right for lot inspection fee invoice and lot inspection fee receipt
                            if ((loan.LotInspectionFee == 0) && ((rgt.rightId == "R11") || (rgt.rightId == "R12")))
                            {
                                //if there is no lot inspection fee, report right for lot inspection fee invoice and lot inspection fee receipt are not added to right list
                                continue;
                            }
                        }
                        user.ReportRightsList.Add(rgt);
                    }
                }
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(user);
                }
                else
                {
           
                    return View(user);
                }
                //return View();
            }
            else {
            if (HttpContext.Request.IsAjaxRequest())
            {
                ViewBag.AjaxRequest = 1;
                    return RedirectToAction("UserDetails");
            }
            else
            {

                    return RedirectToAction("UserDetails");
                }
            }
        }
        public ActionResult UserList()
        {

            int idval;
            int typeval = 0;

            try
            {
                idval = userData.UserId;

                if ((string)Session["searchType"] == "SuperAdmin")
                {
                    typeval = 1;
                    ViewBag.Manage = "Manage SuperAdmins";
                }
                else if ((string)Session["searchType"] == "Admin")
                {
                    typeval = 2;
                    ViewBag.Manage = "Manage Admins";
                }
                else if ((string)Session["searchType"] == "User")
                {
                    typeval = 3;
                    ViewBag.Manage = "Manage Users";
                }

                UserManageAccess obj1 = new UserManageAccess();
                int role = userData.RoleId;
                if ((typeval > 0) && (idval > 0))
                {

                    var ret = obj1.getUserByType(typeval, idval);
                    ViewBag.noList = ret.Count;
                    return PartialView(ret);
                }
                else
                {
                    return PartialView();
                }
            }
            catch (Exception)
            {
                return RedirectToAction("UserLogin", "Login");
            }


        }
        /// <summary>
        /// CreatedBy : Piyumi
        /// CreatedDate: 2016/01/13
        /// 
        /// Showing details of selected user
        /// 
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult Details()
        {
            int id;
            int logId;

            try
            {
                id = (int)Session["rowId"];
                logId = userData.UserId;
                UserManageAccess obj1 = new UserManageAccess();
                if (id != 0)
                {
                    var ret = obj1.getUserById(id);

                    if (id == logId)
                    {
                        ViewBag.userId = ret.userId;
                        Session["editId"] = id;
                    }
                    else
                    {
                        ViewBag.userId = 0;
                    }
                    return PartialView(ret);
                }
                else { return PartialView(); }
            }
            catch (Exception)
            {
                return RedirectToAction("UserLogin", "Login");
            }



        }
        public ActionResult Step6(string dashbrd)
        {
            //dashbrd = 6;
            int userrole = userData.RoleId;
            int userId = userData.UserId;

            if (userrole >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }

            UserManageAccess uma = new UserManageAccess();

            // check if step is less than 6, not allowed to this page...

            int stepNo = loanData.stepId;


            if (stepNo < 0)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
            else if ((stepNo == 0)&&(dashbrd== "bshdrdoanl"))
            {
                stepNo = 6;
                loanData.stepId = 1;
                Session["dashboard"] = 1;

                // set the loan setup session to step 1

               
                Session["companyStep"] = 5;
                loanData.stepId = 1;
                Session["loanStep"] = loanData;



            }

            if(TempData["error"] != null && TempData["error"].ToString() == "error")
            {
                ViewBag.Error = "Failed to create loan";
            }

            // get the Role Name for front end view
            ViewBag.userroleName = uma.getUserRoleName(userId);

            BranchAccess ba = new BranchAccess();

            // get the Company type for front end view
            int comType = ba.getCompanyTypeByUserId(userId);
            //int comType = userData.CompanyType;
            ViewBag.ThisCompanyType = (comType == 1) ? "Lender" : "Dealer";//

            // retrieve registered branches, nonregistered branches using his company Id

            List<Branch> RegisteredBranchLists = (new BranchAccess()).getBranches(userData.Company_Id);
            List<NonRegBranch> NonRegisteredBranchLists = (new BranchAccess()).getNonRegBranches(userData.Company_Id);

            // get the payments method for front End View
            List<string> paymentMethods = new List<string>();
            paymentMethods.Add("Auto Deduct/Deposit");
            paymentMethods.Add("Invoice/Check");
            ViewBag.paymentMethods = paymentMethods;


            // Defaul loan setup form and default dates
            LoanSetupStep1 loanSetupStep1 = new LoanSetupStep1();
            loanSetupStep1.startDate = DateTime.Today;
            loanSetupStep1.maturityDate = DateTime.Today.AddDays(1);

            // get loan Id for each user
            LoanSetupAccess la = new LoanSetupAccess();
            int loanId = 0;

            if ((userrole == 1) || (userrole == 2))
            {
                loanId = loanData.loanId;
            }

            // if loan number exists get the loan details
            if (loanId > 0)
            {
                loanSetupStep1 = la.GetLoanStepOne(loanId);
            }

            if (userrole == 2)
            {
                // if user is a admin, his branch id is registerd branch id
                loanSetupStep1.RegisteredBranchId = userData.BranchId;

                // the get registered branch detail from the company branches list
                foreach (Branch branch in RegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {
                        var newList = new List<Branch>();
                        newList.Add(branch);
                        ViewBag.RegisteredBranchId = new SelectList(newList, "BranchId", "BranchName", userData.BranchId);
                    }
                }
                var newNonRegList = new List<Branch>();

                // 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)
                    {

                        newNonRegList.Add(branch);


                    }
                }



                ViewBag.NonRegisteredBranchId = new SelectList(newNonRegList, "NonRegBranchId", "CompanyNameBranchName");


            }
            // if he is a super admin, add all company branches and non registered branches in to the list
            else
            {
                // if super admin get the branch id of the loan
                if (loanId > 0)
                {
                    NonRegBranch nonRegBranch = (new BranchAccess()).getNonRegBranchByNonRegBranchId(loanSetupStep1.nonRegisteredBranchId);
                    loanSetupStep1.RegisteredBranchId = nonRegBranch.BranchId;

                }

                // add banches which contain non reg branches only
                List<Branch> newBranches = new List<Branch>();
                foreach (Branch branch in RegisteredBranchLists)
                {
                    foreach (NonRegBranch nonbranch in NonRegisteredBranchLists)
                    {
                        if (branch.BranchId == nonbranch.BranchId)
                        {

                            newBranches.Add(branch);

                            break;
                        }
                    }
                }


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

                if (newBranches.Count >= 1)
                {
                    ViewBag.NonRegisteredBranchId = new SelectList(NonRegisteredBranchLists, "NonRegBranchId", "CompanyNameBranchName");
                }

            }

            if (NonRegisteredBranchLists.Count == 1)
            {   
                if(userData.RoleId == 1)
                {
                    // the get registered branch detail from the company branches list
                    foreach (Branch branch in RegisteredBranchLists)
                    {
                        if (branch.BranchId == NonRegisteredBranchLists[0].BranchId)
                        {
                            var newList = new List<Branch>();
                            newList.Add(branch);
                            ViewBag.RegisteredBranchId = new SelectList(newList, "BranchId", "BranchName", userData.BranchId);
                        }
                    }
                }
                loanSetupStep1.nonRegisteredBranchId = NonRegisteredBranchLists[0].NonRegBranchId;
            }

            loanSetupStep1.allUnitTypes = (new LoanSetupAccess()).getAllUnitTypes();

            if (loanId > 0)
            {

                loanSetupStep1.allUnitTypes = (new LoanSetupAccess()).getAllUnitTypes();
                //(new LoanSetupAccess()).getSelectedUnitTypes(loanId, loanSetupStep1);
                foreach (UnitType unitType in (List<UnitType>)loanSetupStep1.selectedUnitTypes)
                {
                    foreach (UnitType allUnitType in (List<UnitType>)loanSetupStep1.allUnitTypes)
                    {
                        if (allUnitType.unitTypeId == unitType.unitTypeId)
                        {
                            allUnitType.isSelected = true;
                            continue;
                        }
                    }

                }


            }



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

                return View(loanSetupStep1);
            }
        }
        public ActionResult Step5(NonRegCompanyBranchModel nonRegCompanyBranch, string branchCode)
        {
            
            CompanyBranchModel nonRegBranch = nonRegCompanyBranch.CompanyBranch;

            int userId = userData.UserId;
           
            BranchAccess ba = new BranchAccess();
            CompanyAccess ca = new CompanyAccess();

            int compType = ba.getCompanyTypeByUserId(userId);

            nonRegBranch.MainBranch.StateId = nonRegCompanyBranch.StateId;

            nonRegBranch.MainBranch.BranchCode = branchCode;
            Company company = new Company();
            //check partner branch code is null
            if (string.IsNullOrEmpty(branchCode))
            {
                //get partner company details
               company = ca.GetNonRegCompanyByCompanyId(nonRegCompanyBranch.NonRegCompanyId);
               
            }

            nonRegBranch.MainBranch = nonRegBranch.MainBranch;

            //Get created branch id
            UserManageAccess uma = new UserManageAccess();
            
            nonRegBranch.MainBranch.BranchCreatedBy = nonRegCompanyBranch.RegBranchId;
            nonRegBranch.MainBranch.BranchCompany = nonRegCompanyBranch.NonRegCompanyId;

            //Set admin branch to new user 
            if (userData.RoleId == 2)
            {
                nonRegBranch.MainBranch.BranchCreatedBy = userData.BranchId;
            }
            //insert or update partner branch details
            int reslt = ba.insertNonRegBranchDetails(nonRegBranch, userId, company.CompanyCode);
            //check result is greater than 0
            if (reslt > 0)
            {
                StepAccess sa = new StepAccess();
                bool reslt2 = false;
                //check user is admin
                if(userData.RoleId == 2)
                {
                    //update company setup and insert a record to loan setup step
                    reslt2 = sa.UpdateLoanSetupStep(userData.UserId,userData.Company_Id, userData.BranchId, reslt, 0, 1);
                }
                //check user is super admin
                else if(userData.RoleId == 1)
                {
                    //update company setup and insert a record to loan setup step
                    reslt2 = sa.UpdateLoanSetupStep(userData.UserId,userData.Company_Id, nonRegCompanyBranch.RegBranchId, reslt, 0, 1);
                }
                //check update result
                if (reslt2)
                {
                   //if lender company
                    if (compType == 1)
                    {
                        ViewBag.SuccessMsg = "Dealer branch is successfully created";
                    }
                    //if dealer company
                    else if (compType == 2)
                    {
                        ViewBag.SuccessMsg = "Lender branch is successfully created";
                    }
                    //----------------
                    //check loan step is less than 1
                    if(loanData.stepId<1)
                    {
                        //update loan step and assign to session
                        loanData.stepId = 1;
                        Session["loanStep"] = loanData;
                    }
                   
                    //------------------------
                    //check user's step status is 1 or 2
                    if((userData.step_status==1)|| (userData.step_status == 2)) {
                        //return to step5
                        return RedirectToAction("Step5", new { lbls = ViewBag.SuccessMsg });
                    }
                    //check user's step status is 0
                    else if (userData.step_status == 0) {
                        //return loan step 1
                        return RedirectToAction("Step6");
                    }
                   
                }

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

            //Get states to list
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");
            //return PartialView();
            //check ajax request
            if (HttpContext.Request.IsAjaxRequest())
            {
                ViewBag.AjaxRequest = 1;
                return PartialView(nonRegCompanyBranch);
            }
            else
            {

                return View(nonRegCompanyBranch);
            }

        }
        public ActionResult SetRights(IList<Right> rightList)
        {

            List<string> returnIntArray = new List<string>();

            for (int i = 0; i < rightList.Count;)
            {
                if (rightList[i].active == false)
                {
                    returnIntArray.Add(rightList[i].rightId);
                }
                i++;
            }
            var resultRightIdString = string.Join(",", returnIntArray);

            var returnRight = new Right();

            returnRight.userId = rightList[0].userId;
            returnRight.editorId = rightList[0].editorId;



            UserManageAccess uma = new UserManageAccess();
            // not allow to edit rights for admin and superadmin... not allow user to use this page
            if (uma.getUserRole(returnRight.userId) < 3 || uma.getUserRole(returnRight.editorId) == 3)
            {
                return new HttpStatusCodeResult(404);
            }
            returnRight.rightsPermissionString = resultRightIdString;

            var returnAccess = new UserRightsAccess();

            if (returnAccess.postNewRights(returnRight))
            {
                ViewBag.SuccessMsg = "Succesfully Updated";
                return RedirectToAction("SetRights", "EditRights", new { lbl1 = ViewBag.SuccessMsg });
            }
            else
            {
                ViewBag.ErrorMsg = "Sorry, rights can't update";
                return RedirectToAction("SetRights", "EditRights", new { lbl2 = ViewBag.ErrorMsg });
            }
        }
        /// <summary>
        /// CreatedBy : Kasun Samarawickrama
        /// CreatedDate: 2016/01/16
        /// Updated by   : kasun Samarawickrama
        /// Updated Date : 2016/01/18
        /// 
        /// Edit User Rights
        /// </summary>
        /// <returns></returns>
        public ActionResult SetRights(string lbl1, string lbl2)
        {
            ViewBag.login = false;
            if (lbl1 != null)
            {
                ViewBag.SuccessMsg = lbl1;
            }
            else if (lbl2 != null)
            {
                ViewBag.ErrorMsg = lbl2;
            }
            else
            {
                ViewBag.SuccessMsg = "";
                ViewBag.ErrorMsg = "";
            }
            if (Session["userId"] == null)
            {
                return RedirectToAction("UserLogin", "Login");
            }
            if (Session["editUserIds"] == null)
            {
                return RedirectToAction("Create", "CreateUser");
            }
            int userId = (int)Session["userId"];
            int ownerId = (int)Session["editUserIds"];

            UserManageAccess uma = new UserManageAccess();
            // not allow to edit rights for admin and superadmin... not allow user to use this page
            if (uma.getUserRole(ownerId) < 3 || uma.getUserRole(userId) == 3)
            {
                return new HttpStatusCodeResult(404);
            }

            if (userId > 0)
            {
                var access = new UserRightsAccess();

                ///retrive all rights
                List<Right> rights = access.getRights();

                ///get permission string for the relevent user
                List<Right> permissionString = access.getRightsString(ownerId,0);

                if (permissionString.Count == 1)
                {


                    string permission = permissionString[0].rightsPermissionString;
                    if (permission != "")
                    {
                        string[] charactors = permission.Split(',');

                        List<string> intArray = new List<string>();

                        foreach (var charactor in charactors)
                        {
                            intArray.Add(charactor);
                        }
                        foreach (var obj in rights)
                        {
                            obj.active = true;
                        }
                        foreach (var chr in intArray)
                        {
                            foreach (var obj in rights)
                            {
                                if (string.Compare(obj.rightId, chr) == 0)
                                {
                                    obj.active = false;
                                }
                                obj.editorId = userId;
                                obj.userId = ownerId;

                            }
                        }
                    }
                    else
                    {
                        foreach (var obj in rights)
                        {

                            obj.editorId = userId;
                            obj.userId = ownerId;

                        }

                    }

                }

                else if (permissionString.Count == 0)
                {
                    foreach (var obj in rights)
                    {

                        obj.editorId = userId;
                        obj.userId = ownerId;

                    }

                }
                else
                {
                    return RedirectToAction("Create", "CreateUser");
                }
                ViewBag.userId = userId;
                ViewBag.ownerId = ownerId;

                return PartialView(rights);
            }
            else
            {
                return RedirectToAction("Create", "CreateUser");
            }
        }