param(
    # Der Schalter -q aktiviert den Silent-Modus (kein GUI)
    [switch]$q,
    
    # Der Parameter -r nimmt eine kommagetrennte Liste von Namen entgegen
    [string]$r
)

# Notwendig für die grafische Anzeige der Boxen
Add-Type -AssemblyName System.Windows.Forms

# --- 1. SCHRITT: Prozess-Prüfung ---
$oneDriveProcess = Get-Process -Name "OneDrive" -ErrorAction SilentlyContinue

if ($null -eq $oneDriveProcess) {
    # Abfrage-Box erstellen
    $title = "OneDrive nicht gestartet"
    $msg   = "OneDrive ist zurzeit nicht gestartet. Möchten Sie OneDrive jetzt starten, um das Backup zu ermöglichen?"
    $buttons = [System.Windows.Forms.MessageBoxButtons]::YesNo
    $icon = [System.Windows.Forms.MessageBoxIcon]::Question

    $result = [System.Windows.Forms.MessageBox]::Show($msg, $title, $buttons, $icon)

    if ($result -eq [System.Windows.Forms.DialogResult]::Yes) {
        # OneDrive starten
        Write-Host "Starte OneDrive..." -ForegroundColor Yellow
        Start-Process "C:\Program Files\Microsoft OneDrive\OneDrive.exe"
        
        # Kurz warten, damit der Prozess Zeit zum Starten hat, bevor die Registry geprüft wird
        Start-Sleep -Seconds 3
    } 
    else {
        Write-Host "Abbruch durch Benutzer." -ForegroundColor Red
        exit
    }
}

# --- 2. SCHRITT: Registry-Prüfung (Anmelde-Status) ---
$registryPath = "HKCU:\Software\Microsoft\OneDrive\Accounts\Business1"
$valueName    = "UserName"

if (Test-Path $registryPath) {
    $val = Get-ItemProperty -Path $registryPath -Name $valueName -ErrorAction SilentlyContinue
    
    if ($null -eq $val -or [string]::IsNullOrWhiteSpace($val.UserName)) {
        [System.Windows.Forms.MessageBox]::Show("OneDrive läuft zwar, aber Sie sind nicht angemeldet. Bitte loggen Sie sich ein.", "Anmeldung erforderlich")
        exit
    }
} 
else {
    [System.Windows.Forms.MessageBox]::Show("Kein OneDrive konfiguriert. Bitte melden Sie sich in OneDrive an.", "Konto fehlt")
    exit
}

# --- 3. SCHRITT: Backup-Start ---
Write-Host "Check erfolgreich. Backup wird gestartet..." -ForegroundColor Green
# Hier folgt dein Backup-Code

# 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

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

$MissingItems = @()

if (-not (Test-Path $ConfigPath -PathType Leaf)) { $MissingItems += "Konfigurationsdatei:`n$ConfigPath" }
if (-not (Test-Path $OneDrivePath -PathType Container)) { $MissingItems += "Ziel-Ordner (OneDrive):`n$OneDrivePath" }

if ($MissingItems.Count -gt 0) {
    if (-not $q) {
        $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 
}

# --- XML LADEN & HELFER-FUNKTIONEN ---
[xml]$script:Config = Get-Content $ConfigPath -Encoding UTF8

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

$BackupBasePath = [Environment]::GetFolderPath("MyDocuments") + "\Backup"
if (!(Test-Path $BackupBasePath)) { New-Item -Path $BackupBasePath -ItemType Directory -Force | Out-Null }

# --- EINSTELLUNGEN LADEN ---
$SettingsFile = Join-Path $BackupBasePath "BarT_Settings.xml"
$script:AppConfig = @{ MaxBackups = 5; MaxLogs = 20; AutoDeleteOldestBackup = $false }
if (Test-Path $SettingsFile) {
    try {
        $loaded = Import-Clixml $SettingsFile
        if ($loaded.MaxBackups) { $script:AppConfig.MaxBackups = $loaded.MaxBackups }
        if ($loaded.MaxLogs) { $script:AppConfig.MaxLogs = $loaded.MaxLogs }
        if ($null -ne $loaded.AutoDeleteOldestBackup) { $script:AppConfig.AutoDeleteOldestBackup = $loaded.AutoDeleteOldestBackup }
    } catch {}
}

# --- LOG FUNKTIONEN ---
function Write-Log($Message) {
    $Time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $formatted = "[$Time] $Message"
    
    if ($q) {
        if ($script:SilentLogPath) { $formatted | Out-File -FilePath $script:SilentLogPath -Append -Encoding utf8 }
    } else {
        if ($null -ne $LogBox) { $LogBox.AppendText("$formatted`r`n"); $LogBox.ScrollToCaret() }
    }
}

function Clean-Logs {
    $logs = Get-ChildItem -Path $BackupBasePath -Filter "*.log" | Sort-Object LastWriteTime -Descending
    if ($logs.Count -gt $script:AppConfig.MaxLogs) {
        $logs | Select-Object -Skip $script:AppConfig.MaxLogs | Remove-Item -Force
    }
}

# --- 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) { 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)" }
}

