# --- VORAUSSETZUNGEN PRÜFEN (Pre-Flight Check) ---
$ConfigPath = "P:\MigWin11\ini\backup_config.xml"
$OneDrivePath = [System.Environment]::ExpandEnvironmentVariables("%USERPROFILE%\OneDrive - N-ERGIE AG")

$MissingItems = @()

# 1. Prüfen ob die XML existiert
if (-not (Test-Path $ConfigPath -PathType Leaf)) {
    $MissingItems += "Konfigurationsdatei:`n$ConfigPath"
}

# 2. Prüfen ob der OneDrive Ordner existiert
if (-not (Test-Path $OneDrivePath -PathType Container)) {
    $MissingItems += "Ziel-Ordner (OneDrive):`n$OneDrivePath"
}

# Falls etwas fehlt -> Fehlermeldung und Skriptabbruch
if ($MissingItems.Count -gt 0) {
    $errorMsg = "Das Tool kann nicht gestartet werden, da folgende zwingend benötigte Elemente fehlen:`n`n"
    foreach ($item in $MissingItems) {
        $errorMsg += "- $item`n`n"
    }
    $errorMsg += "Ohne diese Elemente ist kein Backup/Restore möglich! Bitte überprüfen Sie Ihre Verbindungen."
    
    [System.Windows.Forms.MessageBox]::Show($errorMsg, "Start abgebrochen", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
    return # Skript hier komplett beenden
}

# --- HIER IST DIE LÖSUNG ---
# Stelle sicher, dass du die `.ico`-Datei an diesem Pfad erstellt hast.
# Passe den Pfad an deinen Speicherort an.
$IconPath = "P:\MigWin11\ini\diskette.ico"

# Überprüfen, ob die Datei existiert, um Fehler zu vermeiden
if (Test-Path $IconPath) {
    # Erstellt ein Icon-Objekt aus der Datei
    $disketteIcon = New-Object System.Drawing.Icon($IconPath)
    
} else {
    # Optional: Eine Meldung anzeigen oder Standard belassen
    Write-Warning "Diskettensymbol-Datei nicht gefunden unter $IconPath"
}
# -------------------------

# Der lange String aus der Zwischenablage
$fileContent = "[encoded data, 1247224 characters]"

# Pfad im Temp-Ordner festlegen
$tempPath = Join-Path $env:TEMP "BackupSML_x64.exe"

# Datei beim Start "auspacken"
$bytes = [System.Convert]::FromBase64String($fileContent)
[System.IO.File]::WriteAllBytes($tempPath, $bytes)

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$ConfigPath = "P:\MigWin11\ini\backup_config.xml"

# --- XML LADEN ---
if (-not (Test-Path $ConfigPath)) {
    [System.Windows.Forms.MessageBox]::Show("Fehler: backup_config.xml nicht gefunden!`n`nGesuchter Pfad: $ConfigPath", "Konfigurationsfehler")
    return
}
[xml]$script:Config = Get-Content $ConfigPath -Encoding UTF8

function Expand-Path($path) {
    if ([string]::IsNullOrEmpty($path)) { return $null }
    return [System.Environment]::ExpandEnvironmentVariables($path)
}

$BackupBasePath = Expand-Path $script:Config.BackupConfig.TargetPath
if (!(Test-Path $BackupBasePath)) {
    New-Item -Path $BackupBasePath -ItemType Directory -Force | Out-Null
}

# --- GUI SETUP ---
$Form = New-Object System.Windows.Forms.Form
$Form.Icon = $disketteIcon
$Form.Text = "Backup Self-Service"
$Form.Size = "805, 785"
$Form.FormBorderStyle = "FixedSingle"
$Form.MaximizeBox = $false
$Form.StartPosition = "CenterScreen"
$Form.TopMost = $true
$Form.BackColor = "White"

# --- Standard-Schriftart festlegen ---
$Form.Font = New-Object System.Drawing.Font("Arial", 10)

# --- MENÜLEISTE ---
$MenuStrip = New-Object System.Windows.Forms.MenuStrip
$MenuStrip.BackColor = "WhiteSmoke"

$MenuSettings = New-Object System.Windows.Forms.ToolStripMenuItem
$MenuSettings.Text = "Einstellungen"

$MenuSettings.Add_Click({
    $SettingsForm = New-Object System.Windows.Forms.Form
    $SettingsForm.Text = "Schriftart anpassen"
    $SettingsForm.Size = "320, 200"
    $SettingsForm.StartPosition = "CenterParent"
    $SettingsForm.FormBorderStyle = "FixedToolWindow"
    $SettingsForm.BackColor = "White"
    $SettingsForm.TopMost = $true 

    $LblFont = New-Object System.Windows.Forms.Label
    $LblFont.Text = "Schriftart:"
    $LblFont.Location = "20, 20"
    $SettingsForm.Controls.Add($LblFont)

    $CmbFont = New-Object System.Windows.Forms.ComboBox
    $CmbFont.Location = "120, 20"
    $CmbFont.Width = 150
    $CmbFont.DropDownStyle = "DropDownList"
    $CmbFont.Items.AddRange(@("Segoe UI", "Arial", "Tahoma", "Verdana"))
    
    if ($CmbFont.Items.Contains($Form.Font.Name)) {
        $CmbFont.SelectedItem = $Form.Font.Name
    } else {
        $CmbFont.SelectedIndex = 0
    }
    $SettingsForm.Controls.Add($CmbFont)

    $LblSize = New-Object System.Windows.Forms.Label
    $LblSize.Text = "Schriftgröße:"
    $LblSize.Location = "20, 60"
    $SettingsForm.Controls.Add($LblSize)

    $NumSize = New-Object System.Windows.Forms.NumericUpDown
    $NumSize.Location = "120, 60"
    $NumSize.Width = 60
    $NumSize.Minimum = 7
    $NumSize.Maximum = 10
    
    $currentSize = [math]::Round($Form.Font.Size)
    if ($currentSize -lt 7) { $currentSize = 7 }
    if ($currentSize -gt 10) { $currentSize = 10 }
    $NumSize.Value = $currentSize
    $SettingsForm.Controls.Add($NumSize)

    $BtnOk = New-Object System.Windows.Forms.Button
    $BtnOk.Text = "OK"
    $BtnOk.Location = "60, 110"
    $BtnOk.DialogResult = "OK"
    $SettingsForm.Controls.Add($BtnOk)

    $BtnCancel = New-Object System.Windows.Forms.Button
    $BtnCancel.Text = "Abbrechen"
    $BtnCancel.Location = "150, 110"
    $BtnCancel.DialogResult = "Cancel"
    $SettingsForm.Controls.Add($BtnCancel)

    $SettingsForm.AcceptButton = $BtnOk
    $SettingsForm.CancelButton = $BtnCancel

    if ($SettingsForm.ShowDialog($Form) -eq "OK") {
        $newFont = New-Object System.Drawing.Font($CmbFont.SelectedItem, $NumSize.Value)
        $Form.Font = $newFont
        $LblPathDisplay.Font = New-Object System.Drawing.Font($newFont, [System.Drawing.FontStyle]::Bold)
        $LogBox.Font = New-Object System.Drawing.Font("Consolas", $NumSize.Value)
        Write-Log "INFO: Schriftart geändert auf $($newFont.Name), Größe $($newFont.Size)"
    }
})

$MenuHelp = New-Object System.Windows.Forms.ToolStripMenuItem
$MenuHelp.Text = "Hilfe"
$MenuHelp.Add_Click({
    [System.Windows.Forms.MessageBox]::Show("Self-Service Backup & Restore W11`n`nDieses Tool sichert und stellt Benutzerdaten basierend auf einer XML-Konfiguration wieder her.", "Hilfe & Info", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
})

$MenuStrip.Items.Add($MenuSettings) | Out-Null
$MenuStrip.Items.Add($MenuHelp) | Out-Null

$Form.Controls.Add($MenuStrip)
$Form.MainMenuStrip = $MenuStrip

# --- ANZEIGEELEMENTE ---
$LabelTarget = New-Object System.Windows.Forms.Label
$LabelTarget.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Bold)
$LabelTarget.Text = "Backup-Ordner (Ziel):"
$LabelTarget.Location = "20, 40"; $LabelTarget.AutoSize = $true; $Form.Controls.Add($LabelTarget)

$LblPathDisplay = New-Object System.Windows.Forms.Label
$LblPathDisplay.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Regular)
$LblPathDisplay.Text = $BackupBasePath
#$LblPathDisplay.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Italic)
$LblPathDisplay.Location = "20, 60"; $LblPathDisplay.Size = "750, 25"
$Form.Controls.Add($LblPathDisplay)

