;export_X31.au3

#include <File.au3>

Global $sIn = "FTTX_KIS_GWG_Zaisenhofen_AR_01.b_.txt"
Global $sOut = "Abrechnung.X31"

; 1) GAEB-X31-Header (XML-Start)
Local $sXML = '<?xml version="1.0" encoding="UTF-8"?>' & @CRLF
$sXML &= '<GAEB xmlns="http://www.gaeb.de/GAEB_DA_XML/3.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' & @CRLF
$sXML &= '  <Header>' & @CRLF
$sXML &= '    <Version>3.1</Version>' & @CRLF
$sXML &= '    <Date>' & @YEAR & "-" & StringFormat("%02d", @MON) & "-" & StringFormat("%02d", @MDAY) & '</Date>' & @CRLF
$sXML &= '    <FileType>X31</FileType>' & @CRLF
$sXML &= '  </Header>' & @CRLF
$sXML &= '  <Project>' & @CRLF
$sXML &= '    <ProjectName>Bauprojekt</ProjectName>' & @CRLF
$sXML &= '    <Site>Baustelle Muster</Site>' & @CRLF

; 2) Quelldatei einlesen
Local $aLines = FileReadToArray($sIn)
If @error Then Exit MsgBox(16, "Fehler", "Quelldatei nicht gefunden")

; 3) Aufmaßdaten einlesen
Local $iSection = 0
$sXML &= '    <Positions>' & @CRLF
For $i = 1 To $aLines[0]
    Local $s = StringStripWS($aLines[$i], 3)
    If $s = "[Aufmaßdaten]" Then
        $iSection = 1
    ElseIf $iSection = 1 And StringLeft($s, 1) = "|" Then
        ; CSV-Linie in Felder aufsplitten
        Local $a = StringSplit($s, "|", 12)
        ; GAEB-Positionen erzeugen
        $sXML &= '      <Position>' & @CRLF
        $sXML &= '        <PositionNumber>' & StringStripWS($a[2], 3) & '</PositionNumber>' & @CRLF
        $sXML &= '        <ShortText>' & StringStripWS($a[9], 3) & '</ShortText>' & @CRLF
        $sXML &= '        <Quantity>' & StringReplace($a[10], ",", ".") & '</Quantity>' & @CRLF
        $sXML &= '        <Unit>' & $a[8] & '</Unit>' & @CRLF
        $sXML &= '        <UnitPrice>' & StringReplace($a[11], ",", ".") & '</UnitPrice>' & @CRLF
        $sXML &= '      </Position>' & @CRLF
    EndIf
Next
$sXML &= '    </Positions>' & @CRLF
$sXML &= '  </Project>' & @CRLF

; 4) GAEB-X31-Footer
$sXML &= '</GAEB>'

; 5) XML-Datei speichern
If _FileWriteFromArray($sOut, StringSplit($sXML, @CRLF, 1)) Then
    MsgBox(64, "Erfolgreich", "GAEB-X31-Datei '" & $sOut & "' wurde erstellt.")
Else
    MsgBox(16, "Fehler", "GAEB-X31-Datei konnte nicht erstellt werden.")
EndIf