// Check session in page initial stage
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                if (Session["AuthenticatedUser"] != null)
                {
                    userData = ((User)Session["AuthenticatedUser"]);
                    
                }
                else
                {

                    if (HttpContext.Request.IsAjaxRequest())
                    {

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

                        filterContext.Result = new RedirectResult("/Login/UserLogin?lbl=Due to inactivity your session has timed out, please log in again.");
                    }
                    
                   
                }
            }
            catch
            {
                
                filterContext.Result = new RedirectResult("~/Exceptions/Index");
            }
        }
        // Check session in page initia stage
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                if (Session["AuthenticatedUser"] != null)
                {
                    userData = ((User)Session["AuthenticatedUser"]);
                }
                else
                {
                    if (HttpContext.Request.IsAjaxRequest())
                    {

                        //new HttpStatusCodeResult(404, "Failed to Setup company.");
                        filterContext.Result = new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
                    }
                    else
                    {

                        filterContext.Result = new RedirectResult("/Login/UserLogin?lbl=Due to inactivity your session has timed out, please log in again.");
                    }
                }
            }
            catch(Exception)
            {
                //filterContext.Result = new RedirectResult("~/Login/UserLogin");
                //filterContext.Controller.TempData.Add("UserLogin", "Login");
                filterContext.Result = new RedirectResult("~/Exceptions/Index");
            }
        }
        /// <summary>
        /// CreatedBy : Kanishka SHM
        /// CreatedDate: 2016/01/16
        /// 
        /// Insert User details
        /// 
        /// argument : user (User)
        /// 
        /// 
        /// UpdatedBy : nadeeka
        /// UpdatedDate: 2016/03/03
        /// removed existing connection open method and set parameter's to object list and pass stored procedure name to
        /// call DataHandler class to save user object
        /// </summary>
        /// <returns>1</returns>
        public int InsertUser(User user)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@user_Id", user.UserId });
            paramertList.Add(new object[] { "@user_name", user.UserName });
            paramertList.Add(new object[] { "@password", user.Password });
            paramertList.Add(new object[] { "@first_name", user.FirstName });
            paramertList.Add(new object[] { "@last_name", user.LastName });
            paramertList.Add(new object[] { "@email", user.Email });
            paramertList.Add(new object[] { "@phone_no", user.PhoneNumber });
            paramertList.Add(new object[] { "@status", user.Status });
            paramertList.Add(new object[] { "@is_delete", user.IsDelete });
            paramertList.Add(new object[] { "@created_by", user.CreatedBy });
            paramertList.Add(new object[] { "@create_Date", DateTime.Now });
            paramertList.Add(new object[] { "@branch_id", user.BranchId });
            paramertList.Add(new object[] { "@role_id", user.RoleId });
            paramertList.Add(new object[] { "@Company_id", user.Company_Id });
            paramertList.Add(new object[] { "@step_status", user.step_status });

            try
            {
                return dataHandler.ExecuteSQLReturn("spInsertUser", paramertList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy:Irfan MAM
        /// CreatedDate:2016/2/9
        /// check the loan number is unique for a branch
        /// </summary>
        /// <returns>true or false</returns>
        public bool IsUniqueLoanNumberForBranch(string loanNumber, int RegisteredBranchId, User user,int loanId)
        {
            try
            {
                DataHandler dataHandler = new DataHandler();
                List<object[]> paramertList = new List<object[]>();
                paramertList.Add(new object[] { "@loan_number", loanNumber });
                paramertList.Add(new object[] { "@branch_id", RegisteredBranchId });
                paramertList.Add(new object[] { "@loan_id", loanId });
                DataSet dataSet = dataHandler.GetDataSet("spIsUniqueLoanNumberForBranch", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        // Check session in page initia stage
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                if ((Session["AuthenticatedUser"] != null))// || (Session["loanStep"] != null)
                 {    
                    userData = ((User)Session["AuthenticatedUser"]);
                    if (Session["loanStep"] != null)
                    {
                        
                        loanData = ((LoanSetupStep)Session["loanStep"]);
                        Session["companyStep"] = 5;

                        if(loanData.loanId > 0)
                        {
                            loanstep = loanData.stepId;
                            CurtailmentAccess curtailmentAccess = new CurtailmentAccess();

                           
                            _loan = curtailmentAccess.GetLoanDetailsByLoanId(loanData.loanId);
                            
                            Session["isInterest"] = _loan.isInterestCalculate;
                        }
                        else if (loanData.loanId == 0)
                        {
                            loanstep = 1;
                            //CurtailmentAccess curtailmentAccess = new CurtailmentAccess();


                            // _loan = curtailmentAccess.GetLoanDetailsByLoanId(loanData.loanId);

                            // Session["isInterest"] = _loan.isInterestCalculate;
                        }
                    }
                }
                else
                {
                    if (HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.Result = new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
                    }
                    else
                    {

                        filterContext.Result = new RedirectResult("/Login/UserLogin?lbl=Due to inactivity your session has timed out, please log in again.");
                    }
                }
            }
            catch
            {
                filterContext.Result = new RedirectResult("~/Exceptions/Index");
            }
        }
 public DataSet SelectRequestAns(User user)
 {
     try
     {
         DataHandler dataHandler = new DataHandler();
         List<object[]> paramertList = new List<object[]>();
         paramertList.Add(new object[] { "@user_id", user.UserId });
         return dataHandler.GetDataSet("spGetUserReque", paramertList);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 /// <summary>
 /// CreatedBy : Kasun Samarawickrama
 /// CreatedDate: 2016/01/14
 /// 
 /// user login authentication
 /// 
 /// UpdatedBy : Asanka
 /// UpdatedDate: 2016/03/04
 /// removed existing connection open method and set parameter's to object list and pass stored procedure name to
 /// call DataHandler class to save user object
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// 
 /// <returns>userid</returns>
 public DataSet CheckUserLogin(User user)
 {
     DataHandler dataHandler = new DataHandler();
     List<object[]> paramertList = new List<object[]>();
     
     paramertList.Add(new object[] { "@userName", user.UserName });
     try
     {
         return dataHandler.GetDataSet("spUserLogin", paramertList);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 // Check session in page initia stage
 protected override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     if (Session["AuthenticatedUser"] != null)
     {
         try
         {
             userData = ((User)Session["AuthenticatedUser"]);
         }
         catch
         {
             filterContext.Controller.TempData.Add("UserLogin", "Login");
         }
     }
     else
     {
         filterContext.Controller.TempData.Add("UserLogin", "Login");
         //filterContext.Result = new RedirectResult("~/Login/UserLogin");
         //return RedirectToAction("UserLogin", "Login", new { lbl = "Your Session Expired" });
     }
 }
        /// <summary>
        // Frontend Page: Report page(Branch Summary report)
        /// Title: Display Branch Summary report
        /// Designed: Piyumi Perera
        /// User story: 
        /// Developed: Piyumi Perera
        /// Date created: 
        /// </summary>
        public void RenderReport(int branchId,string branchName, List<RptBranchSummary> branchSummary)
        {
            //check authentication session is null, if null return
            if (Session["AuthenticatedUser"] == null) return;
            User userData = (User)Session["AuthenticatedUser"];

            //set reportviewr properties
            rptViewerBranchSummary.ProcessingMode = ProcessingMode.Local;
            rptViewerBranchSummary.Reset();
            rptViewerBranchSummary.LocalReport.EnableExternalImages = true;
            rptViewerBranchSummary.LocalReport.ReportPath = Server.MapPath("~/Reports/RptBranchSummary.rdlc");
            rptViewerBranchSummary.ZoomMode = ZoomMode.PageWidth;

            ReportAccess ra = new ReportAccess();
            User usr = new User();
            usr = (new UserAccess()).retreiveUserByUserId(userData.UserId);
            List<LoanDetailsRpt> details = new List<LoanDetailsRpt>();
            LoanDetailsRpt detail = new LoanDetailsRpt();
            detail.CompanyName = userData.CompanyName;
            if (userData.RoleId == 1)
            {
                detail.LenderBrnchName = branchName;
            }
            else
            {
                detail.LenderBrnchName = userData.BranchName;
            }
            
            detail.ReportDate = DateTime.Now.ToString("MM/dd/yyyy");
            detail.CreaterName = usr.FirstName + " " + usr.LastName;
            details.Add(detail);
            rptViewerBranchSummary.LocalReport.DataSources.Add(new ReportDataSource("DataSet2", details));

            foreach (var dates in details)
            {
                dates.ReportDate = DateTime.Now.ToString("MM/dd/yyyy");
            }
            
            rptViewerBranchSummary.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", branchSummary));
        }
        /// <summary>
        /// CreatedBy : Kasun Smarawickrama
        /// CreatedDate: 2016/01/14
        /// 
        /// user dashboard view
        /// </summary>
        /// <param name="id">userid fromlogin page</param>
        /// <returns></returns>

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                if (Session["AuthenticatedUser"] != null)
                {
                    userData = ((User)Session["AuthenticatedUser"]);
                }
                else
                {
                    //return RedirectToAction("UserLogin", "Login", new { lbl = "Your Session Expired" });
                    //filterContext.Controller.TempData.Add("UserLogin", "Login");
                    filterContext.Result = new RedirectResult("/Login/UserLogin?lbl=Due to inactivity your session has timed out, please log in again.");
                }
            }
            catch
            {
                //filterContext.Result = new RedirectResult("~/Login/UserLogin");
                //filterContext.Controller.TempData.Add("UserLogin", "Login");
                filterContext.Result = new RedirectResult("~/Exceptions/Index");
            }
        }
        /// <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();
        }
        public ActionResult SignUp(User user)
        {
            if (this.Session["CaptchaImageText"].ToString() == user.SecurityCode)
            {

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

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


            //return View();
            return RedirectToAction("SignUp");
        }
        /// <summary>
        /// CreatedBy : MAM. IRFAN
        /// CreatedDate: 2016/01/13
        /// 
        /// retreive User Detail By UserId
        /// 
        /// argument : user_id (int)
        /// 
        /// 
        /// UpdatedBy : nadeeka
        /// UpdatedDate: 2016/03/03
        /// removed existing connection open method and set parameter to object list and pass stored procedure name
        /// call DataHandler class method and getting dataset object,
        /// create and return user object using that dataset
        /// 
        /// </summary>
        /// <returns>User object</returns>
        public User retreiveUserByUserId(int id)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@user_Id", id });

            DataSet dataSet = dataHandler.GetDataSet("spRetrieveUserByUserId", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
            {
                User user = new User();
                DataRow dataRow = dataSet.Tables[0].Rows[0];

                user.UserId = int.Parse(dataRow["user_id"].ToString());
                user.FirstName = dataRow["first_name"].ToString();
                user.LastName = dataRow["last_name"].ToString();
                user.Email = dataRow["email"].ToString();
                user.PhoneNumber = dataRow["phone_no"].ToString();
                user.Status = (bool)dataRow["status"];
                user.CreatedDate = (DateTime)dataRow["created_date"];

                user.IsDelete = (bool)dataRow["is_delete"];
                user.CreatedBy = int.Parse(dataRow["created_by"].ToString());
                if (dataRow["branch_id"].ToString() != "")
                {
                    user.BranchId = int.Parse(dataRow["branch_id"].ToString());
                }
                else
                {
                    user.BranchId = 0;
                }
                user.RoleId = int.Parse(dataRow["role_id"].ToString());
                user.UserName = dataRow["user_name"].ToString();
                user.UneditUserName = dataRow["user_name"].ToString();
                user.Password = dataRow["password"].ToString();
                if (dataRow["company_id"].ToString() != "")
                {
                    user.Company_Id = int.Parse(dataRow["company_id"].ToString());
                }


                return user;
            }
            else
            {
                return null;
            }
        }
        public ActionResult CreateFirstSuperUser(User user)
        {
            //user.Password = PasswordEncryption.encryptPassword(user.Password);

            string newSalt = PasswordEncryption.RandomString();
            user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
            user.Email = user.NewEmail;
            TempData["User"] = user;
            return RedirectToAction("Setup", "SetupCompany", 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 GetUserByUserId(int userId)
 {
     if (userId > 0)
     {
         User userObj = new User();
         UserAccess uas = new UserAccess();
         userObj = uas.retreiveUserByUserId(userId);
         if (userObj.UserId > 1)
         {
             userObj.PhoneNumber2 = userObj.PhoneNumber;
         }
         //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
         return Json(userObj);
     }
     else
     {
         return RedirectToAction("UserLogin", "Login");
     }
 }
        public int CheckPasswd(int userId,string Cpwd)
        {
            if (userId > 0)
            {
                User userObj = new User();
                UserAccess uas = new UserAccess();
                userObj = uas.retreiveUserByUserId(userId);
                string passwordFromDB = userObj.Password;
                //user.Password = userObj.Password;
                char[] delimiter = { ':' };

                string[] split = passwordFromDB.Split(delimiter);

                var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');

                if (passwordFromDB == null || (checkCharHave == false))
                {
                   // return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username or Password, please confirm and submit." });
                }

                string passwordEncripted = PasswordEncryption.encryptPassword(Cpwd, split[1]);
                int reslt = 0;
                if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                {
                    reslt = 1;

                }
                else
                {
                    reslt = 0;
                    
                }
                return reslt;
            }
            else
            {
                return 0;
            }
        }
        public ActionResult editUser(User user)
        {

            int currentUserId;
            int editUserId;

            string typevalue;



            try
            {
                currentUserId = int.Parse(Session["userId"].ToString());
                editUserId = int.Parse(Session["editId"].ToString());
            }
            catch (Exception)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }

            bool isUpdate;
            if (currentUserId == editUserId)
            {// Update the data into database
                ViewBag.isSame = true;
                isUpdate = (new UserAccess()).updateProfileDetails(editUserId, user.UneditUserName, user.FirstName, user.LastName, user.Email, user.PhoneNumber, DateTime.Now);
            }
            else
            {   // Update the data into database
                ViewBag.isSame = false;
                typevalue = (string)Session["searchtype"];

                if (typevalue == "User")
                {

                    ViewBag.Manage = "Manage Users";
                }
                isUpdate = (new UserAccess()).updateUserDetails(editUserId, user.UneditUserName, user.FirstName, user.LastName, user.Email, user.PhoneNumber, user.Status, user.BranchId, DateTime.Now);
            }





            if (isUpdate)
                ViewBag.SuccessMsg = "Data Successfully Updated";
            else
            {
                ViewBag.ErrorMsg = "Updating failed";
                return View(user);
            }

            user = (new UserAccess()).retreiveUserByUserId(editUserId);
            // get all branches
            List<Branch> branchesLists = (new BranchAccess()).getBranches(user.Company_Id);

            // insert all branches into selectedlist
            List<SelectListItem> branchSelectLists = new List<SelectListItem>();
            foreach (Branch branch in branchesLists)
            {
                branchSelectLists.Add(new SelectListItem() { Text = branch.BranchName, Value = branch.BranchId.ToString() });

            }


            ViewBag.BranchId = new SelectList(branchSelectLists, "Value", "Text", user.BranchId);


            return PartialView(user);
        }
        public ActionResult EditProfile()
        {
            User userObj = new User();
            UserAccess uas = new UserAccess();
            userObj = uas.retreiveUserByUserId(userData.UserId);

            string roleName = "";

            if (userData.RoleId == 1)
                roleName = "Super Admin";
            else if (userData.RoleId == 2)
                roleName = "Admin";
            else if (userData.RoleId == 3)
                roleName = "User";
            else if (userData.RoleId == 4)
                roleName = "Dealer User";

            ViewBag.RoleName = roleName;

            if (TempData["UpdteReslt"] != null)
            {
                if (int.Parse(TempData["UpdteReslt"].ToString()) == 1)
                {
                    ViewBag.SuccessMsg = "Profile is successfully updated";
                }
                else if (int.Parse(TempData["UpdteReslt"].ToString()) == 0)
                {
                    ViewBag.ErrorMsg = "Failed to update Profile";
                }
                else if (int.Parse(TempData["UpdteReslt"].ToString()) == -1)
                {
                    ViewBag.ErrorMsg = "Failed to update Profile";
                }
            }
            userObj.PhoneNumber2 = userObj.PhoneNumber;
            return View(userObj);
        }
        public ActionResult EditProfile(User model)
        {
            if (model != null)
            {
                if ((!string.IsNullOrEmpty(model.CurrentPassword)) && (!string.IsNullOrEmpty(model.Password)) && (!string.IsNullOrEmpty(model.ConfirmPassword)))
                {
                    User userObj = new User();
                    userObj = (new UserAccess()).retreiveUserByUserId(userData.UserId);
                    string passwordFromDB = userObj.Password;
                    //user.Password = userObj.Password;
                    char[] delimiter = { ':' };

                    string[] split = passwordFromDB.Split(delimiter);

                    var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');

                    if (passwordFromDB == null || (checkCharHave == false))
                    {
                        return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username or Password, please confirm and submit." });
                    }

                    string passwordEncripted = PasswordEncryption.encryptPassword(model.CurrentPassword, split[1]);

                    if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                    {
                        string passwordEncripted1 = PasswordEncryption.encryptPassword(model.Password, split[1]);
                        model.Password = passwordEncripted1;
                        model.CurrentPassword = passwordFromDB;

                    }
                    else
                    {

                        TempData["UpdteReslt"] = -1;
                        return RedirectToAction("EditProfile");
                        //return View();
                    }
                    //string newSalt = PasswordEncryption.RandomString();
                    //user.CurrentPassword = PasswordEncryption.encryptPassword(user.CurrentPassword, newSalt);
                    //user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
                }
                model.UserId = userData.UserId;
                model.Status = true;
                UserAccess usrAcc = new UserAccess();
                int reslt = usrAcc.UpdateUser(model, userData.UserId);
                if ((reslt == 1) || (reslt == 2))
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, model.BranchId, 0, "Edit User", "Edit User : "******"UpdteReslt"] = 1;
                }
                else
                {
                    TempData["UpdteReslt"] = 0;
                }
                return RedirectToAction("EditProfile");
            }

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

            
        }
        /// <summary>
        /// Frontend Page: Add Unit
        /// Title:get details of dealer user
        /// Designed: Piyumi Perera
        /// User story:
        /// Developed: Piyumi Perera
        /// Date created: 25/05/2016
        /// </summary>
        /// <returns></returns>
        public User GetDealerUserDetails(int userId, string Code)
        {
            User user2 = new User();
            List<User> users = new List<User>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@user_id", userId });
            paramertList.Add(new object[] { "@loan_code", Code });

            DataSet dataSet = dataHandler.GetDataSet("spGetDealerUserByUserId", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0)
            {
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    User user = new User();

                    user.FirstName = dataRow["first_name"].ToString();
                    user.LastName = dataRow["last_name"].ToString();
                    user.Email = dataRow["email"].ToString();
                    user.PhoneNumber = dataRow["phone_no"].ToString();
                    user.LoanNumber = dataRow["loan_number"].ToString();
                    user.UserIdForSendReq = Convert.ToInt32(dataRow["request_user_id"].ToString());
                    user.UserEmailForSendReq = dataRow["request_email"].ToString();
                    users.Add(user);
                }
                user2.FirstName = users[0].FirstName;
                user2.LastName = users[0].LastName;
                user2.Email = users[0].Email;
                user2.PhoneNumber = users[0].PhoneNumber;
                user2.LoanNumber = users[0].LoanNumber;
                user2.UserIdForSendReq = Convert.ToInt32(users[0].UserIdForSendReq);
                user2.UserEmailForSendReq = users[0].UserEmailForSendReq;
                user2.NoOfUnitsAdded = users.Count;
                user2.AddedDate = DateTime.Now;
                return user2;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// CreatedBy:Piyumi
        /// CreatedDate:4/22/2016
        /// Get all types of users for company
        /// </summary>
        /// <param name="company_Id"></param>
        /// <returns></returns>
        public List<User> GetAllUsersByBranchId(int role_id, int branch_Id)
        {
            List<User> users = new List<User>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@role_id", role_id });
            paramertList.Add(new object[] { "@branch_id", branch_Id });
            DataSet dataSet = dataHandler.GetDataSet("spGetAllUsersByBranchId", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0)
            {
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    User user = new User();
                    user.UserId = Convert.ToInt32(dataRow["user_id"].ToString());
                    user.UserName = dataRow["user_name"].ToString();
                    user.Password = dataRow["password"].ToString();
                    user.FirstName = dataRow["first_name"].ToString();
                    user.LastName = dataRow["last_name"].ToString();
                    user.Email = dataRow["email"].ToString();
                    user.PhoneNumber = dataRow["phone_no"].ToString();
                    user.Status = bool.Parse(dataRow["status"].ToString());
                    user.BranchId = Convert.ToInt32(dataRow["branch_id"].ToString());
                    user.RoleId = Convert.ToInt32(dataRow["role_id"].ToString());

                    users.Add(user);
                }

                return users;
            }
            else
            {
                return null;
            }
        }
 public ActionResult GetSuperAdminsDetails(int roleId)
 {
     if (roleId == 1)
     {
         User eum = new User();
         UserAccess uas = new UserAccess();
         eum.UserList = uas.GetSuperAdminsByCompanyId(userData.Company_Id);
         //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
         //return Json(UserList1);
        if (eum.UserList != null)
         {
             //SelectList UserList1 = new SelectList(eum.UserList, "UserId", "UserName");
             return Json(eum);
         }
         else
         {
             return RedirectToAction("UserLogin", "Login");
         }
     }
     else
     {
         return RedirectToAction("UserLogin", "Login");
     }
 }
        public ActionResult EditUserAtDashboard(User user)
        {
        if(user!=null) 
        {
                if ((!string.IsNullOrEmpty(user.CurrentPassword)) && (!string.IsNullOrEmpty(user.Password)) && (!string.IsNullOrEmpty(user.ConfirmPassword)))
                {
                    User userObj = new User();
                    userObj = (new UserAccess()).retreiveUserByUserId(user.UserId);
                    string passwordFromDB = userObj.Password;
                    //user.Password = userObj.Password;
                    char[] delimiter = { ':' };

                    string[] split = passwordFromDB.Split(delimiter);

                    var checkCharHave = passwordFromDB.ToLowerInvariant().Contains(':');

                    if (passwordFromDB == null || (checkCharHave == false))
                    {
                        return RedirectToAction("UserLogin", "Login");
                    }

                    string passwordEncripted = PasswordEncryption.encryptPassword(user.CurrentPassword, split[1]);

                    if (string.Compare(passwordEncripted, passwordFromDB) == 0)
                    {
                        string passwordEncripted1 = PasswordEncryption.encryptPassword(user.Password, split[1]);
                        user.Password = passwordEncripted1;
                        user.CurrentPassword = passwordFromDB;

                    }
                    else
                    {

                        TempData["UpdteReslt"] = -1;
                        return RedirectToAction("EditUserAtDashboard");
                        //return View();
                    }
                    //string newSalt = PasswordEncryption.RandomString();
                    //user.CurrentPassword = PasswordEncryption.encryptPassword(user.CurrentPassword, newSalt);
                    //user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
                }

                UserAccess usrAcc = new UserAccess();
                int reslt = usrAcc.UpdateUser(user,userData.UserId);
                if((reslt==1)||(reslt == 2)) 
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, user.BranchId, 0, "Edit User", "Edit User : "******"AuthenticatedUser"] = null;
                    }
                    else
                    {
                        TempData["UpdteReslt"] = 1;
                    }
                    


                }
                else 
                {
                    TempData["UpdteReslt"] = 0;
                }
               
                return RedirectToAction("EditUserAtDashboard");
            }
        else 
        {
                return RedirectToAction("UserLogin", "Login");
        }
            
        }
        /// <summary>
        /// CreatedBy  : kasun
        /// CreatedDate: 2016/04/04
        /// 
        /// Update user right details in user permission table
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int updateUserRightDetails(User user, int loggedUser)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@user_Id", user.UserId });
            paramertList.Add(new object[] { "@logged_user_Id", loggedUser });
            paramertList.Add(new object[] { "@loan_id", user.LoanId });
            paramertList.Add(new object[] { "@right_id", user.UserRights });
            if (user.ReportRights != null && user.ReportRights != "")
            {
                paramertList.Add(new object[] { "@report_right_id", user.ReportRights });
            }
            else {
                paramertList.Add(new object[] { "@report_right_id", "" });
            }
            
            paramertList.Add(new object[] { "@modify_date", DateTime.Now });

            try
            {
                return dataHandler.ExecuteSQLReturn("spUpdateUserRightDetails", paramertList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : Kasun Smarawickrama
        /// CreatedDate: 2016/01/17
        /// 
        /// edit rights Set session variables
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public ActionResult editRights(User user)
        {
            int currentUserId = (int)Session["userId"];
            int editUserId = (int)Session["editUserId"];

            Session["editUserIds"] = editUserId;

            return RedirectToAction("EditRights", "EditRights");

        }
        /// <summary>
        /// CreatedBy:Piyumi
        /// CreatedDate:4/23/2016
        /// edit user at dashboard
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int UpdateUser(User user, int userId)
        {
            if (user != null)
            {
                DataHandler dataHandler = new DataHandler();
                List<object[]> paramertList = new List<object[]>();


                paramertList.Add(new object[] { "@user_id", user.UserId });
                paramertList.Add(new object[] { "@current_password", user.CurrentPassword });
                paramertList.Add(new object[] { "@password", user.Password });
                paramertList.Add(new object[] { "@first_name", user.FirstName });
                paramertList.Add(new object[] { "@last_name", user.LastName });
                paramertList.Add(new object[] { "@email", user.Email });
                if (user.RoleId == 1)
                {
                    paramertList.Add(new object[] { "@phone_no", user.PhoneNumber });
                }
                else
                {
                    paramertList.Add(new object[] { "@phone_no", user.PhoneNumber2 });
                }

                if (user.Status)
                {
                    paramertList.Add(new object[] { "@status", 1 });
                }
                else {
                    paramertList.Add(new object[] { "@status", 0 });
                }

                paramertList.Add(new object[] { "@modified_date", DateTime.Now });
                paramertList.Add(new object[] { "@modified_by", userId });

                try
                {
                    return dataHandler.ExecuteSQLReturn("spUpdateUser", paramertList);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                return 0;
            }
        }
        public int InsertUserInDashboard(User user)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            if (user != null)
            {
                paramertList.Add(new object[] { "@user_name", user.UserName });
                paramertList.Add(new object[] { "@password", user.Password });
                paramertList.Add(new object[] { "@first_name", user.FirstName });
                paramertList.Add(new object[] { "@last_name", user.LastName });
                paramertList.Add(new object[] { "@email", user.Email });
                paramertList.Add(new object[] { "@phone_no", user.PhoneNumber2 });
                paramertList.Add(new object[] { "@created_date", DateTime.Now });
                paramertList.Add(new object[] { "@created_by", user.CreatedBy});
                paramertList.Add(new object[] { "@company_id", user.Company_Id });
                paramertList.Add(new object[] { "@branch_id", user.BranchId });
                paramertList.Add(new object[] { "@role_id", user.RoleId});
                

                if (user.RoleId == 3)
                {
                    paramertList.Add(new object[] { "@rights", user.UserRights });
                    paramertList.Add(new object[] { "@report_rights", user.ReportRights });
                    paramertList.Add(new object[] { "@loan_id", user.LoanId });
                }
                else
                {
                    paramertList.Add(new object[] { "@rights",""});
                    paramertList.Add(new object[] { "@report_rights", "" });
                    paramertList.Add(new object[] { "@loan_id", 0 });
                }
                paramertList.Add(new object[] { "@step_status", user.step_status });
                paramertList.Add(new object[] { "@status", user.Status });
            }
           

            try
            {
                return dataHandler.ExecuteSQLReturn("spInsertDashboardUserDetails", paramertList);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Frontend Page : Join Dealer
        /// Title: Get all users for given company id
        /// Designed: Piyumi Perera
        /// User story:
        /// Developed: Piyumi Perera
        /// Date Created: 05/26/2016
        /// </summary>
        /// <param name="companyId"></param>
        /// <returns></returns>
        public List<User> GetUserListByCompany(int companyId)
        {
            List<User> users = new List<User>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@company_id", companyId });

            DataSet dataSet = dataHandler.GetDataSet("spGetUsersbyCompany2", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0)
            {
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    User user = new User();
                    user.UserId = Convert.ToInt32(dataRow["user_id"].ToString());
                    user.UserName = dataRow["user_name"].ToString();
                    user.Password = dataRow["password"].ToString();
                    user.FirstName = dataRow["first_name"].ToString();
                    user.LastName = dataRow["last_name"].ToString();
                    user.NewEmail = dataRow["email"].ToString();
                    user.PhoneNumber = dataRow["phone_no"].ToString();
                    user.BranchId = Convert.ToInt32(dataRow["branch_id"].ToString());
                    user.RoleId = Convert.ToInt32(dataRow["role_id"].ToString());

                    users.Add(user);
                }

                return users;
            }
            else
            {
                return null;
            }
        }
        public ActionResult UserLogin(UserLogin user)
        {
            try
            {
                //string ip = Request.UserHostAddress;
                DataSet dsUser = new DataSet();
                var login = new LoginAccess();
                var step = new StepAccess();
                User userData = new User();
                userData.UserName = user.userName;

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

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

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

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

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

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

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

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

                                        }
                                    }


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

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

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

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

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

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

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

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


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

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







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

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

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

                        //            }

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

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


                        //            }

                        //        }
                        //    }

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

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

                    int islog = (new LogAccess()).InsertLog(log);
                    return RedirectToAction("UserLogin", "Login", new { lbl = "Incorrect Username & Password combination. Please confirm entry and resubmit." });
                }     
            }
            catch
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "An error has occurred.Please try again later" });
            }
            return RedirectToAction("UserLogin", "Login");
        }