Attribute VB_Name = "ExcelRechnung"
'==============================================================================
' ExcelRechnung.bas – VBA-Modul für das Excel-Add-in "eRechnung"
' Windows + macOS kompatibel
'
' Verbindet Excel mit dem lokalen Tool ExcelRechnung (.exe / .app).
' Klick auf den Ribbon-Button speichert die aktuelle Mappe und öffnet das
' Tool mit der Datei vorausgewählt.
'==============================================================================
Option Explicit

Private Const APP_NAME    As String = "ExcelRechnung"
Private Const REG_SECTION As String = "Path"
Private Const REG_KEY     As String = "AppPath"

'------------------------------------------------------------------------------
' Ribbon: Aktuelle Rechnung exportieren
'------------------------------------------------------------------------------
Public Sub ExportInvoice(control As IRibbonControl)
    Dim wb As Workbook
    Set wb = ActiveWorkbook

    If wb Is Nothing Then
        MsgBox "Es ist keine Arbeitsmappe geöffnet.", vbExclamation, APP_NAME
        Exit Sub
    End If

    If wb.Path = "" Then
        MsgBox "Bitte speichern Sie die Excel-Datei zuerst, " & _
               "damit das Tool darauf zugreifen kann.", vbExclamation, APP_NAME
        Exit Sub
    End If

    If Not wb.Saved Then wb.Save

    Dim appPath As String
    appPath = GetAppPath()
    If appPath = "" Then Exit Sub

    If Not LaunchTool(appPath, "--excel """ & wb.FullName & """") Then
        MsgBox "Tool konnte nicht gestartet werden:" & vbCrLf & appPath, _
               vbCritical, APP_NAME
    End If
End Sub

'------------------------------------------------------------------------------
' Ribbon: Tool ohne Datei öffnen
'------------------------------------------------------------------------------
Public Sub OpenToolWithoutFile(control As IRibbonControl)
    Dim appPath As String
    appPath = GetAppPath()
    If appPath = "" Then Exit Sub

    If Not LaunchTool(appPath, "") Then
        MsgBox "Tool konnte nicht gestartet werden:" & vbCrLf & appPath, _
               vbCritical, APP_NAME
    End If
End Sub

'------------------------------------------------------------------------------
' Ribbon: App-Pfad konfigurieren
'------------------------------------------------------------------------------
Public Sub ConfigureExePath(control As IRibbonControl)
    Dim p As String
    p = SelectAppFile()
    If p <> "" Then
        SaveSetting APP_NAME, REG_SECTION, REG_KEY, p
        MsgBox "Pfad gespeichert:" & vbCrLf & vbCrLf & p, vbInformation, APP_NAME
    End If
End Sub

'------------------------------------------------------------------------------
' Ribbon: Über
'------------------------------------------------------------------------------
Public Sub ShowAbout(control As IRibbonControl)
    Dim p As String
    p = GetSetting(APP_NAME, REG_SECTION, REG_KEY, "(noch nicht konfiguriert)")
    MsgBox "Excel eRechnung – Add-in" & vbCrLf & _
           "Erzeugt ZUGFeRD-PDF + XRechnung aus der aktuellen Excel-Mappe." & vbCrLf & vbCrLf & _
           "Tool-Pfad:" & vbCrLf & p, vbInformation, APP_NAME
End Sub

'------------------------------------------------------------------------------
' Ribbon: Lizenzdialog öffnen
'------------------------------------------------------------------------------
Public Sub OpenLicenseManager(control As IRibbonControl)
    Dim appPath As String
    appPath = GetAppPath()
    If appPath = "" Then Exit Sub

    If Not LaunchTool(appPath, "--license") Then
        MsgBox "Lizenzdialog konnte nicht geöffnet werden:" & vbCrLf & appPath, _
               vbCritical, APP_NAME
    End If
End Sub

'------------------------------------------------------------------------------
' Ribbon: Lizenzstatus anzeigen
'------------------------------------------------------------------------------
Public Sub ShowLicenseStatus(control As IRibbonControl)
    Dim sep As String
    sep = Application.PathSeparator

    Dim keyPath As String
    keyPath = GetDataPath() & sep & "license.key"

    Dim statusMsg As String
    Dim statusIcon As VbMsgBoxStyle

    If Dir(keyPath) = "" Then
        statusMsg = "Lizenzstatus: Testversion" & vbCrLf & vbCrLf & _
                    "Keine Lizenzdatei gefunden." & vbCrLf & _
                    "Max. 5 Rechnungen pro Monat kostenlos." & vbCrLf & vbCrLf & _
                    "Lizenz erwerben: info@techit-consulting.de"
        statusIcon = vbExclamation
    Else
        Dim keyContent As String
        keyContent = ReadFileContent(keyPath)

        If Len(Trim(keyContent)) = 0 Then
            statusMsg = "Lizenzstatus: Testversion" & vbCrLf & vbCrLf & _
                        "Lizenzdatei ist leer." & vbCrLf & _
                        "Max. 5 Rechnungen pro Monat kostenlos." & vbCrLf & vbCrLf & _
                        "Lizenz erwerben: info@techit-consulting.de"
            statusIcon = vbExclamation
        ElseIf Left(Trim(keyContent), 5) = "ERNG-" Then
            statusMsg = "Lizenzstatus: Lizenz vorhanden" & vbCrLf & vbCrLf & _
                        "Schlüssel: " & Left(Trim(keyContent), 14) & "..." & vbCrLf & vbCrLf & _
                        "Für Details (Ablaufdatum, Gültigkeit) bitte" & vbCrLf & _
                        """Lizenz aktivieren"" klicken."
            statusIcon = vbInformation
        Else
            statusMsg = "Lizenzstatus: Unbekanntes Format" & vbCrLf & vbCrLf & _
                        "Die Lizenzdatei hat ein unerwartetes Format." & vbCrLf & _
                        "Bitte Lizenz neu eingeben."
            statusIcon = vbExclamation
        End If
    End If

    MsgBox statusMsg, statusIcon, APP_NAME & " — Lizenzstatus"
End Sub

'==============================================================================
' Hilfsfunktionen
'==============================================================================

' Benutzerdaten-Verzeichnis der App (license.key, config.yaml)
Private Function GetDataPath() As String
    #If Mac Then
        GetDataPath = Environ("HOME") & _
                      "/Library/Application Support/Tech-IT Consulting/Excel eRechnung"
    #Else
        GetDataPath = Environ("APPDATA") & _
                      "\Tech-IT Consulting\Excel eRechnung"
    #End If
End Function

' App-Pfad aus Einstellungen lesen – bei erstem Aufruf einmalig abfragen
Private Function GetAppPath() As String
    Dim p As String
    p = GetSetting(APP_NAME, REG_SECTION, REG_KEY, "")

    Dim exists As Boolean
    #If Mac Then
        exists = (p <> "") And (Dir(p, vbDirectory) <> "")
    #Else
        exists = (p <> "") And (Dir(p) <> "")
    #End If

    If Not exists Then
        #If Mac Then
            ' Standardpfad prüfen
            Dim defaultPath As String
            defaultPath = "/Applications/ExcelRechnung.app"
            If Dir(defaultPath, vbDirectory) <> "" Then
                p = defaultPath
                SaveSetting APP_NAME, REG_SECTION, REG_KEY, p
                GetAppPath = p
                Exit Function
            End If
            MsgBox "Bitte wählen Sie einmalig ExcelRechnung.app aus." & vbCrLf & _
                   "(Standardort: Programme / Applications)", vbInformation, APP_NAME
        #Else
            MsgBox "Bitte wählen Sie einmalig die Datei ExcelRechnung.exe aus." & vbCrLf & _
                   "(Der Pfad wird gespeichert und beim nächsten Klick automatisch verwendet.)", _
                   vbInformation, APP_NAME
        #End If
        p = SelectAppFile()
        If p <> "" Then SaveSetting APP_NAME, REG_SECTION, REG_KEY, p
    End If

    GetAppPath = p
End Function

' Tool starten – cross-platform
Private Function LaunchTool(appPath As String, args As String) As Boolean
    On Error GoTo Err_
    #If Mac Then
        Dim script As String
        Dim safeArgs As String
        ' Doppelte Anführungszeichen in einfache umwandeln für AppleScript-Shell
        safeArgs = Replace(args, Chr(34), Chr(39))
        If safeArgs = "" Then
            script = "do shell script " & Chr(34) & _
                     "open -a " & Chr(39) & appPath & Chr(39) & Chr(34)
        Else
            script = "do shell script " & Chr(34) & _
                     "open -a " & Chr(39) & appPath & Chr(39) & _
                     " --args " & safeArgs & Chr(34)
        End If
        MacScript script
    #Else
        Dim cmd As String
        If args = "" Then
            cmd = """" & appPath & """"
        Else
            cmd = """" & appPath & """ " & args
        End If
        Shell cmd, vbNormalFocus
    #End If
    LaunchTool = True
    Exit Function
Err_:
    LaunchTool = False
End Function

' Datei-Auswahl Dialog
Private Function SelectAppFile() As String
    Dim dlg As FileDialog
    Set dlg = Application.FileDialog(msoFileDialogFilePicker)
    With dlg
        .AllowMultiSelect = False
        .Filters.Clear
        #If Mac Then
            .Title = "ExcelRechnung.app auswählen"
            .Filters.Add "Alle Dateien", "*.*"
        #Else
            .Title = "ExcelRechnung.exe auswählen"
            .Filters.Add "Programme", "*.exe"
            .Filters.Add "Alle Dateien", "*.*"
        #End If
        If .Show = -1 Then
            SelectAppFile = .SelectedItems(1)
        Else
            SelectAppFile = ""
        End If
    End With
End Function

Private Function ReadFileContent(filePath As String) As String
    Dim fNum As Integer
    fNum = FreeFile
    Open filePath For Input As #fNum
    Dim content As String, line As String
    Do While Not EOF(fNum)
        Line Input #fNum, line
        content = content & line
    Loop
    Close #fNum
    ReadFileContent = content
End Function