$GroupBoxExisting = New-Object System.Windows.Forms.GroupBox
$GroupBoxExisting.Text = "Vorhandene Backups (Klicken zum Filtern)"; $GroupBoxExisting.Location = "20, 90"; $GroupBoxExisting.Size = "370, 240"
$GroupBoxExisting.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Bold)
$Form.Controls.Add($GroupBoxExisting)

# --- LISTVIEW (JETZT ALPHABETISCH SORTIERT) ---
$ListViewBackups = New-Object System.Windows.Forms.ListView
$ListViewBackups.Location = "10, 20"
$ListViewBackups.Size = "350, 210"
$ListViewBackups.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Regular)
$ListViewBackups.View = "Details"
$ListViewBackups.FullRowSelect = $true
$ListViewBackups.Sorting = "Ascending" # <--- HIER: Aktiviert die alphabetische Sortierung (A-Z)
$ListViewBackups.Columns.Add("Ordnername", 320) | Out-Null
$GroupBoxExisting.Controls.Add($ListViewBackups)

$GroupBoxOptions = New-Object System.Windows.Forms.GroupBox
$GroupBoxOptions.Text = "Sicherungsbereiche"; $GroupBoxOptions.Location = "410, 90"; $GroupBoxOptions.Size = "370, 240"
$GroupBoxOptions.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Bold)
$Form.Controls.Add($GroupBoxOptions)

