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

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

            if (reslt>0)
            {
                ViewBag.SuccessMsg = "Branch is successfully added";
                return RedirectToAction("CreateBranch", "CreateBranch", new {success = 1 });
                //branch = new Branch();
                //return PartialView(branch);
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to add branch";
                return PartialView();
            }
        }
        // GET: CreateBranch
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateBranch(int success = 0)
        {

            if(success == 1)
            {
                ViewBag.SuccessMsg = "Branch is successfully added";
            }
            //Get states to list
            CompanyAccess ca = new CompanyAccess();
            List<State> stateList = ca.GetAllStates();
            ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");
            return PartialView();
        }
        /// <summary>
        /// CreatedBy : Kanishka SHM
        /// CreatedDate: 2016/02/08
        /// 
        /// generate company code
        /// 
        /// argument: companyName(string)
        /// 
        /// </summary>
        /// <returns>companyCode(string)</returns>
        public string GenerateNonRegCompanyCode(string companyName)
        {
            var prefix = companyName.Substring(0, 3).ToUpper();

            var ca = new CompanyAccess();
            var latestCode = ca.GetLatestNonRegCompanyCode(prefix);

            if (latestCode != "")
            {
                var sufix = (Convert.ToInt32(latestCode.Substring(3, latestCode.Length - 3)) + 1).ToString("00");
                return prefix + sufix;
            }
            return prefix + "01";
        }
        // 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");
        }
        /// <summary>
        /// CreatedBy : Kanishka SHM
        /// CreatedDate: 2016/01/18
        /// 
        /// Create company view
        /// </summary>
        /// <returns></returns>
        // GET: SetupCompany
        public ActionResult Setup()
        {
            if (Session["type"] == null)
                return RedirectToAction("UserLogin", "Login");
            var type = (string)Session["type"];
            //if (type == "CompanyEmployee")
            //{

            //}

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

            _user = (User) TempData["User"];
            List<CompanyType> ctList = ca.GetAllCompanyType();
            ViewBag.TypeId = new SelectList(ctList, "TypeId", "TypeName");



            return View();
        }
        /// <summary>
        /// Frontend page: Edit Partner Company
        /// Title: create view of Edit Partner Company
        /// Designed : Piyumi Perera
        /// User story:
        /// Developed: Piyumi Perera
        /// Date created: 5/4/2016
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPartnerCompanyAtDashboard()
        {
            //check user is super admin or admin
            if ((userData.RoleId == 1) || (userData.RoleId == 2))
            {
                CompanyAccess ca = new CompanyAccess();
                //get all states
                List<State> stateList = ca.GetAllStates();
                ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");
                PartnerCompany pc = new PartnerCompany();
                //get all non registered companies by registered company id
                pc.PartnerCompanyList = ca.GetNonRegCompanyDetailsByRegCompanyId2(userData.Company_Id);
                //check partner company list is null
                if (pc.PartnerCompanyList == null)
                {
                    //create empty partner company list
                    pc.PartnerCompanyList =  new List<PartnerCompany>();
                }
                //get company type by user id
                int comType = (new BranchAccess()).getCompanyTypeByUserId(userData.UserId);
                //company type 1(lender) - partner company type 2(dealer)
                //company type 2(dealer) - partner company type 1(lender)
                ViewBag.ThisCompanyType = (comType == 1) ? "Dealer" : "Lender";
                //check result of update partner company is null and value is 1
                if (TempData["partnerEditReslt"] != null && int.Parse(TempData["partnerEditReslt"].ToString()) == 1)
                {
                    //result 1 - success
                    ViewBag.SuccessMsg = "Partner Company Updated Successfully";
                }
                //check result of update partner company is null and value is 0
                else if (TempData["partnerEditReslt"] != null && int.Parse(TempData["partnerEditReslt"].ToString()) == 0)
                {
                    //result 0 - failure
                    ViewBag.ErrorMsg = "Failed to update partner company";
                }
                //return object to view
                return View(pc);
            }
            else
            {
                //if user is not super admin or admin return to login page
                return new HttpStatusCodeResult(404);
            }

        }
        public ActionResult CreatePartnerCompanyAtDashboard(PartnerCompany  partnerCompany)
        {
            //check user is super admin or admin
            if ((userData.RoleId == 1) || (userData.RoleId == 2))
            {
                //check object is not null
                if (partnerCompany != null)
                {
                  //set company zip code
                    partnerCompany.Zip = partnerCompany.ZipPre;
                    if (partnerCompany.Extension != null)
                        partnerCompany.Zip += "-" + partnerCompany.Extension;
                    //assign created by property value as logged user id
                    partnerCompany.CreatedBy = userData.UserId;
                    //assign created company type - (1-Lender, 2-Dealer)
                    partnerCompany.TypeId = (userData.CompanyType == 1) ? 2 : 1; ;
                   
                    CompanyAccess ca = new CompanyAccess();
                 
                    partnerCompany.RegCompanyId = userData.Company_Id; //regCompany.CompanyId;  asanka
                    //check result of create partner company
                    if (ca.InsertNonRegisteredCompanyAtDashboard(partnerCompany) == 1)
                    {
                        //assign result to TempData object
                        TempData["partnerReslt"] = 1;
                    }
                    else
                    {
                        TempData["partnerReslt"] = 0;
                    }
                    //return to create partner company page
                        return RedirectToAction("CreatePartnerCompanyAtDashboard");
                }
                else
                {
                    //if partner company object is null return to login page
                    return new HttpStatusCodeResult(404);
                }
            }
            else
            {
                //if user is not a super admin or admin return to login page
                return new HttpStatusCodeResult(404);
            }

            
        }
 public ActionResult CreatePartnerCompanyAtDashboard()
 {
     //check user is super admin or admin
     if ((userData.RoleId == 1) ||(userData.RoleId == 2))
     {
         //assign company type to variable
         int comType = userData.CompanyType;
         //company type 1 - Lender; Partner company type Dealer
         //company type 2 - Dealer; Partner company type Lender
         ViewBag.ThisCompanyType = (comType == 1) ? "Dealer" : "Lender";
         CompanyAccess ca = new CompanyAccess();
         //get all states
         List<State> stateList = ca.GetAllStates();
         ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");
         //check result of create partner company is not null and 1 - success
         if(TempData["partnerReslt"]!=null && int.Parse(TempData["partnerReslt"].ToString()) == 1)
         {
             ViewBag.SuccessMsg = "Partner Company Created Successfully";
         }
         //check result of create partner company is not null and 0 - failure
         else if (TempData["partnerReslt"] != null && int.Parse(TempData["partnerReslt"].ToString()) == 0)
         {
             ViewBag.ErrorMsg = "Failed to create partner company";
         }
         return View();
     }
     else
     {
         //if user is not a super admin or admin return to login page
         return new HttpStatusCodeResult(404);
     }
    
 }
        public ActionResult EditPartnerBranchAtDashboard(string lbls)
        {
            if (userData.RoleId != 1 && userData.RoleId != 2)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }

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

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

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

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

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

            ViewBag.Count = nonRegBranches.Count;

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

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

            return View(nonRegCompanyBranch);
        }
        public ActionResult 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 Step1()
        {
            int userId = userData.UserId;
            int roleId = userData.RoleId;
            CompanyAccess ca = new CompanyAccess();

            // check he is a super admin or admin
            if (roleId != 1)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "Could not authenticate you." });
            }

            // 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");
            //check company step is greate than or equal to 1
            if (Convert.ToInt32(Session["companyStep"]) >= 1)
            {
                //get company details
                Company preCompany = ca.GetCompanyDetailsCompanyId(userData.Company_Id);
               
                //check ajax request
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(preCompany);
                }
                else
                {

                    return View(preCompany);
                }
            }
            //if company step session is null return to login page with error message
            return new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
           
        }
        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, 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();

        }
        /// <summary>
        /// Frontend page: Edit Company
        /// Title: Get company details for edit company view
        /// Designed : Piyumi Perera
        /// User story:
        /// Developed: Piyumi Perera
        /// Date created: 2016/05/03
        /// </summary>
        /// <returns></returns>
        /// 

        public ActionResult EditCompany()
        {
            //check user is super admin
            if (userData.RoleId == 1)
            {
                
                Company cmp = new Company();
                CompanyAccess ca = new CompanyAccess();
                //Get states to list
                List<State> stateList = ca.GetAllStates();
                ViewBag.StateId = new SelectList(stateList, "StateId", "StateName");
                //check result of update company is not null and value is 1
                if (TempData["updateComReslt"]!=null && int.Parse(TempData["updateComReslt"].ToString()) == 1)
                {
                    ViewBag.SuccessMsg = "Company is updated successfully";
                    
                }
                //check result of update company is not null and value is 0
                else if (TempData["updateComReslt"] != null && int.Parse(TempData["updateComReslt"].ToString()) == 0)
                {
                    ViewBag.ErrorMsg = "Failed to update company";
                }
               
               //get company details of given company id
                cmp = ca.GetCompanyDetailsCompanyId(userData.Company_Id);
                //check company object is not null
                if (cmp != null)
                {
                    //return company object to view
                    return View(cmp);
                }
                else
                {
                    //return empty company object to view
                    cmp = new Company();
                    return View(cmp);
                }
            }
            else
            {
                //if user is not a super admin return to login page
                return new HttpStatusCodeResult(404);
            }
        }
        /// <summary>
        /// CreatedBy : Nadeeka
        /// CreatedDate: 2016/04/01
        /// 
        /// to show the view
        /// </summary>
        /// <returns></returns>
        public ActionResult AssignUserRights()
        {
            CompanyAccess ca = new CompanyAccess();
            BranchAccess ba = new BranchAccess();
            Loan loan = (Loan)Session["loanDashboard"];

            NonRegBranch nonRegBranches = ba.getNonRegBranchByNonRegBranchId(loan.NonRegBranchId);
            ViewBag.nonRegBranches = nonRegBranches.BranchName;// nonRegBranches.BranchName;
            ViewBag.nonRegCompany = nonRegBranches.CompanyNameBranchName;
            return View();
        }
        /// <summary>
        /// Frontend page: Join Dealer
        /// Title: view of Link Dealer page
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 2016/03/30
        /// Edited: Piyumi Perera
        /// </summary>
        /// <returns></returns>
        public ActionResult LinkDealer()
        {
            //Check result of Join Dealer page
            if(TempData["msg"] !=null )
            {
                //Check TempData["msg"] is 1
                if (TempData["msg"].ToString() == "1")
                {
                    ViewBag.SuccessMsg = "User Successfully Created";
                }
                //Check TempData["msg"] is 2
                else if (TempData["msg"].ToString() == "2")
                {
                    ViewBag.Error = "Error";
                }
            }
            CompanyAccess ca = new CompanyAccess();
            BranchAccess ba = new BranchAccess();
            Loan loan = new Loan();
            //Check Session["oneLoanDashboard"] is not null
            if (Session["oneLoanDashboard"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["oneLoanDashboard"];
            }
            //Check Session["loanDashboardJoinDealer"] is not null
            if (Session["loanDashboardJoinDealer"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["loanDashboardJoinDealer"];
            }
            //remove Session["popUpSelectionType"]
            Session.Remove("popUpSelectionType");
           //return non registered branch details by non registered branch id
            NonRegBranch nonRegBranches = ba.getNonRegBranchByNonRegBranchId(loan.NonRegBranchId);
            ViewBag.nonRegBranches = nonRegBranches.BranchName;
            ViewBag.nonRegCompany = nonRegBranches.CompanyNameBranchName;
            List<User> userList = new List<User>();
            //return all users of given company id
            userList = (new UserAccess()).GetUserListByCompany(userData.Company_Id);
            //filter user list who has authorization for selected loan
            userList = userList.FindAll(t => t.BranchId == loan.BranchId || (t.BranchId ==0 && t.RoleId==1));
            ViewBag.UserIdForSendReq = new SelectList(userList, "UserId", "UserName");

            //get report list for dealer user
            List<Right> ReportRightsList = new List<Right>();
            User us = new User();
            us.ReportRightsList = new List<Right>();
            ReportRightsList = (new UserRightsAccess()).getReportRights();
            if(ReportRightsList!=null && ReportRightsList.Count > 0)
            {
                foreach (Right rgt in ReportRightsList)
                {
                    //Check dealer user can view the report
                    if(!rgt.DealerView)
                    {
                        continue;
                    }
                    else
                    {
                        //check title need not to be tracked for selected loan and report right for Title Status
                        if ((loan.IsTitleTrack == 0) && (rgt.rightId=="R04"))
                        {
                            //if title need not to be tracked report right for Title Status is not added to right list
                            continue;
                        }
                        //check there is no advance fee for selected loan and report right for advance fee invoice and advance fee receipt
                        if ((loan.AdvanceFee == 0) && ((rgt.rightId == "R07")||(rgt.rightId == "R08")))
                        {
                            //if there is no advance fee, report right for advance fee invoice and advance fee receipt are not added to right list
                            continue;
                        }
                        //check there is no monthly loan fee for selected loan and report right for monthly loan fee invoice and monthly loan fee receipt
                        if ((loan.MonthlyLoanFee == 0) && ((rgt.rightId == "R09") || (rgt.rightId == "R10")))
                        {
                            //if there is no monthly loan fee, report right for monthly loan fee invoice and monthly loan fee receipt are not added to right list
                            continue;
                        }
                        //check there is no lot inspection fee for selected loan and report right for lot inspection fee invoice and lot inspection fee receipt
                        if ((loan.LotInspectionFee == 0) && ((rgt.rightId == "R11") || (rgt.rightId == "R12")))
                        {
                            //if there is no lot inspection fee, report right for lot inspection fee invoice and lot inspection fee receipt are not added to right list
                            continue;
                        }
                    }
                    us.ReportRightsList.Add(rgt);
                }
            }
            //Check user is super admin
            if (userData.RoleId == 1)
            {
                //convert user list to session object
                Session["UserReqList"] = userList;
            }
            //Check user is admin
            else if (userData.RoleId == 2)
            {
                //convert user list to session object
                Session["UserReqList"] = userList;
            }
            else
            {
                //return to dashboard
                return RedirectToAction("UserDetails", "UserManagement");
            }
            return View(us);
        }
        public ActionResult 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 Step2(string edit1,int? edit)
        {
          
            int userId = userData.UserId;
            int roleId = userData.RoleId;
            // check he is a super admin or admin

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

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

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


                userCompany.Company = preCompany;

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

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

                    return View(userCompany);
                }


            }
            else
            {
                //if company step is less than 2 return to login page with error message
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }
        }
        public ActionResult 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 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);
            }
        }
        /// <summary>
        /// CreatedBy: Kanishka
        /// CreatedDate:2016/1/18
        /// insert first branch details
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateBranchFirstBranch()
        {
            var type = (string)Session["type"];
            if (type == "CompanyEmployee")
            {
                ViewBag.Type = "CompanyEmployee";
                _type = "CompanyEmployee";

                if (TempData["UserCompany"] == null) return RedirectToAction("EmployeeLogin", "Login");

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

                _userCompany = (UserCompanyModel) TempData["UserCompany"];
                _userCompany.Branch = new Branch();

                return View(_userCompany);
            }
            else
            {
                ViewBag.Type = "";
                return RedirectToAction("EmployeeLogin", "Login");
            }
            
        }
        public ActionResult CreateDashboardBranch(CompanyBranchModel userCompany2, string branchCode)
        {
            CompanyAccess userCompany = new CompanyAccess();
            
            int userId = userData.UserId;

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

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

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

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

            return RedirectToAction("CreateDashboardBranch");
            
        }
        /// <summary>
        /// CreatedBy : Irfan MAM
        /// CreatedDate: 2016/01/27
        /// Calling the default view for all step number pages
        /// Redirect to Appropriate controller using step number
        /// 
        /// 
        /// 
        /// </summary>
        /// <returns>Return the view</returns>

        public ActionResult Index()
        {
            //convert Session["companyStep"] to int value
            int stepNo = Convert.ToInt32(Session["companyStep"]);
            //assign logged user id to variable
            int userId = userData.UserId;
            //add step no and loan step(loan setup step 1 is considerd as step 6)
            stepNo = stepNo + loanstep;

            ViewBag.Step = stepNo;
            //assign step number to session variable
            Session["stepNo"] = stepNo;
            //Get company details if branch same as company
            //check step number
            //stepNo 2 - Branch setup
            if (stepNo == 2)
            {
                CompanyAccess ca = new CompanyAccess();
                Company company = ca.GetCompanyDetailsCompanyId(userData.Company_Id);

                //return View();
                return RedirectToAction("Step2");
            }
            //stepNo 5 - Partner Branch setup
            else if (stepNo == 5)
            {
                CompanyAccess ca = new CompanyAccess();
                //get partner company details
                Company nonRegCompany = ca.GetNonRegCompanyDetailsByRegCompanyId(userData.Company_Id);
                //if no partcompanies return to step 4 (Partner Company Setup)
                if (string.IsNullOrEmpty(nonRegCompany.CompanyName)) return RedirectToAction("Step4", "SetupProcess");

                CompanyBranchModel comBranch = new CompanyBranchModel();
                comBranch.Company = nonRegCompany;
                //assign returned partner company object to TempData object
                TempData["NonRegCompany"] = comBranch;

                //return View();
                return RedirectToAction("Step5");
            }
            //check stepNo is 0 and return to login page
            else if (stepNo == 0)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "Company Setup is on going Please Contact Admin" });
            }
            //return to appropriate step
            else
            {
                return RedirectToAction("Step" + stepNo);
            }
        }
        public ActionResult CreateBranchFirstBranch(UserCompanyModel userCompany)
        {
            if (_type == "CompanyEmployee")
            {
                ViewBag.Type = "CompanyEmployee";
                BranchAccess ba = new BranchAccess();
                userCompany.Branch.BranchCode = ba.createBranchCode(_userCompany.Company.CompanyCode);
                _userCompany.Branch = userCompany.Branch;
                _userCompany.Branch.StateId = userCompany.StateId;
                CompanyAccess ca = new CompanyAccess();
                //if (ca.SetupCompany(_userCompany))
                if (ca.SetupCompanyRollback(_userCompany))
                {
                    ViewBag.SuccessMsg = "Company is successfully setup";
                    return View();
                }
                else
                {
                    ViewBag.ErrorMsg = "Failed to setup company";
                    return RedirectToAction("CreateFirstSuperUser", "CreateUser");
                }

            }
            return View();
        }
        public ActionResult EditDashboardBranch()
        {
            CompanyBranchModel userCompany;

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


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

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

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

            userCompany = new CompanyBranchModel();

            ViewBag.BranchIndex = 0;

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

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

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

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

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

            int userId = userData.UserId;

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

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

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

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

            return RedirectToAction("EditDashboardBranch");

        }
        public ActionResult 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 Create(User user)
        {


            int currentUser =0;
            try
            {
                currentUser = int.Parse(Session["userId"].ToString());
            }
            catch (Exception) {
                return RedirectToAction("UserLogin", "Login");
            }

            user.CreatedBy = _createById;
            user.IsDelete = false;
            user.Status = false;

            //Set admin branch to new user 
            if (_curUserRoleId == 2)
            {
                user.BranchId = _curBranchId;
            }

            //Check role is selected
            if (user.RoleId == 0)
                user.RoleId = 2;

            //Check branch is selected
            if (_curUserRoleId == 1 && user.BranchId == 0)
            {
                user.BranchId = _curBranchId;
            }
            string passwordTemp = user.Password;

            UserAccess ua = new UserAccess();

            string newSalt = PasswordEncryption.RandomString();
            user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
            user.Email = user.NewEmail;

            //Check this
            CompanyAccess ca = new CompanyAccess();
            Company company = new Company();//ca.GetCompanyDetailsByFirstSpUserId(currentUser);
            //Insert user
            user.Company_Id = company.CompanyId;
            int res = ua.InsertUser(user);

            //Insert new user to user activation table
            string activationCode = Guid.NewGuid().ToString();
            int userId = (new UserAccess()).getUserId(user.Email);
            res = ua.InsertUserActivation(userId, activationCode);
            if (res == 1)
            {
                ViewBag.SuccessMsg = "Data Successfully inserted!";
                
                string body = "Hi " + user.FirstName + "! <br /><br /> Your account has been successfully created. Below in your account detail." +
                              "<br /><br /> User name: " + user.UserName +
                                    "<br /> Password : <b>" + passwordTemp +
                              "<br />Click <a href='http://localhost:57318/CreateUser/ConfirmAccount?userId=" + userId + "&activationCode=" + activationCode + "'>here</a> to activate your account." +
                              "<br /><br/> Thanks,<br /> Admin.";

                Email email = new Email(user.Email);
                email.SendMail(body, "Account details");

                
                // check the user as superadmin or admin..
                if (user.RoleId == 1 || user.RoleId == 2)
                {
                    ViewBag.SuccessMsg = "User Successfully Created";
                    

                   
                    return RedirectToAction("create",new { lbls = ViewBag.SuccessMsg });
                }

                Session["editUserIds"] = userId;


                return RedirectToAction("SetRights", "EditRights", new {@lbl1 = ViewBag.SuccessMsg });
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to create user!";

                //Restrict to create above user role 
                RoleAccess ra = new RoleAccess();
                List<UserRole> roleList = ra.GetAllUserRoles();
                List<UserRole> tempRoleList = new List<UserRole>();

                for (int i = roleList[_curUserRoleId - 1].RoleId; i <= roleList.Count && _curUserRoleId != 3; i++)
                {
                    UserRole tempRole = new UserRole()
                    {
                        RoleId = roleList[i - 1].RoleId,
                        RoleName = roleList[i - 1].RoleName
                    };
                    tempRoleList.Add(tempRole);
                }

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

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


                return PartialView("Create");
            }
        }
        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");
          
        }