public ActionResult CreateDashboardUser(User userObj)
        {
            //assign phone number to object property
            userObj.PhoneNumber = userObj.PhoneNumber2;
            //assign user id to variable
            int currentUser = userData.UserId;

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

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

            userObj.Email = userObj.NewEmail;

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

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

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

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

                Email email = new Email(userObj.Email);

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

                }

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

            }
            else
            {
                TempData["createUserResult"] = 0;
                //return View();
            }
            return RedirectToAction("CreateDashboardUser");
        }
        public ActionResult CreateDashboardBranch(CompanyBranchModel userCompany2, string branchCode)
        {
            CompanyAccess userCompany = new CompanyAccess();
            
            int userId = userData.UserId;

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

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

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

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

            return RedirectToAction("CreateDashboardBranch");
            
        }
        public ActionResult Step3(string lbls)
        {

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

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

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

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

           

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

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


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

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

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

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

                

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

                    return View();
                }
            }

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


                ViewBag.ErrorMsg = "Failed to create user";

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

                    return View();
                }
            }

            ViewBag.CurrUserRoleType = roleId;

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

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

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

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


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

            //return PartialView(userViewModel);

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

                return View();
            }

        }
        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 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 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");
          
        }