# IT Nexus Announcement Watcher
# Wird alle 15 Sekunden als SYSTEM ausgefuehrt
# Zeigt Ankuendigungen als Desktop-Popup fuer den eingeloggten Benutzer

param()
$cfg = Get-Content 'C:\ProgramData\IT Nexus Agent\config.json' -Raw | ConvertFrom-Json
$url = $cfg.server_url.TrimEnd('/')
$key = $cfg.agent_key

function Show-AnnDialog($ann) {
    $id      = $ann.id
    $dlg     = "C:\ProgramData\IT Nexus Agent\ann_$id.ps1"
    if (Test-Path $dlg) { return }

    $title   = ($ann.title   -replace "'", "''")
    $message = ($ann.message -replace "'", "''")
    $accent  = switch ($ann.type) { 'warning'{'220,50,50'} 'maintenance'{'245,158,11'} default{'99,102,241'} }
    $label   = switch ($ann.type) { 'warning'{'WICHTIGE WARNUNG'} 'maintenance'{'WARTUNGSANKUENDIGUNG'} default{'INFORMATION'} }
    $ackUrl  = "$url/api/announcements/$id/ack-agent"
    $n       = [System.Environment]::NewLine

    $headerColor = switch ($ann.type) { 'warning'{'220,53,69'} 'maintenance'{'255,140,0'} default{'0,120,212'} }
    $iconText    = switch ($ann.type) { 'warning'{'⚠'} 'maintenance'{'🔧'} default{'ℹ'} }

    $code  = "Add-Type -AssemblyName System.Windows.Forms,System.Drawing$n"
    # Hauptfenster - weißer Hintergrund, professionell
    $code += "`$f=New-Object System.Windows.Forms.Form;`$f.Text='IT Nexus Mitteilung';`$f.Size=New-Object System.Drawing.Size(480,320);`$f.StartPosition='CenterScreen';`$f.FormBorderStyle='FixedSingle';`$f.MaximizeBox=`$false;`$f.MinimizeBox=`$false;`$f.TopMost=`$true;`$f.BackColor=[System.Drawing.Color]::White$n"
    # Farbiger Header-Balken
    $code += "`$hdr=New-Object System.Windows.Forms.Panel;`$hdr.Size=New-Object System.Drawing.Size(480,56);`$hdr.Location=New-Object System.Drawing.Point(0,0);`$hdr.BackColor=[System.Drawing.Color]::FromArgb($headerColor);`$f.Controls.Add(`$hdr)$n"
    # Logo-Text links im Header
    $code += "`$logo=New-Object System.Windows.Forms.Label;`$logo.Text='IT Nexus';`$logo.Font=New-Object System.Drawing.Font('Segoe UI',11,[System.Drawing.FontStyle]::Bold);`$logo.ForeColor=[System.Drawing.Color]::White;`$logo.Location=New-Object System.Drawing.Point(16,8);`$logo.Size=New-Object System.Drawing.Size(120,20);`$hdr.Controls.Add(`$logo)$n"
    # Typ-Label im Header
    $code += "`$lbl=New-Object System.Windows.Forms.Label;`$lbl.Text='$label';`$lbl.Font=New-Object System.Drawing.Font('Segoe UI',8);`$lbl.ForeColor=[System.Drawing.Color]::FromArgb(220,240,255);`$lbl.Location=New-Object System.Drawing.Point(16,30);`$lbl.Size=New-Object System.Drawing.Size(420,18);`$hdr.Controls.Add(`$lbl)$n"
    # Titel
    $code += "`$lt=New-Object System.Windows.Forms.Label;`$lt.Text='$title';`$lt.Font=New-Object System.Drawing.Font('Segoe UI',12,[System.Drawing.FontStyle]::Bold);`$lt.ForeColor=[System.Drawing.Color]::FromArgb(30,30,30);`$lt.Location=New-Object System.Drawing.Point(16,72);`$lt.Size=New-Object System.Drawing.Size(444,28);`$f.Controls.Add(`$lt)$n"
    # Trennlinie
    $code += "`$sep=New-Object System.Windows.Forms.Panel;`$sep.Size=New-Object System.Drawing.Size(448,1);`$sep.Location=New-Object System.Drawing.Point(16,104);`$sep.BackColor=[System.Drawing.Color]::FromArgb(220,220,220);`$f.Controls.Add(`$sep)$n"
    # Nachricht
    $code += "`$lm=New-Object System.Windows.Forms.Label;`$lm.Text='$message';`$lm.Font=New-Object System.Drawing.Font('Segoe UI',10);`$lm.ForeColor=[System.Drawing.Color]::FromArgb(60,60,60);`$lm.Location=New-Object System.Drawing.Point(16,112);`$lm.Size=New-Object System.Drawing.Size(444,120);`$lm.AutoSize=`$false;`$f.Controls.Add(`$lm)$n"
    # Button
    $code += "`$btn=New-Object System.Windows.Forms.Button;`$btn.Text='✓  Gelesen und bestätigt';`$btn.Font=New-Object System.Drawing.Font('Segoe UI',10,[System.Drawing.FontStyle]::Bold);`$btn.ForeColor=[System.Drawing.Color]::White;`$btn.BackColor=[System.Drawing.Color]::FromArgb($headerColor);`$btn.FlatStyle='Flat';`$btn.FlatAppearance.BorderSize=0;`$btn.Location=New-Object System.Drawing.Point(16,244);`$btn.Size=New-Object System.Drawing.Size(444,36);`$btn.DialogResult=[System.Windows.Forms.DialogResult]::OK;`$f.Controls.Add(`$btn);`$f.AcceptButton=`$btn$n"
    $code += "if(`$f.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){$n"
    $code += "    `$b=[System.Text.Encoding]::UTF8.GetBytes('{""hostname"":""+`$env:COMPUTERNAME+'""}')$n"
    $code += "    `$r=[System.Net.WebRequest]::Create('$ackUrl')$n"
    $code += "    `$r.Method='POST';`$r.ContentType='application/json';`$r.Headers.Add('X-Agent-Key','$key');`$r.ContentLength=`$b.Length$n"
    $code += "    `$s=`$r.GetRequestStream();`$s.Write(`$b,0,`$b.Length);`$s.Close()$n"
    $code += "    try{`$r.GetResponse().Close()}catch{}$n"
    $code += "    Remove-Item '$dlg' -Force -ErrorAction SilentlyContinue$n"
    $code += "}$n"

    $code | Out-File -FilePath $dlg -Encoding UTF8 -Force

    $loggedUser = (Get-CimInstance Win32_ComputerSystem).UserName
    if ($loggedUser) {
        $tn = "ITNexus-AnnDlg-$id"
        Unregister-ScheduledTask -TaskName $tn -Confirm:$false -ErrorAction SilentlyContinue
        $a = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-ExecutionPolicy Bypass -WindowStyle Hidden -File `"$dlg`""
        $t = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(2)
        $p = New-ScheduledTaskPrincipal -UserId $loggedUser -LogonType Interactive -RunLevel Limited
        $s = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 60) -StartWhenAvailable
        Register-ScheduledTask -TaskName $tn -Action $a -Trigger $t -Principal $p -Settings $s -Force | Out-Null
    }
}

try {
    $body = [System.Text.Encoding]::UTF8.GetBytes('{"hostname":"'+$env:COMPUTERNAME+'"}')
    $req  = [System.Net.WebRequest]::Create("$url/api/monitoring/announcements-poll")
    $req.Method = 'POST'; $req.ContentType = 'application/json'
    $req.Headers.Add('X-Agent-Key', $key); $req.ContentLength = $body.Length
    $st = $req.GetRequestStream(); $st.Write($body, 0, $body.Length); $st.Close()
    $rd = New-Object System.IO.StreamReader($req.GetResponse().GetResponseStream())
    $data = $rd.ReadToEnd() | ConvertFrom-Json
    if ($data.announcements) { foreach ($a in $data.announcements) { Show-AnnDialog $a } }
} catch {}
