$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'Common.ps1')
. (Join-Path $PSScriptRoot 'UIHelpers.ps1')
Initialize-RBWindowsUI

try {
    $state = Get-RBConfiguration
    $language = Get-RBLanguage $state
    $en = $language -eq 'en'
    $account = Get-RBAccountState -State $state
    if ([int64]$account.used_bytes -lt [int64]$account.quota_bytes) {
        [Windows.Forms.MessageBox]::Show($(if($en){'You can start again only after reaching the current FREE quota.'}else{'Puoi ricominciare soltanto dopo aver raggiunto la quota FREE attuale.'}), 'RansomBackup FREE', 'OK', 'Information') | Out-Null
        exit 0
    }
    if (-not (Show-RBRecoveryKeyWindow -RecoveryKey $state.Secrets.repository_password -Email $state.Config.email -Language $language -RequireConfirmation)) { exit 0 }

    $form = New-Object Windows.Forms.Form
    $form.Text = if($en){'Start again - RansomBackup FREE'}else{'Ricomincia - RansomBackup FREE'}
    $form.ClientSize = New-Object Drawing.Size(650, 410)
    $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'
    $title = New-Object Windows.Forms.Label
    $title.Text = if($en){'Create a separate FREE archive'}else{'Crea un nuovo archivio FREE separato'}
    $title.Font = New-Object Drawing.Font('Segoe UI Semibold',18); $title.Location=New-Object Drawing.Point(28,25);$title.AutoSize=$true;$form.Controls.Add($title)
    $warning = New-Object Windows.Forms.Label
    $warning.Text = if($en){"The previous archive is not transferred. It will be deleted after 60 days without qualifying activity. Its protected local credentials will be archived on this PC."}else{"Il vecchio archivio non viene trasferito. Sarà cancellato dopo 60 giorni senza attività valida. Le sue credenziali locali protette saranno archiviate su questo PC."}
    $warning.Location=New-Object Drawing.Point(30,75);$warning.Size=New-Object Drawing.Size(585,70);$warning.ForeColor=[Drawing.Color]::FromArgb(130,55,38);$form.Controls.Add($warning)
    $label = New-Object Windows.Forms.Label
    $label.Text=if($en){'New email address'}else{'Nuovo indirizzo email'};$label.Location=New-Object Drawing.Point(30,160);$label.AutoSize=$true;$form.Controls.Add($label)
    $email = New-Object Windows.Forms.TextBox
    $email.Location=New-Object Drawing.Point(30,187);$email.Size=New-Object Drawing.Size(585,30);$form.Controls.Add($email)
    $termsLink = New-Object Windows.Forms.LinkLabel
    $termsLink.Text=if($en){'Read the Terms of Use'}else{"Leggi le Condizioni d'uso"};$termsLink.Location=New-Object Drawing.Point(30,238);$termsLink.AutoSize=$true;$form.Controls.Add($termsLink)
    $termsLink.Add_LinkClicked({Start-Process $(if($en){'https://www.ransombackup.com/en/terms/'}else{'https://www.ransombackup.com/terms/'})})
    $accept = New-Object Windows.Forms.CheckBox
    $accept.Text=if($en){"I accept the Terms of Use and understand that the previous archive will be deleted."}else{"Accetto le Condizioni d'uso e confermo di aver compreso che il vecchio archivio sarà cancellato."};$accept.Location=New-Object Drawing.Point(30,270);$accept.Size=New-Object Drawing.Size(585,50);$form.Controls.Add($accept)
    $continue = New-Object Windows.Forms.Button
    $continue.Text=if($en){'Create new account'}else{'Crea il nuovo account'};$continue.Location=New-Object Drawing.Point(410,335);$continue.Size=New-Object Drawing.Size(205,44);Set-RBPrimaryButton $continue;$form.Controls.Add($continue)
    $continue.Add_Click({
        if($email.Text -notmatch '^[^\s@]+@[^\s@]+\.[^\s@]+$') {[Windows.Forms.MessageBox]::Show($(if($en){'Enter a valid new email address.'}else{'Inserisci un nuovo indirizzo email valido.'}),'RansomBackup FREE','OK','Warning')|Out-Null;return}
        if($email.Text.Trim().ToLowerInvariant() -eq ([string]$state.Config.email).ToLowerInvariant()) {[Windows.Forms.MessageBox]::Show($(if($en){'The new email must be different.'}else{'La nuova email deve essere diversa.'}),'RansomBackup FREE','OK','Warning')|Out-Null;return}
        if(-not $accept.Checked){[Windows.Forms.MessageBox]::Show($(if($en){'Accept the Terms of Use to continue.'}else{"Accetta le Condizioni d'uso per continuare."}),'RansomBackup FREE','OK','Warning')|Out-Null;return}
        $form.Tag='continue';$form.Close()
    })
    [void]$form.ShowDialog()
    if($form.Tag -ne 'continue'){exit 0}

    $newEmail=$email.Text.Trim().ToLowerInvariant()
    $payload=@{email=$newEmail;terms_version=$script:RBTermsVersion;terms_accepted=$true}|ConvertTo-Json
    $reset=Invoke-RestMethod -Method Post -Uri "$($state.Config.gateway)/api/v1/reset-enrollment-code" -Headers (Get-RBBasicHeader $state) -ContentType 'application/json' -Body $payload -TimeoutSec 30

    $archiveRoot=Join-Path $state.Paths.ArchivedAccounts ("$($state.Config.username)-"+(Get-Date -Format 'yyyyMMdd-HHmmss'))
    New-Item -ItemType Directory -Force -Path $archiveRoot | Out-Null
    Copy-Item -LiteralPath $state.Paths.Config -Destination (Join-Path $archiveRoot 'config.json')
    Copy-Item -LiteralPath $state.Paths.Secrets -Destination (Join-Path $archiveRoot 'secrets.json')
    & icacls.exe $archiveRoot /inheritance:r /grant:r "$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name):(OI)(CI)(F)" | Out-Null
    @(
        "RansomBackup FREE archived account"
        "Username: $($state.Config.username)"
        "Email: $($state.Config.email)"
        "Reset requested: $(Get-Date -Format s)"
        "Expected automatic deletion after 60 days without qualifying activity."
    ) | Set-Content -LiteralPath (Join-Path $archiveRoot 'README.txt') -Encoding UTF8

    & (Join-Path $PSScriptRoot 'SetupWizard.ps1') -Gateway $state.Config.gateway -EnrollmentCode $reset.enrollment_code -Language $language -Email $newEmail -ReplaceExisting
    if($LASTEXITCODE -ne 0){
        Copy-Item -LiteralPath (Join-Path $archiveRoot 'config.json') -Destination $state.Paths.Config -Force
        Copy-Item -LiteralPath (Join-Path $archiveRoot 'secrets.json') -Destination $state.Paths.Secrets -Force
        throw $(if($en){'The new account was not completed. The previous configuration has been restored.'}else{'Il nuovo account non è stato completato. La configurazione precedente è stata ripristinata.'})
    }
    [Windows.Forms.MessageBox]::Show($(if($en){'The new account is active. The previous protected credentials remain in the ArchivedAccounts folder.'}else{'Il nuovo account è attivo. Le credenziali protette del precedente restano nella cartella ArchivedAccounts.'}),'RansomBackup FREE','OK','Information')|Out-Null
} catch {
    [Windows.Forms.MessageBox]::Show($_.Exception.Message,'RansomBackup FREE','OK','Error')|Out-Null
    exit 1
}
