param(
    [string]$Gateway = 'https://free.ransombackup.com',
    [Alias('EnrollmentKey')][string]$EnrollmentCode = '',
    [ValidateSet('','it','en')][string]$Language = '',
    [string]$Email = '',
    [switch]$ReplaceExisting
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'Common.ps1')
. (Join-Path $PSScriptRoot 'UIHelpers.ps1')
Initialize-RBWindowsUI
if (-not $Language) { $Language = Get-RBLanguage }

if (-not $EnrollmentCode) {
    $deploymentPath = Join-Path $PSScriptRoot 'deployment.json'
    if (Test-Path $deploymentPath) {
        $deployment = Get-Content $deploymentPath -Raw | ConvertFrom-Json
        $EnrollmentCode = if ($deployment.enrollment_code) { $deployment.enrollment_code } else { $deployment.enrollment_key }
        if ($deployment.gateway) { $Gateway = $deployment.gateway }
    }
}
$rbPaths = Get-RBPaths
if (-not $ReplaceExisting -and (Test-Path -LiteralPath $rbPaths.Config) -and (Test-Path -LiteralPath $rbPaths.Secrets)) {
    try {
        $existingState = Get-RBConfiguration
        [void](Register-RBScheduledTask)
        if (-not (Show-RBRecoveryKeyWindow -RecoveryKey $existingState.Secrets.repository_password -Email $existingState.Config.email -Language (Get-RBLanguage $existingState) -RequireConfirmation)) { exit 0 }
        & (Join-Path $PSScriptRoot 'ManageFolders.ps1')
        exit $LASTEXITCODE
    } catch {
        [Windows.Forms.MessageBox]::Show("Impossibile riparare la configurazione esistente.`n`n$($_.Exception.Message)", 'RansomBackup FREE', 'OK', 'Error') | Out-Null
        exit 1
    }
}

$form = New-Object Windows.Forms.Form
$form.Text = 'Configura RansomBackup FREE'
$form.ClientSize = New-Object Drawing.Size(760, 690)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
$form.BackColor = [Drawing.Color]::FromArgb(247, 249, 248)
$form.Font = New-Object Drawing.Font('Segoe UI', 10)
$form.AutoScaleMode = 'Dpi'

$header = New-Object Windows.Forms.Panel
$header.Dock = 'Top'; $header.Height = 112; $header.BackColor = [Drawing.Color]::FromArgb(9, 35, 24); $form.Controls.Add($header)
$title = New-Object Windows.Forms.Label
$title.Text = 'Proteggi le cartelle importanti'; $title.ForeColor = [Drawing.Color]::White; $title.Font = New-Object Drawing.Font('Segoe UI Semibold', 21)
$title.Location = New-Object Drawing.Point(30, 18); $title.AutoSize = $true; $header.Controls.Add($title)
$subtitle = New-Object Windows.Forms.Label
$subtitle.Text = 'Puoi scegliere una o più cartelle. Restic invierà soltanto le differenze.'; $subtitle.ForeColor = [Drawing.Color]::FromArgb(184, 211, 197)
$subtitle.Location = New-Object Drawing.Point(33, 67); $subtitle.AutoSize = $true; $header.Controls.Add($subtitle)
$languageBox = New-Object Windows.Forms.ComboBox
$languageBox.DropDownStyle = 'DropDownList'; $languageBox.Location = New-Object Drawing.Point(617, 20); $languageBox.Size = New-Object Drawing.Size(110, 28)
[void]$languageBox.Items.Add('Italiano'); [void]$languageBox.Items.Add('English'); $languageBox.SelectedIndex = if ($Language -eq 'en') { 1 } else { 0 }; $header.Controls.Add($languageBox)

$emailLabel = New-Object Windows.Forms.Label
$codeLabel = New-Object Windows.Forms.Label
$codeLabel.Text = 'Codice di installazione monouso'; $codeLabel.Location = New-Object Drawing.Point(32, 132); $codeLabel.AutoSize = $true; $form.Controls.Add($codeLabel)
$codeBox = New-Object Windows.Forms.TextBox
$codeBox.Location = New-Object Drawing.Point(35, 158); $codeBox.Size = New-Object Drawing.Size(690, 30); $codeBox.Text = $EnrollmentCode; $form.Controls.Add($codeBox)

$emailLabel.Text = 'Email del cliente'; $emailLabel.Location = New-Object Drawing.Point(32, 210); $emailLabel.AutoSize = $true; $form.Controls.Add($emailLabel)
$emailBox = New-Object Windows.Forms.TextBox
$emailBox.Location = New-Object Drawing.Point(35, 236); $emailBox.Size = New-Object Drawing.Size(690, 30); $emailBox.Text = $Email; $form.Controls.Add($emailBox)

