Imports com.esendex.sdk.messaging
Imports com.esendex.sdk.sent
Imports com.esendex.sdk.core
Imports System.Data.SqlClient
Imports System.Reflection

Public Class cSMS
    Dim API_USER_AUTHORIZATION = "040b08e268d340179d922f867816b8a6"

    Property sms_id As Integer
    Property sms_Datum As Date = Now
    Property sms_Firma As Object = Nothing
    Property sms_Account As Object = Nothing

    Property sms_Fahrername As Object = Nothing
    Property sms_KundenNr As Object = Nothing
    Property sms_Kunde As Object = Nothing



    Property sms_Vorwahl As Object = Nothing
    Property sms_Handynummer As Object = Nothing
    Property sms_Nachricht As Object = Nothing
    Property sms_templateID As Object = Nothing
    Property sms_BatchId As Object = Nothing
    Property sms_MessageIds As Object = Nothing
    Property sms_Uris As Object = Nothing
    Property sms_Sachbearbeiter As String = Nothing
    Property sms_SachbearbeiterId As Integer
    Property sms_AvisoId As Object = Nothing

    Property sms_Status As Integer = -1
    Property sms_Queued As Object = Nothing
    Property sms_Sent As Object = Nothing
    Property sms_Delivered As Object = Nothing
    Property sms_Failure As Object = Nothing

    Property sms_art as string= "SMS"
    Property whatsApp_status As Object = Nothing
    Property whatsApp_gatewayId As Object = Nothing
    Property whatsApp_error As Object = Nothing
    Property whatsApp_errorCode As Object = Nothing


    Dim ESENDEX_USER As String = "al@verag.ag"
    Dim ESENDEX_PWD As String = "Developer#2"

    Dim SQL As New SQL

    Sub New()
        sms_Sachbearbeiter = If(sms_Sachbearbeiter, VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME)
        If sms_SachbearbeiterId <= 0 Then sms_SachbearbeiterId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID

    End Sub

    Sub New(sms_id)
        Me.sms_id = sms_id
        LOAD()
    End Sub

    Public Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_id", sms_id, , True, True))


        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Datum", sms_Datum))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Firma", sms_Firma))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Account", sms_Account))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Fahrername", sms_Fahrername))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_KundenNr", sms_KundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Kunde", sms_Kunde))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Vorwahl", sms_Vorwahl))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Handynummer", sms_Handynummer))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Nachricht", sms_Nachricht))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_templateID", sms_templateID))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_BatchId", sms_BatchId))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_MessageIds", sms_MessageIds))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Uris", sms_Uris))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Sachbearbeiter", sms_Sachbearbeiter))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_SachbearbeiterId", sms_SachbearbeiterId))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_AvisoId", sms_AvisoId))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Status", sms_Status))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Queued", sms_Queued))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Sent", sms_Sent))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Delivered", sms_Delivered))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_Failure", sms_Failure))


        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sms_art", sms_art))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("whatsApp_status", whatsApp_status))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("whatsApp_gatewayId", whatsApp_gatewayId))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("whatsApp_error", whatsApp_error))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("whatsApp_errorCode", whatsApp_errorCode))
        Return list
    End Function




    Public Function SAVE() As Boolean
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()


        Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM tblSMS With(updlock, serializable) WHERE sms_id=@sms_id) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

        sms_id = SQL.doSQLVarListID(sms_id, sqlstr, "FMZOLL", , list)
        Return sms_id > 0
    End Function


    Public Sub LOAD()
        Try
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("Select * FROM tblSMS WHERE sms_id=@sms_id  ", conn)
                    cmd.Parameters.AddWithValue("@sms_id", sms_id)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each i In getParameterList()
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(i.Scalarvariable)

                            If dr.Item(i.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(i.Text))
                            End If

                        Next

                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
    End Sub


    Public Function getUpdateCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim str As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE [tblSMS] SET " & str & " WHERE sms_id=@sms_id ")

        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return ""
    End Function


    Public Function getInsertCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim str As String = ""
            Dim values As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO tblSMS  (" & str & ") VALUES(" & values & ")  ")
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return ""
    End Function


    Public Function DELETE() As Boolean 'obj As Object, tablename As String, where As String) As Boolean
        Dim sqlstr = " DELETE FROM [tblSMS] WITH(updlock,serializable) WHERE sms_id=" & Me.sms_id
        Return SQL.doSQL(sqlstr, "FMZOLL")
    End Function

    Function sendSMS() As Boolean
        Try

            Dim messagingService As New MessagingService(ESENDEX_USER, ESENDEX_PWD)
            'SENDEN DER SMS
            Dim result = messagingService.SendMessage(New SmsMessage(Me.sms_Handynummer, Me.sms_Nachricht, Me.sms_Account))

            Dim Uris As String = ""
            Dim msgIDs As String = ""
            Try
                Me.sms_BatchId = result.BatchId

                If result.MessageIds IsNot Nothing Then
                    For Each msg In result.MessageIds
                        Uris &= msg.Uri & ";;"
                        msgIDs &= msg.Id.ToString & ";;"
                    Next
                End If
            Catch ex As Exception
            End Try
            While Uris.EndsWith(";;")
                Uris = Uris.Substring(0, Uris.Length - 2)
            End While
            While msgIDs.EndsWith(";;")
                msgIDs = msgIDs.Substring(0, msgIDs.Length - 2)
            End While

            Me.sms_MessageIds = msgIDs
            Me.sms_Uris = Uris

            If Not Me.SAVE() Then
                MsgBox("Fehler: SMS Daten wurden nicht gespeichert!")
            End If

            Return True
        Catch ex As Exception
            MsgBox("Fehler beim Senden der SMS!" & vbNewLine & ex.Message & ex.StackTrace)
            Return False
        End Try

    End Function



    'Function sendWhatsApp(Originator As String) As Boolean
    '    Return sendWhatsAppMessage(Originator)
    '    'If sendWhatsAppTemplate(Originator) Then
    '    '    Return sendWhatsAppMessage(Originator)
    '    'End If
    '    'Return False
    'End Function
    Function sendWhatsAppMessage(Originator As String) As Boolean
        Try
            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
            Dim API_STRING = "https://connect.esendex.com"

            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)

                Return False
            End If

            rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", API_USER_AUTHORIZATION)
            'rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

            'Dim sbRequestBody As New Chilkat.StringBuilder
            'json.EmitSb(sbRequestBody)
            Me.sms_art = "WHATSAPP"


            Dim absenderFirma As String = Me.sms_Firma
            Dim HandyNr As String = Me.sms_Handynummer
            If HandyNr.ToString.StartsWith("00") Then HandyNr = "+" & HandyNr.Substring(2)

            If Originator = "" Then Originator = absenderFirma
            If Originator.Length > 11 Then Originator = Originator.Substring(0, 11)

            Dim json As New Chilkat.JsonObject

            '---------------------------------------------
            Me.sms_Account = "EX0341154" 'WHATSAPP Account

            'Dim successJsonLoad As Boolean = json.Load(" 
            '            {
            '              ""accountReference"": """ & Me.sms_Account & """,
            '              ""channels"": [
            '                ""WHATSAPP""
            '              ],
            '              ""metadata"":{
            '                ""key"": ""value""
            '              },
            '              ""recipient"": {
            '                ""address"": {
            '                  ""msisdn"": """ & HandyNr & """
            '                }
            '              },
            '              ""content"": {
            '                ""body"": {
            '                  ""text"": {
            '                    ""value"": """ & Me.sms_Nachricht & """
            '                  }
            '                }
            '              },
            '              ""channelSettings"": {
            '                ""sms"": {
            '                  ""originator"": """ & Originator & """,
            '                  ""characterSet"": ""GSM""
            '                }
            '              },
            '              ""expiry"": ""30""
            '            }")

            Dim successJsonLoad As Boolean = json.Load(" 
                        {
                          ""accountReference"": """ & Me.sms_Account & """,
                          ""channels"": [
                            ""WHATSAPP""
                          ],
                          ""metadata"":{
                            ""key"": ""value""
                          },
                          ""recipient"": {
                            ""address"": {
                              ""msisdn"": """ & HandyNr & """
                            }
                          },
                          ""content"": {
                            ""body"": {
                              ""text"": {
                                ""value"": """ & Me.sms_Nachricht & """
                              }
                            }
                          } 
                        }")

            If (successJsonLoad <> True) Then
                MsgBox(json.LastErrorText)
                Return False
            End If


            Dim sbRequestBody As New Chilkat.StringBuilder
            json.EmitSb(sbRequestBody)

            MsgBox(sbRequestBody.ToString)
            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("POST", "/richcontent/v3/send", sbRequestBody, sbResponseBody)
            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return False
            End If
            Dim respStatusCode As Integer = rest.ResponseStatusCode

            Me.whatsApp_status = respStatusCode ' 202 = OK - Gesendet

            If (respStatusCode <> 202) Then

                MsgBox(sbResponseBody.GetAsString())

                Return False
            End If


            Dim jsonResp = New Chilkat.JsonObject()
            jsonResp.LoadSb(sbResponseBody)

            Dim gatewayId = jsonResp.StringOf("gatewayId")
            Dim Resp_error = jsonResp.StringOf("error")
            Dim Resp_errorCode = jsonResp.StringOf("errorCode")

            Me.whatsApp_gatewayId = gatewayId
            MsgBox(gatewayId)
            If Resp_error <> "" Then Me.whatsApp_error = Resp_error
            If Resp_errorCode <> "" Then Me.whatsApp_errorCode = Resp_errorCode

            ' MsgBox(gatewayId)

            If Not Me.SAVE() Then
                MsgBox("Fehler: SMS Daten wurden nicht gespeichert!")
            End If


            Return True
            'productTitle = json.StringOf("product.title");
            'productBody_html = json.StringOf("product.body_html");
            'productVendor = json.StringOf("product.vendor");
            'productProduct_type = json.StringOf("product.product_type");
            'productCreated_at = json.StringOf("product.created_at");
            'productHandle = json.StringOf("product.handle");
            'productUpdated_at = json.StringOf("product.updated_at");
            'productPublished_at = json.IsNullOf("product.published_at");
            'productTemplate_suffix = json.IsNullOf("product.template_suffix");
            'productPublished_scope = json.StringOf("product.published_scope");
            'productTags = json.StringOf("product.tags");
            'productImage = json.IsNullOf("product.image");
            'i = 0;
            'count_i = json.SizeOfArray("product.variants");
            'while (i < count_i) {
            '    json.I = i;
            '    id = json.IntOf("product.variants[i].id");
            '    product_id = json.IntOf("product.variants[i].product_id");
            '    title = json.StringOf("product.variants[i].title");
            '    price = json.StringOf("product.variants[i].price");
            '    sku = json.StringOf("product.variants[i].sku");
            '    position = json.IntOf("product.variants[i].position");
            '    grams = json.IntOf("product.variants[i].grams");
            '    inventory_policy = json.StringOf("product.variants[i].inventory_policy");
            '    compare_at_price = json.IsNullOf("product.variants[i].compare_at_price");
            '    fulfillment_service = json.StringOf("product.variants[i].fulfillment_service");
            '    inventory_management = json.IsNullOf("product.variants[i].inventory_management");
            '    option1 = json.StringOf("product.variants[i].option1");
            '    option2 = json.IsNullOf("product.variants[i].option2");
            '    option3 = json.IsNullOf("product.variants[i].option3");
            '    created_at = json.StringOf("product.variants[i].created_at");
            '    updated_at = json.StringOf("product.variants[i].updated_at");
            '    taxable = json.BoolOf("product.variants[i].taxable");
            '    barcode = json.IsNullOf("product.variants[i].barcode");
            '    image_id = json.IsNullOf("product.variants[i].image_id");
            '    inventory_quantity = json.IntOf("product.variants[i].inventory_quantity");
            '    weight = json.IntOf("product.variants[i].weight");
            '    weight_unit = json.StringOf("product.variants[i].weight_unit");
            '    old_inventory_quantity = json.IntOf("product.variants[i].old_inventory_quantity");
            '    requires_shipping = json.BoolOf("product.variants[i].requires_shipping");
            '    i = i + 1;
            '}
            Return True


        Catch ex As Exception
            MsgBox("Fehler beim Senden der WhatsApp-SMS!" & vbNewLine & ex.Message & ex.StackTrace)
            Return False
        End Try

    End Function


    Function sendWhatsAppTemplate(Originator As String, template_ParamMFGAdditional As String) As Boolean
        Try
            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
            Dim API_STRING = "https://connect.esendex.com"

            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)

                Return False
            End If

            rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", API_USER_AUTHORIZATION)
            'rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")

            'Dim sbRequestBody As New Chilkat.StringBuilder
            'json.EmitSb(sbRequestBody)
            Me.sms_art = "WHATSAPP"


            Dim mfg = ""
            Dim location = ""

            Select Case Originator
                Case "FRONTOFFICE"
                    mfg = "VERAG - UNISPED - IMEX"
                    location = Originator
                Case Else
                    location = Originator
            End Select
            If template_ParamMFGAdditional <> "" Then
                mfg = template_ParamMFGAdditional & " " & mfg
            End If

            Dim absenderFirma As String = Me.sms_Firma
            Dim HandyNr As String = Me.sms_Handynummer.replace(" ", "")
            If HandyNr.ToString.StartsWith("00") Then HandyNr = "+" & HandyNr.Substring(2)

            If Originator = "" Then Originator = absenderFirma
            If Originator.Length > 11 Then Originator = Originator.Substring(0, 11)

            Dim json As New Chilkat.JsonObject

            '---------------------------------------------
            Me.sms_Account = "EX0341154" 'WHATSAPP Account
            ' Dim TemplateId = "e5c1ce77-31a0-4663-9576-be340f73ac1c"


            Dim successJsonLoad As Boolean = json.Load(" 
                        {
                          ""accountReference"": """ & Me.sms_Account & """,
                          ""channels"": [
                            ""WHATSAPP""
                          ],
                          ""metadata"":{
                            ""key"": ""value""
                          },
                          ""recipient"": {
                            ""variables"": {
                               ""mfg"": """ & mfg & """,
                               ""location"": """ & location & """
                            },
                            ""address"": {
                              ""msisdn"": """ & HandyNr & """
                            }
                          },
                          ""content"": {
                            ""templateId"": """ & Me.sms_templateID & """
                            }
                        }")


            If (successJsonLoad <> True) Then
                '  MsgBox(json.LastErrorText)
                Return False
            End If


            Dim sbRequestBody As New Chilkat.StringBuilder
            json.EmitSb(sbRequestBody)

            'MsgBox(sbRequestBody.ToString)
            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("POST", "/richcontent/v3/send", sbRequestBody, sbResponseBody)
            If (success <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return False
            End If
            Dim respStatusCode As Integer = rest.ResponseStatusCode

            Me.whatsApp_status = respStatusCode ' 202 = OK - Gesendet

            If (respStatusCode <> 202) Then

                MsgBox(sbResponseBody.GetAsString())

                Return False
            End If


            Dim jsonResp = New Chilkat.JsonObject()
            jsonResp.LoadSb(sbResponseBody)

            Dim gatewayId = jsonResp.StringOf("gatewayId")
            Dim Resp_error = jsonResp.StringOf("error")
            Dim Resp_errorCode = jsonResp.StringOf("errorCode")

            Me.whatsApp_gatewayId = gatewayId
            '  MsgBox(gatewayId)
            If Resp_error <> "" Then Me.whatsApp_error = Resp_error
            If Resp_errorCode <> "" Then Me.whatsApp_errorCode = Resp_errorCode

            ' MsgBox(gatewayId)

            If Not Me.SAVE() Then
                MsgBox("Fehler: WHATSAPP Daten wurden nicht gespeichert!")
            End If


            Return True
            'productTitle = json.StringOf("product.title");
            'productBody_html = json.StringOf("product.body_html");
            'productVendor = json.StringOf("product.vendor");
            'productProduct_type = json.StringOf("product.product_type");
            'productCreated_at = json.StringOf("product.created_at");
            'productHandle = json.StringOf("product.handle");
            'productUpdated_at = json.StringOf("product.updated_at");
            'productPublished_at = json.IsNullOf("product.published_at");
            'productTemplate_suffix = json.IsNullOf("product.template_suffix");
            'productPublished_scope = json.StringOf("product.published_scope");
            'productTags = json.StringOf("product.tags");
            'productImage = json.IsNullOf("product.image");
            'i = 0;
            'count_i = json.SizeOfArray("product.variants");
            'while (i < count_i) {
            '    json.I = i;
            '    id = json.IntOf("product.variants[i].id");
            '    product_id = json.IntOf("product.variants[i].product_id");
            '    title = json.StringOf("product.variants[i].title");
            '    price = json.StringOf("product.variants[i].price");
            '    sku = json.StringOf("product.variants[i].sku");
            '    position = json.IntOf("product.variants[i].position");
            '    grams = json.IntOf("product.variants[i].grams");
            '    inventory_policy = json.StringOf("product.variants[i].inventory_policy");
            '    compare_at_price = json.IsNullOf("product.variants[i].compare_at_price");
            '    fulfillment_service = json.StringOf("product.variants[i].fulfillment_service");
            '    inventory_management = json.IsNullOf("product.variants[i].inventory_management");
            '    option1 = json.StringOf("product.variants[i].option1");
            '    option2 = json.IsNullOf("product.variants[i].option2");
            '    option3 = json.IsNullOf("product.variants[i].option3");
            '    created_at = json.StringOf("product.variants[i].created_at");
            '    updated_at = json.StringOf("product.variants[i].updated_at");
            '    taxable = json.BoolOf("product.variants[i].taxable");
            '    barcode = json.IsNullOf("product.variants[i].barcode");
            '    image_id = json.IsNullOf("product.variants[i].image_id");
            '    inventory_quantity = json.IntOf("product.variants[i].inventory_quantity");
            '    weight = json.IntOf("product.variants[i].weight");
            '    weight_unit = json.StringOf("product.variants[i].weight_unit");
            '    old_inventory_quantity = json.IntOf("product.variants[i].old_inventory_quantity");
            '    requires_shipping = json.BoolOf("product.variants[i].requires_shipping");
            '    i = i + 1;
            '}
            Return True


        Catch ex As Exception
            MsgBox("Fehler beim Senden der WhatsApp-SMS!" & vbNewLine & ex.Message & ex.StackTrace)
            Return False
        End Try

    End Function


    Function checkSMSStatus(Optional silent = False, Optional insertVermerkAviso = True) As String
        Try

            Select Case Me.sms_Status
                Case MessageStatus.Submitted, MessageStatus.Sent, MessageStatus.Scheduled, MessageStatus.Connecting, -1
                    'Weiter...
                Case Else
                    ' Bereits finaler Status, keine Abfrage nötig
                    Return Me.sms_Status
            End Select

            If If(Me.sms_MessageIds, "") = "" Then
                If Not silent Then MsgBox("Keine MessageId gefunden!")
                Return False ' Keine MsgId
            End If

            Dim sendService As New SentService(ESENDEX_USER, ESENDEX_PWD)

            'Send a message and retrieve the message ID
            Dim MSG = sendService.GetMessage(New Guid(Me.sms_MessageIds.ToString))
            Dim msgStatus = MSG.Status
            '    MsgBox(MSG.Status)
            'Status in DB Ubdaten
            Me.sms_Status = msgStatus
            Me.sms_Sent = MSG.SentAt
            Me.sms_Delivered = MSG.DeliveredAt

            'If IsDate(MSG.DeliveredAt) Then
            '    Me.sms_Status = 2 ': MsgBox("SENT")
            'Else
            '    'MsgBox("NOT SENT")
            'End If

            If MSG.FailureReason IsNot Nothing Then Me.sms_Failure = MSG.FailureReason.Description
            Me.SAVE()

            If True Then
                Try


                    If Me.sms_AvisoId IsNot Nothing AndAlso IsNumeric(Me.sms_AvisoId) Then
                    Select Case MSG.Status
                        Case MessageStatus.Expired, MessageStatus.Failed, MessageStatus.FailedAuthorisation, MessageStatus.Cancelled, MessageStatus.Rejected
                                'Keine Übermittlung.
                                Dim MaId As Integer = SQL.DLookup("LetzterMitarbeiterId", "Aviso", "AvisoId='" & Me.sms_AvisoId & "' ", "AVISO", -1)
                                If MaId > 0 Then
                                    VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(Me.sms_AvisoId, Nothing, 3, "B", MaId, "*SMS Fehler*", 0, "", "Fehler bei der SMS Übermittlung: " & If(Me.sms_Failure, ""))
                                End If
                    End Select

                End If

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

                End Try
            End If
            Return msgStatus
        Catch ex As Exception
            If Not silent Then MsgBox("Fehler beim Prüfen des SMS Status!" & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return ""
    End Function



    Function checkWhatsAppStatus(Optional silent = False, Optional insertVermerkAviso = True) As String
        Try
            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()


            Select Case Me.sms_Status
                Case MessageStatus.Submitted, MessageStatus.Sent, MessageStatus.Scheduled, MessageStatus.Connecting, -1
                    'Weiter...
                Case Else
                    ' Bereits finaler Status, keine Abfrage nötig
                    Return Me.sms_Status
            End Select


            If If(Me.whatsApp_gatewayId, "") = "" Then
                If Not silent Then MsgBox("Keine MessageId gefunden!")
                Return Me.sms_Status ' Keine MsgId
            End If



            Dim API_STRING = "https://connect.esendex.com"

            Dim rest As New Chilkat.Rest
            Dim success As Boolean

            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_STRING, port, bTls, bAutoReconnect)
            If (success <> True) Then
                If Not silent Then MsgBox("ConnectFailReason: " & rest.ConnectFailReason & vbNewLine & rest.LastErrorText)

                Return Me.sms_Status
            End If

            rest.AddHeader("Content-Type", "application/json")
            rest.AddHeader("Authorization", API_USER_AUTHORIZATION)


            Dim sbRequestBody As New Chilkat.StringBuilder

            '   MsgBox(sbRequestBody.ToString)
            Dim sbResponseBody As New Chilkat.StringBuilder
            success = rest.FullRequestSb("GET", "/richcontent/v3/accounts/" & Me.sms_Account & "/messages/" & Me.whatsApp_gatewayId, sbRequestBody, sbResponseBody)
            If (success <> True) Then
                If Not silent Then MsgBox(rest.LastErrorText)
                Return Me.sms_Status
            End If

            Dim respStatusCode As Integer = rest.ResponseStatusCode

            Me.whatsApp_status = respStatusCode ' 200 Abfrage hat funktioniert
            ' MsgBox(respStatusCode)
            If (respStatusCode <> 200) Then

                'Fehler --> --> FALLBACK SMS!!!
                If DateDiff(DateInterval.Minute, Me.sms_Datum, Now) > 10 Then
                    Me.FALLBACK_SMS()
                End If


                '  MsgBox(sbResponseBody.GetAsString())
                If Not silent Then MsgBox("Error: " & respStatusCode)

                Return Me.sms_Status

            End If


            Dim jsonResp = New Chilkat.JsonObject()
            jsonResp.LoadSb(sbResponseBody)
            '  MsgBox(sbResponseBody.ToString)
            Dim allowVermerk = True

            Dim lastUpdatedUtc = jsonResp.StringOf("lastUpdatedUtc")
            Dim StatusResp = jsonResp.StringOf("status")

            Select Case StatusResp
                Case "Submitted"
                    Me.sms_Status = MessageStatus.Submitted

                    If DateDiff(DateInterval.Minute, Me.sms_Datum, Now) > 10 Then
                        '--> FALLBACK SMS!!!
                        allowVermerk = False
                        Me.FALLBACK_SMS()
                    End If
                Case "Delivered"
                    Me.sms_Status = MessageStatus.Delivered
                    Me.sms_Delivered = lastUpdatedUtc
                Case "Failed"
                    Me.sms_Status = MessageStatus.Failed
                    Dim reason = jsonResp.StringOf("reason")
                    Me.sms_Failure = reason

                    '--> FALLBACK SMS!!!
                    allowVermerk = False
                    FALLBACK_SMS()
            End Select

            Me.SAVE()

            If allowVermerk Then
                Try


                    If Me.sms_AvisoId IsNot Nothing AndAlso IsNumeric(Me.sms_AvisoId) Then
                        Select Case StatusResp
                            Case "Failed"
                                'Keine Übermittlung.
                                Dim MaId As Integer = SQL.DLookup("LetzterMitarbeiterId", "Aviso", "AvisoId='" & Me.sms_AvisoId & "' ", "AVISO", -1)
                                If MaId > 0 Then
                                    Dim absenderFirma = ""
                                    VERAG_PROG_ALLGEMEIN.cSMS.GET_AccountInfo(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, Me.sms_Account, absenderFirma)

                                    VERAG_PROG_ALLGEMEIN.cAvisoBenachrichtigungen.INSERT_BENACHRICHTIGUNG(Me.sms_AvisoId, Nothing, 3, "B", MaId, "*WhatsApp Fehler*", 0, "", "Fehler bei der WhatsApp Übermittlung: " & If(Me.sms_Failure, ""),,, absenderFirma)
                                End If
                        End Select

                    End If

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

                End Try
            End If
            Return Me.sms_Status
        Catch ex As Exception
            If Not silent Then MsgBox("Fehler beim Prüfen des SMS Status!" & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return ""
    End Function



    Shared Function SEND_StatusSMS(AVISOId As Integer) As Boolean
        Dim AVISO = cAviso.getAvisoById(AVISOId, "")
        Return SEND_StatusSMS(AVISO)
    End Function


    Sub FALLBACK_SMS()
        '--> FALLBACK SMS!!!
        Me.sms_art = "SMS"
        Me.sms_Account = GET_AccountByAbsFirma(Me.sms_Firma) ' Ändern, da WhatsApp Account nciht in TR freigeschaltet ist.
        Me.sms_Status = -1
        Me.sendSMS()
        Me.SAVE()
    End Sub

    Shared Function SEND_StatusSMS(AVISO As cAviso) As Boolean
        If If(AVISO.FahrerHandy, "") <> "" AndAlso IsNumeric(AVISO.FahrerHandy.trim) Then

            Dim absenderAccount = ""
            Dim absenderFirma = ""

            VERAG_PROG_ALLGEMEIN.cSMS.GET_AccountInfo(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, absenderAccount, absenderFirma)


            ' If vbYes = MsgBox("Soll die Nachricht gesendet werden?" & vbNewLine & "Handy-Nummer: " & nr, MsgBoxStyle.YesNo) Then
            Dim SMS = New VERAG_PROG_ALLGEMEIN.cSMS


            SMS.sms_Vorwahl = ""
            SMS.sms_Handynummer = "00436644178557" 'AVISO.FahrerHandy.trim     'txtHandyNummer.Text.Replace(" ", "").Replace("-", "").Replace("/", "")
            SMS.sms_Nachricht = "Statusmeldung: " & vbNewLine &
            "https://login.verag.ag/status.aspx?AvisoId=" & VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(AVISO.AvisoID)


            SMS.sms_Account = absenderAccount
            SMS.sms_Firma = absenderFirma
            SMS.sms_KundenNr = If(AVISO.Frächter_KdNr > 0, AVISO.Frächter_KdNr, Nothing)
            SMS.sms_Kunde = If(AVISO.Frächter <> "", AVISO.Frächter, Nothing)
            SMS.sms_Fahrername = Nothing 'If(AVISO.fahrern <> "", FahrerName, Nothing)
            SMS.sms_AvisoId = AVISO.AvisoID

            If SMS.sendSMS Then
                Return True
            End If
        End If
        Return False
    End Function

    Shared Sub GET_AccountInfo(Firma, ByRef absenderAccount, ByRef absenderFirma)

        Select Case Firma'cboFirma._value
            Case "VERAG" ', "BEIDE"
                Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_abteilung
                    Case "ZOLL", "QS" : absenderAccount = "EX0252513" : absenderFirma = "VERAG Spedition"
                    Case "MDM" : absenderAccount = "EX0252747" : absenderFirma = "VERAG 360"
                    Case Else : absenderAccount = "EX0252513" : absenderFirma = "VERAG Spedition"
                        'Case Else : MsgBox("Fehler bei der Datenprüfung: Abteilung.") : Exit Sub
                End Select
            Case "ATILLA" : absenderAccount = "EX0252746" : absenderFirma = "ATILLA Spedition"
            Case "IMEX" : absenderAccount = "EX0272082" : absenderFirma = "IMEX Spedition"
            Case "UNISPED" : absenderAccount = "EX0300174" : absenderFirma = "UNISPED Spedition"
            Case "FRONTOFFICE" : absenderAccount = "EX0300173" : absenderFirma = "FRONT-OFFICE SUBEN"
            Case "AMBAR" : absenderAccount = "EX0315223" : absenderFirma = "AMBAR"
            Case Else : MsgBox("Fehler bei der Datenprüfung: Firmendaten.") : Exit Sub
        End Select

    End Sub

    Shared Function GET_AccountByAbsFirma(absenderFirma)

        Select Case absenderFirma'cboFirma._value
            Case "VERAG Spedition" : Return "EX0252513"
            Case "VERAG 360" : Return "EX0252747"
            Case "ATILLA Spedition" : Return "EX0252746"
            Case "IMEX Spedition" : Return "EX0272082"
            Case "UNISPED Spedition" : Return "EX0300174"
            Case "FRONT-OFFICE SUBEN" : Return "EX0300173"
            Case "AMBAR" : Return "EX0315223"

            Case Else : Return "EX0300173"
        End Select

    End Function



End Class