# =================================================================================
# --- SILENT MODUS LOGIK (-q) ---
# =================================================================================
if ($q) {
    $Dest = Join-Path $BackupBasePath "$($env:COMPUTERNAME)_$(Get-Date -Format 'yyyy-MM-dd_HH-mm')"
    $script:SilentLogPath = Join-Path $BackupBasePath "Session_$(Get-Date -Format 'yyyyMMdd_HHmm')_Silent.log"
    
    # Backup-Limit Check im Silent Modus
    $existingBackups = Get-ChildItem -Path $BackupBasePath -Directory | Where-Object { $_.Name -like "$env:COMPUTERNAME*" } | Sort-Object CreationTime
    if ($existingBackups.Count -ge $script:AppConfig.MaxBackups) {
        if ($script:AppConfig.AutoDeleteOldestBackup) {
            # Löscht genau so viele alte Backups, dass wieder Platz für das neue ist
            $numToDelete = ($existingBackups.Count - $script:AppConfig.MaxBackups) + 1
            for ($i = 0; $i -lt $numToDelete; $i++) {
                Write-Log "INFO: Automatisches Löschen des ältesten Backups: $($existingBackups[$i].Name)"
                Remove-Item $existingBackups[$i].FullName -Recurse -Force
            }
        } else {
            Write-Log "ABBRUCH: Maximale Anzahl an Backups ($($script:AppConfig.MaxBackups)) für $env:COMPUTERNAME erreicht. Bitte manuell bereinigen oder Auto-Delete aktivieren."
            Clean-Logs
            return 
        }
    }

    if (!(Test-Path $Dest)) { New-Item $Dest -ItemType Directory -Force | Out-Null }
    Write-Log ">>> BarT Silent Backup Start"
    
    $itemsToProcess = @(); $requestedNames = @()
    if (-not [string]::IsNullOrWhiteSpace($r)) {
        Write-Log "INFO: Parameter -r erkannt. Sichere nur: $r"
        $requestedNames = $r -split ',' | ForEach-Object { $_.Trim() }
    } else { Write-Log "INFO: Kein Parameter -r erkannt. Sichere ALLES." }

    foreach ($Item in $script:Config.BackupConfig.Items.Item) {
        if ($requestedNames.Count -gt 0) {
            if (($requestedNames -contains $Item.Name) -or ($Item.Hidden -eq "true")) { $itemsToProcess += $Item }
        } else { $itemsToProcess += $Item }
    }

    $total = $itemsToProcess.Count; $current = 1
    foreach ($Item in $itemsToProcess) { Execute-BackupAction -Item $Item -SessionPath $Dest -CurrentIdx $current -TotalCnt $total; $current++ }
    
    Write-Log ">>> BarT Silent Backup beendet."
    Clean-Logs
    return 
}
# =================================================================================

# --- GUI SETUP ---
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "BarT"
$Form.Size = "805, 765"
$Form.FormBorderStyle = "FixedSingle"
$Form.MaximizeBox = $false
$Form.StartPosition = "CenterScreen"
$Form.TopMost = $true
$Form.BackColor = "White"

$IconPath = "P:\MigWin11\ini\diskette.ico"
if (Test-Path $IconPath) { $Form.Icon = New-Object System.Drawing.Icon($IconPath) }