$folderLabel = New-Object Windows.Forms.Label
$folderLabel.Text = 'Cartelle da proteggere'; $folderLabel.Location = New-Object Drawing.Point(32, 290); $folderLabel.AutoSize = $true; $form.Controls.Add($folderLabel)
$folderList = New-Object Windows.Forms.ListBox
$folderList.Location = New-Object Drawing.Point(35, 316); $folderList.Size = New-Object Drawing.Size(545, 150); $folderList.HorizontalScrollbar = $true; $form.Controls.Add($folderList)

$addFolder = New-Object Windows.Forms.Button
$addFolder.Text = 'Aggiungi cartella'; $addFolder.Location = New-Object Drawing.Point(595, 316); $addFolder.Size = New-Object Drawing.Size(130, 40); Set-RBPrimaryButton $addFolder
$removeFolder = New-Object Windows.Forms.Button
$removeFolder.Text = 'Rimuovi'; $removeFolder.Location = New-Object Drawing.Point(595, 368); $removeFolder.Size = New-Object Drawing.Size(130, 40); Set-RBSecondaryButton $removeFolder
$form.Controls.AddRange(@($addFolder, $removeFolder))

$quota = New-Object Windows.Forms.Label
$quota.Text = "Il limite FREE e la tolleranza aggiornati sono sempre visibili nell'area personale."; $quota.Location = New-Object Drawing.Point(35, 484); $quota.AutoSize = $true; $quota.ForeColor = [Drawing.Color]::FromArgb(76, 94, 84); $form.Controls.Add($quota)

$termsLink = New-Object Windows.Forms.LinkLabel
$termsLink.Text = "Leggi le Condizioni d'uso"; $termsLink.Location = New-Object Drawing.Point(35, 520); $termsLink.AutoSize = $true; $form.Controls.Add($termsLink)
$termsAccepted = New-Object Windows.Forms.CheckBox
$termsAccepted.Text = "Ho letto e accetto le Condizioni d'uso (versione $script:RBTermsVersion)."; $termsAccepted.Location = New-Object Drawing.Point(35, 552); $termsAccepted.Size = New-Object Drawing.Size(690, 35); $form.Controls.Add($termsAccepted)

$continue = New-Object Windows.Forms.Button
$continue.Text = 'Continua'; $continue.Location = New-Object Drawing.Point(557, 614); $continue.Size = New-Object Drawing.Size(168, 44); Set-RBPrimaryButton $continue; $form.Controls.Add($continue)

function Set-SetupLanguage {
    $script:Language = if ($languageBox.SelectedIndex -eq 1) { 'en' } else { 'it' }
    if ($script:Language -eq 'en') {
        $form.Text='Set up RansomBackup FREE'; $title.Text='Protect your important folders'; $subtitle.Text='Choose one or more folders. Restic will upload only changes.'
        $codeLabel.Text='One-time installation code'; $emailLabel.Text='Customer email'; $folderLabel.Text='Folders to protect'
        $addFolder.Text='Add folder'; $removeFolder.Text='Remove'; $quota.Text='The current FREE limit and technical tolerance are always shown in your account.'; $termsLink.Text='Read the Terms of Use'; $termsAccepted.Text="I have read and accept the Terms of Use (version $script:RBTermsVersion)."; $continue.Text='Continue'
    } else {
        $form.Text='Configura RansomBackup FREE'; $title.Text='Proteggi le cartelle importanti'; $subtitle.Text='Puoi scegliere una o più cartelle. Restic invierà soltanto le differenze.'
        $codeLabel.Text='Codice di installazione monouso'; $emailLabel.Text='Email del cliente'; $folderLabel.Text='Cartelle da proteggere'
        $addFolder.Text='Aggiungi cartella'; $removeFolder.Text='Rimuovi'; $quota.Text="Il limite FREE e la tolleranza aggiornati sono sempre visibili nell'area personale."; $termsLink.Text="Leggi le Condizioni d'uso"; $termsAccepted.Text="Ho letto e accetto le Condizioni d'uso (versione $script:RBTermsVersion)."; $continue.Text='Continua'
    }
}
$languageBox.Add_SelectedIndexChanged({ Set-SetupLanguage })
$termsLink.Add_LinkClicked({ Start-Process $(if($script:Language -eq 'en'){'https://www.ransombackup.com/en/terms/'}else{'https://www.ransombackup.com/terms/'}) })
Set-SetupLanguage

