
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Net.Mail
Imports System.Net.Mime
Imports GrapeCity.Documents.Pdf.AcroForms
Imports sun.java2d
Imports VERAG_PROG_ALLGEMEIN

Public Class frmNewsletter
    Private exporter As New RichTextBoxHtmlExporter()

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try

            ProgressBar1.Minimum = 0
            ProgressBar1.Maximum = MyDatagridview1.SelectedRows.Count
            ProgressBar1.Value = 0
            ProgressBar1.Visible = True
            ProgressBar1.Style = ProgressBarStyle.Continuous

            If MyDatagridview1.SelectedRows.Count = 0 Then
                MsgBox("Bitte mindestens einen Eintrag auswählen.")
                Exit Sub
            End If
            Label5.Text = "0/" & ProgressBar1.Maximum
            Dim mailText = getMailtext()
            Dim ANHAENGE = getAnhaenge()
            Dim Absender = getAbsender()
            Dim Subject = getSubject()

            If MsgBox("Wirklich " & MyDatagridview1.SelectedRows.Count & " Mails senden?", vbYesNoCancel) = vbYes Then
                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(Absender, Subject, mailText, Absender,, False, "", "", ANHAENGE)

                For Each row As DataGridViewRow In MyDatagridview1.SelectedRows
                    Dim mail As String = getValidEmail(If(row.Cells("Email").Value, "").ToString())
                    Dim mailCC As String = getValidEmail(If(row.Cells("EmailCC").Value, "").ToString())
                    Dim mailBCC As String = getValidEmail(If(row.Cells("EmailBCC").Value, "").ToString())

                    If mail <> "" Then
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mail, Subject, mailText, Absender,, False, mailCC, mailBCC, ANHAENGE)
                    End If
                    ' === Fortschritt aktualisieren ===
                    ProgressBar1.Value += 1
                    ProgressBar1.Refresh()
                    Label5.Text = ProgressBar1.Value & "/" & ProgressBar1.Maximum
                    ' Damit UI nicht hängt
                    Application.DoEvents()

                Next
                ProgressBar1.Value = ProgressBar1.Maximum
                Label5.Text = ProgressBar1.Maximum & "/" & ProgressBar1.Maximum
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub

    Private Sub RichTextBox1_KeyDown(
    sender As Object, e As KeyEventArgs) Handles RichTextBox1.KeyDown

        If e.Control AndAlso e.KeyCode = Keys.V AndAlso Clipboard.ContainsImage() Then
            e.SuppressKeyPress = True
            exporter.HandlePaste(RichTextBox1)
        End If
    End Sub

    Public Function getValidEmail(email As Object) As String
        If email Is Nothing OrElse email Is DBNull.Value Then email = ""
        If IsValidEmail(email) Then
            Return email.Trim()
        Else
            Return ""
        End If
    End Function
    Public Function IsValidEmail(email As String) As Boolean
        If String.IsNullOrWhiteSpace(email) Then Return True

        Dim parts = email.Split({";"c, ","c}, StringSplitOptions.RemoveEmptyEntries)

        For Each part In parts
            Dim addrText = part.Trim()
            If addrText = "" Then Continue For

            Try
                Dim addr As New System.Net.Mail.MailAddress(addrText)
                If addr.Address <> addrText Then Return False
            Catch
                Return False
            End Try
        Next

        Return True
    End Function

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Try
            Dim outlookApp As Object

            Try
                ' Laufende Outlook-Instanz holen
                outlookApp = GetObject(, "Outlook.Application")
            Catch
                ' Falls Outlook noch nicht läuft
                outlookApp = CreateObject("Outlook.Application")
            End Try

            Dim mailItem As Object = outlookApp.CreateItem(0) ' 0 = olMailItem

            With mailItem
                .To = ""
                .CC = ""
                .Subject = MyTextBox1.Text
                .HTMLBody = getMailtext()
                .Display() ' Mail öffnen (nicht senden!)
            End With

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try


    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        Dim mailTo = InputBox("Bitte Testmail eingeben:")
        If mailTo <> "" Then
            Try
                '  Dim mailTo = ""
                Dim mailCC = ""
                Dim mailBCC = ""

                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailTo, getSubject(), getMailtext(), getAbsender(), , False, mailCC, mailBCC, getAnhaenge())
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try
        End If
    End Sub


    Function getAnhaenge() As List(Of String)
        Dim anhaenge As New List(Of String)
        '---Anhänge:---------------------------- 
        For Each line In ListBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
            MsgBox(line)
            If File.Exists(line) Then
                anhaenge.Add(line)
            End If
        Next
        Return anhaenge

    End Function
    Private Sub ListBoxFiles_DragEnter(sender As Object, e As DragEventArgs) Handles ListBox1.DragEnter

        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If

    End Sub
    Private Sub ListBoxFiles_DragDrop(sender As Object, e As DragEventArgs) Handles ListBox1.DragDrop

        Dim files As String() =
        CType(e.Data.GetData(DataFormats.FileDrop), String())

        For Each filePath As String In files
            If System.IO.File.Exists(filePath) Then
                If Not ListBox1.Items.Contains(filePath) Then
                    ListBox1.Items.Add(filePath)
                End If
            End If
        Next

    End Sub

    Function getAbsender() As String
        If MyComboBox1._value <> "" Then
            Return MyComboBox1._value
        Else
            Return "support@verag.ag"
        End If
    End Function
    Function getSubject() As String
        Return MyTextBox1.Text

    End Function
    Function getMailtext()
        Dim mailtext As String = ""
        Dim htmlText As String = RichTextBox1.Text
        htmlText = htmlText.Replace(vbCrLf, "<br>")
        htmlText = htmlText.Replace(vbLf, "<br>")
        htmlText = htmlText.Replace(vbCr, "<br>")

        If cbxNewsletter.Checked Then
            mailtext &= getMailtext_NewsletterTop()

            '---Content:---------------------------- 
            ' mailtext &= RichTextBox1.Text
            mailtext &= exporter.BuildHtml(RichTextBox1.Text.Replace(Environment.NewLine, "<br>"))
            '--------------------------------------- 

            If cbxNewsletter.Checked Then mailtext &= getMailtext_NewsletterBottom()
        Else


            mailtext &= "<html><body>" & htmlText.Replace(Environment.NewLine, "<br>") & "</body></html>"
        End If



        Return mailtext

    End Function


    Private Sub ListBox1_KeyDown(sender As Object, e As KeyEventArgs) _
    Handles ListBox1.KeyDown

        If e.KeyCode = Keys.Delete Then

            ' Rückwärts durchgehen, sonst Index-Problem
            For i As Integer = ListBox1.SelectedIndices.Count - 1 To 0 Step -1
                ListBox1.Items.RemoveAt(ListBox1.SelectedIndices(i))
            Next

            e.Handled = True
        End If

    End Sub

    Function getMailtext_NewsletterTop2()
        Dim mailtext As String = ""
        mailtext &= "<html lang=""de"">
                    <body style=""margin:0; padding:0; background-color:#f4f6f8; font-family:Arial, Helvetica, sans-serif; color:#1f2933;"">
                    <table width=""100%"" cellpadding=""0"" cellspacing=""0"" style=""background-color:#f4f6f8;"">
                      <tr>
                        <td align=""center"">
                          <table width=""720"" cellpadding=""0"" cellspacing=""0"" style=""background-color:#ffffff; max-width:720px;"">"



        If MyTextBox2.Text <> "" Then
            mailtext &= "<tr>
                              <td style=""background-color:#0b2a4a; padding:30px 40px; color:#ffffff;"">
                                <h1 style=""margin:0; font-size:28px; line-height:1.3; font-weight:bold;"">
                                  " & MyTextBox2.Text & "
                                </h1>
                              </td>
                            </tr> "
        End If
        mailtext &= "<tr><td>"

        Return mailtext

    End Function


    Function getMailtext_NewsletterTop()
        Dim mailtext As String = ""
        mailtext &= "<html lang=""de"">
                    <body style=""margin:0; padding:0;  font-family:Arial, Helvetica, sans-serif; color:#1f2933;"">
                    <table width=""100%"" cellpadding=""0"" cellspacing=""0"" style="""">
                      <tr>
                        <td align=""left"">
                          <table width=""720"" cellpadding=""0"" cellspacing=""0"" style=""background-color:#ffffff; max-width:720px;"">"



        If MyTextBox2.Text <> "" Then
            mailtext &= "<tr>
                              <td style=""  padding:30px 40px; color:#ffffff;"">
                                <h1 style=""margin:0; font-size:28px; line-height:1.3; font-weight:bold;"">
                                  " & MyTextBox2.Text & "
                                </h1>
                              </td>
                            </tr> "
        End If
        mailtext &= "<tr><td>"

        Return mailtext

    End Function

    Function getMailtext_NewsletterBottom()
        Dim mailtext As String = ""
        mailtext &= "            </td></tr>
                              </table>
                            </td>
                          </tr>
                        </table> 
                        </body>
                        </html> "
        Return mailtext

    End Function

    Private Sub cbxNewsletter_CheckedChanged(sender As Object, e As EventArgs) Handles cbxNewsletter.CheckedChanged
        MyTextBox2.Enabled = cbxNewsletter.Checked
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        MyDatagridview1.Rows.Clear()
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        MyDatagridview1.SelectAll()
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        MyDatagridview1.ClearSelection()
    End Sub


End Class



'Public Class RichTextBoxHtmlImageExporter

'    Private ReadOnly _images As New List(Of ImageInfo)

'    Private Class ImageInfo
'        Public Property Token As String
'        Public Property FilePath As String
'        Public Property ContentId As String
'        Public Property MimeType As String
'    End Class

'    ' Beim Einfügen (Ctrl+V) aufrufen
'    Public Sub HandlePaste(rtb As RichTextBox)
'        If Not Clipboard.ContainsImage() Then Return

'        Dim img As Image = Clipboard.GetImage()

'        ' Wichtig: Guid NICHT als Variable überschreiben.
'        Dim id As String = System.Guid.NewGuid().ToString("N")

'        Dim token As String = $"[IMG_{id}]"
'        Dim filePath As String = Path.Combine(Path.GetTempPath(), $"rtb_img_{id}.png")

'        img.Save(filePath, ImageFormat.Png)

'        _images.Add(New ImageInfo With {
'            .Token = token,
'            .FilePath = filePath,
'            .ContentId = id,
'            .MimeType = "image/png"
'        })

'        ' Token an Cursorposition einfügen (Bild selbst bleibt nicht im RTF)
'        rtb.SelectedText = token & Environment.NewLine
'    End Sub

'    ' HTML + AlternateView (mit LinkedResources) erzeugen
'    Public Function BuildHtmlView(rtb As RichTextBox) As AlternateView
'        Dim htmlBody As String = rtb.Text

'        ' Minimal-HTML-Escaping + Zeilenumbrüche
'        htmlBody = htmlBody.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;")
'        htmlBody = htmlBody.Replace(Environment.NewLine, "<br>")

'        ' Tokens durch CID-Images ersetzen
'        For Each img In _images
'            htmlBody = htmlBody.Replace(
'                img.Token,
'                $"<img src=""cid:{img.ContentId}"" style=""max-width:100%; display:block; margin:10px 0;"">"
'            )
'        Next

'        Dim fullHtml As String =
'            $"<!DOCTYPE html>
'            <html>
'            <head><meta charset=""UTF-8""></head>
'            <body style=""font-family:Arial,Helvetica,sans-serif; font-size:14px; line-height:1.5;"">
'            {htmlBody}
'            </body>
'            </html>"

'        Dim view As AlternateView =
'            AlternateView.CreateAlternateViewFromString(fullHtml, Nothing, MediaTypeNames.Text.Html)

'        ' LinkedResources hinzufügen (Inline Attachments)
'        For Each img In _images
'            Dim lr As New LinkedResource(img.FilePath, img.MimeType)
'            lr.ContentId = img.ContentId
'            lr.TransferEncoding = TransferEncoding.Base64
'            view.LinkedResources.Add(lr)
'        Next

'        Return view
'    End Function

'    ' Temp-Dateien löschen (optional)
'    Public Sub Cleanup()
'        For Each img In _images
'            Try
'                If File.Exists(img.FilePath) Then File.Delete(img.FilePath)
'            Catch
'                ' optional: Logging
'            End Try
'        Next
'        _images.Clear()
'    End Sub

'End Class
Public Class RichTextBoxHtmlExporter

    Private ReadOnly _images As New List(Of ImageInfo)

    Private Class ImageInfo
        Public Property Token As String
        Public Property FilePath As String
    End Class

    ' Beim Einfügen eines Bildes (Ctrl+V)
    Public Sub HandlePaste(rtb As RichTextBox)
        If Not Clipboard.ContainsImage() Then Return

        Dim img As Image = Clipboard.GetImage()

        Dim id As String = System.Guid.NewGuid().ToString("N")
        Dim token As String = $"[IMG_{id}]"
        Dim filePath As String =
            Path.Combine(Path.GetTempPath(), $"rtb_img_{id}.png")

        img.Save(filePath, ImageFormat.Png)

        _images.Add(New ImageInfo With {
            .Token = token,
            .FilePath = filePath
        })

        rtb.SelectedText = token & Environment.NewLine
    End Sub

    ' HTML-Text erzeugen
    Public Function BuildHtml(html) As String
        'Dim html As String = rtb.Text

        ' Grundlegendes Escaping
        'html = html.Replace("&", "&amp;").
        '            Replace("<", "&lt;").
        '            Replace(">", "&gt;")

        'html = html.Replace(Environment.NewLine, "<br>")

        ' Tokens durch IMG-Tags ersetzen
        For Each img In _images
            Dim uri As String = New Uri(img.FilePath).AbsoluteUri
            html = html.Replace(
                img.Token,
                $"<img src=""{uri}"" style=""max-width:100%; display:block; margin:10px 0;"">"
            )
        Next

        Return WrapHtml(html)
    End Function

    Private Function WrapHtml(body As String) As String
        Return $"
<!DOCTYPE html>
<html>
<head>
<meta charset=""UTF-8"">
</head>
<body style=""font-family:Arial,Helvetica,sans-serif; font-size:14px; line-height:1.5;"">
{body}
</body>
</html>"
    End Function

    ' Optional: Temp-Dateien löschen
    Public Sub Cleanup()
        For Each img In _images
            Try
                If File.Exists(img.FilePath) Then File.Delete(img.FilePath)
            Catch
            End Try
        Next
        _images.Clear()
    End Sub

End Class