private void btnRelease_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (status == "Releasing" || status == "Renewal")
                {
                    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) && status=="Releasing")
                    {
                        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.)", "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, MessageBoxImage.Question);
                    if (mr == MessageBoxResult.Yes)
                    {
                        if (status == "Renewal")
                        {
                            using (var ctx = new finalContext())
                            {
                                var bk = ctx.Banks.Where(x => x.BankName == cmbBank.Text).First();
                                int bId = bk.BankID;
                                var rn = ctx.LoanRenewals.Where(x => x.newLoanID == lId).First();
                                var lon = ctx.Loans.Find(rn.LoanID);
                                lon.Status = "Paid";
                                int tlID = lon.LoanID;
                                var pys = from p in ctx.FPaymentInfo
                                          where p.LoanID == rn.LoanID
                                          select p;
                                foreach (var itm in pys)
                                {
                                    itm.PaymentStatus = "Cleared";
                                }
                                lon = ctx.Loans.Find(lId);
                                lon.Status = "Released";
                                var cn = ctx.Services.Find(lon.ServiceID);
                                double co = cn.AgentCommission / 100;
                                double cm = Convert.ToDouble(txtAmt.Text) * co;
                                ReleasedLoan rl = new ReleasedLoan { LoanID=lId, AgentsCommission = cm, DateReleased = DateTime.Now.Date, MonthlyPayment = Convert.ToDouble(lblMonthly.Content), NetProceed = Convert.ToDouble(lblProceed.Content), Principal = Convert.ToDouble(txtAmt.Text), TotalLoan = Convert.ToDouble(lblInt.Content) };
                                var lo = from l in ctx.GenSOA
                                         select l;
                                int y = 0;
                                ctx.ReleasedLoans.Add(rl);
                                ctx.SaveChanges();
                                var inf = from i in ctx.CollateralLoanInfoes
                                          where i.LoanID == tlID
                                          select i;

                                foreach (var itm in inf)
                                {
                                    CollateralLoanInfo ci = new CollateralLoanInfo { CollateralInformationID = itm.CollateralInformationID, LoanID = lId, Value = itm.Value };
                                    ctx.CollateralLoanInfoes.Add(ci);
                                }

                                foreach (var item in lo)
                                {
                                    FPaymentInfo fp = new FPaymentInfo { PaymentNumber = item.PaymentNumber, Amount = Convert.ToDouble(item.Amount), ChequeInfo = textarray[y].Text, LoanID = lId, ChequeDueDate = item.PaymentDate, PaymentDate = item.PaymentDate, PaymentStatus = "Pending", RemainingBalance = Convert.ToDouble(item.RemainingBalance) };
                                    ctx.FPaymentInfo.Add(fp);
                                    y++;
                                }
                                AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Released loan renewal (" + lon.Service.Name + ") for client " + lon.Client.FirstName + " " + lon.Client.MiddleName + " " + lon.Client.LastName + " " + lon.Client.Suffix };
                                ctx.AuditTrails.Add(at);
                                ctx.SaveChanges();
                                printSOA();
                                MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                this.Close();
                            }
                        }
                        else
                        {
                            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";
                                lon.BankID = bId;
                                lon.Mode = cmbMode.Text;
                                lon.Term = Convert.ToInt32(txtTerm.Text);
                                var cn = ctx.Services.Find(lon.ServiceID);
                                double co = cn.AgentCommission / 100;
                                double cm = Convert.ToDouble(txtAmt.Text) * co;
                                //MessageBox.Show(cm.ToString());
                                ReleasedLoan rl = new ReleasedLoan { AgentsCommission = cm, DateReleased = DateTime.Today.Date, LoanID = lId, MonthlyPayment = Convert.ToDouble(lblMonthly.Content), NetProceed = Convert.ToDouble(lblProceed.Content), Principal = Convert.ToDouble(txtAmt.Text), TotalLoan = Convert.ToDouble(lblInt.Content) };
                                lon.ReleasedLoan = rl;
                                var lo = from l in ctx.GenSOA
                                         select l;
                                int y = 0;
                                foreach (var item in lo)
                                {
                                    FPaymentInfo fp = new FPaymentInfo { PaymentNumber = item.PaymentNumber, Amount = Convert.ToDouble(item.Amount), ChequeInfo = textarray[y].Text, LoanID = lId, ChequeDueDate = item.PaymentDate, PaymentDate = item.PaymentDate, PaymentStatus = "Pending", RemainingBalance = Convert.ToDouble(item.RemainingBalance) };
                                    ctx.FPaymentInfo.Add(fp);
                                    y++;
                                }
                                AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Released loan (" + lon.Service.Name + ") for client " + lon.Client.FirstName + " " + lon.Client.MiddleName + " " + lon.Client.LastName + " " + lon.Client.Suffix };
                                ctx.AuditTrails.Add(at);
                                ctx.SaveChanges();
                                printSOA();
                                MessageBox.Show("Transaction has been successfully processed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                this.Close();
                            }
                        }
                    }
                }
                else if (status == "UReleasing")
                {
                    int myCtr = 0;
                    using (var ctx = new finalContext())
                    {
                        var lons = from lo in ctx.FPaymentInfo
                                   where lo.LoanID == lId
                                   select lo;
                        foreach (var item in lons)
                        {
                            item.ChequeInfo = textarray[myCtr].Text;
                            myCtr++;
                        }
                        var lon = ctx.Loans.Find(lId);
                        var bk = ctx.Banks.Where(x => x.BankName == cmbBank.Text).First();
                        int bId = bk.BankID;
                        lon.BankID = bId;

                        AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Updated Released loan (" + lon.Service.Name + ") for client " + lon.Client.FirstName + " " + lon.Client.MiddleName + " " + lon.Client.LastName + " " + lon.Client.Suffix };
                        ctx.AuditTrails.Add(at);
                        ctx.SaveChanges();
                        MessageBox.Show("Transaction has been successfully updated", "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;
            }
        }
        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;
            }
        }