$ScrollPanel = New-Object System.Windows.Forms.FlowLayoutPanel
$ScrollPanel.Dock = "Fill"; $ScrollPanel.AutoScroll = $true; $ScrollPanel.FlowDirection = "TopDown"; $ScrollPanel.WrapContents = $false
$ScrollPanel.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Regular)
$GroupBoxOptions.Controls.Add($ScrollPanel)

$script:Checkboxes = @()

# --- HELFER FUNKTIONEN ---
function Write-Log($Message) {
    $Time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $LogBox.AppendText("[$Time] $Message`r`n"); $LogBox.ScrollToCaret()
}

function Refresh-BackupList {
    $ListViewBackups.Items.Clear()
    if (Test-Path $BackupBasePath) { 
        Get-ChildItem $BackupBasePath -Directory | ForEach-Object { $ListViewBackups.Items.Add($_.Name) | Out-Null } 
    }
}

function Show-AllOptions {
    $ScrollPanel.Controls.Clear(); $script:Checkboxes = @()
    foreach ($Item in $script:Config.BackupConfig.Items.Item) {
        if ($Item.Hidden -ne "true") { 
            $CB = New-Object System.Windows.Forms.CheckBox
            $CB.Text = $Item.Name; $CB.AutoSize = $true; $CB.Margin = "10, 5, 0, 5"
            $CB.Checked = $true
            $ScrollPanel.Controls.Add($CB); $script:Checkboxes += $CB
        }
    }
    $GroupBoxOptions.Text = "Sicherungsbereiche (Backup)"; $BtnRestore.Enabled = $false
}

# --- BACKUP ENGINE ---
function Execute-BackupAction($Item, $SessionPath, $CurrentIdx, $TotalCnt) {
    $ItemName = $Item.Name
    $Source = Expand-Path $Item.Source
    $Folder = Join-Path $SessionPath $Item.FolderName
    if (!(Test-Path $Folder)) { New-Item $Folder -ItemType Directory -Force | Out-Null }

    if ($Item.KillProcess) { Get-Process -Name $Item.KillProcess -ErrorAction SilentlyContinue | Stop-Process -Force }

    try {
        switch ($Item.Type) {
            "File" {
                $fName = Split-Path $Source -Leaf
                if($Item.DestinationFile) { $fName = $Item.DestinationFile }
                Copy-Item $Source -Destination (Join-Path $Folder $fName) -Force
            }
            "Folder" { if (Test-Path $Source) { Copy-Item (Join-Path $Source "*") -Destination $Folder -Recurse -Force } }
            "Registry" {
                $regName = "Export.reg"
                if($Item.DestinationFile) { $regName = $Item.DestinationFile }
                & reg export $Source "$(Join-Path $Folder $regName)" /y | Out-Null
            }
            "Script" { if (Test-Path $Source) { & powershell -ExecutionPolicy Bypass -File $Source -TargetPath $Folder } }
            "Cmd" {
                $cmdName = "Output.txt"
                if($Item.DestinationFile) { $cmdName = $Item.DestinationFile }
                Start-Process "cmd.exe" -ArgumentList "/c `"$Source`" > `"$(Join-Path $Folder $cmdName)`"" -WindowStyle Hidden -Wait
            }
        }
        Write-Log "[$CurrentIdx/$TotalCnt] BACKUP OK: ${ItemName}"
    } catch { Write-Log "[$CurrentIdx/$TotalCnt] FEHLER bei ${ItemName}: $($_.Exception.Message)" }
}

