# Check-MachineNumber.ps1 - Logon-triggered check for placeholder machine
# number. If UDC or eDNC are still at 9999, pops an InputBox for the user
# to enter the real number. On success, unregisters the scheduled task so
# the prompt never appears again.
#
# Runs as the LOGGED-IN USER (not SYSTEM) because it needs to show GUI.
# Writing to ProgramData + HKLM is possible because 02-MachineNumberACLs.ps1
# pre-granted BUILTIN\Users write access on those specific targets during
# imaging.
#
# Registered/unregistered by Configure-PC.ps1 (item 6 in the toggle list).

# --- Transcript logging ---
$logDir = 'C:\Logs\SFLD'
if (-not (Test-Path $logDir)) {
    try { New-Item -ItemType Directory -Path $logDir -Force | Out-Null } catch { $logDir = $env:TEMP }
}
$transcriptPath = Join-Path $logDir 'Check-MachineNumber.log'
try { Start-Transcript -Path $transcriptPath -Append -Force | Out-Null } catch {}
Write-Host "Check-MachineNumber.ps1 starting $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Host "Running as: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"

. "$PSScriptRoot\lib\Get-PCProfile.ps1"
. "$PSScriptRoot\lib\Update-MachineNumber.ps1"

Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms

$taskName = 'Check Machine Number'
$site     = if ($siteConfig) { $siteConfig.siteName } else { 'West Jefferson' }

# --- Read current values ---
$currentMN   = Get-CurrentMachineNumber
$currentUdc  = $currentMN.Udc
$currentEdnc = $currentMN.Ednc

# --- Check if placeholder ---
Write-Host "UDC  machine number: $(if ($currentUdc) { $currentUdc } else { '(not found)' })"
Write-Host "eDNC machine number: $(if ($currentEdnc) { $currentEdnc } else { '(not found)' })"

if ($currentUdc -ne '9999' -and $currentEdnc -ne '9999') {
    Write-Host "Machine number is set (not 9999). Unregistering task and exiting."
    try {
        Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
    } catch {}
    try { Stop-Transcript | Out-Null } catch {}
    exit 0
}

Write-Host "Placeholder 9999 detected - showing prompt."

# --- Show prompt ---
$promptLines = @()
$promptLines += "The machine number on this PC is still set to the"
$promptLines += "placeholder value (9999). Please enter the correct"
$promptLines += "machine number for this workstation."
$promptLines += ""
if ($currentUdc)  { $promptLines += "Current UDC:  $currentUdc" }
if ($currentEdnc) { $promptLines += "Current eDNC: $currentEdnc" }
$promptLines += ""
$promptLines += "Enter the new Machine Number:"

$prompt = $promptLines -join "`n"
$new = [Microsoft.VisualBasic.Interaction]::InputBox($prompt, "Set Machine Number", "")

if ([string]::IsNullOrWhiteSpace($new)) {
    Write-Host "User cancelled. Will prompt again next logon."
    try { Stop-Transcript | Out-Null } catch {}
    exit 0
}

$new = $new.Trim()

# --- Validate ---
if ($new -notmatch '^\d+$') {
    Write-Host "Invalid input: '$new' (not digits only). Will prompt again next logon."
    [System.Windows.Forms.MessageBox]::Show(
        "Machine number must be digits only.`n`nYou entered: '$new'`n`nThe prompt will appear again at next logon.",
        "Invalid Machine Number",
        [System.Windows.Forms.MessageBoxButtons]::OK,
        [System.Windows.Forms.MessageBoxIcon]::Error
    ) | Out-Null
    try { Stop-Transcript | Out-Null } catch {}
    exit 0
}

# --- Update via shared helper ---
$mnResult = Update-MachineNumber -NewNumber $new -Site $site

$results = @()
if ($mnResult.UdcUpdated)  { $results += "UDC updated to $new" }
if ($mnResult.EdncUpdated) { $results += "eDNC updated to $new" }
foreach ($err in $mnResult.Errors) { $results += $err -replace '^', 'FAILED: ' }

# --- Show result ---
$summary = ($results -join "`n") + "`n`nTo apply eDNC changes, restart any running DncMain.exe."
[System.Windows.Forms.MessageBox]::Show(
    $summary,
    "Machine Number Updated",
    [System.Windows.Forms.MessageBoxButtons]::OK,
    [System.Windows.Forms.MessageBoxIcon]::Information
) | Out-Null

# --- Unregister task on success ---
Write-Host "Results: $($results -join '; ')"
$anyFail = $results | Where-Object { $_ -match 'FAILED' }
if (-not $anyFail) {
    Write-Host "All updates succeeded. Unregistering logon task."
    try {
        Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
    } catch {}
} else {
    Write-Host "Some updates failed. Task stays registered - will prompt again next logon."
}

Write-Host "Check-MachineNumber.ps1 finished $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
try { Stop-Transcript | Out-Null } catch {}
exit 0