$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 = "Sicherungseinstellungen"
    $SettingsForm.Size = "350, 240"
    $SettingsForm.StartPosition = "CenterParent"
    $SettingsForm.FormBorderStyle = "FixedToolWindow"
    $SettingsForm.BackColor = "White"; $SettingsForm.TopMost = $true 

    # --- Backup Limit ---
    $LblBackup = New-Object System.Windows.Forms.Label
    $LblBackup.Text = "Maximal Anzahl von`nBackups pro Maschine (1 - 10)"
    $LblBackup.Location = "20, 20"; $LblBackup.Size = "200, 35"
    $SettingsForm.Controls.Add($LblBackup)

    $NumBackups = New-Object System.Windows.Forms.NumericUpDown
    $NumBackups.Location = "250, 25"; $NumBackups.Width = 60
    $NumBackups.Minimum = 1; $NumBackups.Maximum = 10; $NumBackups.Value = $script:AppConfig.MaxBackups
    $SettingsForm.Controls.Add($NumBackups)

    # --- Auto-Delete Checkbox (NEU) ---
    $ChkAutoDelete = New-Object System.Windows.Forms.CheckBox
    $ChkAutoDelete.Text = "Ältestes Backup bei Limit-Erreichung automatisch löschen"
    $ChkAutoDelete.Location = "20, 70"
    $ChkAutoDelete.AutoSize = $true
    $ChkAutoDelete.Checked = $script:AppConfig.AutoDeleteOldestBackup
    $SettingsForm.Controls.Add($ChkAutoDelete)

    # --- Log Limit ---
    $LblLogs = New-Object System.Windows.Forms.Label
    $LblLogs.Text = "Maximal Anzahl`nvon Logs (1-50)"
    $LblLogs.Location = "20, 105"; $LblLogs.Size = "200, 35"
    $SettingsForm.Controls.Add($LblLogs)

    $NumLogs = New-Object System.Windows.Forms.NumericUpDown
    $NumLogs.Location = "250, 110"; $NumLogs.Width = 60
    $NumLogs.Minimum = 1; $NumLogs.Maximum = 50; $NumLogs.Value = $script:AppConfig.MaxLogs
    $SettingsForm.Controls.Add($NumLogs)

    # --- Buttons ---
    $BtnOk = New-Object System.Windows.Forms.Button; $BtnOk.Text = "OK"; $BtnOk.Location = "100, 160"; $BtnOk.Width = 80; $BtnOk.DialogResult = "OK"
    $SettingsForm.Controls.Add($BtnOk)

    $BtnCancel = New-Object System.Windows.Forms.Button; $BtnCancel.Text = "Abbrechen"; $BtnCancel.Location = "190, 160"; $BtnCancel.Width = 80; $BtnCancel.DialogResult = "Cancel"
    $SettingsForm.Controls.Add($BtnCancel)

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

    if ($SettingsForm.ShowDialog($Form) -eq "OK") {
        $script:AppConfig.MaxBackups = $NumBackups.Value
        $script:AppConfig.MaxLogs = $NumLogs.Value
        $script:AppConfig.AutoDeleteOldestBackup = $ChkAutoDelete.Checked
        Export-Clixml -InputObject $script:AppConfig -Path $SettingsFile
        Write-Log "INFO: Einstellungen gespeichert (Max Backups: $($script:AppConfig.MaxBackups), Auto-Delete: $($script:AppConfig.AutoDeleteOldestBackup), Max Logs: $($script:AppConfig.MaxLogs))"
    }
})

