public string GenerateUnitId(string loanCode, int loanId)
        {
            string unitId;
            var ua = new UnitAccess();
            string latestUnitId = ua.GetLatestUnitId(loanId);

            if (latestUnitId == "")
            {
                unitId = loanCode + "-000001";
            }
            else
            {
                var sufix = (Convert.ToInt32(latestUnitId.Substring(latestUnitId.Length - 6, 6)) + 1).ToString("000000");
                unitId = loanCode + "-" + sufix;
            }


            return unitId;
        }
        private AdvanceUnit GetAdvanceUnitList(int loanId)
        {
            UnitAccess unitAccess = new UnitAccess();
            List<Models.Unit> unitList = new List<Models.Unit>();
            unitList = unitAccess.GetNotAdvancedUnitDetailsByLoanId(loanId);
            List<Models.Unit> unitList2 = new List<Models.Unit>();
            AdvanceUnit unitList1 = new AdvanceUnit();
            unitList1.NotAdvanced = unitList;

            unitList1.Search = unitList2;
            unitList1.AdvanceDate = DateTime.Now;
            return unitList1;
        }
        public int UnitListPay(List<UnitPayOffModel> payOffModelList, DateTime payDate, string titleReturn)
        {
            if (Session["PayOffUnitloanId"] == null)
            {
                return -1;
            }
            
            var loanId = (int) Session["PayOffUnitloanId"];
            try
            {
                XElement xEle = new XElement("Units",
                    from unit in payOffModelList
                    select new XElement("Unit",
                        new XElement("LoanId", loanId),
                        new XElement("UnitId", unit.UnitId),
                        new XElement("Balance", unit.Balance)
                        ));
                string xmlDoc = xEle.ToString();

                int titleStatus = 0;

                if (userData.CompanyType == 1)
                    titleStatus = titleReturn == "Yes" ? 2 : 4;
                else if (userData.CompanyType == 2)
                    titleStatus = titleReturn == "Yes" ? 3 : 4;

                var result = (new CurtailmentAccess()).PayOffUnits(xmlDoc, payDate, titleStatus);

                if(result == 1)
                {
                    //if mention advance fee, then insert in to fee table - asanka
                    UnitAccess unitAccess = new UnitAccess();
                   

                    if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                    {
                        
                        Loan loanObj;
                        if (Session["loanDashboard"] != null)
                        {
                            loanObj = (Loan)Session["loanDashboard"];
                        }
                        else
                        {
                            loanObj = (Loan)Session["oneLoanDashboard"];
                        }

                        if (loanObj.AdvanceFee == 1)
                        {
                            //check advance amount and other details      
                            foreach (var payoff in payOffModelList)
                            {
                                unitAccess.insertFreeDetailsForPayOffPage(payoff, payDate,userData.UserId);
                            }
                         }
                    }


                    List<string> IDNumbers = new List<string>();

                    foreach (var payoff in payOffModelList)
                    {
                        IDNumbers.Add(payoff.IdentificationNumber);
                       

                    }

                    //insert to log 
                    Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, payOffModelList[0].LoanId, "Pay Off", "Pay Off unit(s) : " + string.Join(",", IDNumbers) + ", Pay Date : " + payDate.ToString("dd/MM/yyyy"), DateTime.Now);

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

                TempData["message"] = result;
                
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        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");
        }
        private Models.AdvanceUnit GetAdvanceUnitList(int loanId)
        {
            UnitAccess unitAccess = new UnitAccess();
            List<BankLoanSystem.Models.Unit> unitList = new List<Models.Unit>();
            unitList = unitAccess.GetNotAdvancedUnitDetailsByLoanId(loanId);
            List<BankLoanSystem.Models.Unit> unitList2 = new List<Models.Unit>();
            Models.AdvanceUnit unitList1 = new Models.AdvanceUnit();
            unitList1.NotAdvanced = unitList;

            unitList1.Search = unitList2;
           
            return unitList1;
        }
        /// <summary>
        /// Frontend page: Advance Unit
        /// Title: Advance one unit
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 02/24/2016
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Return partial view</returns>
        public int UpdateAdvance(BankLoanSystem.Models.Unit unit)
        {            
            string loanCode;
            try
            {
                //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                throw;
            }
            //get loan details by loan code
            LoanSetupStep1 loanSetupStep1 = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);           
            ViewBag.ErrorMsg = "";
            UnitAccess unitAccess = new UnitAccess();
            //check Session["notAdvancedList"] is not null
            if (Session["notAdvancedList"] != null)
            {
                //convert Session["notAdvancedList"] to list object
                List<Models.Unit> lstUnit = (List<Models.Unit>)Session["notAdvancedList"];
                //check advance amount can not be edited and given advance amount in loanset up and advance amount of selected unit is equal
                if(!loanSetupStep1.isEditAllowable && lstUnit.Find(a => a.UnitId == unit.UnitId).AdvanceAmount != unit.AdvanceAmount)
                {
                   
                    TempData["updateReslt"] = 3;
                    return 3;
                    
                }
                
            }
            //get result of advance one item
            int reslt = unitAccess.AdvanceItem(unit, loanSetupStep1.loanId, userData.UserId, unit.AdvanceDate);
            TempData["updateReslt"] = reslt;

            // after success save**
            //check result of advance
            if (reslt == 1)
            {
                //if mention advance fee, then insert in to fee table - asanka
                if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                {
                    Loan loanObj = new Loan();
                    if(Session["loanDashboard"] != null){
                        loanObj = (Loan)Session["loanDashboard"];
                    }
                    else if (Session["oneLoanDashboard"] != null)
                    {
                        loanObj = (Loan)Session["oneLoanDashboard"];
                    }
                    if (loanObj.AdvanceFee == 1)
                    {
                        //check advance amount and other details
                        unitAccess.insertFreeDetailsForAdvance(unit, loanSetupStep1.loanId);
                    }
                }

                //insert to log 
                
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanSetupStep1.loanId, "Advance Unit", "Advanced Unit:" + unit.IdentificationNumber + (unit.Cost * loanSetupStep1.advancePercentage / 100 != unit.AdvanceAmount ? ",Advance amount edited to: " + unit.AdvanceAmount : ",Advance amount: " + unit.AdvanceAmount) + " ,Advance date:" + unit.AdvanceDate, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);
                // saving for reporting purpose
                if (Session["AdvItems"] == null)
            {
                List<Models.Unit> unitlist = new List<Models.Unit>();
                unitlist.Add(unit);
                Session["AdvItems"] = unitlist;
            }
            else
            {
                List<Models.Unit> unitlist = new List<Models.Unit>();
                unitlist = (List<Models.Unit>)Session["AdvItems"];
                unitlist.Add(unit);
                Session["AdvItems"] = unitlist;
            }
            }
           

            return reslt;
        }
        /// <summary>
        /// Frontend page: Advance Unit
        /// Title: Advance more than one unit
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 02/25/2016
        /// CreatedBy : Nadeeka
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Return partial view</returns>
        public int UpdateAdvanceAll(ListViewModel list)
        {           
            string loanCode;
            try
            {
                //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                throw;
            }
            //get loan details by loan code
            LoanSetupStep1 loanSetupStep1 = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);
            ViewBag.ErrorMsg = "";
            //check Session["notAdvancedList"] is not null
            if (Session["notAdvancedList"] != null)
            {
                List<Models.Unit> lstUnit = (List<Models.Unit>)Session["notAdvancedList"];
                foreach (Models.Unit modifiedUnit in list.ItemList)
                {
                    //check advance amount can not be edited and given advance amount in loanset up and advance amount of selected unit is equal
                    if (!loanSetupStep1.isEditAllowable && lstUnit.Find(a => a.UnitId == modifiedUnit.UnitId).AdvanceAmount != modifiedUnit.AdvanceAmount)
                    {
                        TempData["updateReslt"] = 3;
                        return 0;
                    }
                }

            }

            UnitAccess unitAccess = new UnitAccess();
            //get result of advance item list
            int reslt = unitAccess.AdvanceItemList(list.ItemList, loanSetupStep1.loanId, userData.UserId, list.ItemList[0].AdvanceDate);
            TempData["updateReslt"] = reslt;

            // after success save**
            if (reslt == 1)
            {
                string[] arrList = new string[list.ItemList.Count];
                int i = 0;
                foreach (var x in list.ItemList)
                {
                    if (!string.IsNullOrEmpty(x.UnitId))
                    {
                        arrList[i] = "Advanced Unit: " + x.IdentificationNumber + " ,Advance amount:" + x.AdvanceAmount + " ,Advance date: " + x.AdvanceDate;
                        i++;
                    }
                }
                
         
                string units = string.Join(",", arrList);
                //insert log data
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanSetupStep1.loanId, "Advance Unit", units, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);
                //if mention advance fee, then insert in to fee table - asanka
                if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                {
                    Loan loanObj = new Loan();
                    if (Session["loanDashboard"] != null)
                    {
                        loanObj = (Loan)Session["loanDashboard"];
                    }
                    else
                    {
                        loanObj = (Loan)Session["oneLoanDashboard"];
                    }
                        //loanObj = (Loan)Session["loanDashboard"]; 
                    if (loanObj.AdvanceFee == 1)
                    {
                        //check advance amount and other details
                        foreach (BankLoanSystem.Models.Unit unitObj in list.ItemList)
                        {
                            unitAccess.insertFreeDetailsForAdvance(unitObj, loanSetupStep1.loanId);
                        }
                    }
                }

                // saving for reporting purpose
                if (Session["AdvItems"] == null)
                {
            Session["AdvItems"] = list.ItemList;
            }
            else
            {
                List<Models.Unit> unitlist = new List<Models.Unit>();
                unitlist = (List<Models.Unit>)Session["AdvItems"];
                unitlist.AddRange(list.ItemList);
                Session["AdvItems"] = unitlist;
            }
            }
            return reslt;        
        }
        /*

         Frontend page   : Delete units
         Title           : Get all active and pending units
         Designed        : Kanishka Mahanama
         User story      : 
         Developed       : Kanishka Mahanama
         Date created    : 

         */
        public ActionResult Delete()
        {
            string loanCode;

            //get loan code, if it is null return to the login
            try
            {
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }

            //check user role, if it is user then check he has right to delete unit page
            if (_userData.RoleId == 3)
            {
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    string rgts = "";
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList = null;
                    if (rgts != "")
                    {
                        rgtList = rgts.Split(',');
                    }
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            if (x == "U08")
                            {
                                checkPermission = true;
                            }
                        }
                        if (checkPermission == false)
                        {
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        return RedirectToAction("UserDetails", "UserManagement");
                    }

                }
            }
            else if (_userData.RoleId == 4)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }

            //get loan details
            int loanId = _userData.LoanId;
            LoanSetupStep1 loan = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);

            UnitDeleteViewModel unitDeleteViewModel = new UnitDeleteViewModel();

            //get all units
            UnitAccess ua = new UnitAccess();
            unitDeleteViewModel.DeleteUnits = ua.GetAllUnitsByLoanId(loan.loanId);
            Session["UnitDeleteList"] = unitDeleteViewModel.DeleteUnits;
            Session["deleteUnitloanId"] = loan.loanId;
            ViewBag.DeleteList = unitDeleteViewModel.DeleteUnits;

            return View(unitDeleteViewModel);
        }
        public ActionResult DeleteUnitPost(string unitId,string identificationNo, string reason)
        {
            decimal paidCurtAmount = 0.00M;
            if (Session["PaidCurtAmount"] != null)
            {
                paidCurtAmount = (decimal) Session["PaidCurtAmount"];
            }


            int loanId = (int) Session["deleteUnitloanId"];
            UnitAccess ua = new UnitAccess();
            UnitDeleteViewModel unitModel = new UnitDeleteViewModel();
            int res = ua.DeleteUnit(loanId, unitId, paidCurtAmount, reason);
            
            if (res == 1)
            {
                if (Session["UnitDeleteList"] != null)
                {
                    unitModel.DeleteUnits = (List<UnitDeleteModel>) Session["UnitDeleteList"];
                    var itemToRemove = unitModel.DeleteUnits.Single(r => r.UnitId == unitId);
                    unitModel.DeleteUnits.Remove(itemToRemove);
                    Session["UnitDeleteList"] = unitModel.DeleteUnits;
                }

                Log log = new Log(_userData.UserId, _userData.Company_Id, _userData.BranchId, loanId, "Delete Unit", "Delete Unit:" + identificationNo, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);
            }
            else
            {
                return new HttpStatusCodeResult(400, "Failed to delete unit, try again!");
            }

            if (Session["DeleteSearchUnit"] != null)
            {
                DeleteSearchUnit seachUnit = (DeleteSearchUnit) Session["DeleteSearchUnit"];
                unitModel = GetGridViewDetails(seachUnit.ViewType, seachUnit.Id, seachUnit.Year, seachUnit.Make,
                    seachUnit.Model);
            }
            ViewBag.DeleteList = unitModel.DeleteUnits;
            return PartialView("GridView", unitModel);
        }
        public ActionResult FeeDetails(string unitId)
        {
            decimal paidCurtAmount = 0.00M;

            UnitFeeTypeViewModel feeDetailsModel = new UnitFeeTypeViewModel();

            UnitAccess ua = new UnitAccess();
            feeDetailsModel.UnitFeeTypes = ua.GetUnitFeeType(unitId);

            UnitFeeTypeViewModel feeDetailsModelNew = new UnitFeeTypeViewModel();

            var lists = feeDetailsModel.UnitFeeTypes.GroupBy(x=>x.CurtNumber).ToList();
            feeDetailsModelNew.UnitFeeTypes = new List<UnitFeeType>();

            foreach (var grp in lists)
            {
                int i = 0;
                var count = grp.Select(p => new { p.LoanId, p.UnitId, p.CurtNumber, p.TblName, p.FeeType, p.PaidAmount, p.PaidDate }).Distinct().Count();

                foreach (var d in grp)
                {
                    if (count == 3)
                    {
                        if (d.TblName == "CS")
                        {
                            i++;
                            continue;
                        }
                        paidCurtAmount += d.PaidAmount;
                        feeDetailsModelNew.UnitFeeTypes.Add(new UnitFeeType { LoanId = d.LoanId, UnitId = d.UnitId, CurtNumber = d.CurtNumber, TblName = d.TblName, FeeType = d.FeeType, PaidAmount = d.PaidAmount, PaidDate = d.PaidDate });
                        i++;
                    }
                    else
                    {
                        if(d.TblName != "F")
                            paidCurtAmount += d.PaidAmount;
                        feeDetailsModelNew.UnitFeeTypes.Add(new UnitFeeType { LoanId = d.LoanId, UnitId = d.UnitId, CurtNumber = d.CurtNumber, TblName = d.TblName, FeeType = d.FeeType, PaidAmount = d.PaidAmount, PaidDate = d.PaidDate });
                    }
                }
            }
            Session["PaidCurtAmount"] = paidCurtAmount;
            return PartialView(feeDetailsModelNew);
        }
        /*

        Frontend page   : Add Unit 
        Title           : Add or Advance Units
        Designed        : Kasun Samarawickrama
        User story      : 
        Developed       : Kasun Samarawickrama
        Date created    : 02/24/2016

        */
        public ActionResult AddUnit()
        {
            // Handle Record successfully update or Error message

            int Flag = 0;
            if (TempData["Msg"] != null)
            {
                Flag = int.Parse(TempData["Msg"].ToString());
                if (Flag == 1)
                {
                    ViewBag.Msg = "Success";
                }
                else if (Flag == 3)
                {
                    ViewBag.Msg = "Requested";
                }
                else if (Flag == 2)
                {
                    ViewBag.Msg = "Error";
                }
            }
           

            int userId = userData.UserId;
            ViewBag.Role = userData.RoleId; ;

            //Check loan is null or not
            if (Session["loanCode"] == null || Session["loanCode"].ToString() == "")
                return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });

            // for role id3 - user section
            if (userData.RoleId == 3)
            {
                // check user has rights to access this loan - if not redirect to dashboard
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    var checkAdvance = false;

                    // check user permission to the site
                    string rgts = "";
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList =null;
                    //spit the permission string
                    if (rgts != "") {
                        rgtList = rgts.Split(',');
                    }
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            //check user have rights to add unit page
                            if (x == "U04")
                            {
                                checkPermission = true;
                            }
                            // check user have right to advance units in this page
                            if (x == "U01")
                            {
                                checkAdvance = true;
                            }
                        }
                        if (checkAdvance == true)
                        {
                            ViewBag.advanceAllow = true;
                        }
                        else {
                            ViewBag.advanceAllow = false;
                        }
                        if (checkPermission == false)
                        {
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        return RedirectToAction("UserDetails", "UserManagement");
                    }
                    
                }
            }
            string loanCode = Session["loanCode"].ToString();
            // retrive loan details
            LoanSetupStep1 loan = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);

            int loanId = loan.loanId;
            Session["addUnitloan"] = loan;


            ViewBag.loanDetails = loan;
            //set default unit type for add unit page
            if (loan.selectedUnitTypes.Count == 1) {
                ViewBag.UnitTypeId = loan.selectedUnitTypes[0].unitTypeName;
            }

            Models.Unit unit = new Models.Unit();

            unit.AdvancePt = loan.advancePercentage;
            unit.LoanId = loanId;
            unit.LoanAmount = loan.loanAmount;
            unit.AdvanceDate = DateTime.Now;
            unit.StartDate = loan.startDate;
            unit.EndDate = loan.maturityDate;

            //get company type
            //1 - Lender
            //2 - Dealer
            BranchAccess ba = new BranchAccess();
            int companyType = ba.getCompanyTypeByUserId(userId);

            ViewBag.CompabyType = companyType;
            ViewBag.RoleId = userData.RoleId;

            //Check title 
            TitleAccess ta = new TitleAccess();
            Title title = ta.getTitleDetails(loan.loanId);
            // check title track allow or not
            if (title != null)
            {
                bool isTitleTrack = title.IsTitleTrack;
                if (isTitleTrack)
                    ViewBag.IsTitleTrack = "Yes";

                string upload = title.TitleAcceptMethod;
                if (!string.IsNullOrEmpty(upload) && upload == "Scanned Title Adequate")
                    ViewBag.Upload = "Yes";

            }
            // loan Details for (loan Detail box) in the page 
            UnitAccess ua = new UnitAccess();
            LoanPaymentDetails loanPaymentDetails = ua.GetLoanPaymentDetailsByLoanId(loanId);

            unit.Balance = loanPaymentDetails.BalanceAmount;
            // check balane field is editable or not for this loan
            ViewBag.Editable = loan.isEditAllowable ? "Yes" : "No";

            
            //set user role to restrict add & advance unit if this user is dealer user(role id = 4)
            ViewBag.RoleId = userData.RoleId; 

            return PartialView(unit);
        }
        public ActionResult AddUnitPost(Models.Unit unit, List<HttpPostedFileBase> fileUpload)
        {

           int userId = userData.UserId;
            // check this is an advance or add unit
            switch (unit.AdvanceNow)
            {
                case "No":
                    unit.IsAdvanced = false;
                    unit.AddAndAdvance = false;
                    break;
                case "Yes":
                    unit.IsAdvanced = true;
                    unit.AddAndAdvance = true;
                    break;
            }

            if (Session["loanCode"] == null) {
                return RedirectToAction("UserLogin", "Login", null);
            }
            string loanCode = Session["loanCode"].ToString();
            
            //check this posted vin unique in database

            int num = 0;
            // vehile ID number
            if (unit.UnitTypeId == 1)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.vehicle.IdentificationNumber, unit.LoanId);
            }
            // rv ID number
            else if (unit.UnitTypeId == 2)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.rv.IdentificationNumber , unit.LoanId);

            }
            // camper ID number
            else if (unit.UnitTypeId == 3)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.camper.IdentificationNumber, unit.LoanId);
            }
            // atv ID number
            else if (unit.UnitTypeId == 4)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.atv.IdentificationNumber, unit.LoanId);
            }
            // boat ID number
            else if (unit.UnitTypeId == 5)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.boat.IdentificationNumber, unit.LoanId);
            }
            // motorcycle ID number 
            else if (unit.UnitTypeId == 6)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.motorcycle.IdentificationNumber, unit.LoanId);
            }
            // snowmobile ID number 
            else if (unit.UnitTypeId == 7)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.snowmobile.IdentificationNumber, unit.LoanId);
            }
            // heavyequipment ID number 
            else if (unit.UnitTypeId == 8)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.heavyequipment.SerialNumber, unit.LoanId);
            }

            //only allow to add if and only if vin already not existing in this loan
            if (num != 0 && num != 1)
            {

                string IDNumber;
                UnitAccess ua = new UnitAccess();
                //inserting the unit to the database
                string res = ua.InsertUnit(unit, userId, loanCode, out IDNumber);

                //if mention advance fee, then insert in to fee table
                if (!string.IsNullOrEmpty(res) && unit.AddAndAdvance)
                {


                    if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                    {
                        Loan loanObj = new Loan();
                        if (Session["loanDashboard"] != null)
                        {
                            loanObj = (Loan)Session["loanDashboard"];
                        }
                        else
                        {
                            loanObj = (Loan)Session["oneLoanDashboard"];
                        }
                        if (loanObj.AdvanceFee == 1)
                        {
                            //check advance amount and other details

                            ua.insertFreeDetails(unit);
                        }
                    }
                }
                
                if (!string.IsNullOrEmpty(res))
                {
                    if (Session["addUnitloan"] == null)
                    {
                        return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });
                    }
                    LoanSetupStep1 loan = (LoanSetupStep1)Session["addUnitloan"];
                    //insert to log 
                    Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, unit.LoanId, "Add Unit", (unit.AddAndAdvance ? "Added and advanced" : "Added") + " unit : " + IDNumber + ", Cost Amount : " + unit.Cost + (unit.Cost * loan.advancePercentage / 100 != unit.AdvanceAmount ? ", Edited Advance amount " + unit.AdvanceAmount : ", Advance amount : " + unit.AdvanceAmount), DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                    //Handling file attachments

                    //Check directory is already exists, if not create new
                    string mapPath = "~/Uploads/" + loan.RegisteredCompanyCode + "/" + loan.RegisteredBranchCode + "/";
                    if (!Directory.Exists(Server.MapPath(mapPath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(mapPath));
                    }

                    List<TitleUpload> titleList = new List<TitleUpload>();

                    int imageNo = 1;
                    // if unit successfully updated then upload files
                    if (unit.FileName != null && fileUpload != null)
                    {
                        foreach (var file in fileUpload)
                        {
                            if (file != null && Array.Exists(unit.FileName.Split(','), s => s.Equals(file.FileName)))
                            {
                                if (file.ContentLength > 3 * 1024 * 1024)
                                {
                                    break;
                                }
                                unit.UnitId = res;
                                string extension = Path.GetExtension(file.FileName);

                                string filename = unit.UnitId + "_" + imageNo.ToString("00") + extension;

                                file.SaveAs(Server.MapPath(mapPath + filename));
                                string filepathtosave = mapPath + filename;

                                //add file information to list
                                TitleUpload title = new TitleUpload();
                                title.UploadId = imageNo;
                                title.FilePath = filepathtosave;
                                title.UnitId = unit.UnitId;
                                title.OriginalFileName = file.FileName;

                                titleList.Add(title);

                                imageNo++;
                            }
                        }

                        try
                        {
                            XElement xEle = new XElement("Titles",
                                from title in titleList
                                select new XElement("Title",
                                    new XElement("FilePath", title.FilePath),
                                    new XElement("UnitId", title.UnitId),
                                    new XElement("OriginalFileName", title.OriginalFileName)
                                    ));
                            string xmlDoc = xEle.ToString();

                            bool res1 = ua.InsertTitleDocumentUploadInfo(xmlDoc, unit.UnitId);

                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    TempData["Msg"] = 1;

                    return RedirectToAction("AddUnit");
                }
            }
            TempData["Msg"] = 2;
            return RedirectToAction("AddUnit", unit);
        }