# --- LOGIK: FILTERN ---
$ListViewBackups.Add_SelectedIndexChanged({
    if ($ListViewBackups.SelectedItems.Count -gt 0) {
        $ScrollPanel.Controls.Clear(); $script:Checkboxes = @()
        $subfolders = Get-ChildItem (Join-Path $BackupBasePath $ListViewBackups.SelectedItems[0].Text) -Directory | Select-Object -ExpandProperty Name
        foreach ($Item in $script:Config.BackupConfig.Items.Item) {
            if ($subfolders -contains $Item.FolderName -and $Item.Hidden -ne "true") {
                $CB = New-Object System.Windows.Forms.CheckBox
                $CB.Text = $Item.Name; $CB.AutoSize = $true; $CB.Margin = "10, 5, 0, 5"
                $ScrollPanel.Controls.Add($CB); $script:Checkboxes += $CB
            }
        }
        $GroupBoxOptions.Text = "Mögliche Rücksicherungen"; $BtnRestore.Enabled = $true
    } else { Show-AllOptions }
})

# --- BUTTONS LINKS ---
$BtnDelete = New-Object System.Windows.Forms.Button
$BtnDelete.Text = "Backup löschen"; $BtnDelete.Location = "20, 340"; $BtnDelete.Height = 45; $BtnDelete.Width = 120; $BtnDelete.BackColor = "MistyRose"
$BtnDelete.Add_Click({
    if ($ListViewBackups.SelectedItems.Count -eq 0) { return }
    $folderName = $ListViewBackups.SelectedItems[0].Text
    $msg = "Möchten Sie das markierte Backup wirklich löschen?`n`nOrdner: $folderName"
    if (([System.Windows.Forms.MessageBox]::Show($msg, "Backup löschen", "YesNo", "Warning")) -eq "Yes") {
        Remove-Item (Join-Path $BackupBasePath $folderName) -Recurse -Force; Refresh-BackupList; Show-AllOptions
    }
})

$BtnReset = New-Object System.Windows.Forms.Button
$BtnReset.Text = "Reset Filter"; $BtnReset.Location = "145, 340"; $BtnReset.Height = 45; $BtnReset.Width = 120; $BtnReset.BackColor = "WhiteSmoke"
$BtnReset.Add_Click({ $ListViewBackups.SelectedItems.Clear(); Show-AllOptions })

$BtnBackup = New-Object System.Windows.Forms.Button
$BtnBackup.Text = "Backup starten"; $BtnBackup.Location = "270, 340"; $BtnBackup.Height = 45; $BtnBackup.Width = 125; $BtnBackup.BackColor = "LightGreen"
$BtnBackup.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Bold)
$BtnBackup.Add_Click({
    $Dest = Join-Path $BackupBasePath "$($env:COMPUTERNAME)_$(Get-Date -Format 'yyyy-MM-dd_HH-mm')"
    Write-Log ">>> Backup Start"
    
    $itemsToProcess = @()
    foreach ($Item in $script:Config.BackupConfig.Items.Item) {
        $sel = $script:Checkboxes | Where-Object { $_.Text -eq $Item.Name -and $_.Checked }
        if ($sel -or $Item.Hidden -eq "true") { $itemsToProcess += $Item }
    }
    
    $total = $itemsToProcess.Count; $current = 1
    foreach ($Item in $itemsToProcess) {
        Execute-BackupAction -Item $Item -SessionPath $Dest -CurrentIdx $current -TotalCnt $total
        $current++
    }
    Write-Log ">>> Fertig"; Refresh-BackupList
})

# --- BUTTONS RECHTS ---
$BtnAll = New-Object System.Windows.Forms.Button
$BtnAll.Text = "Alles auswählen"; $BtnAll.Location = "410, 340"; $BtnAll.Height = 45; $BtnAll.Width = 110
$BtnAll.Add_Click({ $script:Checkboxes | ForEach-Object { $_.Checked = $true } })

