/// <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;
            }
        }
        public ActionResult Selectloan(string type)
        {



            LoanSelection detail = new LoanSelection();
            //if edit loan
            if (!string.IsNullOrEmpty(type) && type.Contains("tidenaol"))
            {
                detail = (new UnitAccess()).GetInActiveLoans(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail != null)
                {
                    Session["detail"] = detail;
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else if (!string.IsNullOrEmpty(type) && type.Contains("aticno"))
            {
                detail = (new UnitAccess()).GetPermisssionGivenLoanwithBranchDeatils(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail != null)
                {
                    Session["detail"] = detail;
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else if(!string.IsNullOrEmpty(type) && type.Contains("tcaninaol"))
            {
                detail = (new UnitAccess()).GetActiveLoanforInactive(userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail != null)
                {
                    Session["detail"] = detail;
                }
                else
                {
                    return RedirectToAction("UserLogin", "Login");
                }
            }
            else if (!string.IsNullOrEmpty(type))
            {
                detail = (new UnitAccess()).GetPermisssionGivenLoanwithBranchDeatils(userData.UserId, userData.Company_Id, userData.BranchId, userData.RoleId);
                if (detail == null)
                {
                    ViewBag.type = "return";
                    return PartialView();
                }
                else if (detail != null) {
                    Session["detail"] = detail;
                }


            }



            int userId = userData.UserId;
            // if Session is expired throw an error


            loanSelection.RegBranches = new List<Branch>();
            loanSelection.NonRegBranchList = new List<NonRegBranch>();
            loanSelection.LoanList = new List<LoanSetupStep1>();


            //getting user role
            UserAccess ua = new UserAccess();



            // curUser.Company_Id   asanka 8/3/2016
            //create list for nonRegisterCompaniers

            List<NonRegBranch> NonRegisteredBranchLists = detail.NonRegBranchList; //(new BranchAccess()).getNonRegBranches(userData.Company_Id);

            if (userData.RoleId == 1)
            {

                loanSelection.RegBranches = detail.RegBranches; //(new BranchAccess()).getBranches(userData.Company_Id);

                if (loanSelection.RegBranches != null && loanSelection.RegBranches.Count() == 1)
                {



                    // the get non registered branches details for perticular branch  from the non registeres branches list
                    foreach (NonRegBranch branch in NonRegisteredBranchLists)
                    {
                        if (branch.BranchId == loanSelection.RegBranches[0].BranchId)
                        {
                            loanSelection.NonRegBranchList.Add(branch);
                        }
                    }

                    if (loanSelection.NonRegBranchList.Count() == 1)
                    {

                        List<LoanSetupStep1> loanLists = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);
                        loanSelection.LoanList = new List<LoanSetupStep1>();
                        foreach (LoanSetupStep1 loan in loanLists) {
                            // if(loan.LoanStatus == true)
                            //  {
                            loanSelection.LoanList.Add(loan);
                            //  }
                        }

                        //if loans count is one redirect to add unit page
                    }
                }

            } else if (userData.RoleId == 2)
            {

                //loanSelection.RegBranches.Add((new BranchAccess()).getBranchByBranchId(userData.BranchId));
                if (detail.RegBranches != null && detail.RegBranches.Count > 0)
                {
                    loanSelection.RegBranches.Add(detail.RegBranches[0]);
                }



                // the get non registered branches details for perticular branch  from the non registeres branches list
                foreach (NonRegBranch branch in NonRegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {

                        loanSelection.NonRegBranchList.Add(branch);


                    }
                }
                if (loanSelection.NonRegBranchList.Count() == 1)
                {
                    loanSelection.LoanList = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);

                }
            }
            else if (userData.RoleId == 3)
            {

                //loanSelection.RegBranches.Add((new BranchAccess()).getBranchByBranchId(userData.BranchId));

                loanSelection.RegBranches.Add(detail.RegBranches[0]);


                // the get non registered branches details for perticular branch  from the non registeres branches list
                foreach (NonRegBranch branch in NonRegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {
                        loanSelection.NonRegBranchList.Add(branch);
                    }
                }
                if (loanSelection.NonRegBranchList.Count() == 1)
                {
                    loanSelection.LoanList = detail.LoanList; //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);

                }
            }


            Session["popUpSelectionType"] = type;
            if (type == "asderruy") // for add unit page
            {
                ViewBag.type = "AddUnit";
                return PartialView(loanSelection);
            }

            else if (type == "tyuirede") // for add unit page
            {
                ViewBag.type = "Advance";
                return PartialView(loanSelection);
            }

            else if (type == "sedretyt")
            {
                ViewBag.type = "Curtailment";
                return PartialView(loanSelection);
            }

            else if (type == "wsedtgio")
            {
                ViewBag.type = "PayOff";
                return PartialView(loanSelection);
            }

            else if (type == "frtgcvfd")
            {
                ViewBag.type = "Title";
                return PartialView(loanSelection);
            }
            else if (type == "dashboard")
            {
                ViewBag.type = "DashBoard";
                return PartialView(loanSelection);
            }
            else if (type == "linkDealer")
            {
                ViewBag.type = "linkDealer";
                return PartialView(loanSelection);
            }
            else if (type == "assignRights")
            {
                ViewBag.type = "assignRights";
                return PartialView(loanSelection);
            }

            else if (type == "tidenaol") // for add unit page
            {
                ViewBag.type = "EditLoan";
                return PartialView(loanSelection);
            }
            else if (type == "tcaninaol") 
            {
                ViewBag.type = "InactiveLoan";
                return PartialView(loanSelection);
            }
            else if (type == "aticno")
            {
                ViewBag.type = "RenewLoan";
                return PartialView(loanSelection);
            }
            return PartialView(loanSelection);
        }
        /// <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;
            }
        }
        public ActionResult getNonRegBranchesByRegBranchId(int RegBranchId, string type)
        {
            LoanSelection list = (LoanSelection)Session["detail"];

            List<NonRegBranch> NonRegisteredBranchLists = list.NonRegBranchList;//(new BranchAccess()).getNonRegBranches(userData.Company_Id);
            LoanSelection loanSelection = new LoanSelection();

            loanSelection.NonRegBranchList = new List<NonRegBranch>();
            loanSelection.LoanList = new List<LoanSetupStep1>();

            // the get non registered branches details for perticular branch  from the non registeres branches list
            foreach (NonRegBranch branch in NonRegisteredBranchLists)
            {
                if (branch.BranchId == RegBranchId)
                {
                    loanSelection.NonRegBranchList.Add(branch);
                }
            }


            ViewBag.type = type;



            if (loanSelection.NonRegBranchList != null && loanSelection.NonRegBranchList.Count() == 1)
            {

                //loanSelection.LoanList = list.LoanList;   //new LoanSetupAccess().GetLoanDetailsByNonRegBranchId(loanSelection.NonRegBranchList[0].NonRegBranchId);
                //if loans count is one redirect to add unit page
                foreach (LoanSetupStep1 l in list.LoanList)
                {
                    if (loanSelection.NonRegBranchList[0].NonRegBranchId == l.nonRegisteredBranchId)
                    {
                        //loanSelection.NonRegBranchList.Add(branch);
                        loanSelection.LoanList.Add(l);
                    }
                }
            }


            return PartialView(loanSelection);
        }