$addFolder.Add_Click({
    $dialog = New-Object Windows.Forms.FolderBrowserDialog
    $dialog.Description = Get-RBText 'Scegli una cartella da proteggere' $script:Language
    if ($dialog.ShowDialog() -eq 'OK' -and -not $folderList.Items.Contains($dialog.SelectedPath)) { [void]$folderList.Items.Add($dialog.SelectedPath) }
})
$removeFolder.Add_Click({ if ($folderList.SelectedIndex -ge 0) { $folderList.Items.RemoveAt($folderList.SelectedIndex) } })
$continue.Add_Click({
    if ([string]::IsNullOrWhiteSpace($codeBox.Text)) {
        [Windows.Forms.MessageBox]::Show((Get-RBText 'Inserisci il codice monouso ricevuto da RansomBackup.' $script:Language), 'RansomBackup FREE', 'OK', 'Warning') | Out-Null; return
    }
    if ($emailBox.Text -notmatch '^[^\s@]+@[^\s@]+\.[^\s@]+$') {
        [Windows.Forms.MessageBox]::Show((Get-RBText 'Inserisci un indirizzo email valido.' $script:Language), 'RansomBackup FREE', 'OK', 'Warning') | Out-Null; return
    }
    if ($folderList.Items.Count -lt 1) {
        [Windows.Forms.MessageBox]::Show((Get-RBText 'Aggiungi almeno una cartella da proteggere.' $script:Language), 'RansomBackup FREE', 'OK', 'Warning') | Out-Null; return
    }
    if (-not $termsAccepted.Checked) {
        [Windows.Forms.MessageBox]::Show((Get-RBText "Devi accettare le Condizioni d'uso." $script:Language), 'RansomBackup FREE', 'OK', 'Warning') | Out-Null; return
    }
    $form.Tag = 'continue'; $form.Close()
})

[void]$form.ShowDialog()
if ($form.Tag -ne 'continue') { exit 0 }

$email = $emailBox.Text.Trim().ToLowerInvariant()
$sources = @($folderList.Items | ForEach-Object { [string]$_ })
$recoveryKey = New-RBRecoveryKey
if (-not (Show-RBRecoveryKeyWindow -RecoveryKey $recoveryKey -Email $email -Language $script:Language -RequireConfirmation)) { exit 0 }

try {
    $payload = @{ email=$email; device_name=$env:COMPUTERNAME; language=$script:Language; terms_version=$script:RBTermsVersion; terms_accepted=$true } | ConvertTo-Json
    $enrollment = Invoke-RestMethod -Method Post -Uri "$($Gateway.TrimEnd('/'))/api/v1/enroll" -Headers @{ 'X-RB-Enrollment-Code'=$codeBox.Text.Trim() } -ContentType 'application/json' -Body $payload -TimeoutSec 30
    Save-RBConfiguration -Enrollment $enrollment -Email $email -Sources $sources -Gateway $Gateway -RecoveryKey $recoveryKey -Language $script:Language
    $state = Get-RBConfiguration
    Set-RBResticEnvironment -State $state
    $initOutput = & $state.Paths.Restic init 2>&1
    if ($LASTEXITCODE -ne 0) { throw "$(Get-RBText 'Impossibile inizializzare il backup:' $script:Language) $($initOutput -join ' ')" }
    [void](Register-RBScheduledTask)
    Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $PSScriptRoot 'LaunchHidden.vbs')`"",'Backup.ps1')
    [Windows.Forms.MessageBox]::Show("$(Get-RBText 'Configurazione completata.' $script:Language)`n`n$(Get-RBText 'Il primo backup è partito. Puoi aggiungere o rimuovere cartelle dal menu Start.' $script:Language)", 'RansomBackup FREE', 'OK', 'Information') | Out-Null
} catch {
    New-Item -ItemType Directory -Force -Path $rbPaths.Logs | Out-Null
    Add-Content -LiteralPath (Join-Path $rbPaths.Logs 'install.log') -Encoding UTF8 -Value "$(Get-Date -Format s) $($_.Exception.ToString())"
    [Windows.Forms.MessageBox]::Show("$(Get-RBText 'Configurazione non completata.' $script:Language)`n`n$($_.Exception.Message)`n`n$(Get-RBText 'Dettagli salvati nel log di installazione.' $script:Language)", 'RansomBackup FREE', 'OK', 'Error') | Out-Null
    exit 1
} finally {
    Clear-RBResticEnvironment
}