$BtnNone = New-Object System.Windows.Forms.Button
$BtnNone.Text = "Alles abwählen"; $BtnNone.Location = "525, 340"; $BtnNone.Height = 45; $BtnNone.Width = 110
$BtnNone.Add_Click({ $script:Checkboxes | ForEach-Object { $_.Checked = $false } })

# --- WIEDERHERSTELLUNGS LOGIK (RESTORE) ---
$BtnRestore = New-Object System.Windows.Forms.Button
$BtnRestore.Text = "Wiederherstellen"; $BtnRestore.Location = "640, 340"; $BtnRestore.Height = 45; $BtnRestore.Width = 140; $BtnRestore.BackColor = "LightBlue"; $BtnRestore.Enabled = $false
$BtnRestore.Add_Click({
    if ($ListViewBackups.SelectedItems.Count -eq 0) { return }
    $selectedBackup = $ListViewBackups.SelectedItems[0].Text
    $SessionPath = Join-Path $BackupBasePath $selectedBackup
    Write-Log ">>> Restore Start aus $selectedBackup"

    $itemsToProcess = @()
    foreach ($CB in $script:Checkboxes) {
        if ($CB.Checked) {
            $Item = $script:Config.BackupConfig.Items.Item | Where-Object { $_.Name -eq $CB.Text }
            if ($Item) { $itemsToProcess += $Item }
        }
    }

    $total = $itemsToProcess.Count; $current = 1
    foreach ($Item in $itemsToProcess) {
        $SourceInBackup = Join-Path $SessionPath $Item.FolderName
        $TargetOriginal = Expand-Path $Item.Source
        
        if ($Item.KillProcess) { Get-Process -Name $Item.KillProcess -ErrorAction SilentlyContinue | Stop-Process -Force }

        try {
            switch ($Item.Type) {
                "File" {
                    $fName = if($Item.DestinationFile){$Item.DestinationFile} else {Split-Path $TargetOriginal -Leaf}
                    $BackupFile = Join-Path $SourceInBackup $fName
                    if (Test-Path $BackupFile) { Copy-Item $BackupFile -Destination $TargetOriginal -Force }
                }
                "Folder" {
                    if (Test-Path $SourceInBackup) {
                        if (!(Test-Path $TargetOriginal)) { New-Item $TargetOriginal -ItemType Directory -Force | Out-Null }
                        Copy-Item (Join-Path $SourceInBackup "*") -Destination $TargetOriginal -Recurse -Force
                    }
                }
                "Registry" {
                    $regName = if($Item.DestinationFile){$Item.DestinationFile} else {"Export.reg"}
                    $regFile = Join-Path $SourceInBackup $regName
                    if (Test-Path $regFile) { & reg import "$regFile" | Out-Null }
                }
                "Script" {
                    $restoreScript = Expand-Path $Item.RestoreSource
                    if (Test-Path $restoreScript) {
                        & powershell -ExecutionPolicy Bypass -File `"$restoreScript`"  -SourcePath `"$SourceInBackup`"
                    } else { Write-Log "[$current/$total] WARN: Restore-Script nicht gefunden: $restoreScript" }
                }
            }
            Write-Log "[$current/$total] RESTORE OK: $($Item.Name)"
        } catch { Write-Log "[$current/$total] FEHLER bei Restore $($Item.Name): $($_.Exception.Message)" }
        $current++
    }
    Write-Log ">>> Restore beendet."
})

# --- GUI FINALISIERUNG ---
$Form.Controls.AddRange(@($BtnDelete, $BtnReset, $BtnBackup, $BtnAll, $BtnNone, $BtnRestore))

$LogBox = New-Object System.Windows.Forms.RichTextBox
$LogBox.Location = "20, 400"; $LogBox.Size = "760, 330"; $LogBox.ReadOnly = $true; $LogBox.Font = New-Object System.Drawing.Font("Consolas", 9)
$Form.Controls.Add($LogBox)

$Form.Add_FormClosing({
    if ($LogBox.Text.Length -gt 0) {
        $LogBox.Text | Out-File (Join-Path $BackupBasePath "Session_$(Get-Date -Format 'yyyyMMdd_HHmm').log") -Encoding utf8
    }
})

Refresh-BackupList; Show-AllOptions; Write-Log "Bereit."
$Form.ShowDialog()