Imports System.Data.SqlClient
Imports System.Reflection

Public Class cGreendeal_CBAM_Trn

    ' =====================================================
    '  Properties = Spalten tblGreendeal_CBAM_Trn
    ' =====================================================
    Public Property cbam_Id As Integer
    Public Property trnPattern As String
    Public Property ware As String
    Public Property sektor As String
    Public Property hinweis As String
    Public Property is_exclusion As Boolean?
    Public Property is_active As Boolean?
    Public Property start_date As Date?
    Public Property end_date As Date?

    Public Property hasEntry As Boolean = False

    Private SQL As New SQL

    ' =====================================================
    '  Konstruktor
    ' =====================================================
    Sub New()

    End Sub
    Sub New(cbam_Id As Integer)
        Me.cbam_Id = cbam_Id
        LOAD()
    End Sub

    ' =====================================================
    '  Parameterliste (Mapping Property <-> SQL)
    ' =====================================================
    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("cbam_Id", cbam_Id,, True))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("trnPattern", trnPattern))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ware", ware))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("sektor", sektor))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("hinweis", hinweis))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("is_exclusion", is_exclusion))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("is_active", is_active))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("start_date", start_date))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("end_date", end_date))

        Return list
    End Function

    ' =====================================================
    '  SAVE (Insert / Update)
    ' =====================================================
    Public Function SAVE() As Boolean

        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

        Dim sqlstr As String =
            " BEGIN TRAN " &
            " IF EXISTS (SELECT 1 FROM tblGreendeal_CBAM_Trn WHERE cbam_Id=@cbam_Id) " &
            " BEGIN " & getUpdateCmd() & " END " &
            " ELSE " &
            " BEGIN " & getInsertCmd() & " END " &
            " COMMIT TRAN "

        Return SQL.doSQLVarList(sqlstr, "VERAG", , list)

    End Function

    ' =====================================================
    '  LOAD
    ' =====================================================
    Public Sub LOAD()
        Try
            hasEntry = False

            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand(
                    "SELECT * FROM tblGreendeal_CBAM_Trn WHERE cbam_Id=@cbam_Id", conn)

                    cmd.Parameters.AddWithValue("@cbam_Id", cbam_Id)

                    Using dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim pi As PropertyInfo =
                                    Me.GetType.GetProperty(li.Scalarvariable)

                                If pi IsNot Nothing Then
                                    If dr.Item(li.Text) Is DBNull.Value Then
                                        pi.SetValue(Me, Nothing)
                                    Else
                                        pi.SetValue(Me, dr.Item(li.Text))
                                    End If
                                End If
                            Next
                            hasEntry = True
                        End If
                    End Using
                End Using
            End Using

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

    ' =====================================================
    '  UPDATE Command
    ' =====================================================
    Private Function getUpdateCmd() As String
        Try
            Dim list = getParameterList()
            Dim str As String = ""

            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & ","
                End If
            Next

            str = str.Substring(0, str.Length - 1)

            Return " UPDATE tblGreendeal_CBAM_Trn SET " & str &
                   " WHERE cbam_Id=@cbam_Id "

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

        Return ""
    End Function

    ' =====================================================
    '  INSERT Command
    ' =====================================================
    Private Function getInsertCmd() As String
        Try
            Dim list = getParameterList()
            Dim cols As String = ""
            Dim vals As String = ""

            For Each i In list
                If Not i.isPrimaryParam Then
                    cols &= "[" & i.Text & "],"
                    vals &= "@" & i.Scalarvariable & ","
                End If
            Next

            cols = cols.Substring(0, cols.Length - 1)
            vals = vals.Substring(0, vals.Length - 1)

            Return " INSERT INTO tblGreendeal_CBAM_Trn (" & cols & ") VALUES (" & vals & ") "

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

        Return ""
    End Function

    Public Shared Function BuildCBAMPatternWhereClause(columnName As String, Optional onlyActive As Boolean = True, Optional includeExclusions As Boolean = False) As String

        Dim sql As String =
        "SELECT trnPattern " &
        " FROM VERAG.dbo.tblGreendeal_CBAM_Trn " &
        " WHERE trnPattern IS NOT NULL " &
        "  AND LTRIM(RTRIM(trnPattern)) <> '' "

        If onlyActive Then
            sql &= " AND is_active = 1 " &
               " AND (start_date IS NULL OR start_date <= GETDATE()) " &
               " AND (end_date   IS NULL OR end_date   >= GETDATE()) "
        End If

        If Not includeExclusions Then
            sql &= " AND ISNULL(is_exclusion,0) = 0 "
        End If

        Dim dt As DataTable = (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql(sql, "FMZOLL")

        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            Return "1=0"   ' bewusst: keine Patterns → kein Treffer
        End If

        Dim conditions As New List(Of String)

        For Each r As DataRow In dt.Rows
            Dim pattern As String = r("trnPattern").ToString().Trim()

            ' einfache SQL-Escaping-Sicherheit
            pattern = pattern.Replace("'", "''")

            conditions.Add($"{columnName} LIKE '{pattern}'")
        Next

        Return "(" & String.Join(" OR ", conditions) & ")"

    End Function


    Public Shared Function isCBAMTnr(TNR As String, Optional LIST As List(Of String) = Nothing) As Boolean

        If LIST Is Nothing Then
            If VERAG_PROG_ALLGEMEIN.cAllgemein.CBAM_LIST Is Nothing Then VERAG_PROG_ALLGEMEIN.cAllgemein.CBAM_LIST = cGreendeal_CBAM_Trn.LoadCBAMTariffNumbers
            LIST = VERAG_PROG_ALLGEMEIN.cAllgemein.CBAM_LIST
        End If

        If TNR Is Nothing Then Return False
        If String.IsNullOrWhiteSpace(TNR) Then Return False


        For Each cbamTnr As String In LIST
            If Not String.IsNullOrWhiteSpace(cbamTnr) Then
                If TNR.StartsWith(cbamTnr.Replace("%", "").Trim) Then
                    Return True
                End If
            End If
        Next

        Return False

    End Function

    Public Shared Function LoadCBAMTariffNumbers(Optional onlyActive As Boolean = True,
                                             Optional includeExclusions As Boolean = False) _
                                             As List(Of String)

        Dim sql As String =
        "SELECT DISTINCT trnPattern " &
        "FROM VERAG.dbo.tblGreendeal_CBAM_Trn " &
        "WHERE trnPattern IS NOT NULL " &
        "AND LTRIM(RTRIM(trnPattern)) <> '' "

        If onlyActive Then
            sql &= " AND is_active = 1 " &
               " AND (start_date IS NULL OR start_date <= GETDATE()) " &
               " AND (end_date   IS NULL OR end_date   >= GETDATE()) "
        End If

        If Not includeExclusions Then
            sql &= " AND ISNULL(is_exclusion,0) = 0 "
        End If

        Dim dt As DataTable =
        (New VERAG_PROG_ALLGEMEIN.SQL).loadDgvBySql(sql, "FMZOLL")

        Dim result As New List(Of String)

        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            Return result
        End If

        For Each r As DataRow In dt.Rows
            Dim pattern As String = r("trnPattern").ToString().Trim()

            ' % entfernen → reine Tarifnummer
            pattern = pattern.Replace("%", "")

            ' nur numerische Werte zulassen
            If pattern <> "" AndAlso pattern.All(AddressOf Char.IsDigit) Then
                result.Add(pattern)
            End If
        Next

        Return result.Distinct().OrderBy(Function(x) x).ToList()

    End Function

    Public Shared Function DELETE_ALL() As Boolean
        Try

            Dim sqlstr As String = " DELETE FROM tblGreendeal_CBAM_Trn "
            Return (New VERAG_PROG_ALLGEMEIN.SQL).doSQL(sqlstr, "VERAG", , Nothing)

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

        Return False
    End Function

End Class