public ActionResult CreateBranchPost(Branch branch)
        {
            ViewBag.Type = "";

            int id = userData.UserId;
            //branch.StateId = branch.StateId2;
            BranchAccess br = new BranchAccess();
            //int reslt = br.insertBranchDetails(branch, id);
            int reslt = 0;
            CompanyAccess ca = new CompanyAccess();
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");

            if (reslt>0)
            {
                ViewBag.SuccessMsg = "Branch is successfully added";
                return RedirectToAction("CreateBranch", "CreateBranch", new {success = 1 });
                //branch = new Branch();
                //return PartialView(branch);
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to add branch";
                return PartialView();
            }
        }
        public ActionResult CreateDashboardBranch(CompanyBranchModel userCompany2, string branchCode)
        {
            CompanyAccess userCompany = new CompanyAccess();
            
            int userId = userData.UserId;

            userCompany2.Company = userCompany.GetCompanyDetailsCompanyId(userData.Company_Id);
            userCompany2.MainBranch.StateId = userCompany2.StateId;
            userCompany2.MainBranch.BranchCode = branchCode;

            BranchAccess ba = new BranchAccess();
            //Insert record for Branch Table
            int reslt = ba.insertFirstBranchDetails(userCompany2, userId);

            //Create new record for company Step Table
            StepAccess sa = new StepAccess();
            sa.UpdateCompanySetupStep(userData.Company_Id, reslt, 3);

            if (reslt > 0)
            {
                TempData["createBranchResult"] = 1;
            }
            else
            {
                TempData["createBranchResult"] = 0;
            }

            return RedirectToAction("CreateDashboardBranch");
            
        }
        /// <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();
        }
        /*

        Frontend page   : Add Unit 
        Title           : Add or Advance Units
        Designed        : Kasun Samarawickrama
        User story      : 
        Developed       : Kasun Samarawickrama
        Date created    : 02/24/2016

        */
        public ActionResult AddUnit()
        {
            // Handle Record successfully update or Error message

            int Flag = 0;
            if (TempData["Msg"] != null)
            {
                Flag = int.Parse(TempData["Msg"].ToString());
                if (Flag == 1)
                {
                    ViewBag.Msg = "Success";
                }
                else if (Flag == 3)
                {
                    ViewBag.Msg = "Requested";
                }
                else if (Flag == 2)
                {
                    ViewBag.Msg = "Error";
                }
            }
           

            int userId = userData.UserId;
            ViewBag.Role = userData.RoleId; ;

            //Check loan is null or not
            if (Session["loanCode"] == null || Session["loanCode"].ToString() == "")
                return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });

            // for role id3 - user section
            if (userData.RoleId == 3)
            {
                // check user has rights to access this loan - if not redirect to dashboard
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    var checkAdvance = false;

                    // check user permission to the site
                    string rgts = "";
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList =null;
                    //spit the permission string
                    if (rgts != "") {
                        rgtList = rgts.Split(',');
                    }
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            //check user have rights to add unit page
                            if (x == "U04")
                            {
                                checkPermission = true;
                            }
                            // check user have right to advance units in this page
                            if (x == "U01")
                            {
                                checkAdvance = true;
                            }
                        }
                        if (checkAdvance == true)
                        {
                            ViewBag.advanceAllow = true;
                        }
                        else {
                            ViewBag.advanceAllow = false;
                        }
                        if (checkPermission == false)
                        {
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        return RedirectToAction("UserDetails", "UserManagement");
                    }
                    
                }
            }
            string loanCode = Session["loanCode"].ToString();
            // retrive loan details
            LoanSetupStep1 loan = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);

            int loanId = loan.loanId;
            Session["addUnitloan"] = loan;


            ViewBag.loanDetails = loan;
            //set default unit type for add unit page
            if (loan.selectedUnitTypes.Count == 1) {
                ViewBag.UnitTypeId = loan.selectedUnitTypes[0].unitTypeName;
            }

            Models.Unit unit = new Models.Unit();

            unit.AdvancePt = loan.advancePercentage;
            unit.LoanId = loanId;
            unit.LoanAmount = loan.loanAmount;
            unit.AdvanceDate = DateTime.Now;
            unit.StartDate = loan.startDate;
            unit.EndDate = loan.maturityDate;

            //get company type
            //1 - Lender
            //2 - Dealer
            BranchAccess ba = new BranchAccess();
            int companyType = ba.getCompanyTypeByUserId(userId);

            ViewBag.CompabyType = companyType;
            ViewBag.RoleId = userData.RoleId;

            //Check title 
            TitleAccess ta = new TitleAccess();
            Title title = ta.getTitleDetails(loan.loanId);
            // check title track allow or not
            if (title != null)
            {
                bool isTitleTrack = title.IsTitleTrack;
                if (isTitleTrack)
                    ViewBag.IsTitleTrack = "Yes";

                string upload = title.TitleAcceptMethod;
                if (!string.IsNullOrEmpty(upload) && upload == "Scanned Title Adequate")
                    ViewBag.Upload = "Yes";

            }
            // loan Details for (loan Detail box) in the page 
            UnitAccess ua = new UnitAccess();
            LoanPaymentDetails loanPaymentDetails = ua.GetLoanPaymentDetailsByLoanId(loanId);

            unit.Balance = loanPaymentDetails.BalanceAmount;
            // check balane field is editable or not for this loan
            ViewBag.Editable = loan.isEditAllowable ? "Yes" : "No";

            
            //set user role to restrict add & advance unit if this user is dealer user(role id = 4)
            ViewBag.RoleId = userData.RoleId; 

            return PartialView(unit);
        }
        public ActionResult EditPartnerBranchAtDashboard(EditPartnerBranceModel model, string branchCode)
        {
            if (userData.RoleId != 1 && userData.RoleId != 2)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }

            CompanyBranchModel nonRegBranch = model.CompanyBranch;

            nonRegBranch.MainBranch.StateId = model.StateId;
            nonRegBranch.MainBranch.BranchCode = branchCode;

            nonRegBranch.MainBranch.BranchCreatedBy = model.RegBranchId;
            nonRegBranch.MainBranch.BranchCompany = model.NonRegCompanyId;

            BranchAccess ba = new BranchAccess();
            int reslt = ba.insertNonRegBranchDetails(nonRegBranch, userData.UserId);

            if (reslt > 0)
            {
                if (_compType == 1)
                {
                    ViewBag.SuccessMsg = "Dealer branch is successfully updated";
                }
                else if (_compType == 2)
                {
                    ViewBag.SuccessMsg = "Lender branch is successfully updated";
                }
                if (Session["loanDashboard"] != null)
                {
                    if (((Loan)Session["loanDashboard"]).NonRegBranchId == model.CompanyBranch.MainBranch.NonRegBranchId)
                    {
                        ((Loan)Session["loanDashboard"]).PartnerName = model.NonRegCompanyName+" - "+model.CompanyBranch.MainBranch.BranchName;
                    }
                }
                else if (Session["LoanOne"] != null)
                {
                    if (((Loan)Session["LoanOne"]).NonRegBranchId == model.CompanyBranch.MainBranch.NonRegBranchId)
                    {
                        ((Loan)Session["LoanOne"]).PartnerName = model.NonRegCompanyName + " - " + model.CompanyBranch.MainBranch.BranchName;
                    }
                }
                return RedirectToAction("EditPartnerBranchAtDashboard", new { lbls = ViewBag.SuccessMsg });
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to update";
                return RedirectToAction("EditPartnerBranchAtDashboard", new { lbls = ViewBag.ErrorMsg });
            }
        }
        public ActionResult Step2(CompanyBranchModel userCompany2)
        {
            int userId = (int)Session["userId"];
            //int userId = 68;

            BranchAccess ba = new BranchAccess();
            userCompany2.MainBranch.StateId = userCompany2.StateId;
            userCompany2.MainBranch.BranchCode = ba.createBranchCode(userCompany.Company.CompanyCode);
            userCompany.MainBranch = userCompany2.MainBranch;
            int reslt = ba.insertFirstBranchDetails(userCompany, userId);
            if (reslt>0)
            {
                StepAccess sa = new StepAccess();
                if (sa.updateStepNumberByUserId(userId, 3))
                {
                    bool reslt2 = ba.updateUserBranchId(userCompany2, userId);
                    if (reslt2)
                    {
                        return RedirectToAction("Step3");
                    }
                }
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to create first branch";
            }
            return View();
        }
        public ActionResult Step2(string edit1,int? edit)
        {
          
            int userId = userData.UserId;
            int roleId = userData.RoleId;
            // check he is a super admin or admin

            if (roleId != 1)
            {
                //if not a super admin return to login page
                return RedirectToAction("UserLogin", "Login");
            }
            //check insert or update result of branch setup is >0
            if (TempData["Step2Reslt"] != null && int.Parse(TempData["Step2Reslt"].ToString())>0)
            {
                ViewBag.SuccessMsg = "Branch Successfully Created";
            }
            //check insert or update result of branch setup is 0
            else if (TempData["Step2Reslt"] != null && int.Parse(TempData["Step2Reslt"].ToString()) == 0)
            {
                ViewBag.SuccessMsg = "Branch Successfully Updated";
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to Create Branch";
            }
            //convert Session["companyStep"] to integer     
                int reslt = Convert.ToInt32(Session["companyStep"]);
           //check step is greater  than or equal to 2
            if (reslt >= 2)
            {
                CompanyBranchModel userCompany = new CompanyBranchModel();
                //check TempData["Company"] is not null and not empty
                if ((TempData["Company"] != null) && (TempData["Company"].ToString() != ""))
                {
                    //convert TempData["Company"] to object
                    userCompany = (CompanyBranchModel)TempData["Company"];
                    //check zip extension is null
                    if (userCompany.Company.Extension == null)
                        //assign empty string to extension
                        userCompany.Company.Extension = "";
                }

                userCompany.MainBranch = new Branch();
                ViewBag.BranchIndex = 0;

                //Get company details by company id
                CompanyAccess ca = new CompanyAccess();
                Company preCompany = ca.GetCompanyDetailsCompanyId(userData.Company_Id);


                userCompany.Company = preCompany;

                BranchAccess ba = new BranchAccess();
                IList<Branch> branches = ba.getBranchesByCompanyCode(preCompany.CompanyCode);
                userCompany.SubBranches = branches;

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

                    return View(userCompany);
                }


            }
            else
            {
                //if company step is less than 2 return to login page with error message
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }
        }
        public ActionResult CreatePartnerBranchAtDashboard(EditPartnerBranceModel model)
        {
            if (userData.RoleId != 1 && userData.RoleId != 2)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }

            CompanyBranchModel nonRegBranch = model.CompanyBranch;

            nonRegBranch.MainBranch.StateId = model.StateId;

            nonRegBranch.MainBranch.BranchCreatedBy = model.RegBranchId;
            nonRegBranch.MainBranch.BranchCompany = model.NonRegCompanyId;

            CompanyAccess ca = new CompanyAccess();
            BranchAccess ba = new BranchAccess();
            Company company = ca.GetNonRegCompanyByCompanyId(model.NonRegCompanyId);
            //nonRegBranch.MainBranch.BranchCode = ba.createNonRegBranchCode(company.CompanyCode);

            
            int reslt = ba.insertNonRegBranchDetails(nonRegBranch, userData.UserId, company.CompanyCode);

            if (reslt > 0)
            {
                //update Companay Step States in incomplete Branches continued in dashboard
                StepAccess sa = new StepAccess();
                sa.UpdateLoanSetupStep(userData.UserId, userData.Company_Id, model.RegBranchId, reslt, 0, 1);

                if (_compType == 1)
                {
                    ViewBag.SuccessMsg = "Dealer branch is successfully inserted";
                }
                else if (_compType == 2)
                {
                    ViewBag.SuccessMsg = "Lender branch is successfully inserted";
                }

                return RedirectToAction("CreatePartnerBranchAtDashboard", new { lbls = ViewBag.SuccessMsg });
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to udate";
                return RedirectToAction("CreatePartnerBranchAtDashboard", new { lbls = ViewBag.ErrorMsg });
            }
        }
        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 Step8()
        {

            var userId = userData.UserId;

            BranchAccess branch = new BranchAccess();
            //check user is user or dealer user
            if (userData.RoleId >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
            //get company type
            int companyType = branch.getCompanyTypeByUserId(userId);
            //check lender company
            if (companyType == 1)
            {
                ViewBag.isLender = true;
            }
            //check dealer company
            else
            {
                ViewBag.isLender = false;
            }
            Fees fee = new Fees();
            LoanSetupAccess loan = new LoanSetupAccess();
           
            fee.LoanId = loanData.loanId;
            //check insert or update
            if (loanData.stepId > 3)
            {
                ViewBag.isEdit = "editable";
                //get fee details
                var hasLoan = loan.checkLoanIsInFeesTables(fee.LoanId);
                //check advance amount
                if (hasLoan.AdvanceAmount == 0)
                {
                    hasLoan.AdvanceId = "2";
                }
                else {
                    hasLoan.AdvanceId = "1";
                }
                if (hasLoan.MonthlyLoanAmount == 0)
                {
                    hasLoan.MonthlyLoanId = "2";
                }
                else {
                    hasLoan.MonthlyLoanId = "1";
                }
                if (hasLoan.LotInspectionAmount == 0)
                {
                    hasLoan.LotInspectionId = "2";
                }
                else {
                    hasLoan.LotInspectionId = "1";
                }

                if (hasLoan.AdvanceAmount > 0 || hasLoan.MonthlyLoanAmount > 0 || hasLoan.LotInspectionAmount > 0)
                {
                    hasLoan.LoanId = fee.LoanId;
                    hasLoan.isEdit = true;
                    //hasLoan.IsAdvanceFeeCompleteEmailReminder = false;
                    //hasLoan.IsLoanFeeCompleteEmailReminder = false;
                    //hasLoan.IsLotFeeCompleteEmailReminder = false;
                    hasLoan.IsAdvanceFeeDueEmailReminder = false;
                    hasLoan.IsLoanFeeDueEmailReminder = false;
                    hasLoan.IsLotFeeDueEmailReminder = false;

                    //if (hasLoan.AdvanceFeeDealerEmail != "")
                    //{
                    //    hasLoan.IsAdvanceFeeCompleteEmailReminder = true;
                    //}
                    //if (hasLoan.MonthlyLoanFeeDealerEmail != "")
                    //{
                    //    hasLoan.IsLoanFeeCompleteEmailReminder = true;
                    //}
                    //if (hasLoan.LotInspectionFeeDealerEmail != "")
                    //{
                    //    hasLoan.IsLotFeeCompleteEmailReminder = true;
                    //}
                    if (hasLoan.AdvanceDueEmail != "")
                    {
                        hasLoan.IsAdvanceFeeDueEmailReminder = true;
                    }
                    if (hasLoan.MonthlyLoanDueEmail != "")
                    {
                        hasLoan.IsLoanFeeDueEmailReminder = true;
                    }
                    if (hasLoan.LotInspectionDueEmail != "")
                    {
                        hasLoan.IsLotFeeDueEmailReminder = true;
                    }
                }

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

                    return View(hasLoan);
                }
            }
            else
            {
                ViewBag.isEdit = "notEditable";

                Fees feeNew = new Fees();
                feeNew.LoanId = fee.LoanId;

                if (feeNew.LoanId > 0)
                {
                    feeNew.isEdit = false;
                    var email = loan.getAutoRemindEmailByLoanId(feeNew.LoanId);
                    if (email != null)
                    {
                        feeNew.AdvanceDueEmail = email;
                        feeNew.MonthlyLoanDueEmail = email;
                        feeNew.LotInspectionDueEmail = email;
                    }
                    //feeNew.IsAdvanceFeeCompleteEmailReminder = false;
                    //feeNew.IsLotFeeCompleteEmailReminder = false;
                    //feeNew.IsLoanFeeCompleteEmailReminder = false;
                    feeNew.IsAdvanceFeeDueEmailReminder = false;
                    feeNew.IsLotFeeDueEmailReminder = false;
                    feeNew.IsLoanFeeDueEmailReminder = false;

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

                        return View(feeNew);
                    }

                }
                else
                {
                    return RedirectToAction("Step7");
                }
            }

        }
        public ActionResult Step5(string lbls)
         {
            int userId = userData.UserId;
            BranchAccess ba = new BranchAccess();
            //get company type
            int compType = ba.getCompanyTypeByUserId(userId);
            //if lender company
            if (compType == 1)
            {
                ViewBag.ThisCompanyType = "Dealer";
            }
            //if dealer company
            else if (compType == 2)
            {
                ViewBag.ThisCompanyType = "Lender";
            }
            else
            {
                ViewBag.compType = "";
            }
            StepAccess cs = new StepAccess();
            //convert session to integer
            int stepNo = Convert.ToInt32(Session["companyStep"]);
            //check step is less than 0
            if (stepNo < 0)
            {
                stepNo = Convert.ToInt32(Session["companyStep"]);
            }
            //check step is less than 5 and return to login page
            if (stepNo < 5) return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            //check result of insert or update
            if (lbls != null && (lbls.Equals("Dealer branch is successfully created") || lbls.Equals("Lender branch is successfully created")))
            {
                ViewBag.SuccessMsg = lbls;
               //check ajax request
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView();
                }
                else
                {

                    return View();
                }
            }

            CompanyBranchModel userNonRegCompany = new CompanyBranchModel();
            //check TempData["NonRegCompany"] (partner company ) is not null and empty
            if ((TempData["NonRegCompany"] != null) && (TempData["NonRegCompany"].ToString() != ""))
            {
                //convert to model object 
                userNonRegCompany = (CompanyBranchModel)TempData["NonRegCompany"];
                userNonRegCompany.MainBranch = new Branch();
                //check extension is null
                if (userNonRegCompany.Company.Extension == null)
                    userNonRegCompany.Company.Extension = "";
            }


            ViewBag.CurrUserRoleType = userData.RoleId;

            //Get states to list
            CompanyAccess ca = new CompanyAccess();
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");

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

            //Get all non reg companies
            List<Company> nonRegCompanyList = ca.GetCompanyByCreayedCompany(userData.Company_Id);
            ViewBag.NonRegCompanyId = new SelectList(nonRegCompanyList, "CompanyId", "CompanyName", 1);

            NonRegCompanyBranchModel nonRegCompanyBranch = new NonRegCompanyBranchModel();
            nonRegCompanyBranch.CompanyBranch = new CompanyBranchModel();
            nonRegCompanyBranch.CompanyBranch.Company = new Company();
            nonRegCompanyBranch.NonRegCompany= new Company();
            //Get all non registered branches by company id
            List<NonRegBranch> nonRegBranches = ba.getNonRegBranches(userData.Company_Id);
            nonRegCompanyBranch.NonRegBranches = nonRegBranches;
            if ((TempData["NonRegCompany"] != null) && (TempData["NonRegCompany"].ToString() != ""))
            {
                nonRegCompanyBranch.CompanyBranch.Company = userNonRegCompany.Company;
            }
            else {
                nonRegCompanyBranch.CompanyBranch.Company = nonRegCompanyList[0];
            }
            //check partner company list is not null
            if (nonRegCompanyList != null)
            {
                //check if one partner company and assign that company id
                if (nonRegCompanyList.Count() == 1)
                {
                    nonRegCompanyBranch.NonRegCompany.CompanyId = nonRegCompanyList[0].CompanyId;
                }
            }
            //check user is not admin
            if (userData.RoleId != 2)
            {
                //check ajax request
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(nonRegCompanyBranch);
                }
                else
                {

                    return View(nonRegCompanyBranch);
                }

            }
            //Select non registered branch for admin's branch
           
            if (nonRegBranches != null) {
                var adminBonRegBranches = new List<NonRegBranch>();
                adminBonRegBranches.AddRange(nonRegBranches.Where(t => userData.BranchId == t.BranchId));
                nonRegCompanyBranch.NonRegBranches = adminBonRegBranches;
            }

            //check ajax request
            if (HttpContext.Request.IsAjaxRequest())
            {
                ViewBag.AjaxRequest = 1;
                return PartialView(nonRegCompanyBranch);
            }
            else
            {

                return View(nonRegCompanyBranch);
            }
        }
        public ActionResult Step4()
        {
           
            StepAccess sa = new StepAccess();
            //convert session to integer
            int stepNo = Convert.ToInt32(Session["companyStep"]);
            //check company step is 3
            if (stepNo == 3)
            {
                //update company set up step to 4
                if (sa.UpdateCompanySetupStep(userData.Company_Id, userData.BranchId, 4))
                {
                    //check Session["companyStep"] value is less than 4 
                    if (Convert.ToInt32(Session["companyStep"].ToString()) < 4)
                    {
                        //update Session["companyStep"] to 4
                        Session["companyStep"] = 4;
                    }

                    
                }
                stepNo = Convert.ToInt32(Session["companyStep"]);
            }
            
            //check company step is equal or greater than 3
            if (stepNo >= 3)
            {
                BranchAccess ba = new BranchAccess();
                //get company type
               int comType = ba.getCompanyTypeByUserId(userData.UserId);
                //set partner company type
                //company type 1-lender,company type 2 - dealer
                ViewBag.ThisCompanyType = (comType == 1) ? "Dealer" : "Lender";

                //Get states to list
                CompanyAccess ca = new CompanyAccess();
                List<State> stateList = ca.GetAllStates();
                ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");
                //get partner companies
                List<Company> nonRegCompanies = ca.GetCompanyByCreayedCompany(userData.Company_Id);//regCompany.CompanyId   asanka

                CompanyViewModel companyViewModel = new CompanyViewModel();
                companyViewModel.Companies = nonRegCompanies;
                //check ajax request
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(companyViewModel);
                }
                else
                {

                    return View(companyViewModel);
                }

            }
            //is company step is less than 3 return to login page
            return RedirectToAction("UserLogin", "Login");
          
        }
        /*
        Frontend page: Update Titles
        Title: Return View of Update Titles page
        Designed: Piyumi
        User story:
        Developed: Piyumi
        Date created: 03/17/2016
        */
        public ActionResult TitleStatusUpdate()
        {
            //Check Session["IsTitleTrack"] is not null and value is 0
            if (Session["IsTitleTrack"] !=null && int.Parse(Session["IsTitleTrack"].ToString()) == 0)
            {
                //return to dashboard if title doesnot need to be tracked
                return RedirectToAction("UserDetails", "UserManagement");
            }
            //user role 3 - user
            else if (userData.RoleId == 3)
            {
                //Check Session["CurrentLoanRights"] is not null or empty
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    //return to dashboard if Session["CurrentLoanRights"] is null or empty
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    string rgts = "";
                    //convert Session["CurrentLoanRights"] to string
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList = null;
                    //Check string is not empty
                    if (rgts != "")
                    {
                        //split right string and insert to a list
                        rgtList = rgts.Split(',');
                    }
                    //Check list is not null
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            //Check right list contains the relevant right which represent Update Titles page
                            if (x == "U02")
                            {
                                checkPermission = true;
                            }
                        }
                        //Check user is given permission to Update Titles page
                        if (checkPermission == false)
                        {
                            //if no permission to Update Titles page return to dashboard
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        //if right list is null return to dashboard
                        return RedirectToAction("UserDetails", "UserManagement");
                    }

                }
            }
            //user role 4 - dealer user
            else if (userData.RoleId == 4)
            {
                //if dealer user return to dashboard
                return RedirectToAction("UserDetails", "UserManagement");
            }
            TitleStatus obj2 = new TitleStatus();
            obj2.TitleList = new List<Models.Unit>();
            int compType = 0;
            
            //get company type by company id
            if (userData.UserId > 0)
            {
                BranchAccess obj1 = new BranchAccess();
                compType = obj1.getCompanyTypeByUserId(userData.UserId);
            }
            //Check company type is greater than 0
            if (compType > 0)
            {
                //assign company type to viewbag variable
                ViewBag.CompanyType = compType;
            }
            int flag = -1;

            //Check result after updating title status
            if ((TempData["reslt"] !=null)&& (TempData["reslt"].ToString() != ""))
            {
                //assign result value to a variable
                flag = int.Parse(TempData["reslt"].ToString());
                //Check value of result
                if (flag == 1)
                {
                    ViewBag.Msg = "Success";
                }
                else if (flag == 0)
                {
                    ViewBag.Msg = "Error";
                }
                //return TitleStatus model object to view
                return View(obj2);
            }
            else
            {
                //return TitleStatus model object to view
                return View(obj2);
            }
            
           
        }
        public ActionResult EditDashboardBranch()
        {
            CompanyBranchModel userCompany;

            //edit = 3;
            int userId = userData.UserId;
            int roleId = userData.RoleId;
            // check he is a super admin or admin


            if (roleId != 1)
            {
                return RedirectToAction("UserLogin", "Login");
            }

            if (TempData["editBranchResult"] != null)
            {
                if (int.Parse(TempData["editBranchResult"].ToString()) == 1)
                {
                    ViewBag.SuccessMsg = "Branch is successfully updated";
                }

                else if (int.Parse(TempData["editBranchResult"].ToString()) == 0)
                {
                    ViewBag.ErrorMsg = "Failed To Update Branch";
                }
            }

            userCompany = new CompanyBranchModel();

            ViewBag.BranchIndex = 0;

            //Get company details by company id
            CompanyAccess ca = new CompanyAccess();
            Company preCompany = ca.GetCompanyDetailsCompanyId(userData.Company_Id);

            BranchAccess ba = new BranchAccess();
            IList<Branch> branches = ba.getBranchesByCompanyCode(preCompany.CompanyCode);
            userCompany.SubBranches = branches;

            //Get states to list
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");

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

                return View(userCompany);
            }
        }
        public ActionResult Step2(CompanyBranchModel userCompany2, string branchCode)
        {
            //assign logged user's user id to variable
            int userId = userData.UserId;
            //check Session["companyStep"] is null
            if (Session["companyStep"] == null)
            {
                //check ajax request
                if (HttpContext.Request.IsAjaxRequest())
                {
                    //return to login page with error message
                    return new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
                }
                else
                {
                    //return to login page with error message
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            //assign selected state id to branch object property
            userCompany2.MainBranch.StateId = userCompany2.StateId;
            //assign branch code to branch object property
            userCompany2.MainBranch.BranchCode = branchCode;

            BranchAccess ba = new BranchAccess();

            userCompany2.Company = new Company();
            //check company code of userdata object is not null
            if (!string.IsNullOrEmpty(userData.CompanyCode))
            {
                //assign company code of userdata to company object company code
                userCompany2.Company.CompanyCode = userData.CompanyCode;
            }
            else
            {
                //get company details
                Company cmp = new Company();
                cmp = (new CompanyAccess()).GetCompanyDetailsCompanyId(userData.Company_Id);
                //assign retrieved company code to company object company code
                userCompany2.Company.CompanyCode = cmp.CompanyCode ;
            }
            //insert branch details
            int reslt = ba.insertFirstBranchDetails(userCompany2, userId);
            //check inserted or updated result is not 0
            if (reslt >= 0)
            {
                //assign result to a TempData object
                TempData["Step2Reslt"] = reslt;
                //check current value of company setup is less than 3
                if(Convert.ToInt32(Session["companyStep"].ToString()) < 3){ 
                    //assign 3 for Session["companyStep"]
                Session["companyStep"] = 3;
                }

                //user object pass to session
                if (userData.BranchId == 0)
                {
                    userData.BranchId = reslt;
                }
                
                Session["AuthenticatedUser"] = userData;

                StepAccess sa = new StepAccess();
                //update company setup step table check result
                if (sa.UpdateCompanySetupStep(userData.Company_Id, reslt, 3))
                {
                    //return to branch setup page
                    return RedirectToAction("Step2");

                }
            }
            else
            {
                //if update or insert result is less than to 0 assign 0 to TempData object
                TempData["Step2Reslt"] = 0;
                return RedirectToAction("UserLogin", "Login", new { lbl = "Failed to set up branch" });
                
            }

            ViewBag.BranchIndex = 0;

            //Get company details by user id
            userId = userData.UserId;

            // need common method for that - asanka

            CompanyAccess ca = new CompanyAccess();
            Company preCompany = ca.GetCompanyDetailsCompanyId(userData.Company_Id);

            IList<Branch> branches = ba.getBranchesByCompanyCode(preCompany.CompanyCode);

            //Get states to list
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");


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

        }
        public ActionResult EditDashboardBranch(CompanyBranchModel userCompany2, string branchCode)
        {
            CompanyAccess userCompany = new CompanyAccess();

            int userId = userData.UserId;

            userCompany2.Company = userCompany.GetCompanyDetailsCompanyId(userData.Company_Id);
            userCompany2.MainBranch.StateId = userCompany2.StateId;
            userCompany2.MainBranch.BranchCode = branchCode;

            BranchAccess ba = new BranchAccess();
            if (string.IsNullOrEmpty(branchCode))
            {
                userCompany2.MainBranch.BranchCode = ba.createBranchCode(userCompany2.Company.CompanyCode);
            }

            int reslt = ba.insertFirstBranchDetails(userCompany2, userId);
            if (reslt == 0)
            {
                TempData["editBranchResult"] = 1;

                if (Session["loanDashboard"] != null)
                {
                    if (((Loan)Session["loanDashboard"]).BranchId == userCompany2.MainBranch.BranchId)
                    {
                        ((Loan)Session["loanDashboard"]).BranchName = userCompany2.MainBranch.BranchName;
                    }
                }
            }
            else
            {
                TempData["editBranchResult"] = 0;
            }

            return RedirectToAction("EditDashboardBranch");

        }
        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 EditPartnerBranchAtDashboard(string lbls)
        {
            if (userData.RoleId != 1 && userData.RoleId != 2)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }

            if (lbls != null &&
                (lbls.Equals("Dealer branch is successfully updated") ||
                 lbls.Equals("Lender branch is successfully updated")))
            {
                ViewBag.SuccessMsg = lbls;
            }
            else if (lbls != null &&
                (lbls.Equals("Failed to update")))
            {
                ViewBag.ErrorMsg = lbls;
            }

            BranchAccess ba = new BranchAccess();
            _compType = ba.getCompanyTypeByUserId(userData.UserId);

            //int compType = userData.CompanyType;
            if (_compType == 1)
            {
                ViewBag.ThisCompanyType = "Dealer";
            }
            else if (_compType == 2)
            {
                ViewBag.ThisCompanyType = "Lender";
            }
            else
            {
                ViewBag.compType = "";
            } 
            
            // get all branches
            List<Branch> branchesLists = (new BranchAccess()).getBranches(userData.Company_Id);

            //Get all non registered branches by company id
            EditPartnerBranceModel nonRegCompanyBranch = new EditPartnerBranceModel();
            
            List<NonRegBranch> nonRegBranches = ba.getNonRegBranches(userData.Company_Id);
            

            //filter admin's branch
            if (userData.RoleId == 2)
            {
                branchesLists = branchesLists.Where(x => x.BranchId == userData.BranchId).ToList();
                nonRegBranches = nonRegBranches.Where(x => x.BranchId == userData.BranchId).ToList();
            }
            nonRegCompanyBranch.NonRegBranches = nonRegBranches;
            ViewBag.RegBranchId = new SelectList(branchesLists, "BranchId", "BranchName");

            ViewBag.Count = nonRegBranches.Count;

            //Get all non reg companies
            CompanyAccess ca = new CompanyAccess();
            List<Company> nonRegCompanyList = ca.GetCompanyByCreayedCompany(userData.Company_Id);
            ViewBag.NonRegCompanyId = new SelectList(nonRegCompanyList, "CompanyId", "CompanyName", 1);

            //Get states to list
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");

            return View(nonRegCompanyBranch);
        }
        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>
        /// Frontend page: Advance Unit
        /// Title: Get loan details and not advanced unit details from database and return to view
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 02/24/2016
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Return partial view</returns>
        public ActionResult Advance()
        {
            int flag = -1;
            //assign logged user id to variable
            int userId = userData.UserId;
            string loanCode;
            try
            {
                //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                //if exception occured return to login page
                return RedirectToAction("UserLogin", "Login");
            }
            BranchAccess branch = new BranchAccess();
            //retrieve company type for given user id
            int companyType = branch.getCompanyTypeByUserId(userId);
            //check company type 1-Lender
            if (companyType == 1)
            {
                ViewBag.isLender = true;
            }
            //company type 2 - Dealer
            else
            {
                ViewBag.isLender = false;
            }

            ViewBag.unitClickId = "";
            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            //retrieve loan delails for given loan code
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);
            //check logged user role is user
            if (userData.RoleId == 3)
            {
                //check Session["CurrentLoanRights"] is null or empty
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    string rgts = "";
                    //convert Session["CurrentLoanRights"] to string variable
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList = null;
                    //check right string is not empty
                    if (rgts != "")
                    {
                        //split string
                        rgtList = rgts.Split(',');
                    }
                    //check right list is not null
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            //check relevant right for Advance Unit page contains in the user right list
                            if (x == "U01")
                            {
                                checkPermission = true;
                            }
                        }
                        //check permission value is false
                        if (checkPermission == false)
                        {
                            //return to dashboard
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        //return to dashboard
                        return RedirectToAction("UserDetails", "UserManagement");
                    }

                }
            }
            //check logged user is dealer user
            else if (userData.RoleId == 4)
            {
                //return to dashboard
                return RedirectToAction("UserDetails", "UserManagement");
            }
            ViewBag.loanDetails = loanDetails;
            Models.Unit unit = new Models.Unit();
            //get units which need to advance for given loan id
            AdvanceUnit advanceUnit = this.GetAdvanceUnitList(loanDetails.loanId);
            //assign loan id to session object
            Session["advUnitloanId"] = loanDetails.loanId;
            //assign not advanced unit list to session object
            Session["notAdvancedList"] = advanceUnit.NotAdvanced;
            ViewBag.advanceList = advanceUnit.NotAdvanced;
            //check update result of Advance Unit page
            if((TempData["updateReslt"]!=null)&&(TempData["updateReslt"].ToString() != ""))
            {
                //convert result to integer
                flag = int.Parse(TempData["updateReslt"].ToString());
            }
            //check result value is 1
            if (flag == 1)
            {
                //flag 1 - success
                ViewBag.Msg = "Success";
            }
            else if (flag == 0)
            {
                //flag 0 - error
                ViewBag.Msg = "Error";
            }
            else if (flag == 2)
            {
                //flag 2 - Advance amount error
                ViewBag.Msg = "Advance amount error";
            }else if(flag == 3)
            {
                //flag 3 - Advance error
                ViewBag.Msg = "Advance Error";
            }
            
            //return advance unit list to view
            return View(advanceUnit);
        }
        /// <summary>
        /// Frontend page: Join Dealer
        /// Title: view of Link Dealer page
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 2016/03/30
        /// Edited: Piyumi Perera
        /// </summary>
        /// <returns></returns>
        public ActionResult LinkDealer()
        {
            //Check result of Join Dealer page
            if(TempData["msg"] !=null )
            {
                //Check TempData["msg"] is 1
                if (TempData["msg"].ToString() == "1")
                {
                    ViewBag.SuccessMsg = "User Successfully Created";
                }
                //Check TempData["msg"] is 2
                else if (TempData["msg"].ToString() == "2")
                {
                    ViewBag.Error = "Error";
                }
            }
            CompanyAccess ca = new CompanyAccess();
            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"];
            }
            //remove Session["popUpSelectionType"]
            Session.Remove("popUpSelectionType");
           //return non registered branch details by non registered branch id
            NonRegBranch nonRegBranches = ba.getNonRegBranchByNonRegBranchId(loan.NonRegBranchId);
            ViewBag.nonRegBranches = nonRegBranches.BranchName;
            ViewBag.nonRegCompany = nonRegBranches.CompanyNameBranchName;
            List<User> userList = new List<User>();
            //return all users of given company id
            userList = (new UserAccess()).GetUserListByCompany(userData.Company_Id);
            //filter user list who has authorization for selected loan
            userList = userList.FindAll(t => t.BranchId == loan.BranchId || (t.BranchId ==0 && t.RoleId==1));
            ViewBag.UserIdForSendReq = new SelectList(userList, "UserId", "UserName");

            //get report list for dealer user
            List<Right> ReportRightsList = new List<Right>();
            User us = new User();
            us.ReportRightsList = new List<Right>();
            ReportRightsList = (new UserRightsAccess()).getReportRights();
            if(ReportRightsList!=null && ReportRightsList.Count > 0)
            {
                foreach (Right rgt in ReportRightsList)
                {
                    //Check dealer user can view the report
                    if(!rgt.DealerView)
                    {
                        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;
                        }
                    }
                    us.ReportRightsList.Add(rgt);
                }
            }
            //Check user is super admin
            if (userData.RoleId == 1)
            {
                //convert user list to session object
                Session["UserReqList"] = userList;
            }
            //Check user is admin
            else if (userData.RoleId == 2)
            {
                //convert user list to session object
                Session["UserReqList"] = userList;
            }
            else
            {
                //return to dashboard
                return RedirectToAction("UserDetails", "UserManagement");
            }
            return View(us);
        }
        public ActionResult CreateBranchFirstBranch(UserCompanyModel userCompany)
        {
            if (_type == "CompanyEmployee")
            {
                ViewBag.Type = "CompanyEmployee";
                BranchAccess ba = new BranchAccess();
                userCompany.Branch.BranchCode = ba.createBranchCode(_userCompany.Company.CompanyCode);
                _userCompany.Branch = userCompany.Branch;
                _userCompany.Branch.StateId = userCompany.StateId;
                CompanyAccess ca = new CompanyAccess();
                //if (ca.SetupCompany(_userCompany))
                if (ca.SetupCompanyRollback(_userCompany))
                {
                    ViewBag.SuccessMsg = "Company is successfully setup";
                    return View();
                }
                else
                {
                    ViewBag.ErrorMsg = "Failed to setup company";
                    return RedirectToAction("CreateFirstSuperUser", "CreateUser");
                }

            }
            return View();
        }
        /// <summary>
        /// CreatedBy : Nadeeka
        /// CreatedDate: 2016/04/01
        /// 
        /// to show the view
        /// </summary>
        /// <returns></returns>
        public ActionResult AssignUserRights()
        {
            CompanyAccess ca = new CompanyAccess();
            BranchAccess ba = new BranchAccess();
            Loan loan = (Loan)Session["loanDashboard"];

            NonRegBranch nonRegBranches = ba.getNonRegBranchByNonRegBranchId(loan.NonRegBranchId);
            ViewBag.nonRegBranches = nonRegBranches.BranchName;// nonRegBranches.BranchName;
            ViewBag.nonRegCompany = nonRegBranches.CompanyNameBranchName;
            return View();
        }
        public ActionResult loadGrid()
        {
            string loanCode;

            try
            {
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                //filterContext.Controller.TempData.Add("UserLogin", "Login");
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }          

            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);



            BranchAccess ba = new BranchAccess();
            ViewBag.ComType = userData.CompanyType;
            ViewBag.loanId = loanDetails.loanId;
            ViewBag.loanDetails = loanDetails;

            UnitPayOffViewModel unitPayOffViewModel = new UnitPayOffViewModel();
            CurtailmentAccess payoff = new CurtailmentAccess();
            unitPayOffViewModel.UnitPayOffList = new List<UnitPayOffModel>();
            unitPayOffViewModel.PayDate = DateTime.Now;

            unitPayOffViewModel.UnitPayOffList = payoff.GetUnitPayOffList(loanDetails.loanId);

            decimal advanceFee = 0;
            advanceFee = payoff.AdvanceForPayOffUnits(loanDetails.loanId);

            //int advanceFeeAtPayoff = payoff.CheckAdvanceFeeAtPayOff(loanDetails.loanId);

            //if (advanceFeeAtPayoff == 1) {
            //    foreach (var unit in unitPayOffViewModel.UnitPayOffList) {
            //        unit.IsAdvancePaid = false;
            //    }
            //}
            ViewBag.AdvanceFee = advanceFee;

            var unitPayOffList = unitPayOffViewModel.UnitPayOffList;

            Session["payoffList"] = unitPayOffList;
            ViewBag.payOffList = unitPayOffList;

            TitleAccess ta = new TitleAccess();
            Title title = ta.getTitleDetails(loanDetails.loanId);

            Session["PayOffUnitloanId"] = loanDetails.loanId;

            if (title != null)
            {
                bool isTitleTrack = title.IsTitleTrack;
                if (isTitleTrack)
                    ViewBag.IsTitleTrack = "Yes";

            }

            return PartialView(unitPayOffViewModel);
        }
        public ActionResult LoanInfo(string title, string msg)
        {
            ViewBag.Msg = msg;
            int userId;
            string loanCode = null;
            try {
                userId = userData.UserId;

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

            if(Session["loanCode"] != null) { 
            loanCode = Session["loanCode"].ToString();
            }

            ViewBag.Title = title;
            
            ViewBag.Username = userData.UserName;
            BranchAccess ba = new BranchAccess();
          
        
          
                ViewBag.roleId = userData.RoleId;
            // get the Company type for front end view
            int comType = ba.getCompanyTypeByUserId(userId);
            ViewBag.loanCompanyType = (comType == 1) ? "Dealer" : "Lender";


            if(loanCode != null) {
            LoanSetupStep1 loan = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);
            Session["addUnitloan"] = loan;
            NonRegBranch nonRegBranch = ba.getNonRegBranchByNonRegBranchId(loan.nonRegisteredBranchId);

            ViewBag.NonRegBranchName = nonRegBranch.BranchName;

            //dealer email address, this will be used on curtailment page
            Session["DealerEmail"] = nonRegBranch.BranchEmail;

            ViewBag.loanBranchAddress =  (nonRegBranch.BranchAddress1 != "" ? nonRegBranch.BranchAddress1 : "") + (nonRegBranch.BranchAddress2 != "" ? ", " + nonRegBranch.BranchAddress2 : "") + (nonRegBranch.BranchCity != "" ? ", " + nonRegBranch.BranchCity : "");

            ViewBag.CurtailmentDueDate = loan.CurtailmentDueDate;

            ViewBag.LoanNumber = loan.loanNumber;

            }

            return View();
        }