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

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

            if (reslt>0)
            {
                ViewBag.SuccessMsg = "Branch is successfully added";
                return RedirectToAction("CreateBranch", "CreateBranch", new {success = 1 });
                //branch = new Branch();
                //return PartialView(branch);
            }
            else
            {
                ViewBag.ErrorMsg = "Failed to add branch";
                return PartialView();
            }
        }
        /// <summary>
        /// CreatedBy: MAM. IRFAN
        /// CreatedDate: 2016/01/16
        /// 
        /// Getting all branches
        /// 
        /// 
        /// UpdatedBy : nadeeka
        /// UpdatedDate: 2016/03/04
        /// removed existing connection open method and set parameter to object list and pass stored procedure name to
        /// call DataHandler class method and getting dataset object,
        /// create and return branche object list using that dataset
        /// 
        /// </summary>
        /// <returns> a list contain all branches</returns>
        /// 
        public List<Branch> getBranches(int companyId)
        {
            List<Branch> branchesLists = new List<Branch>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@companyId", companyId });
            try
            {
            DataSet dataSet = dataHandler.GetDataSet("spGetBranchesByCompanyId", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0)
            {
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    Branch branch = new Branch();
                    branch.BranchId = Convert.ToInt32(dataRow["branch_id"].ToString());
                    branch.BranchName = dataRow["branch_name"].ToString();
                    branch.BranchCode = dataRow["branch_code"].ToString();
                    branch.BranchAddress1 = dataRow["branch_address_1"].ToString();

                    branchesLists.Add(branch);
                }

                return branchesLists;
            }
            else
            {
                return null;
            }
        }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy:Asanka Senarathna
        /// CreatedDate:6/27/2016
        /// Get Active Loans for Inactive
        /// </summary>
        /// <param name="company_Id"></param>
        /// <param name="branchId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public LoanSelection GetActiveLoanforInactive( int companyId, int branchId, int roleId)
        {
            LoanSelection detailList = new LoanSelection();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();

            paramertList.Add(new object[] { "@companyId", companyId });
            paramertList.Add(new object[] { "@branchId", branchId });
            paramertList.Add(new object[] { "@roleId", roleId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetActiveLoansforInactive", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0)
                {
                    List<Branch> RegBranches = new List<Branch>();
                    List<NonRegBranch> NonRegBranchList = new List<NonRegBranch>();
                    List<LoanSetupStep1> LoanList = new List<LoanSetupStep1>();

                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        Branch branch = new Branch();
                        NonRegBranch nonRegBranch = new NonRegBranch();
                        LoanSetupStep1 loan = new LoanSetupStep1();

                        branch.BranchId = int.Parse(dataRow["branch_id"].ToString());
                        branch.BranchName = dataRow["regBranchName"].ToString();

                        nonRegBranch.NonRegBranchId = int.Parse(dataRow["non_reg_branch_id"].ToString());
                        nonRegBranch.BranchId = branch.BranchId;
                        nonRegBranch.CompanyNameBranchName = dataRow["nonRegBranchName"].ToString();

                        loan.loanId = int.Parse(dataRow["loan_id"].ToString());
                        loan.loanNumber = dataRow["loan_number"].ToString();
                        loan.loanCode = dataRow["loan_code"].ToString();
                        loan.loanAmount = decimal.Parse(dataRow["loan_amount"].ToString());
                        loan.CreatedDate = DateTime.Parse(dataRow["created_date"].ToString());
                        loan.startDate = DateTime.Parse(dataRow["start_date"].ToString());
                        loan.maturityDate = DateTime.Parse(dataRow["maturity_date"].ToString());
                        loan.CurrentLoanStatus = bool.Parse(dataRow["loan_status"].ToString());

                        loan.nonRegisteredBranchId = nonRegBranch.NonRegBranchId;
                        bool checkBranch = false;
                        bool checkNonRegBranch = false;
                        bool checkLoan = false;
                        foreach (var br in RegBranches)
                        {
                            if (br.BranchId == branch.BranchId)
                            {
                                checkBranch = true;
                            }
                        }
                        if (checkBranch == false)
                        {
                            RegBranches.Add(branch);
                        }
                        foreach (var nrbr in NonRegBranchList)
                        {
                            if (nrbr.NonRegBranchId == nonRegBranch.NonRegBranchId)
                            {
                                checkNonRegBranch = true;
                            }
                        }
                        if (checkNonRegBranch == false)
                        {
                            NonRegBranchList.Add(nonRegBranch);
                        }

                        foreach (var l in LoanList)
                        {
                            if (l.loanId == loan.loanId)
                            {
                                checkLoan = true;
                            }
                        }
                        if (checkLoan == false)
                        {
                            LoanList.Add(loan);
                        }

                    }
                    detailList.RegBranches = RegBranches;
                    detailList.NonRegBranchList = NonRegBranchList;
                    detailList.LoanList = LoanList;

                    return detailList;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : Kasun
        /// CreatedDate: 2016/03/30
        /// 
        /// get permissioned loans with branch , non reg branch and loan details
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public LoanSelection GetPermisssionGivenLoanwithBranchDeatils(int userId,int companyId,int? branchId,int roleId)
        {
            LoanSelection detailList = new LoanSelection();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();

            paramertList.Add(new object[] { "@userId", userId });
            paramertList.Add(new object[] { "@companyId", companyId });
            paramertList.Add(new object[] { "@branchId", branchId });
            paramertList.Add(new object[] { "@roleId", roleId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spRetrivePermissionGivenLoans", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0)
                {
                    List<Branch> RegBranches = new List<Branch>();
                    List<NonRegBranch> NonRegBranchList = new List<NonRegBranch>();
                    List<LoanSetupStep1> LoanList =  new List<LoanSetupStep1>();

                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        Branch branch = new Branch();
                        NonRegBranch nonRegBranch = new NonRegBranch();
                        LoanSetupStep1 loan = new LoanSetupStep1();

                        branch.BranchId = int.Parse(dataRow["branch_id"].ToString());
                        branch.BranchName = dataRow["regBranchName"].ToString();

                        nonRegBranch.NonRegBranchId = int.Parse(dataRow["non_reg_branch_id"].ToString());
                        nonRegBranch.BranchId = branch.BranchId;
                        nonRegBranch.CompanyNameBranchName = dataRow["nonRegBranchName"].ToString();

                        loan.loanId = int.Parse(dataRow["loan_id"].ToString());
                        loan.loanNumber = dataRow["loan_number"].ToString();
                        loan.loanCode = dataRow["loan_code"].ToString();
                        loan.rightId = dataRow["right_id"].ToString();
                        loan.loanAmount = decimal.Parse(dataRow["loan_amount"].ToString());
                        loan.startDate = DateTime.Parse(dataRow["start_date"].ToString());
                        loan.maturityDate = DateTime.Parse(dataRow["maturity_date"].ToString()) ;
                        loan.CreatedDate = DateTime.Parse(dataRow["created_date"].ToString()) ;

                        if (dataRow["is_title_tracked"].ToString() != null && dataRow["is_title_tracked"].ToString() != "") {
                            loan.titleTracked = bool.Parse(dataRow["is_title_tracked"].ToString());
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_lot_inspection_fee"].ToString()))
                        {
                            if (bool.Parse(dataRow["has_lot_inspection_fee"].ToString()))
                            {
                                loan.LotInspectionFee = 1;
                            }
                            else
                            {
                                loan.LotInspectionFee = 0;
                            }
                        }

                        else
                        {
                            loan.LotInspectionFee = 0;
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_monthly_loan_fee"].ToString()))
                        {
                            if (bool.Parse(dataRow["has_monthly_loan_fee"].ToString()))
                            {
                                loan.MonthlyLoanFee = 1;
                            }
                            else
                            {
                                loan.MonthlyLoanFee = 0;
                            }
                        }

                        else
                        {
                            loan.MonthlyLoanFee = 0;
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_advance_fee"].ToString()))
                        {
                            if (bool.Parse(dataRow["has_advance_fee"].ToString()))
                            {
                                loan.AdvanceFee = 1;
                            }
                            else
                            {
                                loan.AdvanceFee = 0;
                            }
                            if (!string.IsNullOrEmpty(dataRow["payment_due_method"].ToString()))
                            {
                                if (dataRow["payment_due_method"].ToString().Contains("Vehicle Payoff"))
                                {
                                    loan.AdvanceFeePayAtPayoff = true;
                                }
                                else
                                {
                                    loan.AdvanceFeePayAtPayoff = false;
                                }

                            }
                        }

                        else
                        {
                            loan.AdvanceFee = 0;
                        }
                        loan.nonRegisteredBranchId = nonRegBranch.NonRegBranchId;
                        bool checkBranch = false;
                        bool checkNonRegBranch = false;
                        bool checkLoan = false;
                        foreach (var br in RegBranches) {
                            if (br.BranchId == branch.BranchId) {
                                checkBranch = true;
                            }
                        }
                        if (checkBranch == false) {
                            RegBranches.Add(branch);
                        }
                        foreach (var nrbr in NonRegBranchList)
                        {
                            if (nrbr.NonRegBranchId == nonRegBranch.NonRegBranchId)
                            {
                                checkNonRegBranch = true;
                            }
                        }
                        if (checkNonRegBranch == false)
                        {
                            NonRegBranchList.Add(nonRegBranch);
                        }

                        foreach (var l in LoanList)
                        {
                            if (l.loanId == loan.loanId)
                            {
                                checkLoan = true;
                            }
                        }
                        if (checkLoan == false)
                        {
                            LoanList.Add(loan);
                        }
                        
                    }
                    detailList.RegBranches = RegBranches;
                    detailList.NonRegBranchList = NonRegBranchList;
                    detailList.LoanList = LoanList;

                    return detailList;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : kasun Samarawickrama
        /// CreatedDate: 2016/02/03
        /// 
        /// get Branchs by company code 
        /// </summary>
        /// <returns>branches list</returns>
        /// 
        public IList<Branch> getBranchesByCompanyCode(string companyCode)
        {
            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["AutoDealersConnection"].ToString()))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand("spGetBranchesByCompanyCode", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@company_code", SqlDbType.VarChar).Value = companyCode;

                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();

                        List<Branch> branchesLists = new List<Branch>();


                        while (reader.Read())
                        {
                            Branch branch = new Branch();
                            branch.BranchId = int.Parse(reader["branch_id"].ToString());
                            branch.BranchName = reader["branch_name"].ToString();
                            branch.BranchCode = reader["branch_code"].ToString();
                            branch.BranchAddress1 = reader["branch_address_1"].ToString();
                            branch.BranchAddress2 = reader["branch_address_2"].ToString();
                            branch.StateId = int.Parse(reader["state_id"].ToString());
                            branch.BranchCity = reader["city"].ToString();
                            branch.BranchZip = reader["zip"].ToString();
                            branch.BranchEmail = reader["email"].ToString();
                            branch.BranchPhoneNum1 = reader["phone_num_1"].ToString();
                            branch.BranchPhoneNum2 = reader["phone_num_2"].ToString();
                            branch.BranchPhoneNum3 = reader["phone_num_3"].ToString();
                            branch.BranchFax = reader["fax"].ToString();
                            branchesLists.Add(branch);

                        }
                        return branchesLists;

                    }

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public  List<Branch> GetLoansByBranches(int branchIdL)
        {
            List<Branch> branchesLists = new List<Branch>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@branch_id", branchIdL });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetLoanByBranchId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0)
                {
                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        Branch branch = new Branch();
                        branch.BranchId = Convert.ToInt32(dataRow["branch_id"].ToString());
                        branch.BranchName = dataRow["branch_name"].ToString();
                        branch.LoanId = int.Parse(dataRow["loan_id"].ToString());
                        branch.LoanNumber = dataRow["loan_number"].ToString();
                        if (!string.IsNullOrEmpty(dataRow["is_title_tracked"].ToString()))
                        {
                            branch.IsTitleTrack = bool.Parse(dataRow["is_title_tracked"].ToString());
                        }
                        else
                        {
                            branch.IsTitleTrack = false;
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_advance_fee"].ToString()) || !string.IsNullOrEmpty(dataRow["has_monthly_loan_fee"].ToString()) || !string.IsNullOrEmpty(dataRow["has_lot_inspection_fee"].ToString()))
                        {
                           
                            branch.HasAdvanceFee = (dataRow["has_advance_fee"]) != DBNull.Value ? (bool)dataRow["has_advance_fee"] : false;
                            branch.HasMonthlyFee = (dataRow["has_monthly_loan_fee"]) != DBNull.Value ? (bool)dataRow["has_monthly_loan_fee"] : false;
                            branch.HasLotFee = (dataRow["has_lot_inspection_fee"]) != DBNull.Value ? (bool)dataRow["has_lot_inspection_fee"] : false;
                            if(branch.HasAdvanceFee || branch.HasMonthlyFee || branch.HasLotFee)
                            {
                                branch.HasFee = true;
                            }
                            else
                            {
                                branch.HasFee = false;
                            }
                        }
                        else
                        {
                            branch.HasFee = false;
                        }
                        branchesLists.Add(branch);
                    }

                    return branchesLists;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : nadeeka
        /// UpdatedDate: 2016/03/04
        /// set parameter's to object list and pass stored procedure name to DataHandler class to save branch object
        /// 
        /// </summary>
        /// <param name="branch">branch object</param>
        /// <param name="id"> user id</param>
        /// <returns></returns>
        public int insertBranch(Branch branch, int id,string companyCode)
        {
            //if (string.IsNullOrEmpty(branch.BranchCode))
            //{
            //    branch.BranchCode = createBranchCode(getCompanyCodeByUserId(id));
            //}

            //branch.BranchCompany = getCompanyIdByUserId(id);

            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@user_id", id });
            paramertList.Add(new object[] { "@branch_code", branch.BranchCode });
            paramertList.Add(new object[] { "@company_code", companyCode });
            paramertList.Add(new object[] { "@branch_name", branch.BranchName });
            paramertList.Add(new object[] { "@branch_address_1", branch.BranchAddress1 });
            paramertList.Add(new object[] { "@branch_address_2", branch.BranchAddress2 ?? "" });
            paramertList.Add(new object[] { "@state_id", branch.StateId });
            paramertList.Add(new object[] { "@city", branch.BranchCity });
            if ((branch.Extention != null) && (branch.Extention.ToString() != ""))
            {
                branch.BranchZip = branch.ZipPre + "-" + branch.Extention;
            }
            else
            {
                branch.BranchZip = branch.ZipPre;
            }
            paramertList.Add(new object[] { "@zip", branch.BranchZip });
            paramertList.Add(new object[] { "@email", branch.BranchEmail });
            paramertList.Add(new object[] { "@phone_num_1", branch.BranchPhoneNum1 });
            paramertList.Add(new object[] { "@phone_num_2", branch.BranchPhoneNum2 ?? "" });
            paramertList.Add(new object[] { "@phone_num_3", branch.BranchPhoneNum3 ?? "" });
            paramertList.Add(new object[] { "@fax", branch.BranchFax ?? "" });
            paramertList.Add(new object[] { "@created_date", DateTime.Now });
            paramertList.Add(new object[] { "@company_id", branch.BranchCompany });

            try
            {
                return dataHandler.ExecuteSQLReturn("spInsertBranch", paramertList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy:Irfan
        /// CreatedDate:2016/02/11
        /// Get Branch by branch Id
        /// 
        /// UpdatedBy : nadeeka
        /// UpdatedDate: 2016/03/04
        /// removed existing connection open method and set parameter to object list and pass stored procedure name
        /// call DataHandler class method and getting dataset object,
        /// return branch object using dataset object   
        /// 
        /// </summary>
        /// <param name="branch Id"></param>
        /// <returns></returns>
        public Branch getBranchByBranchId(int branchId)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@branch_id", branchId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetBranchByBranchId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    DataRow dataRow = dataSet.Tables[0].Rows[0];
                    Branch branch = new Branch();

                    branch.BranchCode = dataRow["branch_code"].ToString();
                    branch.BranchId = int.Parse(dataRow["branch_id"].ToString());
                    branch.BranchName = dataRow["branch_name"].ToString();

                    return branch;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : kasun Samarawickrama
        /// CreatedDate: 2016/02/03
        /// 
        /// UpdatedBy : nadeeka
        /// UpdatedDate: 2016/03/04
        /// removed existing connection open method and set parameter to object list and pass stored procedure name to
        /// call DataHandler class method and getting dataset object,
        /// create and return branch object list using that dataset          
        /// 
        /// 
        /// get Branchs by company code 
        /// </summary>
        /// <returns>branches list</returns>
        /// 
        public IList<Branch> getBranchesByCompanyCode(string companyCode)
        {
            List<Branch> branchesLists = new List<Branch>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@company_code", companyCode });
            try
            {
            DataSet dataSet = dataHandler.GetDataSet("spGetBranchesByCompanyCode", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0)
            {
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    Branch branch = new Branch();
                    branch.BranchId = Convert.ToInt32(dataRow["branch_id"].ToString());
                    branch.BranchName = dataRow["branch_name"].ToString();
                    branch.BranchCode = dataRow["branch_code"].ToString();
                    branch.BranchAddress1 = dataRow["branch_address_1"].ToString();
                    branch.BranchAddress2 = dataRow["branch_address_2"].ToString();
                    branch.StateId = int.Parse(dataRow["state_id"].ToString());
                    branch.BranchCity = dataRow["city"].ToString();
                    branch.BranchZip = dataRow["zip"].ToString();

                    string[] zipWithExtention = branch.BranchZip.Split('-');
                    if (zipWithExtention[0] != null) branch.ZipPre = zipWithExtention[0];
                    if (zipWithExtention.Count() >= 2 && zipWithExtention[1] != null) branch.Extention = zipWithExtention[1];
                    else if(zipWithExtention.Count() == 1)
                        {
                            branch.Extention = "";
                        }

                            branch.BranchEmail = dataRow["email"].ToString();
                    branch.BranchPhoneNum1 = dataRow["phone_num_1"].ToString();
                    branch.BranchPhoneNum2 = dataRow["phone_num_2"].ToString();
                    branch.BranchPhoneNum3 = dataRow["phone_num_3"].ToString();
                    branch.BranchFax = dataRow["fax"].ToString();

                    branchesLists.Add(branch);
                }

                return branchesLists;
            }
            else
            {
                return null;
            }
        }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy:Piyumi
        /// CreatedDate:4/22/2016
        /// Get all branches by companyId
        /// </summary>
        /// <param name="company_Id"></param>
        /// <returns></returns>
        public List<Branch> GetBranchesByCompanyId(int company_Id)
        {
            List<Branch> branchesLists = new List<Branch>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@companyId", company_Id });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetBranchesByCompanyId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0)
                {
                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        Branch branch = new Branch();

                        branch.BranchId = int.Parse(dataRow["branch_id"].ToString());

                        branch.BranchName = dataRow["branch_name"].ToString();
                        branch.BranchCode = dataRow["branch_code"].ToString();
                        //branch.BranchId = int.Parse(dataRow["branch_id"].ToString());
                        branch.BranchAddress1 = dataRow["branch_address_1"].ToString();
                       
                        branch.BranchCity = dataRow["city"].ToString();

                        if (!string.IsNullOrEmpty(branch.BranchAddress1) && !string.IsNullOrEmpty(branch.BranchCity))
                        {
                            branch.BranchNameAddress = branch.BranchName + "-" + branch.BranchAddress1 + "," + branch.BranchCity;
                        }
                        else
                        {
                            branch.BranchNameAddress = branch.BranchName;
                        }
                      
                        branchesLists.Add(branch);
                    }
                    return branchesLists;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }