private void btnAdjust_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                /*MessageBoxResult mr = MessageBox.Show("Sure?", "Question", MessageBoxButton.YesNo);
                if (mr == MessageBoxResult.Yes)
                {
                    using (var ctx = new finalContext())
                    {
                        AdjustedLoan al = new AdjustedLoan { DateAdjusted = DateTime.Today.Date, Days = Convert.ToInt32(txtDays.Text), Fee = Convert.ToDouble(lblFee.Content), LoanID = lId };
                        var py = from p in ctx.FPaymentInfo
                                 where p.PaymentStatus != "Cleared" && p.LoanID == lId
                                 select p;
                        foreach (var item in py)
                        {
                            item.PaymentDate = item.PaymentDate.AddDays(Convert.ToDouble(txtDays.Text));
                        }
                        ctx.AdjustedLoans.Add(al);
                        ctx.SaveChanges();
                        this.Close();
                    }
                }
                 * */

                if (Convert.ToInt32(txtDays.Text) > 14)
                {
                    MessageBox.Show("Maximum of 14 days only", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                wpfCheckout frm = new wpfCheckout();
                frm.status = "Adjustment";
                frm.days = Convert.ToDouble(txtDays.Text);
                frm.lId = lId;
                frm.lbl2.Content = lblFee.Content;
                frm.ShowDialog();
                this.Close();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (status == "UReleasing")
                {
                    if (iDept == "Financing")
                    {
                        wpfFReleasing frm = new wpfFReleasing();
                        frm.status = "UReleasing";
                        frm.UserID = UserID;
                        frm.lId = lId;
                        this.Close();
                        frm.ShowDialog();
                    }
                    else
                    {
                        wpfMReleasing frm = new wpfMReleasing();
                        frm.status = "UReleasing";
                        frm.UserID = UserID;
                        frm.lId = lId;
                        this.Close();
                        frm.ShowDialog();
                    }
                }
                else if (status == "Holding")
                {
                    using (var ctx = new finalContext())
                    {
                        //var dts = ctx.FPaymentInfo.Where(x => x.LoanID == lId && x.PaymentStatus == "Pending").First();
                        if (DateTime.Today.Date > Convert.ToDateTime(lblEDt.Content) || DateTime.Today.Date < Convert.ToDateTime(lblSDt.Content))
                        {
                            System.Windows.MessageBox.Show("Unable to hold next cheque", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                        /*MessageBoxResult mr = System.Windows.MessageBox.Show("You sure?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (mr == MessageBoxResult.Yes)
                        {
                            var dts = ctx.FPaymentInfo.Where(x => x.LoanID == lId && (x.PaymentStatus == "Pending" || x.PaymentStatus == "On Hold")).First();
                            double hFee = dts.Amount * (dts.Loan.Service.Holding / 100);
                            hFee = Convert.ToDouble(hFee.ToString("N2"));
                            HeldCheque hc = new HeldCheque { DateHeld = DateTime.Today.Date, LoanID = lId, NewPaymentDate = dts.PaymentDate.AddDays(7), OriginalPaymentDate = dts.PaymentDate, PaymentNumber = dts.PaymentNumber, HoldingFee = hFee };
                            dts.PaymentDate = dts.PaymentDate.AddDays(7);
                            dts.PaymentStatus = "On Hold";
                            ctx.HeldCheques.Add(hc);
                            ctx.SaveChanges();
                            reset();

                            System.Windows.MessageBox.Show("Okay");


                        }*/
                        wpfCheckout frm = new wpfCheckout();
                        frm.lId = lId;
                        frm.UserID = UserID;
                        frm.status = "Holding";
                        frm.ShowDialog();

                    }
                }
                else if (status == "Adjustment")
                {
                    wpfPaymentAdjustment frm = new wpfPaymentAdjustment();
                    frm.UserID = UserID;
                    frm.lId = lId;
                    this.Close();
                    frm.ShowDialog();
                }
                else if (status == "Restructure")
                {
                    wpfLoanRestructure frm = new wpfLoanRestructure();
                    frm.lId = lId;
                    frm.UserID = UserID;
                    this.Close();
                    frm.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
        private void btnRenew_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (var i in textarray)
                {
                    if (i.Text.Length != 6)
                    {
                        System.Windows.MessageBox.Show("Please input all cheque numbers", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    bool err;
                    int res;
                    String str = i.Text;
                    err = int.TryParse(str, out res);
                    if (err == false)
                    {
                        System.Windows.MessageBox.Show("Please input the correct format for cheque numbers(Strictly numbers only.)", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }

                for (int x = 0; x < textarray.Length; x++)
                {
                    for (int y = x + 1; y < textarray.Length; y++)
                    {
                        if (textarray[x].Text == textarray[y].Text)
                        {
                            System.Windows.MessageBox.Show("No duplications of cheque numbers", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }
                }



                MessageBoxResult mr = MessageBox.Show("Are you sure you want to process this transaction?", "Question", MessageBoxButton.YesNo);
                if (mr == MessageBoxResult.Yes)
                {
                    wpfCheckout frm = new wpfCheckout();
                    frm.status = "RenewClosed";
                    frm.lId = lId;
                    frm.ShowDialog();

                    if (cont == false)
                    {
                        System.Windows.MessageBox.Show("Please pay the Closed Account Penalty first", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    using (var ctx = new finalContext())
                    {
                        var bk = ctx.Banks.Where(x => x.BankName == cmbBank.Text).First();
                        int bId = bk.BankID;
                        var lon = ctx.Loans.Find(lId);
                        lon.Status = "Released";//active
                        lon.BankID = bId;
                        var ch = from c in ctx.FPaymentInfo
                                 where c.LoanID == lId && c.PaymentStatus == "Void"
                                 select c;
                        int Interval = 0;
                        DateInterval dInt = new DateInterval();
                        if (lon.Mode == "Monthly")
                        {
                            Interval = 1;
                            dInt = DateInterval.Month;
                        }
                        else if (lon.Mode == "Semi-Monthly")
                        {
                            Interval = 15;
                            dInt = DateInterval.Day;
                        }
                        else if (lon.Mode == "Weekly")
                        {
                            Interval = 7;
                            dInt = DateInterval.Day;
                        }
                        else if (lon.Mode == "Daily")
                        {
                            Interval = 1;
                            dInt = DateInterval.Day;
                        }
                        /*else if (cmbMode.Text == "One-Time Payment")
                        {
                            NetProceed = NetProceed - ((Convert.ToDouble(txtAmt.Text) * TotalInt));
                            lblProceed.Content = NetProceed.ToString("N2");
                            lblInt.Content = txtAmt.Text;
                            Remaining = Convert.ToDouble(lblPrincipal.Content);
                            Payment = Remaining;
                            Interval = Convert.ToInt32(txtTerm.Text);
                            dInt = DateInterval.Month;
                            lbl4.Content = "Total Payment";
                        }*/
                        DateTime dt = dtPcker.SelectedDate.Value.Date;
                        int num = 0;
                        foreach (var item in ch)
                        {
                            item.ChequeInfo = textarray[num].Text;
                            item.ChequeDueDate = dt;
                            item.PaymentDate = dt;
                            item.PaymentStatus = "Pending";
                            dt = DateAndTime.DateAdd(dInt, Interval, dt);
                            num++;
                        }

                        var cc = ctx.ClosedAccounts.Where(x => x.LoanID == lId && x.isPaid == false).First();
                        cc.isPaid = true;

                        AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Processed renewal for Closed Account Loan " + lon.LoanID };
                        ctx.AuditTrails.Add(at);

                        ctx.SaveChanges();
                        MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
 private void btnCash_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         using (var ctx = new finalContext())
         {
             int id = Convert.ToInt32(getRow(dg, 0));
             int num = Convert.ToInt32(getRow(dg, 1));
             FPaymentInfo fp = ctx.FPaymentInfo.Where(x => x.LoanID == id && x.PaymentNumber == num).First();
             DepositedCheque dp = ctx.DepositedCheques.Find(fp.FPaymentInfoID);
             wpfCheckout frm = new wpfCheckout();
             frm.status = "PBC";//pay by cash
             frm.fId = fp.FPaymentInfoID;
         }
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         return;
     }
 }
        private void btnDep_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (status == "Deposit")
                {
                    if (state == "Dep")
                    {
                        MessageBoxResult mr = MessageBox.Show("Are you sure you want to deposit the selected cheque(s)?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (mr == MessageBoxResult.Yes)
                        {
                            using (var ctx = new finalContext())
                            {
                                var chq = from ch in ctx.FPaymentInfo
                                          where ch.PaymentStatus == "Due"
                                          select ch;
                                foreach (var item in chq)
                                {
                                    /*var ctr = ctx.FPaymentInfo.Where(x => x.LoanID == item.LoanID && x.PaymentStatus == "Due/Pending").Count();
                                    if (ctr != 0)
                                    {
                                        var hq = ctx.FPaymentInfo.Where(x => x.LoanID == item.LoanID && x.PaymentStatus == "Due/Pending").First();
                                        hq.PaymentStatus = "Due";
                                    }*/
                                    var ch = ctx.DepositedCheques.Where(x => x.FPaymentInfoID == item.FPaymentInfoID).Count();
                                    if (ch > 0)
                                    {
                                        item.DepositedCheque.DepositDate = DateTime.Today.Date;
                                        item.PaymentStatus = "Deposited";
                                    }
                                    else
                                    {
                                        item.PaymentStatus = "Deposited";
                                        DepositedCheque dc = new DepositedCheque { DepositDate = DateTime.Today.Date, FPaymentInfoID = item.FPaymentInfoID };
                                        ctx.DepositedCheques.Add(dc);
                                    }
                                }
                                AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Deposited Cheque(s)" };
                                ctx.AuditTrails.Add(at);

                                ctx.SaveChanges();
                                MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                rg();
                            }
                        }
                    }
                    else if (state == "Undep")
                    {
                        using (var ctx = new finalContext())
                        {
                            int id = Convert.ToInt32(getRow(dg, 0));
                            int num = Convert.ToInt32(getRow(dg, 1));
                            FPaymentInfo fp = ctx.FPaymentInfo.Where(x => x.LoanID == id && x.PaymentNumber == num).First();
                            DepositedCheque dp = ctx.DepositedCheques.Find(fp.FPaymentInfoID);
                            MessageBoxResult mr = MessageBox.Show("Are you sure you want to void this transaction?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (mr == MessageBoxResult.Yes)
                            {
                                fp.PaymentStatus = "Due";
                                ctx.DepositedCheques.Remove(dp);
                                ctx.SaveChanges();
                                MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                checkDue();
                                rg();
                                rdDue.IsChecked = true;
                            }
                        }
                    }
                    else if (state == "Redep")
                    {
                        using (var ctx = new finalContext())
                        {
                            int id = Convert.ToInt32(getRow(dg, 0));
                            int num = Convert.ToInt32(getRow(dg, 1));
                            FPaymentInfo fp = ctx.FPaymentInfo.Where(x => x.LoanID == id && x.PaymentNumber == num).First();
                            DepositedCheque dp = ctx.DepositedCheques.Find(fp.FPaymentInfoID);
                            MessageBoxResult mr = MessageBox.Show("Are you sure you want to redeposit this cheque?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (mr == MessageBoxResult.Yes)
                            {
                                wpfCheckout frm = new wpfCheckout();
                                frm.status = "Daif";
                                frm.fId = fp.FPaymentInfoID;
                                frm.ShowDialog();

                                if (cont == false)
                                {
                                    System.Windows.MessageBox.Show("Please pay the DAIF fee first", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }

                                fp.PaymentStatus = "Deposited";
                                dp.DepositDate = DateTime.Today.Date;
                                AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Redeposit cheque " + fp.ChequeInfo };
                                ctx.AuditTrails.Add(at);
                                ctx.SaveChanges();
                                MessageBox.Show("Transaction has been successfully processed.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                checkDue();
                                rg();
                                //rdDue.IsChecked = true;
                            }
                        }
                    }
                }
                else if(status == "Returning")
                {
                    if (state == "Undep")//for returning
                    {
                        int id = Convert.ToInt32(getRow(dg, 0));
                        int num = Convert.ToInt32(getRow(dg, 1));
                        using (var ctx = new finalContext())
                        {
                            FPaymentInfo fp = ctx.FPaymentInfo.Where(x => x.LoanID == id && x.PaymentNumber == num).First();

                            var ctr = ctx.ReturnedCheques.Where(x => x.FPaymentInfoID==fp.FPaymentInfoID).Count();

                            if (ctr > 0)
                            {
                                MessageBox.Show("Cheque has already been returned once", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                return;
                            }

                            wpfChequeReturning frm = new wpfChequeReturning();
                            frm.fId = fp.FPaymentInfoID;
                            frm.UserID = UserID;
                            frm.ShowDialog();
                        }
                    }
                    else if (state == "Redep")//for voiding
                    {
                        int id = Convert.ToInt32(getRow(dg, 0));
                        int num = Convert.ToInt32(getRow(dg, 1));
                        using (var ctx = new finalContext())
                        {
                            FPaymentInfo fp = ctx.FPaymentInfo.Where(x => x.LoanID == id && x.PaymentNumber == num).First();
                            ReturnedCheque rc = ctx.ReturnedCheques.Find(fp.FPaymentInfoID);
                            fp.PaymentStatus = "Deposited";
                            ctx.ReturnedCheques.Remove(rc);
                            ctx.SaveChanges();
                            MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var ctx = new finalContext())
                {
                    FPaymentInfo fp = ctx.FPaymentInfo.Find(fId);
                    DepositedCheque dp = ctx.DepositedCheques.Find(fId);
                    MessageBoxResult mr = MessageBox.Show("Are you sure you want to process this transaction?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (mr == MessageBoxResult.Yes)
                    {

                        if (status == "Full")
                        {
                            var fp2 = from f in ctx.FPaymentInfo
                                     where f.LoanID == lID && f.PaymentStatus != "Cleared"
                                     select f;
                            double tot = 0;
                            foreach (var itm in fp2)
                            {
                                itm.PaymentStatus = "Cleared";
                                ClearedCheque cc = new ClearedCheque { FPaymentInfoID = itm.FPaymentInfoID, DateCleared = DateTime.Now };
                            }

                            FPaymentInfo f2 = new FPaymentInfo { Amount = double.Parse(txtAmt.Text), ChequeDueDate = DateTime.Now.Date, ChequeInfo = txtId.Text, LoanID = lID, PaymentNumber = fp2.Count() + 1, PaymentStatus = "Cleared", PaymentDate = DateTime.Now, RemainingBalance = 0 };
                            ctx.FPaymentInfo.Add(f2);
                            var lon = ctx.Loans.Find(lID);
                            lon.Status = "Paid";
                            PaidLoan pl = new PaidLoan { DateFinished = DateTime.Now, LoanID = lID };
                            ctx.PaidLoans.Add(pl);
                            ctx.SaveChanges();
                            ClearedCheque cc2 = new ClearedCheque { DateCleared = DateTime.Now, FPaymentInfoID = f2.FPaymentInfoID };
                            MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            this.Close();
                            return;
                        }


                        if (chDaif.IsChecked == false)
                        {
                            wpfCheckout frm = new wpfCheckout();
                            frm.status = "Daif";
                            frm.fId = fId;
                            frm.ShowDialog();

                            if (cont == false)
                            {
                                System.Windows.MessageBox.Show("Please pay the DAIF fee first", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                        }

                        AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Changed Cheque " + fp.ChequeInfo + " to " + txtId.Text + "" };
                        ctx.AuditTrails.Add(at);
                        fp.PaymentStatus = "Deposited";
                        fp.ChequeInfo = txtId.Text;
                        dp.DepositDate = DateTime.Today.Date;
                        

                        fp.ReturnedCheque.isPaid = true;


                        if (chDaif.IsChecked == true)
                        {
                            fp.Amount = fp.Amount + fp.ReturnedCheque.Fee;
                        }
                        ctx.SaveChanges();
                        MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Runtime Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
        private void btnRestructure_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                double max = 0;
                double min = 0;
                using (var ctx = new finalContext())
                {
                    var lon = ctx.Loans.Find(lId);
                    var ser = ctx.Services.Find(lon.ServiceID);
                    max = ser.MaxTerm;
                    min = ser.MinTerm;


                    if (Convert.ToDouble(txtTerm.Text) > max || Convert.ToDouble(txtTerm.Text) < min)
                    {
                        System.Windows.MessageBox.Show("Term must not be greater than the maximum term(" + ser.MaxTerm + " mo.) OR less than the minimum term(" + ser.MinTerm + " mo.)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    max = ser.MaxValue;
                    min = ser.MinValue;

                    //if (Convert.ToDouble(txtAmt.Text) > max || Convert.ToDouble(txtAmt.Text) < min)
                    //{
                    //    System.Windows.MessageBox.Show("Principal amount must not be greater than the maximum loanable amount OR less than the minimum loanable amount", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    //    return;
                    //}
                }

                if (Convert.ToDouble(txtAmt.Text) > Convert.ToDouble(lblPrincipal.Content))
                {
                    MessageBox.Show("Principal amount must not be greater than the maximum loanable amount", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                foreach (var i in textarray)
                {
                    if (i.Text.Length != 6)
                    {
                        System.Windows.MessageBox.Show("Please input all cheque numbers", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    bool err;
                    int res;
                    String str = i.Text;
                    err = int.TryParse(str, out res);
                    if (err == false)
                    {
                        System.Windows.MessageBox.Show("Please input the correct format for cheque numbers(Strictly numbers only.)");
                        return;
                    }
                }

                for (int x = 0; x < textarray.Length; x++)
                {
                    for (int y = x + 1; y < textarray.Length; y++)
                    {
                        if (textarray[x].Text == textarray[y].Text)
                        {
                            System.Windows.MessageBox.Show("No duplications of cheque numbers", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }
                }

                MessageBoxResult mr = MessageBox.Show("Are you sure you want to process this transaction?", "Question", MessageBoxButton.YesNo);
                if (mr == MessageBoxResult.Yes)
                {
                    using (var ctx = new finalContext())
                    {
                        wpfCheckout frm = new wpfCheckout();
                        var lon = ctx.Loans.Find(lId);
                        frm.lId = lId;
                        frm.status = "Restructure";
                        frm.lbl2.Content = (Convert.ToDouble(txtAmt.Text) * (lon.Service.RestructureFee / 100)).ToString("N2");
                        if(lon.Status == "Closed Account")
                        {
                            var cc = ctx.ClosedAccounts.Where(x=> x.LoanID==lId && x.isPaid == false).First();
                            frm.lbl2.Content = (Double.Parse(frm.lbl2.Content.ToString()) + cc.Fee).ToString("N2");
                        }
                        frm.ShowDialog();
                    }
                    if (cont != true)
                    {
                        MessageBox.Show("Please pay restructure fee and/or closed account fee first", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }

                    using (var ctx = new finalContext())
                    {
                        var bk = ctx.Banks.Where(x => x.BankName == cmbBank.Text).First();
                        int bId = bk.BankID;
                        var lon = ctx.Loans.Find(lId);
                        if (lon.Status == "Closed Account")
                        {
                            var cc = ctx.ClosedAccounts.Where(x => x.LoanID == lId && x.isPaid == false).First();
                            cc.isPaid = true;
                        }
                        lon.Status = "Resturctured";
                        Loan l = new Loan { AgentID = lon.AgentID, CI = 0, Term = Convert.ToInt32(txtTerm.Text), Status = "Released", ServiceID = lon.ServiceID, Mode = cmbMode.Text, CoBorrower = lon.CoBorrower, ClientID = lon.ClientID, BankID = bId };
                        ReleasedLoan rl = new ReleasedLoan { LoanID = l.LoanID, AgentsCommission = 0, DateReleased = DateTime.Today.Date, MonthlyPayment = Convert.ToDouble(lblMonthly.Content), NetProceed = 0, Principal = 0, TotalLoan = Convert.ToDouble(lblInt.Content) };
                        //RestructuredLoan rln = new RestructuredLoan { LoanID = lId, NewLoanID = l.LoanID, DateRestructured = DateTime.Today, Fee = Convert.ToDouble(txtAmt.Text) * (lon.Service.RestructureFee / 100) };
                        var fp = from f in ctx.FPaymentInfo
                                 where f.PaymentStatus != "Cleared" && f.LoanID == lId
                                 select f;
                        foreach (var item in fp)
                        {
                            item.PaymentStatus = "Void";
                        }

                        var lo = from ly in ctx.GenSOA
                                 select ly;
                        int y = 0;
                        foreach (var item in lo)
                        {
                            FPaymentInfo fpy = new FPaymentInfo { PaymentNumber = item.PaymentNumber, Amount = Convert.ToDouble(item.Amount), ChequeInfo = textarray[y].Text, LoanID = l.LoanID, ChequeDueDate = item.PaymentDate, PaymentDate = item.PaymentDate, PaymentStatus = "Pending", RemainingBalance = Convert.ToDouble(item.RemainingBalance) };
                            ctx.FPaymentInfo.Add(fpy);
                            y++;
                        }

                        AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Processed Restructure for Loan " + lId + "" };
                        ctx.AuditTrails.Add(at);

                        ctx.Loans.Add(l);
                        ctx.ReleasedLoans.Add(rl);
                        ctx.SaveChanges();
                        RestructuredLoan rln = new RestructuredLoan { LoanID = lId, NewLoanID = l.LoanID, DateRestructured = DateTime.Today, Fee = Convert.ToDouble(txtAmt.Text) * (lon.Service.RestructureFee / 100) };
                        ctx.RestructuredLoans.Add(rln);

                        

                        ctx.SaveChanges();
                        printSOA();
                        MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
                

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Incorrect Format on some Fields / Incomplete Input(s)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }