public ActionResult CancelLoanRepayments(long LoanId)
        {
            //var query = from c in db.sdtoLoanRepayments
            //join o in db.sdtoLoanInfoes on c.LoanId equals o.LoanId
            //where c.LoanId == ((LoanId == null || LoanId.Value == 0) ? c.LoanId : LoanId)
            //group c by c.LoanId into g
            //select new
            //{
            //  Name = g.Key,
            //  Sum = g.Sum(oi => oi.RepaymentAmount),
            //  RepaymentCode = c.RepaymentCode
            //};

            sdtoLoanRepayment repay = new sdtoLoanRepayment();
            var itemsLoan = db.sdtoLoanInfoes.Include(x => x.Member).Where(x => x.Status == LoanStatus.Active).ToList();
            var itemsLoans = itemsLoan.Select(x => new SelectListItem() { Value = x.LoanId.ToString(), Text = x.LoanId + " - " + x.LoanAmount + "[" + x.Member.FirstName + " " + x.Member.LastName + "]" }).ToList();
            itemsLoans.Insert(0, new SelectListItem() { Value = "0", Text = "Select a loan" });
            ViewBag.LoanList = new SelectList(itemsLoans, "Value", "Text");

            ViewBag.LoanDetails = db.sdtoLoanInfoes.Where(x => x.LoanId == LoanId).FirstOrDefault();

            //var sdtoLoanRepayments = db.sdtoLoanRepayments.Where(x => x.LoanId == ((LoanId == null || LoanId.Value == 0) ? x.LoanId : LoanId)).Include(s => s.LoanDetails);
            var sdtoLoanRepayments = db.sdtoLoanRepayments.Where(x => x.LoanId == LoanId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled).Include(s => s.LoanDetails).Select(x => new sdtoViewRepaymentOfLoans()
            {
                ChequeDetails = x.ChequeDetails,
                InterestAmount = x.InterestAmount,
                InterestRate = x.InterestRate,
                LoanId = x.LoanId,
                LoanRepaymentId = x.LoanRepaymentId,
                Notes = x.Notes,
                PaymentMode = x.PaymentMode,
                PreviousPaymentDueAmount = x.PreviousPaymentDueAmount,
                PendingInstallments = x.PendingInstallments,
                PendingPrincipalAmount = x.PendingPrincipalAmount,
                PrincipalAmount = x.PrincipalAmount,
                RepaymentAmount = x.RepaymentAmount,
                RepaymentCode = x.RepaymentCode,
                RepaymentDate = x.RepaymentDate,
                Status = x.Status
            }).ToList();

            if (sdtoLoanRepayments != null && sdtoLoanRepayments.Count() > 0)
            {
                ViewBag.TotalPaid = sdtoLoanRepayments.Sum(y => y.RepaymentAmount);
                ViewBag.TotalPendingPrincipal = sdtoLoanRepayments.OrderByDescending(x => x.LoanRepaymentId).FirstOrDefault().PendingPrincipalAmount;
            }
            sdtoViewLoanRepayments viewItem = new sdtoViewLoanRepayments() { LoanId = LoanId, Repayments = sdtoLoanRepayments };
            return View(viewItem);
        }
        // GET: LoanRepayments
        public ActionResult Index(long? LoanId)
        {
            //var query = from c in db.sdtoLoanRepayments
            //join o in db.sdtoLoanInfoes on c.LoanId equals o.LoanId
            //where c.LoanId == ((LoanId == null || LoanId.Value == 0) ? c.LoanId : LoanId)
            //group c by c.LoanId into g
            //select new
            //{
            //  Name = g.Key,
            //  Sum = g.Sum(oi => oi.RepaymentAmount),
            //  RepaymentCode = c.RepaymentCode
            //};

            sdtoLoanRepayment repay = new sdtoLoanRepayment();
            var itemsLoan = db.sdtoLoanInfoes.Include(x => x.Member).Where(x => x.Status == LoanStatus.Active).ToList();
            var itemsLoans = itemsLoan.Select(x => new SelectListItem() { Value = x.LoanId.ToString(), Text = x.LoanId + " - " + x.LoanAmount + "[" + x.Member.FirstName + " " + x.Member.LastName + "]" }).ToList();
            itemsLoans.Insert(0, new SelectListItem() { Value = "0", Text = "Select a loan" });
            ViewBag.LoanList = new SelectList(itemsLoans, "Value", "Text");

            ViewBag.LoanDetails = db.sdtoLoanInfoes.Where(x => x.LoanId == LoanId).FirstOrDefault();

            //var sdtoLoanRepayments = db.sdtoLoanRepayments.Where(x => x.LoanId == ((LoanId == null || LoanId.Value == 0) ? x.LoanId : LoanId)).Include(s => s.LoanDetails);
            var sdtoLoanRepayments = db.sdtoLoanRepayments.Where(x => x.LoanId == LoanId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled).Include(s => s.LoanDetails);
            if (sdtoLoanRepayments != null && sdtoLoanRepayments.Count() > 0)
            {
                ViewBag.TotalPaid = sdtoLoanRepayments.Sum(y => y.RepaymentAmount);
                ViewBag.TotalPendingPrincipal = sdtoLoanRepayments.OrderByDescending(x => x.LoanRepaymentId).FirstOrDefault().PendingPrincipalAmount;
            }
            return View(sdtoLoanRepayments.ToList());
        }
        public ActionResult Edit(//[Bind(Include = "LoanRepaymentId,LoanId,RepaymentCode,PrincipalAmount,InterestAmount,InterestRate,RepaymentAmount,PendingPrincipalAmount,Status,PaymentMode,ChequeDetails,Notes,CreatedOn,ModifiedOn,CreatedBy,ModifiedBy,IsDeleted,DeletedBy,DeletedOn")]
            sdtoLoanRepayment sdtoLoanRepayment)
        {
            if (ModelState.IsValid)
            {
                var loandetails = db.sdtoLoanInfoes.Find(sdtoLoanRepayment.LoanId);
                var lastRepaymentDate = loandetails.RepaymentStartDate.Value;
                var pendingPrincipalAmount = loandetails.LoanAmount;
                decimal previousDue = 0;

                var previousLoanRepayment1 = db.sdtoLoanRepayments.Where(x => x.LoanId == sdtoLoanRepayment.LoanId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled && x.LoanRepaymentId != sdtoLoanRepayment.LoanRepaymentId).OrderByDescending(x => x.LoanRepaymentId).FirstOrDefault();
                if (previousLoanRepayment1 != null && previousLoanRepayment1.LoanRepaymentId > 0)
                {
                    lastRepaymentDate = previousLoanRepayment1.RepaymentDate.Value;
                    pendingPrincipalAmount = previousLoanRepayment1.PendingPrincipalAmount;
                    previousDue = previousLoanRepayment1.PreviousPaymentDueAmount;
                }
                var loanRepayment1 = db.sdtoLoanRepayments.Where(x => x.LoanRepaymentId == sdtoLoanRepayment.LoanRepaymentId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled).FirstOrDefault();

                if (loanRepayment1 != null && loanRepayment1.LoanRepaymentId > 0)
                {
                    var days = (sdtoLoanRepayment.RepaymentDate.Value - lastRepaymentDate).Days;
                    days = days == 0 ? 1 : days;
                    var repaymentInterestAmt = (pendingPrincipalAmount * Convert.ToDecimal(sdtoLoanRepayment.InterestRate / 100) * days) / 365;

                    sdtoLoanRepayment.InterestAmount = Math.Round(repaymentInterestAmt, 2);

                    decimal paymentBalance = sdtoLoanRepayment.RepaymentAmount - repaymentInterestAmt - loandetails.InstallmentAmount;
                    sdtoLoanRepayment.PreviousPaymentDueAmount = paymentBalance > 0 ? (previousDue - paymentBalance) : (previousDue + paymentBalance);

                    sdtoLoanRepayment.PendingPrincipalAmount = pendingPrincipalAmount - loandetails.InstallmentAmount + sdtoLoanRepayment.PreviousPaymentDueAmount; //(sdtoLoanRepayment.RepaymentAmount - repaymentInterestAmt);
                    sdtoLoanRepayment.PendingInstallments -= Convert.ToInt32(Math.Floor(sdtoLoanRepayment.PendingPrincipalAmount / loandetails.InstallmentAmount));
                    sdtoLoanRepayment.PrincipalAmount = loandetails.LoanAmount;
                }

                db.Entry(sdtoLoanRepayment).State = EntityState.Modified;
                db.SaveChanges();

                bfTransaction objTrans = new bfTransaction(db);
                objTrans.CancelPostedLoanRepayment(sdtoLoanRepayment);
                objTrans.PostLoanRepayment(sdtoLoanRepayment);

                return RedirectToAction("Index", new { LoanId = sdtoLoanRepayment.LoanId });
            }
            var itemsLoan = db.sdtoLoanInfoes.Include(x => x.Member).ToList();
            var itemsLoans = itemsLoan.Select(x => new SelectListItem() { Value = x.LoanId.ToString(), Text = x.LoanId + " - " + x.LoanAmount + "[" + x.Member.FirstName + " " + x.Member.LastName + "]" }).ToList();
            itemsLoans.Insert(0, new SelectListItem() { Value = "0", Text = "Select a loan" });
            ViewBag.LoanList = new SelectList(itemsLoans, "Value", "Text");

            return View(sdtoLoanRepayment);
        }
        public ActionResult Create(//[Bind(Include = "LoanRepaymentId,LoanId,RepaymentCode,PrincipalAmount,InterestAmount,InterestRate,RepaymentAmount,PendingPrincipalAmount,Status,PaymentMode,ChequeDetails,Notes,CreatedOn,ModifiedOn,CreatedBy,ModifiedBy,IsDeleted,DeletedBy,DeletedOn")] 
            sdtoLoanRepayment sdtoLoanRepayment)
        {
            if (ModelState.IsValid)
            {
                if (sdtoLoanRepayment.LoanId > 0)
                {
                    var loandetails = db.sdtoLoanInfoes.Find(sdtoLoanRepayment.LoanId);

                    var loanPendingAmt = loandetails.LoanAmount;
                    var loanInterest = loandetails.InteresRate;
                    var loanPendingInstallments = loandetails.TotalInstallments;

                    var loanRepayment = db.sdtoLoanRepayments.Where(x => x.LoanId == sdtoLoanRepayment.LoanId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled).OrderByDescending(x => x.LoanRepaymentId).FirstOrDefault();
                    var repaymentInterest = loanInterest;
                    var repaymentInterestAmt = (loanPendingAmt * Convert.ToDecimal(repaymentInterest / 100)) / 365;
                    var lastRepaymentDate = loandetails.RepaymentStartDate.Value;
                    var days = (DateTime.Now.Date - loandetails.RepaymentStartDate.Value).Days;

                    bfReport objReport = new bfReport(db);

                    if (loanRepayment != null && loanRepayment.LoanRepaymentId > 0)
                    {
                        if (loanRepayment.RepaymentDate != null)
                            lastRepaymentDate = loanRepayment.RepaymentDate.Value;
                        days = (sdtoLoanRepayment.RepaymentDate.Value - lastRepaymentDate).Days;
                        days = days == 0 ? 1 : days;
                        if (days < 0)
                            days = 0;

                        loanPendingAmt = loanRepayment.PendingPrincipalAmount;
                        loanPendingInstallments = loanRepayment.PendingInstallments;
                        repaymentInterest = loanRepayment.InterestRate;

                        repaymentInterestAmt = (loanPendingAmt * Convert.ToDecimal(repaymentInterest / 100) * days) / 365;
                        sdtoLoanRepayment.RepaymentCode = loanRepayment.RepaymentCode;

                        decimal paymentBalance = sdtoLoanRepayment.RepaymentAmount - repaymentInterestAmt - (loandetails.InstallmentAmount * days);
                        decimal previousDue = paymentBalance > 0 ? (loanRepayment.PreviousPaymentDueAmount - paymentBalance) : (loanRepayment.PreviousPaymentDueAmount + paymentBalance);
                        sdtoLoanRepayment.PreviousPaymentDueAmount = previousDue;
                    }

                    sdtoLoanRepayment.InterestAmount = Math.Round(repaymentInterestAmt, 2);
                    sdtoLoanRepayment.PendingPrincipalAmount = loanPendingAmt - (loandetails.InstallmentAmount * days) + sdtoLoanRepayment.PreviousPaymentDueAmount; //(sdtoLoanRepayment.RepaymentAmount - repaymentInterestAmt);
                    sdtoLoanRepayment.PendingInstallments -= Convert.ToInt32(Math.Floor(sdtoLoanRepayment.PendingPrincipalAmount / loandetails.InstallmentAmount));
                    sdtoLoanRepayment.PrincipalAmount = loandetails.LoanAmount;

                    sdtoLoanRepayment.Status = Data.Models.Enumerations.RepaymentStatus.Paid;
                    sdtoLoanRepayment.CreatedOn = DateTime.Now;

                    sdtoLoanRepayment.RepaymentCode = objReport.GenerateCode("LoanRepayment");

                    db.sdtoLoanRepayments.Add(sdtoLoanRepayment);
                    db.SaveChanges();

                    bfTransaction objTrans = new bfTransaction(db);
                    objTrans.PostLoanRepayment(sdtoLoanRepayment);

                    return RedirectToAction("Index", new { LoanId = sdtoLoanRepayment.LoanId });
                }
            }

            var itemsLoan = db.sdtoLoanInfoes.Include(x => x.Member).ToList();
            var itemsLoans = itemsLoan.Select(x => new SelectListItem() { Value = x.LoanId.ToString(), Text = x.LoanId + " - " + x.LoanAmount + "[" + x.Member.FirstName + " " + x.Member.LastName + "]" }).ToList();
            itemsLoans.Insert(0, new SelectListItem() { Value = "0", Text = "Select a loan" });
            ViewBag.LoanList = new SelectList(itemsLoans, "Value", "Text");

            return View(sdtoLoanRepayment);
        }
        public ActionResult Create(int? LoanId)
        {
            sdtoLoanRepayment repay = new sdtoLoanRepayment();
            var itemsLoan = db.sdtoLoanInfoes.Include(x => x.Member).Where(x => x.Status == LoanStatus.Active).ToList();
            var itemsLoans = itemsLoan.Select(x => new SelectListItem() { Value = x.LoanId.ToString(), Text = x.LoanId + " - " + x.LoanAmount + "[" + x.Member.FirstName + " " + x.Member.LastName + "]" }).ToList();
            itemsLoans.Insert(0, new SelectListItem() { Value = "0", Text = "Select a loan" });
            ViewBag.LoanList = new SelectList(itemsLoans, "Value", "Text");

            bfReport objReport = new bfReport(db);

            if (LoanId != null && LoanId.Value > 0)
            {
                var loandetails = db.sdtoLoanInfoes.Find(LoanId);

                var loanPendingAmt = loandetails.LoanAmount;
                var loanInterest = loandetails.InteresRate;
                var loanPendingInstallments = loandetails.TotalInstallments;

                var loanRepayment = db.sdtoLoanRepayments.Where(x => x.LoanId == LoanId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled).OrderByDescending(x => x.LoanRepaymentId).FirstOrDefault();
                var repaymentInterest = loanInterest;
                var days = (DateTime.Now.Date - loandetails.RepaymentStartDate.Value).Days;
                days = days == 0 ? 1 : days;
                if (days < 0)
                    days = 0;
                var repaymentInterestAmt = (loanPendingAmt * Convert.ToDecimal(repaymentInterest / 100) * days) / 365;
                var lastRepaymentDate = loandetails.RepaymentStartDate.Value;

                if (loanRepayment != null && loanRepayment.LoanRepaymentId > 0)
                {
                    if (loanRepayment.RepaymentDate != null)
                        lastRepaymentDate = loanRepayment.RepaymentDate.Value;
                    days = (DateTime.Now.Date - lastRepaymentDate).Days;
                    days = days == 0 ? 1 : days;
                    if (days < 0)
                        days = 0;

                    loanPendingAmt = loanRepayment.PendingPrincipalAmount;
                    loanPendingInstallments = loanRepayment.PendingInstallments;
                    repaymentInterest = loanRepayment.InterestRate;

                    repaymentInterestAmt = (loanPendingAmt * Convert.ToDecimal(repaymentInterest / 100) * days) / 365;
                    repay.RepaymentCode = loanRepayment.RepaymentCode;
                }

                repay.RepaymentDate = lastRepaymentDate.AddDays(1);
                repay.InterestRate = repaymentInterest;
                repay.InterestAmount = Math.Round(repaymentInterestAmt, 2);
                repay.PendingPrincipalAmount = loanPendingAmt;
                repay.PendingInstallments = loanPendingInstallments;
                repay.PrincipalAmount = loandetails.LoanAmount;

                repay.Status = Data.Models.Enumerations.RepaymentStatus.Paid;
                repay.PaymentMode = ModeOfPayment.Cash;

                repay.RepaymentAmount = (loandetails.InstallmentAmount * days) + repay.InterestAmount + repay.PreviousPaymentDueAmount;
                repay.RepaymentCode = objReport.GenerateCode("LoanRepayment");

                ViewBag.InstallmentAmount = loandetails.InstallmentAmount;
            }

            return View(repay);
        }
        public bool CancelPostedLoanRepayment(sdtoLoanRepayment LoanRepaymentInfo)
        {
            bool bFlag = true;
            var LoanInfo = AppDb.sdtoLoanInfoes.Find(LoanRepaymentInfo.LoanId);
            var member = AppDb.User.Where(x => x.UserID == LoanInfo.UserId).FirstOrDefault();
            if (member != null)
            {
                var accHeadMember = AppDb.AccountHeads.Find(member.AccountHeadId);
                if (accHeadMember != null)
                {
                    var settingCashBookId = AppDb.GeneralSettings.FirstOrDefault().CashBookId;
                    //Post for Bank book
                    var accCashBook = AppDb.AccountBooks.Where(x => x.AccountBookId == settingCashBookId).FirstOrDefault();
                    if (accCashBook != null)
                    {
                        var header = AppDb.ReceiptHeader.Where(x => x.IsDeleted == false && x.Cancelled == 0 && x.BookId == accCashBook.AccountBookId && x.TransId == LoanRepaymentInfo.LoanRepaymentId && x.Transaction == TransactionType.LoanRepayment).FirstOrDefault();
                        if (header != null)
                        {
                            header.Cancelled = 1;
                            AppDb.Entry(header).State = EntityState.Modified;
                            AppDb.SaveChanges();

                            var dtls = AppDb.ReceiptDetails.Where(x => x.ReceiptsId == header.Id && x.IsDeleted == false).ToList();
                            //dtls.ForEach(x => x.IsDeleted = true);

                            foreach (var dtlItem in dtls)
                            {
                                dtlItem.IsDeleted = true;
                                AppDb.Entry(dtlItem).State = EntityState.Modified;
                            }

                            AppDb.SaveChanges();
                        }
                    }
                }
            }
            return bFlag;
        }
        public bool PostLoanRepayment(sdtoLoanRepayment LoanRepaymentInfo)
        {
            bool tranFlag = true;
            var LoanInfo = AppDb.sdtoLoanInfoes.Find(LoanRepaymentInfo.LoanId);

            var member = AppDb.User.Where(x => x.UserID == LoanInfo.UserId).FirstOrDefault();
            if (member != null)
            {
                var accHeadMember = AppDb.AccountHeads.Find(member.AccountHeadId);
                if (accHeadMember != null)
                {
                    var settingCashBookId = AppDb.GeneralSettings.FirstOrDefault().CashBookId;
                    var settingsInterestAccountId = AppDb.GeneralSettings.FirstOrDefault().InterestAccountId;
                    //Post for Bank book
                    var accCashBook = AppDb.AccountBooks.Where(x => x.AccountBookId == settingCashBookId).FirstOrDefault();
                    var accInterest = AppDb.AccountHeads.Where(x => x.AccountHeadId == settingsInterestAccountId).FirstOrDefault();
                    if (accCashBook != null)
                    {
                        var receipt = new sdtoReceiptHeader()
                        {
                            BookId = accCashBook.AccountBookId,
                            TransDate = DateTime.Now,
                            VoucherTotal = LoanInfo.LoanAmount, //Doubt: Voucher total should be loan amount or loan amount + additional value from user
                            TransType = ReceiptType.Receipt,
                            FinancialYearId = CurrentUser.UserSession.FinancialYearId.Value,
                            FromModule = 1,  //Doubt: 0 for "From Accounts", 1 for "From Posting"
                            Transaction = TransactionType.LoanRepayment, //Doubt: //0 for Cash Receipt, 1 for Cash Payment, 2 for "Loan Entry", 3 for "Loan repayment"
                            TransId = LoanRepaymentInfo.LoanRepaymentId, //Doubt: Is transaction id loan id?
                            Cancelled = 0
                        };
                        AppDb.ReceiptHeader.Add(receipt);
                        AppDb.SaveChanges();

                        receipt.VoucherNo = accCashBook.ReceiptVoucherPrefix + receipt.Id + accCashBook.ReceiptVoucherSuffix;
                        AppDb.Entry(receipt).State = EntityState.Modified;
                        AppDb.SaveChanges();

                        // Member
                        var receiptDetailsCr = new sdtoReceiptDetails()
                        {
                            ReceiptsId = receipt.Id,
                            AccountId = accHeadMember.AccountHeadId,
                            Narration = "Loan Repayment received",
                            Amount = -1 * LoanRepaymentInfo.RepaymentAmount,
                            Display = 1
                        };

                        UpdateClosingBalance(accHeadMember.AccountHeadId, CurrentUser.UserSession.FinancialYearId.Value, -1 * LoanRepaymentInfo.RepaymentAmount);
                        UpdateDayBookBalance(accHeadMember.AccountHeadId, CurrentUser.UserSession.FinancialYearId.Value, LoanInfo.TransactionDate.Value, -1 * LoanRepaymentInfo.RepaymentAmount, TransactionType.LoanRepayment);

                        // Cash Account
                        var receiptDetailsDb = new sdtoReceiptDetails()
                        {
                            ReceiptsId = receipt.Id,
                            AccountId = accCashBook.AccountHeadId.Value,
                            Narration = "Loan Repayment received",
                            Amount = (LoanRepaymentInfo.RepaymentAmount - LoanRepaymentInfo.InterestAmount),
                            Display = 1
                        };

                        UpdateClosingBalance(accCashBook.AccountHeadId.Value, CurrentUser.UserSession.FinancialYearId.Value, (LoanRepaymentInfo.RepaymentAmount - LoanRepaymentInfo.InterestAmount));
                        UpdateDayBookBalance(accCashBook.AccountHeadId.Value, CurrentUser.UserSession.FinancialYearId.Value, LoanInfo.TransactionDate.Value, (LoanRepaymentInfo.RepaymentAmount - LoanRepaymentInfo.InterestAmount), TransactionType.LoanRepayment);

                        var receiptDetailsDbInt = new sdtoReceiptDetails()
                        {
                            ReceiptsId = receipt.Id,
                            AccountId = accInterest.AccountHeadId,
                            Narration = "Loan Repayment received",
                            Amount = LoanRepaymentInfo.InterestAmount,
                            Display = 1
                        };

                        AppDb.ReceiptDetails.Add(receiptDetailsDbInt);
                        AppDb.ReceiptDetails.Add(receiptDetailsCr);
                        AppDb.ReceiptDetails.Add(receiptDetailsDb);
                        AppDb.SaveChanges();
                    }
                }
            }

            return tranFlag;
        }
        public ActionResult ImportView(HttpPostedFileBase DeviceInput)
        {
            StreamReader reader = new StreamReader(DeviceInput.InputStream);
            while (!reader.EndOfStream)
            {
                string lineInput = reader.ReadLine();
                if (!string.IsNullOrWhiteSpace(lineInput))
                {
                    string[] arrLines = lineInput.Split("\0".ToCharArray());
                    if (arrLines != null && arrLines.Length > 0)
                    {
                        foreach (string strLine in arrLines)
                        {
                            string[] arrValues = strLine.Split(",".ToCharArray());
                            if (arrValues != null && arrValues.Length > 10)
                            {
                                sdtoLoanRepayment repayment = new sdtoLoanRepayment();
                                long iLoanId = 0;
                                long.TryParse(arrValues[2], out iLoanId);
                                repayment.LoanId = iLoanId;
                                if (repayment.LoanId > 0)
                                {
                                    float fPaymentAmount = 0;
                                    float.TryParse(arrValues[3], out fPaymentAmount);

                                    DateTime dt = DateTime.Now;
                                    DateTime.TryParse(arrValues[8], out dt);

                                    repayment.RepaymentDate = dt;

                                    var loandetails = db.sdtoLoanInfoes.Find(repayment.LoanId);

                                    if (loandetails != null)
                                    {
                                        var loanPendingAmt = loandetails.LoanAmount;
                                        var loanInterest = loandetails.InteresRate;
                                        var loanPendingInstallments = loandetails.TotalInstallments;

                                        var loanRepayment = db.sdtoLoanRepayments.Where(x => x.LoanId == repayment.LoanId && x.IsDeleted == false && x.Status != RepaymentStatus.Cancelled).OrderByDescending(x => x.LoanRepaymentId).FirstOrDefault();
                                        var repaymentInterest = loanInterest;
                                        var repaymentInterestAmt = (loanPendingAmt * Convert.ToDecimal(repaymentInterest / 100)) / 365;

                                        if (loanRepayment != null && loanRepayment.LoanRepaymentId > 0)
                                        {
                                            loanPendingAmt = loanRepayment.PendingPrincipalAmount;
                                            loanPendingInstallments = loanRepayment.PendingInstallments;
                                            repaymentInterest = loanRepayment.InterestRate;

                                            repaymentInterestAmt = (loanPendingAmt * Convert.ToDecimal(repaymentInterest / 100)) / 365;
                                            repayment.RepaymentCode = loanRepayment.RepaymentCode;
                                        }

                                        repayment.InterestAmount = Math.Round(repaymentInterestAmt, 2);
                                        repayment.PendingPrincipalAmount = loanPendingAmt - (repayment.RepaymentAmount - repaymentInterestAmt);
                                        repayment.PendingInstallments -= Convert.ToInt32(Math.Floor(repayment.PendingPrincipalAmount / loandetails.InstallmentAmount));
                                        repayment.PrincipalAmount = loandetails.LoanAmount;

                                        repayment.Status = Data.Models.Enumerations.RepaymentStatus.Paid;
                                        repayment.CreatedOn = DateTime.Now;

                                        db.sdtoLoanRepayments.Add(repayment);
                                        db.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            reader.Close();

            sdtoUser sessionUser = UtilityHelper.UserSession.GetSession(UtilityHelper.UserSession.LoggedInUser) as sdtoUser;
            long CompanyId = 0;
            if (sessionUser != null && sessionUser.CompanyId != null)
                CompanyId = sessionUser.CompanyId.Value;

            DataTable dtRptParams = new DataTable();
            dtRptParams.Columns.Add(new DataColumn("EntityId", typeof(long)));
            dtRptParams.Columns.Add(new DataColumn("EntityStartDate", typeof(DateTime)));
            dtRptParams.Columns.Add(new DataColumn("EntityEndDate", typeof(DateTime)));
            dtRptParams.Columns.Add(new DataColumn("EntityIntVal", typeof(int)));
            dtRptParams.Columns.Add(new DataColumn("EntityStrVal", typeof(string)));
            dtRptParams.Columns.Add(new DataColumn("EntityType", typeof(string)));

            bfReport objReport = new bfReport(null);
            var loanInfoList = objReport.GetRptLoanSummary(CompanyId, dtRptParams).ToList().Select(x => new sdtoLoanRepayment() { LoanId = x.LoanId, LoanDetails = new sdtoLoanInfo() { Member = new sdtoUser() { FirstName = x.FirstName, LastName = x.LastName } }, PendingPrincipalAmount = x.BalanceLoanAmount });

            return View(loanInfoList);
        }