private void btnContinue_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtCat.Text == "Non Collateral")
                {
                    using (var ctx = new finalContext())
                    {
                        var ictr = ctx.Loans.Where(x => x.ClientID == cId && x.Status == "Released" && x.Service.Type == "Non Collateral" && x.Service.Department == iDept).Count();
                        if (ictr > 0)
                        {
                            System.Windows.MessageBox.Show("Client has an existing Non-Collateral loan. The client can only apply for collateral loan.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }
                    if (string.IsNullOrWhiteSpace(txtID.Text))
                    {
                        System.Windows.MessageBox.Show("Client Must have co-borrower", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }
                if (cmbServices.Text == "" || cmbMode.Text == "" || txtAmt.Text == "" || txtTerm.Text == "")
                {
                    System.Windows.MessageBox.Show("Please complete the required information", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                if (cboxAgent.IsChecked == true && txtAgent.Text == "")
                {
                    System.Windows.MessageBox.Show("Please select the agent");
                    return;
                }

                using (var ctx = new finalContext())
                {
                    var ser = ctx.Services.Find(servId);
                    if (ser.Type == "Non Collateral" && txtID.Text == "")
                    {
                        System.Windows.MessageBox.Show("Please select the Co-Borrower", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    double val = Convert.ToDouble(txtAmt.Text);
                    if (val > ser.MaxValue || val < ser.MinValue)
                    {
                        System.Windows.MessageBox.Show("Invalid loan ammount", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    var lon = ctx.Loans.Find(lId);
                    if (status == "Renewal")
                    {
                        if (val < lon.ReleasedLoan.TotalLoan)
                        {
                            System.Windows.MessageBox.Show("Amount must be greater than or equal the Total Loan Amount of Previous loan(" + lon.ReleasedLoan.TotalLoan.ToString("N2") + ")", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }
                    val = Convert.ToDouble(txtTerm.Text);
                    if (val > ser.MaxTerm || val < ser.MinTerm)
                    {
                        System.Windows.MessageBox.Show("Invalid desired term", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }

                }


                using (var ctx = new finalContext())
                {
                    var ser = ctx.Services.Find(servId);
                    double deduction = 0;
                    var ded = from de in ctx.Deductions
                              where de.ServiceID == servId
                              select de;
                    foreach (var item in ded)
                    {
                        deduction = deduction + item.Percentage;
                    }
                    deduction = deduction + ser.AgentCommission;
                    if (ser.Type == "Collateral")
                    {
                        cbId = 0;
                    }

                    if (status == "Add" || status == "Confirmation" || status=="Renewal")
                    {
                        if (status == "Confirmation")
                        {
                            Loan loan = new Loan { };

                            LoanApplication la = new LoanApplication { AmountApplied = Convert.ToDouble(txtAmt.Text), DateApplied = DateTime.Now.Date };
                            if (cboxAgent.IsChecked == true)
                            {
                                loan = new Loan { CI = ciId, AgentID = agentId, ClientID = cId, CoBorrower = cbId, ServiceID = servId, Status = "Applied", Term = Convert.ToInt32(txtTerm.Text), LoanApplication = la, Mode = cmbMode.Text, ApplicationType = "Online" };
                            }
                            else
                            {
                                string str = "Applied";
                                loan = new Loan { CI = ciId, AgentID = 0, ClientID = cId, CoBorrower = cbId, ServiceID = servId, Status = str, Term = Convert.ToInt32(txtTerm.Text), LoanApplication = la, Mode = cmbMode.Text , ApplicationType = "Online"};
                            }
                            ctx.Loans.Add(loan);
                            ctx.SaveChanges();
                            


                            string folderName = @"F:\Loan Files";
                            string pathString = System.IO.Path.Combine(folderName, "Loan " + loan.LoanID.ToString());
                            if (!Directory.Exists(pathString))
                            {
                                System.IO.Directory.CreateDirectory(pathString);
                            }
                            else
                            {
                                Directory.Delete(pathString, true);
                                System.IO.Directory.CreateDirectory(pathString);
                            }

                            using (var ictx = new finalContext())
                            {
                                var ln = ictx.TemporaryLoanApplications.Find(lId);
                                string pathString2 = @"F:\Loan Files\Applications Online\Application " + lId.ToString();
                                if (Directory.Exists(pathString2))
                                {
                                    Copy(pathString2, pathString);
                                    Directory.Delete(pathString2, true);
                                }


                                ictx.TemporaryLoanApplications.Remove(ln);
                                ictx.SaveChanges();
                                System.Windows.MessageBox.Show("Loan has been successfuly confirmed", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                this.Close();
                            }
                            
                        }
                        else
                        {
                            Loan loan = new Loan { };

                            LoanApplication la = new LoanApplication { AmountApplied = Convert.ToDouble(txtAmt.Text), DateApplied = DateTime.Now.Date };
                            if (cboxAgent.IsChecked == true)
                            {
                                loan = new Loan { CI = ciId, AgentID = agentId, ClientID = cId, CoBorrower = cbId, ServiceID = servId, Status = "Applied", Term = Convert.ToInt32(txtTerm.Text), LoanApplication = la, Mode = cmbMode.Text, ApplicationType = "Walk-In" };
                            }
                            else
                            {
                                string str = "Applied";
                                if (status == "Renewal")
                                    str = "Applied for Renewal";
                                loan = new Loan { CI = ciId, AgentID = 0, ClientID = cId, CoBorrower = cbId, ServiceID = servId, Status = str, Term = Convert.ToInt32(txtTerm.Text), LoanApplication = la, Mode = cmbMode.Text, ApplicationType = "Walk-In" };
                            }

                            //AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Processed new loan application (" + cmbServices.Text + ") for client " + txtFName.Text + " " + txtMName.Text + " " + txtLName.Text + " " + txtSuffix.Text };
                            //ctx.AuditTrails.Add(at);

                            ctx.Loans.Add(loan);
                            ctx.SaveChanges();

                            if (status == "Renewal")
                            {
                                LoanRenewal lr = new LoanRenewal { LoanID = lId, newLoanID = loan.LoanID, Status = "Pending" };
                                ctx.LoanRenewals.Add(lr);
                                ctx.SaveChanges();
                            }

                            string folderName = @"F:\Loan Files";
                            string pathString = System.IO.Path.Combine(folderName, "Loan " + loan.LoanID.ToString());
                            if (!Directory.Exists(pathString))
                            {
                                System.IO.Directory.CreateDirectory(pathString);
                            }
                            else
                            {
                                Directory.Delete(pathString, true);
                                System.IO.Directory.CreateDirectory(pathString);
                            }

                            if (status == "Renewal")
                            {
                                string pathString2 = @"F:\Loan Files\Loan " + lId.ToString();
                                if (Directory.Exists(pathString2))
                                {
                                    Copy(pathString2, pathString);
                                    Directory.Delete(pathString2, true);
                                }
                            }

                            System.Windows.MessageBox.Show("Loan has been successfuly applied", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            this.Close();
                        }
                    }
                    else
                    {

                        System.Windows.Forms.DialogResult dr = System.Windows.Forms.MessageBox.Show("Are you sure you want to update this loan?", "Question", MessageBoxButtons.YesNo);

                        if (dr == System.Windows.Forms.DialogResult.Yes)
                        {
                            var ln = ctx.Loans.Find(lId);
                            if (cboxAgent.IsChecked == true)
                            {
                                ln.AgentID = agentId;
                                ln.CoBorrower = cbId;
                                ln.Mode = cmbMode.Text;
                                ln.CI = ciId;
                                ln.LoanApplication.AmountApplied = Convert.ToDouble(txtAmt.Text);
                                ln.Term = Convert.ToInt32(txtTerm.Text);
                            }
                            else
                            {
                                ln.CoBorrower = cbId;
                                ln.Mode = cmbMode.Text;
                                ln.CI = ciId;
                                ln.LoanApplication.AmountApplied = Convert.ToDouble(txtAmt.Text);
                                ln.Term = Convert.ToInt32(txtTerm.Text);
                            }
                            //AuditTrail at = new AuditTrail { EmployeeID = UserID, DateAndTime = DateTime.Now, Action = "Updated loan application (" + cmbServices.Text + ") for client " + txtFName.Text + " " + txtMName.Text + " " + txtLName.Text + " " + txtSuffix.Text };
                            //ctx.AuditTrails.Add(at);

                            ctx.SaveChanges();
                            System.Windows.MessageBox.Show("Record has been successfully updated", "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;
            }
        }