public ActionResult Setup(Company company)
        {
            if (Session["type"] == null)
                return RedirectToAction("UserLogin", "Login");

            //if (type == "CompanyEmployee")
            //{

            //}

            GeneratesCode gc = new GeneratesCode();
            company.CompanyCode = gc.GenerateCompanyCode(company.CompanyName);

            UserCompanyModel userCom = new UserCompanyModel();
            userCom.User = _user;

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

            userCom.Company = company;

            TempData["UserCompany"] = userCom;
            return RedirectToAction("CreateBranchFirstBranch", "CreateBranch", new { id = 0, type = "CompanyEmployee" });
        }
        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 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 EditCompany(Company company)
        {
            //check user is super admin
            if (userData.RoleId == 1)
            {
                //set zip code 
                company.Zip = company.ZipPre;
                if (company.Extension != null)
                    company.Zip += "-" + company.Extension;
                //get result of update company
                int reslt = (new CompanyAccess().UpdateCompany(company,userData.UserId));
                //check update result is 1
                if(reslt == 1)
                {
                    //insert log data
                    Log log = new Log(userData.UserId, userData.Company_Id, 0, 0, "Edit Company", "Edit Company : " + userData.Company_Id, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                    //assign result to TempData object
                    TempData["updateComReslt"] = reslt;
                    //check Session["AuthenticatedUser"] is not null
                    if (Session["AuthenticatedUser"] != null)
                    {
                        //assign updated company name to session company name 
                        ((User)Session["AuthenticatedUser"]).CompanyName = company.CompanyName;
                    }
                }
                else
                {
                    TempData["updateComReslt"] = 0;
                }
                //return to edit company view
                return RedirectToAction("EditCompany");
            }
            else
            {
                //if user is not super admin return to login page
                return new HttpStatusCodeResult(404);
            }
        }
        /// <summary>
        /// CreatedBy : Kanishka SHM
        /// CreatedDate: 01/27/2016
        /// </summary>
        /// <param name="regCompanyId"></param>
        /// <returns></returns>
        public Company GetNonRegCompanyDetailsByRegCompanyId(int regCompanyId)
        {

            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();

            paramertList.Add(new object[] { "@reg_company_id", regCompanyId });
            try
            {
                Company company = new Company();
                DataSet dsCompany = dataHandler.GetDataSet("spGetNonRegCompanyDetailsByRegCompanyId", paramertList);

                company.CompanyId = int.Parse(dsCompany.Tables[0].Rows[0]["company_Id"].ToString());
                company.CompanyName = dsCompany.Tables[0].Rows[0]["company_name"].ToString();
                company.CompanyCode = dsCompany.Tables[0].Rows[0]["company_code"].ToString();
                company.CompanyAddress1 = dsCompany.Tables[0].Rows[0]["company_address_1"].ToString();
                company.CompanyAddress2 = dsCompany.Tables[0].Rows[0]["company_address_2"].ToString();
                company.StateId = int.Parse(dsCompany.Tables[0].Rows[0]["stateId"].ToString());
                company.City = dsCompany.Tables[0].Rows[0]["city"].ToString();
                company.Zip = dsCompany.Tables[0].Rows[0]["zip"].ToString();

                string[] zipWithExtention = company.Zip.Split('-');

                if (zipWithExtention[0] != null) company.ZipPre = zipWithExtention[0];
                if (zipWithExtention.Count() >= 2 && zipWithExtention[1] != null) company.Extension = zipWithExtention[1];

                company.Email = dsCompany.Tables[0].Rows[0]["email"].ToString();
                company.PhoneNum1 = dsCompany.Tables[0].Rows[0]["phone_num_1"].ToString().Trim();
                company.PhoneNum2 = dsCompany.Tables[0].Rows[0]["phone_num_2"].ToString().Trim();
                company.PhoneNum3 = dsCompany.Tables[0].Rows[0]["phone_num_3"].ToString().Trim();
                company.Fax = dsCompany.Tables[0].Rows[0]["fax"].ToString().Trim();
                company.WebsiteUrl = dsCompany.Tables[0].Rows[0]["website_url"].ToString();
                company.TypeId = int.Parse(dsCompany.Tables[0].Rows[0]["company_type"].ToString());

                return company;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <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 : Kanishka SHM
        /// CreatedDate: 01/26/2016
        /// 
        /// Insert company in setup process
        /// 
        /// UpdatedBy : nadeeka
        /// UpdatedDate: 2016/03/06
        /// removed existing connection open method and set parameter's to object list and pass stored procedure name to
        /// call DataHandler class to save company object
        /// 
        /// </summary>
        /// <param name="company"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public int InsertCompany(Company company, string type)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@company_name", company.CompanyName ?? "" });
            paramertList.Add(new object[] { "@company_code", company.CompanyCode ?? "" });
            paramertList.Add(new object[] { "@company_address_1", company.CompanyAddress1 ?? "" });
            paramertList.Add(new object[] { "@company_address_2", company.CompanyAddress2 ?? "" });
            paramertList.Add(new object[] { "@stateId", company.StateId });
            paramertList.Add(new object[] { "@city", company.City ?? "" });
            paramertList.Add(new object[] { "@zip", company.Zip ?? "" });
            paramertList.Add(new object[] { "@email", company.Email ?? "" });
            paramertList.Add(new object[] { "@phone_num_1", company.PhoneNum1 ?? "" });
            paramertList.Add(new object[] { "@phone_num_2", company.PhoneNum2 ?? "" });
            paramertList.Add(new object[] { "@phone_num_3", company.PhoneNum3 ?? "" });
            paramertList.Add(new object[] { "@fax", company.Fax ?? "" });
            paramertList.Add(new object[] { "@website_url", company.WebsiteUrl ?? "" });
            paramertList.Add(new object[] { "@created_by", company.CreatedBy });
            paramertList.Add(new object[] { "@created_date", DateTime.Now });
            paramertList.Add(new object[] { "@company_type", company.TypeId });
            paramertList.Add(new object[] { "@first_super_admin_id", company.FirstSuperAdminId });
            paramertList.Add(new object[] { "@company_status", company.CompanyStatus });
            paramertList.Add(new object[] { "@transaction_type", type });

            try
            {
                return dataHandler.ExecuteSQLWithReturnVal("spInsertCompany", paramertList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : Irfan
        /// CreatedDate: 01/27/2016
        /// 
        /// Insert company in setup process 
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>
        public bool InsertNonRegisteredCompany(Company company)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@company_name", company.CompanyName.Trim() });
            paramertList.Add(new object[] { "@company_code", company.CompanyCode.Trim() });
            paramertList.Add(new object[] { "@company_address_1", company.CompanyAddress1.Trim() });
            if (!string.IsNullOrEmpty(company.CompanyAddress2))
            {
                company.CompanyAddress2.Trim();
                paramertList.Add(new object[] { "@company_address_2", company.CompanyAddress2.Trim() });
            }
           
            paramertList.Add(new object[] { "@stateId", company.StateId });
            paramertList.Add(new object[] { "@city", company.City.Trim() });
            paramertList.Add(new object[] { "@zip", company.Zip.Trim() });
            if (!string.IsNullOrEmpty(company.Email))
            {
                company.Email.Trim();
            }
            if (!string.IsNullOrEmpty(company.PhoneNum2))
            {
                company.PhoneNum2.Trim();
            }
            if (!string.IsNullOrEmpty(company.PhoneNum3))
            {
                company.PhoneNum3.Trim();
            }
            paramertList.Add(new object[] { "@email", company.Email });
            paramertList.Add(new object[] { "@phone_num_1", company.PhoneNum1 });
            paramertList.Add(new object[] { "@phone_num_2", company.PhoneNum2 });
            paramertList.Add(new object[] { "@phone_num_3", company.PhoneNum3 });
            paramertList.Add(new object[] { "@fax", company.Fax });
            paramertList.Add(new object[] { "@website_url", company.WebsiteUrl });
            paramertList.Add(new object[] { "@created_by", company.CreatedBy });
            paramertList.Add(new object[] { "@created_date", DateTime.Now });
            paramertList.Add(new object[] { "@company_type", company.TypeId });
            paramertList.Add(new object[] { "@reg_company_id", company.CreatedByCompany });


            try
            {
                return dataHandler.ExecuteSQL("spInsertNonRegisteredCompany", paramertList);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        public Company GetNonRegCompanyByCompanyId(int companyId)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@company_id", companyId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetNonRegCompanyByCompanyId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    DataRow dataRow = dataSet.Tables[0].Rows[0];
                    Company nonRegCompany = new Company();

                    nonRegCompany.CompanyId = Convert.ToInt32(dataRow["company_id"]);
                    nonRegCompany.CompanyName = dataRow["company_name"].ToString();
                    nonRegCompany.CompanyCode = dataRow["company_code"].ToString();
                    nonRegCompany.CompanyAddress1 = dataRow["company_address_1"].ToString();
                    nonRegCompany.CompanyAddress2 = dataRow["company_address_2"].ToString();
                    nonRegCompany.StateId = Convert.ToInt32(dataRow["stateId"]);
                    nonRegCompany.City = dataRow["city"].ToString();
                    nonRegCompany.Zip = dataRow["zip"].ToString();

                    string[] zipWithExtention = nonRegCompany.Zip.Split('-');

                    if (zipWithExtention[0] != null) nonRegCompany.ZipPre = zipWithExtention[0];
                    if (zipWithExtention.Count() >= 2 && zipWithExtention[1] != null) nonRegCompany.Extension = zipWithExtention[1];

                    nonRegCompany.Email = dataRow["email"].ToString();
                    nonRegCompany.PhoneNum1 = dataRow["phone_num_1"].ToString();
                    nonRegCompany.PhoneNum2 = dataRow["phone_num_2"].ToString();
                    nonRegCompany.PhoneNum3 = dataRow["phone_num_3"].ToString();
                    nonRegCompany.Fax = dataRow["fax"].ToString();



                    return nonRegCompany;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// CreatedBy:Piyumi
        /// CreatedDate:5/3/2016
        /// Update Company details
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>
        public int UpdateCompany(Company company,int userId)
        {
            if (company != null)
            {
                DataHandler dataHandler = new DataHandler();
                List<object[]> paramertList = new List<object[]>();


                paramertList.Add(new object[] { "@company_id", company.CompanyId });
                paramertList.Add(new object[] { "@company_name", company.CompanyName });
                paramertList.Add(new object[] { "@address1", company.CompanyAddress1 });
                if (!string.IsNullOrEmpty(company.CompanyAddress2)){
                    paramertList.Add(new object[] { "@address2", company.CompanyAddress2 });
                }
                else
                {
                    paramertList.Add(new object[] { "@address2", null });
                }
                paramertList.Add(new object[] { "@city",company.City });
                paramertList.Add(new object[] { "@state", company.StateId });
                paramertList.Add(new object[] { "@zip", company.Zip });
                paramertList.Add(new object[] { "@phone_no", company.PhoneNum1 });
                if (!string.IsNullOrEmpty(company.PhoneNum2))
                {
                    paramertList.Add(new object[] { "@phone_no2", company.PhoneNum2 });
                }
                else
                {
                    paramertList.Add(new object[] { "@phone_no2", null });
                }
                if (!string.IsNullOrEmpty(company.PhoneNum3))
                {
                    paramertList.Add(new object[] { "@phone_no3", company.PhoneNum3 });
                }
                else
                {
                    paramertList.Add(new object[] { "@phone_no3", null });
                }

                if (!string.IsNullOrEmpty(company.Fax))
                {
                    paramertList.Add(new object[] { "@fax", company.Fax });
                }
                else
                {
                    paramertList.Add(new object[] { "@fax", null });
                }
                if (!string.IsNullOrEmpty(company.Email))
                {
                    paramertList.Add(new object[] { "@email", company.Email });
                }
                else
                {
                    paramertList.Add(new object[] { "@email", null });
                }
                if (!string.IsNullOrEmpty(company.WebsiteUrl))
                {
                    paramertList.Add(new object[] { "@web", company.WebsiteUrl });
                }
                else
                {
                    paramertList.Add(new object[] { "@web", null });
                }
                paramertList.Add(new object[] { "@modified_date", DateTime.Now });
                paramertList.Add(new object[] { "@modified_by", userId });

                try
                {
                    return dataHandler.ExecuteSQLReturn("spUpdateCompany", paramertList);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                return 0;
            }
        }
        public List<Company> GetCompanyByCreayedCompany(int createdByComId)
        {
            List<Company> nonRegCompanies = new List<Company>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@reg_company_id", createdByComId });
            
                try
                {
                    DataSet dsCompany = dataHandler.GetDataSet("spGetNonRegCompanyByCreatedCompany", paramertList);
                    if (dsCompany != null && dsCompany.Tables.Count != 0)
                    {
                        foreach (DataRow dataRow in dsCompany.Tables[0].Rows)
                        {
                           
                            Company company = new Company();
                            company.CompanyId = Convert.ToInt32(dataRow["company_id"]);
                            company.CompanyName = dataRow["company_name"].ToString().Trim();
                            company.CompanyCode = dataRow["company_code"].ToString().Trim();
                            company.CompanyAddress1 = dataRow["company_address_1"].ToString().Trim();
                            company.CompanyAddress2 = dataRow["company_address_2"].ToString().Trim();
                            company.StateId = Convert.ToInt32(dataRow["stateId"]);
                            company.City = dataRow["city"].ToString().Trim();
                            company.Zip = dataRow["zip"].ToString().Trim();

                            string[] zipWithExtention = company.Zip.Split('-');

                            if (zipWithExtention[0] != null) company.ZipPre = zipWithExtention[0];
                            if (zipWithExtention.Count() >= 2 && zipWithExtention[1] != null) company.Extension = zipWithExtention[1];
                            else if (zipWithExtention.Count() == 1) company.Extension = "";

                            company.Email = dataRow["email"].ToString().Trim();
                            company.PhoneNum1 = dataRow["phone_num_1"].ToString().Trim();
                            company.PhoneNum2 = dataRow["phone_num_2"].ToString().Trim();
                            company.PhoneNum3 = dataRow["phone_num_3"].ToString().Trim();
                            company.Fax = dataRow["fax"].ToString().Trim();
                        company.WebsiteUrl = dataRow["website_url"] == null ? "" : dataRow["website_url"].ToString();

                            nonRegCompanies.Add(company);
                        }

                    }
                }
            catch (Exception ex)
            {
                throw ex;
            }


            return nonRegCompanies;
        }
        /// <summary>
        ///  CreatedBy : Asanka Senarathna
        ///  CreatedDate: 9/03/201
        ///  Pass company list object to addunit page
        /// </summary>
        /// <param name="regCompanyId"></param>
        /// <returns></returns>
        public List<Company> GetNonRegCompanyDetailsByRegCompanyId1(int regCompanyId)
        {
            List<Company> companyList = new List<Company>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@reg_company_id", regCompanyId });

            try
            {
                DataSet dsCompany = dataHandler.GetDataSet("spGetNonRegCompanyDetailsByRegCompanyId", paramertList);
                if (dsCompany != null && dsCompany.Tables.Count != 0)
                {
                    foreach (DataRow dataRow in dsCompany.Tables[0].Rows)
                    {
                        Company company = new Company();
                        company.CompanyId = int.Parse(dsCompany.Tables[0].Rows[0]["company_Id"].ToString());
                        company.CompanyName = dsCompany.Tables[0].Rows[0]["company_name"].ToString();
                        company.CompanyCode = dsCompany.Tables[0].Rows[0]["company_code"].ToString();
                        company.CompanyAddress1 = dsCompany.Tables[0].Rows[0]["company_address_1"].ToString();
                        company.CompanyAddress2 = dsCompany.Tables[0].Rows[0]["company_address_2"].ToString();
                        company.StateId = int.Parse(dsCompany.Tables[0].Rows[0]["stateId"].ToString());
                        company.City = dsCompany.Tables[0].Rows[0]["city"].ToString();
                        company.Zip = dsCompany.Tables[0].Rows[0]["zip"].ToString();
                        company.Email = dsCompany.Tables[0].Rows[0]["email"].ToString();
                        company.PhoneNum1 = dsCompany.Tables[0].Rows[0]["phone_num_1"].ToString();
                        company.PhoneNum2 = dsCompany.Tables[0].Rows[0]["phone_num_2"].ToString();
                        company.PhoneNum3 = dsCompany.Tables[0].Rows[0]["phone_num_3"].ToString();
                        company.Fax = dsCompany.Tables[0].Rows[0]["fax"].ToString();
                        companyList.Add(company);
                    }
                    return companyList;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        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 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);
            }

        }