$MenuHelp = New-Object System.Windows.Forms.ToolStripMenuItem; $MenuHelp.Text = "Hilfe"
$MenuHelp.Add_Click({ [System.Windows.Forms.MessageBox]::Show("Backup Self-Service Tool BarT`n`nSichert 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.Text = "Backup-Ordner (Ziel):"; $LabelTarget.Location = "20, 35"; $LabelTarget.AutoSize = $true; $Form.Controls.Add($LabelTarget)
$LblPathDisplay = New-Object System.Windows.Forms.Label; $LblPathDisplay.Text = $BackupBasePath; $LblPathDisplay.Location = "20, 55"; $LblPathDisplay.Size = "750, 25"; $LblPathDisplay.Font = New-Object System.Drawing.Font($Form.Font, [System.Drawing.FontStyle]::Regular); $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"; $Form.Controls.Add($GroupBoxExisting)
$ListViewBackups = New-Object System.Windows.Forms.ListView; $ListViewBackups.Location = "10, 20"; $ListViewBackups.Size = "350, 210"; $ListViewBackups.View = "Details"; $ListViewBackups.FullRowSelect = $true; $ListViewBackups.Sorting = "Ascending"; $ListViewBackups.Columns.Add("Ordnername", 346) | Out-Null; $GroupBoxExisting.Controls.Add($ListViewBackups)

$GroupBoxOptions = New-Object System.Windows.Forms.GroupBox; $GroupBoxOptions.Text = "Sicherungsbereiche"; $GroupBoxOptions.Location = "410, 90"; $GroupBoxOptions.Size = "370, 240"; $Form.Controls.Add($GroupBoxOptions)
$ScrollPanel = New-Object System.Windows.Forms.FlowLayoutPanel; $ScrollPanel.Dock = "Fill"; $ScrollPanel.AutoScroll = $true; $ScrollPanel.FlowDirection = "TopDown"; $ScrollPanel.WrapContents = $false; $GroupBoxOptions.Controls.Add($ScrollPanel)

$script:Checkboxes = @()

# --- GUI LOGIK ---
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
}

$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"; $CB.Checked = $true
                $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.Width = 110; $BtnDelete.Height = 35; $BtnDelete.BackColor = "MistyRose"
$BtnDelete.Add_Click({
    if ($ListViewBackups.SelectedItems.Count -eq 0) { return }
    $folderName = $ListViewBackups.SelectedItems[0].Text
    if (([System.Windows.Forms.MessageBox]::Show("Möchten Sie das markierte Backup wirklich löschen?`n`nOrdner: $folderName", "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 = "135, 340"; $BtnReset.Width = 110; $BtnReset.Height = 35; $BtnReset.BackColor = "WhiteSmoke"
$BtnReset.Add_Click({ $ListViewBackups.SelectedItems.Clear(); Show-AllOptions })

$BtnBackup = New-Object System.Windows.Forms.Button; $BtnBackup.Text = "Backup starten"; $BtnBackup.Location = "250, 340"; $BtnBackup.Width = 140; $BtnBackup.Height = 35; $BtnBackup.BackColor = "LightGreen"
$BtnBackup.Add_Click({
    $checkedCount = ($script:Checkboxes | Where-Object { $_.Checked }).Count
    if ($checkedCount -eq 0) { [System.Windows.Forms.MessageBox]::Show("Bitte Sicherungsbereiche auswählen!", "Achtung", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning); return }

    # --- NEU: BACKUP LIMIT PRÜFEN (GUI MODUS) ---
    $existingBackups = Get-ChildItem -Path $BackupBasePath -Directory | Where-Object { $_.Name -like "$env:COMPUTERNAME*" } | Sort-Object CreationTime
    if ($existingBackups.Count -ge $script:AppConfig.MaxBackups) {
        if ($script:AppConfig.AutoDeleteOldestBackup) {
            # Löscht genau so viele alte Backups, dass wieder Platz für das neue ist
            $numToDelete = ($existingBackups.Count - $script:AppConfig.MaxBackups) + 1
            for ($i = 0; $i -lt $numToDelete; $i++) {
                Write-Log "INFO: Automatisches Löschen des ältesten Backups: $($existingBackups[$i].Name)"
                Remove-Item $existingBackups[$i].FullName -Recurse -Force
            }
        } else {
            [System.Windows.Forms.MessageBox]::Show("Maximale Anzahl an Backups ($($script:AppConfig.MaxBackups)) für den PC $env:COMPUTERNAME erreicht!`n`nBitte löschen Sie zuerst ein altes Backup.", "Limit erreicht", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning)
            return
        }
    }

    $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.Width = 110; $BtnAll.Height = 35
$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.Width = 110; $BtnNone.Height = 35
$BtnNone.Add_Click({ $script:Checkboxes | ForEach-Object { $_.Checked = $false } })

$BtnRestore = New-Object System.Windows.Forms.Button; $BtnRestore.Text = "Wiederherstellen"; $BtnRestore.Location = "640, 340"; $BtnRestore.Width = 140; $BtnRestore.Height = 35; $BtnRestore.BackColor = "LightBlue"; $BtnRestore.Enabled = $false
$BtnRestore.Add_Click({
    $checkedCount = ($script:Checkboxes | Where-Object { $_.Checked }).Count
    if ($checkedCount -eq 0) { [System.Windows.Forms.MessageBox]::Show("Bitte wählen Sie mindestens einen Bereich für die Wiederherstellung aus.", "Keine Auswahl", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning); return }

    if ($ListViewBackups.SelectedItems.Count -eq 0) { return }
    $SessionPath = Join-Path $BackupBasePath $ListViewBackups.SelectedItems[0].Text
    Write-Log ">>> Restore Start aus $($ListViewBackups.SelectedItems[0].Text)"

    $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`"
                        write-host $restoreScript - $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."
})

$Form.Controls.AddRange(@($BtnDelete, $BtnReset, $BtnBackup, $BtnAll, $BtnNone, $BtnRestore))

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

# --- PROGRAMM ENDE (Logs aufräumen) ---
$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 
    }
    Clean-Logs
})

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