// GET: SetupProcessTest
        public ActionResult Step1(int? edit)
        {
            Session["userId"] = 229;

            if (Session["userId"] == null || Session["userId"].ToString() == "")
                return RedirectToAction("UserLogin", "Login");

            int userId = Convert.ToInt32(Session["userId"]);
            CompanyAccess ca = new CompanyAccess();
            StepAccess sa = new StepAccess();
            // Get company types to list
            List<CompanyType> ctList = ca.GetAllCompanyType();
            ViewBag.TypeId = new SelectList(ctList, "TypeId", "TypeName");

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

            if (Convert.ToInt32(Session["companyStep"]) == 1 && edit != 1)
            {
                return View();
            }

            if (edit == 1)
            {
                if (!string.IsNullOrEmpty(Session["userId"].ToString()))
                {
                    userId = Convert.ToInt32(Session["userId"]);
                    //----------
                    Company preCompany = ca.GetCompanyDetailsCompanyId(userData.Company_Id);
                    

                    _comCode = preCompany.CompanyCode;
                    ViewBag.Edit = "Yes";

                    return View(preCompany);
                }
            }

            return RedirectToAction("UserLogin", "Login");
        }
        public ActionResult SignUp(User user)
        {
            if (this.Session["CaptchaImageText"].ToString() == user.SecurityCode)
            {

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

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


            //return View();
            return RedirectToAction("SignUp");
        }
        public ActionResult 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 AddCurtailment(List<Curtailment> curtailmentList, CurtailmentModel curtaiulmentModel)
        {
            //calculate payment percentage
            if (userData.RoleId >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }

            CurtailmentAccess curtailmentAccess = new CurtailmentAccess();
            StepAccess sa = new StepAccess();
            if (curtailmentAccess.InsertCurtailment(curtailmentList, loanData.loanId) > 0)
            {
                ViewBag.SuccessMsg = "Curtailment Details added successfully";
                sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 6);
               
                    Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, loanData.loanId, "Curtailment", "Inserted curtailment details of loan : " + loanData.loanId, DateTime.Now);

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

                ViewBag.Redirect = 1;
            }
            else
            {
                sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 6);
                
                    Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, loanData.loanId, "Curtailment", "Edited curtailment details of loan : " + loanData.loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
               
                ViewBag.SuccessMsg = "Curtailment Details updated successfully";
            }

            //bool loanActive = curtaiulmentModel.LoanStatus == "Yes";

            LoanSetupAccess loanAccess = new LoanSetupAccess();
            loanAccess.UpdateLoanCurtailment(curtaiulmentModel, loanData.loanId);
            TempData["LoanId"] = loanData.loanId;
            return RedirectToAction("Step10", new { lbl = "Details added successfully" });
        }
        public ActionResult CreateDashboardUser(User userObj)
        {
            //assign phone number to object property
            userObj.PhoneNumber = userObj.PhoneNumber2;
            //assign user id to variable
            int currentUser = userData.UserId;

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

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

            userObj.Email = userObj.NewEmail;

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

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

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

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

                Email email = new Email(userObj.Email);

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

                }

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

            }
            else
            {
                TempData["createUserResult"] = 0;
                //return View();
            }
            return RedirectToAction("CreateDashboardUser");
        }
        public ActionResult 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");
            
        }
        public ActionResult Step4(CompanyViewModel nonRegComModel, string companyCode)
        {
            //assign company code to object
            nonRegComModel.Company.CompanyCode = companyCode;
            //check company step is null
            if (Session["companyStep"] == null)
            {
                //check ajax request
                if (HttpContext.Request.IsAjaxRequest())
                {
                    //return to login with error code 404
                    return new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
                }
                else
                {
                    //return to login page
                    return RedirectToAction("UserLogin", "Login");
                }
            }

            //assign companay zip with extension
            nonRegComModel.Company.Zip = nonRegComModel.Company.ZipPre;
            if (nonRegComModel.Company.Extension != null)
                nonRegComModel.Company.Zip += "-" + nonRegComModel.Company.Extension;
            //assign created by,company type and state id
            int userId = userData.UserId;
            nonRegComModel.Company.CreatedBy = userId;
            nonRegComModel.Company.TypeId = (userData.CompanyType == 1) ? 2:1;
            nonRegComModel.Company.StateId = nonRegComModel.StateId;

            CompanyAccess ca = new CompanyAccess();

            nonRegComModel.Company.CreatedByCompany = userData.Company_Id; //regCompany.CompanyId;  asanka

            Company nonRegCom = nonRegComModel.Company;
            //check result of insert or update partner company 
            if (ca.InsertNonRegisteredCompany(nonRegCom))
            {
                //assign success msg according to company type
                ViewBag.SuccessMsg = ((userData.CompanyType == 1) ? "Dealer" : "Lender") + " Successfully created.";

                //If succeed update step table to step2 
                StepAccess sa = new StepAccess();
                //sa.updateStepNumberByUserId(userId, 5);
                sa.UpdateCompanySetupStep(userData.Company_Id, userData.BranchId, 5);

                

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

                

                //Send company detail to step 2
                CompanyBranchModel comBranch = new CompanyBranchModel();
                comBranch.Company = nonRegCom;

                TempData["NonRegCompany"] = comBranch;
                return RedirectToAction("Step5");
            }
            ViewBag.ErrorMsg = "Failed to create " + ((userData.CompanyType == 1) ? "Dealer" : "Lender") + " company.";

            //return new HttpStatusCodeResult(404, ViewBag.ErrorMsg);
            return RedirectToAction("UserLogin", "Login", new { lbl = ViewBag.ErrorMsg });
        }
        public ActionResult CreateDashboardUser(string lbls)
        {

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

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

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

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

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

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

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

                return View();
            }

        }
        public ActionResult 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 Step1(Company company, int? edit)
        {
            if (Session["userId"] == null || Session["userId"].ToString() == "")
                return RedirectToAction("UserLogin", "Login");


            string type;
            if (edit != 1)
            {
                GeneratesCode gc = new GeneratesCode();
                _comCode = company.CompanyCode = gc.GenerateCompanyCode(company.CompanyName);
                type = "INSERT";
            }
            else
            {
                company.CompanyCode = _comCode;
                type = "UPDATE";
            }

            //
            company.Zip = company.ZipPre;
            if (company.Extension != null)
                company.Zip += "-" + company.Extension;

            company.CreatedBy = company.FirstSuperAdminId = Convert.ToInt32(Session["userId"]);
            company.CompanyStatus = true;
            CompanyAccess ca = new CompanyAccess();

            //check this record is new one or exitsting one
            //string type = (edit == 1) ? "UPDATE" : "INSERT";

            int companyId = ca.InsertCompany(company, type);

            if (companyId > 0)
            {
                ViewBag.SuccessMsg = "Company Successfully setup.";

                CompanyType = (company.TypeId == 1) ? "Lender" : "Dealer";

                //If succeed update step table to step2 
                StepAccess sa = new StepAccess();
                sa.updateStepNumberByUserId(company.FirstSuperAdminId, 2);

                //Send company detail to step 2
                CompanyBranchModel comBranch = new CompanyBranchModel();
                comBranch.Company = company;

                TempData["Company"] = comBranch;

                return RedirectToAction("Step2");
            }
            ViewBag.ErrorMsg = "Failed to Setup company.";

            // Get company types to list
            List<CompanyType> ctList = ca.GetAllCompanyType();
            ViewBag.TypeId = new SelectList(ctList, "TypeId", "TypeName");

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

            return View();

        }
        public ActionResult Step10(string lbl)
        {
            CurtailmentModel curtailment = new CurtailmentModel();

            int userId = userData.UserId;
            if (userData.RoleId >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }

            //check user step is valid for this step
            StepAccess sa = new StepAccess();
            if (loanData.stepId == 5)
            {
                ViewBag.LoanId = 0;
                if (lbl == "Details added successfully")
                {
                    ViewBag.SuccessMsg = "Loan setup is completed";
                    Session["loanStep"] = null;
                    if (TempData["LoanId"] != null && (int)TempData["LoanId"] > 0) {
                        ViewBag.LoanId = (int)TempData["LoanId"];
                    }
                   
                    if (HttpContext.Request.IsAjaxRequest())
                    {
                        ViewBag.AjaxRequest = 1;
                        return PartialView(curtailment);
                    }
                    return View(curtailment);
                }

                int branchId = loanData.BranchId;

                LoanSetupAccess la = new LoanSetupAccess();
                int loanId = loanData.loanId;
                CurtailmentAccess curAccess = new CurtailmentAccess();
                _loan = curAccess.GetLoanDetailsByLoanId(loanId);
                _loan.loanId = loanId;
                
                curtailment.AdvancePt = _loan.advancePercentage;
                curtailment.RemainingPercentage = curtailment.AdvancePt;

                curtailment.InfoModel = new List<Curtailment>();

                var curtailments = curAccess.retreiveCurtailmentByLoanId(loanId);

                int payPercentage = _loan.advancePercentage;
                int? totalPercentage = 0;

                int curId = 0;
                if (curtailments != null && curtailments.Count > 0)
                {
                    for (int i = 0; i < curtailments.Count; i++)
                    {
                        curId++;
                        totalPercentage += curtailments[i].Percentage;
                        curtailment.InfoModel.Add(new Curtailment { CurtailmentId = curId, TimePeriod = curtailments[i].TimePeriod, Percentage = curtailments[i].Percentage });
                    }
                    curtailment.LoanStatus = _loan.LoanStatus ? "Yes" : "No";

                    curtailment.CalculationBase = _loan.CurtailmentCalculationBase == "a" ? "Advance" : "Full payment";
                    curtailment.DueDate = _loan.CurtailmentDueDate;
                    curtailment.AutoRemindEmail = _loan.CurtailmentAutoRemindEmail;
                    curtailment.EmailRemindPeriod = _loan.CurtailmentEmailRemindPeriod;
                }

                ViewBag.CalMode = "Full Payment";
                curtailment.RemainingPercentage = payPercentage - totalPercentage;

                if (curtailment.RemainingPercentage > 0)
                    curtailment.InfoModel.Add(new Curtailment { CurtailmentId = curId + 1 });
                ViewData["objmodel"] = curtailment;

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

                    return View(curtailment);
                }
            }
            return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
        }
        public ActionResult UserLogin(UserLogin user)
        {
            try
            {
                //string ip = Request.UserHostAddress;
                DataSet dsUser = new DataSet();
                var login = new LoginAccess();
                var step = new StepAccess();
                User userData = new User();
                userData.UserName = user.userName;

                //pass user name to database and get user details
                dsUser = login.CheckUserLogin(userData);
                if (dsUser.Tables[0].Rows.Count > 0)
                {
                    userData.UserId = int.Parse(dsUser.Tables[0].Rows[0]["user_id"].ToString());
                    userData.UserName = dsUser.Tables[0].Rows[0]["user_name"].ToString();
                    userData.Password = dsUser.Tables[0].Rows[0]["password"].ToString();
                   
                    userData.RoleId = int.Parse(dsUser.Tables[0].Rows[0]["role_id"].ToString());
                    if (userData.RoleId == 4)
                    {
                        DataSet dsDelearCompany = new DataSet();
                        dsDelearCompany = login.GetDealerUserCompanyBranch(userData.UserId);
                        if (dsDelearCompany.Tables[0].Rows[0]["company_id"].ToString() != "")
                        {
                            userData.Company_Id = int.Parse(dsDelearCompany.Tables[0].Rows[0]["company_id"].ToString());
                            userData.CompanyName = dsDelearCompany.Tables[0].Rows[0]["company_name"].ToString();
                        }
                        if (dsDelearCompany.Tables[0].Rows[0]["branch_id"].ToString() != "")
                        {
                            userData.BranchId = int.Parse(dsDelearCompany.Tables[0].Rows[0]["branch_id"].ToString());
                            userData.BranchName = dsDelearCompany.Tables[0].Rows[0]["branch_name"].ToString();
                        }

                    }
                    else {
                        userData.BranchId = int.Parse(dsUser.Tables[0].Rows[0]["branch_id"].ToString());
                        userData.BranchName = dsUser.Tables[0].Rows[0]["branch_name"].ToString();
                        if (dsUser.Tables[0].Rows[0]["company_id"].ToString() != "")
                        {
                            userData.Company_Id = int.Parse(dsUser.Tables[0].Rows[0]["company_id"].ToString());
                            userData.CompanyType = int.Parse(dsUser.Tables[0].Rows[0]["company_type"].ToString());
                            userData.CompanyCode = dsUser.Tables[0].Rows[0]["company_code"].ToString();
                        }
                        else
                        {
                            userData.Company_Id = 0;
                        }
                        userData.CompanyName = dsUser.Tables[0].Rows[0]["company_name"].ToString();
                    }
                    
                    userData.step_status = int.Parse(dsUser.Tables[0].Rows[0]["step_status"].ToString());
                    
                    //To compair Database password and user enter password
                    string passwordFromDB = userData.Password;
                    char[] delimiter = { ':' };
                    string[] split = passwordFromDB.Split(delimiter);
                    var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');
                    if (passwordFromDB == null || (checkCharHave == false))
                    {
                        Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" was unable to login, Entered password did not match", DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                        return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username & Password combination. Please confirm entry and resubmit." });
                    }

                    string passwordEncripted = PasswordEncryption.encryptPassword(user.password, split[1]);
                    if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                    {
                       
                        //user object pass to session
                        Session["AuthenticatedUser"] = userData;

                        // Does not complete atleast one cycle
                        if (userData.step_status == 0)
                        {
                            if (userData.RoleId == 3)
                            {
                                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" was unable to login", DateTime.Now);

                                int islog = (new LogAccess()).InsertLog(log);
                                return RedirectToAction("UserLogin", "Login", new { lbl = "Company setup process is on going please contact admin." });
                            }
                            else
                            {
                                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" has logged successfully", DateTime.Now);

                                int islog = (new LogAccess()).InsertLog(log);
                                if (userData.Company_Id == 0)
                                {
                                    Session["companyStep"] = 1;
                                    return RedirectToAction("Index", "SetupProcess");
                                }
                                else if (userData.Company_Id > 0)
                                {
                                    if (userData.RoleId == 1)
                                    {
                                        DataSet dsStepNo = new DataSet();
                                        dsStepNo = step.checkSuperAdminLoginWhileCompanySetup(userData);
                                        if (dsStepNo.Tables[0].Rows.Count > 0)
                                        {
                                            Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                                            return RedirectToAction("Index", "SetupProcess");
                                        }
                                        else
                                        {
                                            LoanSetupStep loanStep = new LoanSetupStep();
                                            DataSet dsLoanStepNo = new DataSet();
                                            dsLoanStepNo = step.checkUserLoginWhileLoanSetup(userData);
                                            if (dsLoanStepNo.Tables[0].Rows.Count > 0)
                                            {
                                                loanStep.CompanyId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["company_id"].ToString());
                                                loanStep.BranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["branch_id"].ToString());
                                                loanStep.stepId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["step_number"].ToString());
                                                loanStep.nonRegisteredBranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["non_registered_branch_id"].ToString());
                                                if (dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString() != "")
                                                {
                                                    loanStep.loanId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString());
                                                }
                                                else
                                                {
                                                    loanStep.loanId = 0;
                                                }
                                                Session["loanStep"] = loanStep;
                                                if (userData.RoleId == 1)
                                                {
                                                    return RedirectToAction("Step" + (loanStep.stepId + 5), "SetupProcess");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //if step table has record pass(company id and branch id)
                                        DataSet dsStepNo = new DataSet();
                                        dsStepNo = step.checkUserLoginWhileCompanySetup(userData);
                                        if (dsStepNo.Tables[0].Rows.Count > 0)
                                        {
                                            Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                                            return RedirectToAction("Index", "SetupProcess");
                                        }
                                        else
                                        {
                                            //No Step recor in relavent Company and branch
                                            LoanSetupStep loanStep = new LoanSetupStep();
                                            DataSet dsLoanStepNo = new DataSet();
                                            dsLoanStepNo = step.checkUserLoginWhileLoanSetup(userData);
                                            if (dsLoanStepNo.Tables[0].Rows.Count > 0)
                                            {
                                                loanStep.CompanyId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["company_id"].ToString());
                                                loanStep.BranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["branch_id"].ToString());
                                                loanStep.stepId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["step_number"].ToString());
                                                loanStep.nonRegisteredBranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["non_registered_branch_id"].ToString());
                                                if (dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString() != "")
                                                {
                                                    loanStep.loanId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString());
                                                }
                                                else
                                                {
                                                    loanStep.loanId = 0;
                                                }

                                                Session["loanStep"] = loanStep;
                                                return RedirectToAction("Step" + (loanStep.stepId + 5), "SetupProcess");
                                            }

                                        }
                                    }


                                }
                            }
                        }
                        // Complete cycle and no start new cycle
                        else if (userData.step_status == 1 || userData.step_status == 2)
                        {
                            //delete just added unit if exists
                            UnitAccess ua = new UnitAccess();
                            ua.DeleteJustAddedUnits(userData.UserId);

                            //insert log
                            Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" has logged successfully", DateTime.Now);

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

                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                        // atleast one cycle complete and Start new cycle 
                        //else if (userData.step_status == 2)
                        //{

                        //    //delete just added unit if exists
                        //    UnitAccess ua = new UnitAccess();
                        //    ua.DeleteJustAddedUnits(userData.UserId);
                        //    //insert log
                        //    Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" has logged successfully", DateTime.Now);

                        //    int islog = (new LogAccess()).InsertLog(log);
                        //    if (userData.RoleId == 1)
                        //    {
                        //        DataSet dsStepNo = new DataSet();
                        //        dsStepNo = step.checkSuperAdminLoginWhileCompanySetup(userData);
                        //        if (dsStepNo.Tables[0].Rows.Count > 0)
                        //        {
                        //            Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //            Session["isNotCompleteStep"] = 1;
                        //            //return RedirectToAction("Index", "SetupProcess");
                        //            return RedirectToAction("UserLogin", "Login");
                        //        }
                        //        else
                        //        {
                        //            LoanSetupStep loanStep = new LoanSetupStep();
                        //            DataSet dsLoanStepNo = new DataSet();
                        //            dsLoanStepNo = step.checkUserLoginWhileLoanSetup(userData);
                        //            if (dsLoanStepNo.Tables[0].Rows.Count > 0)
                        //            {
                        //                loanStep.CompanyId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["company_id"].ToString());
                        //                loanStep.BranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["branch_id"].ToString());
                        //                loanStep.stepId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                loanStep.nonRegisteredBranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["non_registered_branch_id"].ToString());
                        //                if (dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString() != "")
                        //                {
                        //                    loanStep.loanId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString());
                        //                }
                        //                else
                        //                {
                        //                    loanStep.loanId = 0;
                        //                }
                        //                Session["isNotCompleteStep"] = 1;
                        //                Session["loanStep"] = loanStep;
                        //                if (userData.RoleId == 1)
                        //                {
                        //                    //return RedirectToAction("Step" + (loanStep.stepId + 5), "SetupProcess");
                        //                    return RedirectToAction("UserLogin", "Login");
                        //                }
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        //if step table has record pass(company id and branch id)
                        //        DataSet dsStepNo = new DataSet();
                        //        dsStepNo = step.checkUserLoginWhileCompanySetup(userData);
                        //        if (dsStepNo.Tables[0].Rows.Count > 0)
                        //        {
                        //            Session["isNotCompleteStep"] = 1;
                        //            Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //            return RedirectToAction("UserLogin", "Login");
                        //        }
                        //        else
                        //        {
                        //            //No Step recor in relavent Company and branch
                        //            LoanSetupStep loanStep = new LoanSetupStep();
                        //            DataSet dsLoanStepNo = new DataSet();
                        //            dsLoanStepNo = step.checkUserLoginWhileLoanSetup(userData);
                        //            if (dsLoanStepNo.Tables[0].Rows.Count > 0)
                        //            {
                        //                loanStep.CompanyId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["company_id"].ToString());
                        //                loanStep.BranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["branch_id"].ToString());
                        //                loanStep.stepId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                loanStep.nonRegisteredBranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["non_registered_branch_id"].ToString());
                        //                if (dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString() != "")
                        //                {
                        //                    loanStep.loanId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString());
                        //                }
                        //                else
                        //                {
                        //                    loanStep.loanId = 0;
                        //                }

                        //                Session["isNotCompleteStep"] = 1;
                        //                Session["loanStep"] = loanStep;

                        //                //return RedirectToAction("Step" + (loanStep.stepId + 5), "SetupProcess");
                        //                return RedirectToAction("UserLogin", "Login");
                        //            }
                        //            //if SA stepstatus 2 and no records in loan setup and companysetup
                        //            else
                        //            {
                        //                return RedirectToAction("UserDetails", "Usermanagement");
                        //            }
                        //        }


                        //    }
                        //}
                        else
                        {
                            //insert log
                            Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" was unable to login", DateTime.Now);

                            int islog = (new LogAccess()).InsertLog(log);
                            return RedirectToAction("UserLogin", "Login", new { lbl = "Company setup process is on going please contact admin." });
                        }







                        //    //check Company setup process
                        //    //Check SuperAdmin
                        //    //company ID null or 0 then redirect to step process 1
                        //    if (userData.Company_Id == 0)
                        //    {
                        //        Session["companyStep"] = 1;
                        //        return RedirectToAction("Index", "SetupProcess");
                        //    }
                        //    else if (userData.Company_Id > 0)
                        //    {
                        //        //check branch count more than one and 
                        //        if (userData.RoleId == 1)
                        //        {
                        //            //check branch count in view and step table row count
                        //            //IF more than branch count and has step record ask question

                        //            DataSet dsStepNo = new DataSet();
                        //            dsStepNo = step.checkSuperAdminLoginWhileCompanySetup(userData);
                        //            if (dsStepNo.Tables[0].Rows.Count > 0)
                        //            {
                        //                int bcount = 0;
                        //                if (dsStepNo.Tables[0].Rows[0]["branchCount"].ToString() != "")
                        //                {
                        //                    bcount = int.Parse(dsStepNo.Tables[0].Rows[0]["branchCount"].ToString());
                        //                }
                        //                int scount = 0;
                        //                if (dsStepNo.Tables[0].Rows[0]["stepCount"].ToString() != "")
                        //                {
                        //                    scount = int.Parse(dsStepNo.Tables[0].Rows[0]["stepCount"].ToString());
                        //                }
                        //                if (bcount <= scount)
                        //                {
                        //                    Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                    return RedirectToAction("Index", "SetupProcess");

                        //                }
                        //                else
                        //                {
                        //                    //message: Not complete Step, Do you want to complete it.
                        //                    Session["isNotCompleteStep"] = 1;
                        //                    Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                    return RedirectToAction("UserLogin", "Login");
                        //                }
                        //            }
                        //            else
                        //            {
                        //                LoanSetupStep loanStep = new LoanSetupStep();
                        //                DataSet dsLoanStepNo = new DataSet();
                        //                dsLoanStepNo = step.checkUserLoginWhileLoanSetup(userData);
                        //                if (dsLoanStepNo.Tables[0].Rows.Count > 0)
                        //                {
                        //                    loanStep.CompanyId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["company_id"].ToString());
                        //                    loanStep.BranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["branch_id"].ToString());
                        //                    loanStep.stepId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                    loanStep.nonRegisteredBranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["non_registered_branch_id"].ToString());
                        //                    if (dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString() != "")
                        //                    {
                        //                        loanStep.loanId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString());
                        //                    }
                        //                    else
                        //                    {
                        //                        loanStep.loanId = 0;
                        //                    }
                        //                    Session["loanStep"] = loanStep;
                        //                    if (userData.RoleId == 1)
                        //                    {
                        //                        return RedirectToAction("Step" + (loanStep.stepId + 5), "SetupProcess");
                        //                    }
                        //                }
                        //                else
                        //                {
                        //                    //Redirect to Super Admin dashboard
                        //                    return RedirectToAction("UserDetails", "UserManagement");
                        //                }

                        //            }

                        //        }
                        //        else
                        //        {
                        //            //if step table has record pass(company id and branch id)
                        //            DataSet dsStepNo = new DataSet();
                        //            dsStepNo = step.checkUserLoginWhileCompanySetup(userData);
                        //            if (dsStepNo.Tables[0].Rows.Count > 0)
                        //            {
                        //                Session["companyStep"] = int.Parse(dsStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                if (userData.RoleId == 2)
                        //                {
                        //                    return RedirectToAction("Index", "SetupProcess");
                        //                }
                        //                else
                        //                {
                        //                    return RedirectToAction("UserLogin", "Login", new { lbl = "Company setup process is on going please contact admin." });
                        //                }
                        //            }
                        //            else
                        //            {
                        //                //No Step recor in relavent Company and branch
                        //                LoanSetupStep loanStep = new LoanSetupStep();
                        //                DataSet dsLoanStepNo = new DataSet();
                        //                dsLoanStepNo = step.checkUserLoginWhileLoanSetup(userData);
                        //                if (dsLoanStepNo.Tables[0].Rows.Count > 0)
                        //                {
                        //                    loanStep.CompanyId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["company_id"].ToString());
                        //                    loanStep.BranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["branch_id"].ToString());
                        //                    loanStep.stepId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["step_number"].ToString());
                        //                    loanStep.nonRegisteredBranchId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["non_registered_branch_id"].ToString());
                        //                    if (dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString() != "")
                        //                    {
                        //                        loanStep.loanId = int.Parse(dsLoanStepNo.Tables[0].Rows[0]["loan_id"].ToString());
                        //                    }
                        //                    else
                        //                    {
                        //                        loanStep.loanId = 0;
                        //                    }

                        //                    Session["loanStep"] = loanStep;
                        //                    if (userData.RoleId == 2)
                        //                    {
                        //                        //return RedirectToAction("Index", "SetupProcess");
                        //                        return RedirectToAction("Step" + (loanStep.stepId+5), "SetupProcess");
                        //                    }
                        //                }
                        //                else
                        //                {
                        //                    if (userData.RoleId == 2)
                        //                    {
                        //                        //Redirect to Branch Admin dashboard
                        //                        return RedirectToAction("UserDetails", "UserManagement");
                        //                    }
                        //                    else
                        //                    {
                        //                        //Redirect to User dashboard
                        //                        return RedirectToAction("UserDetails", "UserManagement");
                        //                    }
                        //                }


                        //            }

                        //        }
                        //    }

                        //}
                        //else
                        //{
                        //    //User Name Correct but user enter password does not match with database password value
                        //    return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username or Password, please confirm and submit." });
                        //}
                        //insert log entry
                      
                    }
                    else
                    {
                        //User Name Correct but user enter password does not match with database password value
                        Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" was unable to login, Entered password did not match ", DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                        return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username & Password combination. Please confirm entry and resubmit." });
                    }
                }
                else
                {
                    //Incorrect UserName
                    Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, 0, "User Login", "User : "******" was unable to login, Entered username did not exist ", DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                    return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username & Password combination. Please confirm entry and resubmit." });
                }     
            }
            catch
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "An error has occurred.Please try again later" });
            }
            return RedirectToAction("UserLogin", "Login");
        }
        public ActionResult Step9(Title title)
        {
            int userId = userData.UserId;
            int branchId = loanData.BranchId;
            //check user is user or dealer user
            if (userData.RoleId >= 3)
            {
                //return to login page
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
         
            TitleAccess ta = new TitleAccess();
            LoanSetupAccess la = new LoanSetupAccess();
            StepAccess sa = new StepAccess();
          
            int loanId = loanData.loanId;
            title.LoanId = loanId;

            if (title.ReceivedTimeLimit == "1")
            {
                title.ReceivedTimeLimit = "Title required to advance";
            }
            else if (title.ReceivedTimeLimit == "2")
            {
                title.ReceivedTimeLimit = "Title can arrive at any time";
            }
            else if (title.ReceivedTimeLimit == "3")
            {
                title.ReceivedTimeLimit = "Title must arrive within a specified time";
            }

            if (title.ReceiptRequiredMethod == "1")
            {
                title.ReceiptRequiredMethod = "Must be physically present";
            }
            else if (title.ReceiptRequiredMethod == "2")
            {
                title.ReceiptRequiredMethod = "Scanned copy only";
            }
            else if (title.ReceiptRequiredMethod == "3")
            {
                title.ReceiptRequiredMethod = "Physically present or scanned copy";
            }
            //insert or update title details and get result
            int reslt = ta.insertTitleDetails(title);
            //check result is not 0
            if (reslt >= 0)
            {
                //update loan setup step table
                if (sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 5))
                {
                    //check current step value of loanData object is less than 5
                    if (loanData.stepId < 5)
                    {
                        //update step
                        loanData.stepId = 5;
                    }
                    //if title update or insert result is 0
                    if (reslt == 0)
                    {
                        //insert record in to log table as insert
                        Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, title.LoanId, "Title", "Edited title details of loan : " + title.LoanId, DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                    }
                    if (reslt > 0)
                    {
                        //insert record in to log table as update
                        Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, title.LoanId, "Title", "Inserted title details of loan : " + title.LoanId, DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                    }
                    //convert loan data object to session variable
                    Session["loanStep"] = loanData;
                    //return to curtailment page
                    return RedirectToAction("Step10");
                }
                //if update loan setup step result is false return to login page
                else
                {
                    return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
                }
            }
           
            else
            {
                return new HttpStatusCodeResult(404);
            }
            
        }
        public ActionResult Step8(Fees fees)
        {
            if (userData.RoleId >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
            StepAccess step = new StepAccess();

            if (fees.AdvanceDue == "Vehicle Payoff")
            {
                fees.AdvanceDueDate = "VP";
            }
            if (fees.AdvanceDue == "Time of Advance")
            {
                fees.AdvanceDueDate = "ToA";
            }

            //if (fees.IsAdvanceFeeCompleteEmailReminder == false)
            //{
            //    fees.AdvanceFeeDealerEmail = "";
            //    fees.AdvanceFeeDealerEmailRemindPeriod = 0;
            //}
            //if (fees.IsLoanFeeCompleteEmailReminder == false)
            //{
            //    fees.MonthlyLoanFeeDealerEmail = "";
            //    fees.MonthlyLoanFeeDealerEmailRemindPeriod = 0;
            //}
            //if (fees.IsLotFeeCompleteEmailReminder == false)
            //{
            //    fees.LotInspectionFeeDealerEmail = "";
            //    fees.LotInspectionFeeDealerEmailRemindPeriod = 0;
            //}
            if (fees.IsAdvanceFeeDueEmailReminder == false)
            {
                fees.AdvanceDueEmail = "";
                fees.AdvanceDueEmailRemindPeriod = 0;
            }
            if (fees.IsLoanFeeDueEmailReminder == false)
            {
                fees.MonthlyLoanDueEmail = "";
                fees.MonthlyLoanDueEmailRemindPeriod = 0;
            }
            if (fees.IsLotFeeDueEmailReminder == false)
            {
                fees.LotInspectionDueEmail = "";
                fees.LotInspectionDueEmailRemindPeriod = 0;
            }
            fees.LoanId = loanData.loanId;

            // after hide the due methods

            fees.MonthlyLoanDue = "Once a Month";
            fees.LotInspectionDue = "Monthly";

            if (step.InsertFeesDetails(fees))
            {
                var userId = userData.UserId;
                var branchId = loanData.loanId;

                if (fees.isEdit == true)
                {
                    return RedirectToAction("Step9");
                }
                else if (step.UpdateLoanSetupStep(userData.UserId, loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 4))
                {

                    if (loanData.stepId < 4)
                    {
                        loanData.stepId = 4;
                        Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, fees.LoanId, "Fees", "Inserted fees details of loan : " + fees.LoanId, DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                    }
                    else
                    {
                        Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, fees.LoanId, "Fees", "Edited fees details of loan : " + fees.LoanId, DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                    }
                    Session["loanStep"] = loanData;
                    return RedirectToAction("Step9");
                }
                else
                {
                    return RedirectToAction("Step8");
                }
            }
            else
            {
                return RedirectToAction("Step8");
            }

        }
        public ActionResult Step6_Post(LoanSetupStep1 loanSetupStep1)
        {
            int userId = userData.UserId;
          
            if (!CheckTheRangeOfPayOffPeriod(loanSetupStep1.autoReminderPeriod, loanSetupStep1.startDate, loanSetupStep1.maturityDate, 0))
            {

                return new HttpStatusCodeResult(404, "Auto reminder period is out of range");
            }

            if (!IsAtleastOneSelectUnitType(loanSetupStep1.allUnitTypes))
            {
                return new HttpStatusCodeResult(404, "Select Atleast One Unit Type");
            }

            // check he is super admin or admin
            if (userData.RoleId > 2)
            {
                return new HttpStatusCodeResult(404, "Not Allowed");
            }

            if ((Session["dashboard"] !=null))
            {
                loanData.stepId = 1;
            }
            // check if   step is 6...
            StepAccess sa = new StepAccess();
            if (loanData.stepId < 1)
            {
                return new HttpStatusCodeResult(404, "Not Allowed");
            }

            LoanSetupAccess loanSetupAccess = new LoanSetupAccess();

            LoanSetupAccess la = new LoanSetupAccess();
            int loanId = loanData.loanId;

            loanData.CompanyId = userData.Company_Id;

            
            Session["loanStep"] = loanData;

            if (loanId > 0)
            {
                loanId = loanSetupAccess.insertLoanStepOne(loanSetupStep1, loanId);
                if (loanId > 0)
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, loanSetupStep1.RegisteredBranchId, loanId, "Loan Details", "Edited Loan : " + loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                }
                else
                {
                    TempData["error"] = "error";
                    return RedirectToAction("step6");
                }
              
            }
            else
            {
                //loanId = la.getLoanIdByUserId(userId);


                loanId = loanSetupAccess.insertLoanStepOne(loanSetupStep1, loanId);
                if (loanId > 0)
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, loanSetupStep1.RegisteredBranchId, loanId, "Loan Details", "Inserted Loan : " + loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                }
                //need to update loanSetup object
                else
                {
                    TempData["error"] = "error";
                    return RedirectToAction("step6");
                }


            }
            if (loanId > 0)
            {
                if (loanSetupStep1.isInterestCalculate)
                {
                    
                    sa.UpdateLoanSetupStep(userData.UserId, loanData.CompanyId, loanSetupStep1.RegisteredBranchId, loanSetupStep1.nonRegisteredBranchId, loanId, 2);
                    if (loanData.stepId < 2)
                    {
                        loanData.stepId = 2;
                    }
                    //loanData.stepId = 2;
                }
                else
                {
                    sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanSetupStep1.RegisteredBranchId, loanSetupStep1.nonRegisteredBranchId, loanId, 3);
                    if (loanData.stepId < 3)
                    {
                        loanData.stepId = 3;
                    }
                }
                loanData.BranchId = loanSetupStep1.RegisteredBranchId;
                loanData.nonRegisteredBranchId = loanSetupStep1.nonRegisteredBranchId;
                loanData.loanId = loanId;
                
                Session["loanStep"] = loanData;
            }
            Session["loanStep"] = loanData;
            if (loanSetupStep1.isInterestCalculate)
            {
                return RedirectToAction("step7");
            }
            else
            {
                //sa.UpdateLoanSetupStep(loanData.CompanyId, loanData.BranchId, loanSetupStep1.nonRegisteredBranchId, loanId, 3);
                return RedirectToAction("step8");
            }






        }
        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 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 Step2()
        {
            Session["userId"] = 229;
            //Session["userId"] = 4;
            //int userId = 68;
            if ((Session["userId"] != null) && (Session["userId"].ToString() != ""))
            //if(userId>0)
            {
                int userId = (int)Session["userId"];
                StepAccess cs = new StepAccess();
                int reslt = Convert.ToInt32(Session["companyStep"]);
                if (reslt == 2)
                {
                    if ((TempData["Company"] != null) && (TempData["Company"].ToString() != ""))
                    {
                        userCompany = new CompanyBranchModel();
                        userCompany = (CompanyBranchModel)TempData["Company"];

                        CompanyType = (userCompany.Company.TypeId == 1) ? "Lender" : "Dealer";

                        userCompany.MainBranch = new Branch();
                        if (userCompany.Company.Extension == null)
                            userCompany.Company.Extension = "";
                    }

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

                    return View(userCompany);

                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else
            {
                return RedirectToAction("UserLogin", "Login");
            }
        }
        public ActionResult Step1(Company company)
        {
            string type;
            //check session company step 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");
                }
            }
            type = "UPDATE";
            //check company code is null
            if (string.IsNullOrEmpty(company.CompanyCode))
            {
              //assign type as insert 
                type = "INSERT";
            }
            //set zip code
            company.Zip = company.ZipPre;
            if (company.Extension != null)
                company.Zip += "-" + company.Extension;
            //assign looged user id to created by property
            company.CreatedBy = company.FirstSuperAdminId = userData.UserId;
            //assign true for company status
            company.CompanyStatus = true;
            CompanyAccess ca = new CompanyAccess();
            //insert company details and return inserted company id
            int companyId = ca.InsertCompany(company, type);
            //check company id is not 0
            if (companyId > 0)
            {
                //assign success message
                ViewBag.SuccessMsg = "Company Successfully setup.";
                //assign company code and company type to user data object company code and company type
                userData.CompanyCode = company.CompanyCode;
                userData.CompanyType = company.TypeId;

                //If succeed update step table to step2 
                StepAccess sa = new StepAccess();
                if (type == "INSERT")
                {
                    bool res = sa.UpdateCompanySetupStep(companyId, userData.BranchId, 2);

                    //insert to log 
                    Log log = new Log(userData.UserId, companyId, 0, 0, "Company Step", "Inserted company : " + company.CompanyCode, DateTime.Now);

                    (new LogAccess()).InsertLog(log);
                }
                else if (type == "UPDATE")
                {
                    //insert to log 
                    Log log = new Log(userData.UserId, companyId, 0, 0, "Company Step", "Updated company : " + company.CompanyCode, DateTime.Now);

                    (new LogAccess()).InsertLog(log);
                }
                //check company step is 1
                if (Convert.ToInt32(Session["companyStep"].ToString()) < 2)
                {
                    //update company step to 2
                    Session["companyStep"] = 2;
                }


                //user object pass to session
                userData.Company_Id = companyId;
                userData.CompanyName = company.CompanyName;
                Session["AuthenticatedUser"] = userData;


                //Send company detail to step 2
                CompanyBranchModel comBranch = new CompanyBranchModel();
                comBranch.Company = company;

                TempData["Company"] = comBranch;
                return RedirectToAction("Step2");
            }

            //return RedirectToAction("UserLogin", "Login", new { lbl = "Failed to Setup company." });
            return new HttpStatusCodeResult(404, "Failed to Setup company.");
        }
        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 Step3(string lbls)
        {

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

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

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

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

           

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

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


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

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

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

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

                

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

                    return View();
                }
            }

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


                ViewBag.ErrorMsg = "Failed to create user";

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

                    return View();
                }
            }

            ViewBag.CurrUserRoleType = roleId;

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

            for (int i = roleId - 1; i < roleList.Count && ViewBag.CurrUserRoleType != 3; i++)
            {
                if ((roleList[i].RoleId == 3)||(roleList[i].RoleId == 4))
                {
                    continue;
                }
                UserRole tempRole = new UserRole()
                {
                    RoleId = roleList[i].RoleId,
                    RoleName = roleList[i].RoleName
                };
                tempRoleList.Add(tempRole);
            }

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

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


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

            //return PartialView(userViewModel);

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

                return View();
            }

        }
        /// <summary>
        /// CreatedBy : Nadeeka
        /// CreatedDate: 2016/03/15
        /// 
        /// Get loan curtailment schedule by calling StepAccess class method, and creating curtailment date using that values
        /// 
        /// </summary>
        /// <param name="loanId"></param>
        public bool GetLoanCurtailmentDetails(int loanId, string unitId, DateTime advaceDate, decimal advanceAmount, decimal cost)
        {
            try
            {
                StepAccess stepAccess = new StepAccess();
            LoanSetupStep1 loan = stepAccess.GetLoanCurtailmentBreakdown(loanId);
            Int32 curtailmentNo = 1;
            //bool isEditAdvanceAmount = false;
            //isEditAdvanceAmount = ((cost * loan.advancePercentage) / 100) == advanceAmount ? false : true;
            foreach (Curtailment curtailment in loan.curtailmetList)
            {
                curtailment.CurtailmentId = curtailmentNo;
                //check pay off period as days or month               
                curtailment.CurtailmentDate = loan.payOffPeriodType == 0 ? (advaceDate.AddDays(Convert.ToDouble(curtailment.TimePeriod))) : advaceDate.AddMonths(curtailment.TimePeriod ?? 0);
                if (loan.CurtailmentCalculationBase == "f")
                { 
                    if (loan.curtailmetList.Count==curtailmentNo)
                    {
                        curtailment.Amount = Math.Round(advanceAmount - GetCurtailmentCurrentTotal(loan.curtailmetList),2);
                    }
                    else
                    {
                        curtailment.Amount = Math.Round(this.CalculateAdditionalPercentage(advanceAmount, curtailment.Percentage, loan.advancePercentage), 2);
                    }
                }
                else if (loan.CurtailmentCalculationBase == "a")
                {
                    if (loan.curtailmetList.Count == curtailmentNo)
                    {
                        curtailment.Amount = Math.Round(advanceAmount - GetCurtailmentCurrentTotal(loan.curtailmetList), 2);
                    }
                    else
                    {
                        curtailment.Amount = Math.Round((advanceAmount * curtailment.Percentage ?? 0) / 100, 2);
                    }                   
                }
                curtailmentNo++;
            }

           
                XElement xEle = new XElement("Curtailments",
                    from curtailment in loan.curtailmetList
                    select new XElement("Curtailment",
                        new XElement("LoanId", loanId),
                        new XElement("UnitId", unitId),
                        new XElement("CurtNo", curtailment.CurtailmentId),
                        new XElement("CurtAmount", curtailment.Amount),
                        new XElement("CurtDueDate", curtailment.CurtailmentDate),
                        new XElement("CurtStatus", 0)
                        ));
                string xmlDoc = xEle.ToString();
                CurtailmentAccess curtailmentAccess = new CurtailmentAccess();
                return curtailmentAccess.InsertCurtailmentScheduleInfo(xmlDoc, unitId, loanId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        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");
          
        }