# ============================================================
#  PDV Potpis Helper v4.1
#  Autor: TehnoKlik
#  Web: www.tehnoklik.ba
# ============================================================

$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# ---- Admin provjera ----
$current   = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($current)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    [System.Windows.Forms.MessageBox]::Show(
        "Molimo pokrenite ovaj program kao Administrator.`n`nDesni klik -> Pokreni kao administrator",
        "Potrebne admin dozvole", "OK", "Warning")
    exit 1
}

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$nexusMSI  = Join-Path $scriptDir "personal-5.17.0_amd64.msi"
if (-not (Test-Path $nexusMSI)) {
    $nexusMSI = Join-Path $scriptDir "personal-5_17_0_amd64.msi"
}

# ---- Helper funkcije ----
function Get-NexusEntry {
    $roots = @(
        'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
        'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
    )
    foreach ($root in $roots) {
        $hit = Get-ItemProperty -Path $root -ErrorAction SilentlyContinue |
            Where-Object { $_.DisplayName -and ($_.DisplayName -match 'Nexus' -or $_.Publisher -match 'Nexus') } |
            Select-Object -First 1
        if ($hit) { return $hit }
    }
    return $null
}

function Get-NexusInstalled { return ($null -ne (Get-NexusEntry)) }

function Stop-NexusProcesses {
    @('personal', 'personal64', 'personalmonitor', 'nexus', 'plugout', 'plugout64') | ForEach-Object {
        Get-Process -Name $_ -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
    }
    Start-Sleep -Milliseconds 800
}

function Uninstall-Nexus {
    Stop-NexusProcesses
    $entry = Get-NexusEntry
    if (-not $entry) { return $false }
    $guid = $entry.PSChildName
    Start-Process "msiexec.exe" -ArgumentList "/x $guid /qn /norestart" -Wait
    Start-Sleep -Seconds 3
    return (-not (Get-NexusInstalled))
}

function Install-Nexus {
    if (-not (Test-Path $nexusMSI)) { return $false }
    Start-Process "msiexec.exe" -ArgumentList "/i `"$nexusMSI`" /qn /norestart" -Wait
    Start-Sleep -Seconds 4
    return (Get-NexusInstalled)
}

function Find-TaxApp {
    $paths = @(
        'C:\Program Files (x86)\DigitalSignature\TaxationDigitalSignature.exe',
        'C:\Program Files\DigitalSignature\TaxationDigitalSignature.exe'
    )
    foreach ($p in $paths) { if (Test-Path $p) { return $p } }
    foreach ($root in @('C:\Program Files (x86)', 'C:\Program Files')) {
        $hit = Get-ChildItem -Path $root -Filter 'TaxationDigitalSignature.exe' -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
        if ($hit) { return $hit.FullName }
    }
    return $null
}

# ---- Crtanje ikone (pero/olovka) ----
function New-PenIcon($size, $color) {
    $bmp = New-Object System.Drawing.Bitmap($size, $size)
    $g   = [System.Drawing.Graphics]::FromImage($bmp)
    $g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
    $g.Clear([System.Drawing.Color]::Transparent)
    $pen   = New-Object System.Drawing.Pen($color, 2)
    $brush = New-Object System.Drawing.SolidBrush($color)
    # Tijelo olovke
    $body = New-Object System.Drawing.Drawing2D.GraphicsPath
    $body.AddPolygon(@(
        [System.Drawing.PointF]::new($size*0.25, $size*0.15),
        [System.Drawing.PointF]::new($size*0.75, $size*0.15),
        [System.Drawing.PointF]::new($size*0.75, $size*0.72),
        [System.Drawing.PointF]::new($size*0.25, $size*0.72)
    ))
    $g.FillPath($brush, $body)
    # Vrh olovke
    $tip = New-Object System.Drawing.Drawing2D.GraphicsPath
    $tip.AddPolygon(@(
        [System.Drawing.PointF]::new($size*0.25, $size*0.72),
        [System.Drawing.PointF]::new($size*0.75, $size*0.72),
        [System.Drawing.PointF]::new($size*0.50, $size*0.92)
    ))
    $tipBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(220,180,60))
    $g.FillPath($tipBrush, $tip)
    # Gumica
    $eraserBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(220,100,100))
    $g.FillRectangle($eraserBrush, $size*0.25, $size*0.05, $size*0.50, $size*0.12)
    $g.Dispose()
    return $bmp
}

# ================================================================
#  GUI
# ================================================================
$form = New-Object System.Windows.Forms.Form
$form.Text            = "PDV Potpis Helper"
$form.Size            = New-Object System.Drawing.Size(460, 430)
$form.StartPosition   = "CenterScreen"
$form.FormBorderStyle = "FixedSingle"
$form.MaximizeBox     = $false
$form.BackColor       = [System.Drawing.Color]::FromArgb(245,245,250)

# Ikona forme
$formIcon = New-PenIcon 32 ([System.Drawing.Color]::FromArgb(30,60,120))
$form.Icon = [System.Drawing.Icon]::FromHandle($formIcon.GetHicon())

# Naslov
$lblTitle = New-Object System.Windows.Forms.Label
$lblTitle.Text      = "PDV Potpis Helper"
$lblTitle.Font      = New-Object System.Drawing.Font("Segoe UI",13,[System.Drawing.FontStyle]::Bold)
$lblTitle.Location  = New-Object System.Drawing.Point(20,15)
$lblTitle.Size      = New-Object System.Drawing.Size(420,30)
$lblTitle.ForeColor = [System.Drawing.Color]::FromArgb(30,60,120)
$form.Controls.Add($lblTitle)

$lblSub = New-Object System.Windows.Forms.Label
$lblSub.Text      = "Rjesenje konflikta: Nexus Personal (KEP) vs UINO Digitalni potpis"
$lblSub.Font      = New-Object System.Drawing.Font("Segoe UI",8)
$lblSub.Location  = New-Object System.Drawing.Point(20,47)
$lblSub.Size      = New-Object System.Drawing.Size(420,18)
$lblSub.ForeColor = [System.Drawing.Color]::Gray
$form.Controls.Add($lblSub)

$sep = New-Object System.Windows.Forms.Panel
$sep.Location  = New-Object System.Drawing.Point(20,70)
$sep.Size      = New-Object System.Drawing.Size(415,2)
$sep.BackColor = [System.Drawing.Color]::FromArgb(200,200,220)
$form.Controls.Add($sep)

# Status box
$pnlStatus = New-Object System.Windows.Forms.Panel
$pnlStatus.Location    = New-Object System.Drawing.Point(20,82)
$pnlStatus.Size        = New-Object System.Drawing.Size(415,62)
$pnlStatus.BackColor   = [System.Drawing.Color]::White
$pnlStatus.BorderStyle = "FixedSingle"
$form.Controls.Add($pnlStatus)

# PictureBox za ikonu statusa (pero)
$picStatus = New-Object System.Windows.Forms.PictureBox
$picStatus.Location  = New-Object System.Drawing.Point(10,8)
$picStatus.Size      = New-Object System.Drawing.Size(38,44)
$picStatus.SizeMode  = "Zoom"
$pnlStatus.Controls.Add($picStatus)

$lblStatus = New-Object System.Windows.Forms.Label
$lblStatus.Location = New-Object System.Drawing.Point(54,8)
$lblStatus.Size     = New-Object System.Drawing.Size(350,48)
$lblStatus.Font     = New-Object System.Drawing.Font("Segoe UI",9,[System.Drawing.FontStyle]::Bold)
$pnlStatus.Controls.Add($lblStatus)

# MSI upozorenje
$pnlWarn = New-Object System.Windows.Forms.Panel
$pnlWarn.Location    = New-Object System.Drawing.Point(20,154)
$pnlWarn.Size        = New-Object System.Drawing.Size(415,26)
$pnlWarn.BackColor   = [System.Drawing.Color]::FromArgb(255,240,200)
$pnlWarn.BorderStyle = "FixedSingle"
$pnlWarn.Visible     = $false
$form.Controls.Add($pnlWarn)

$lblWarn = New-Object System.Windows.Forms.Label
$lblWarn.Text      = "  UPOZORENJE: personal-5.17.0_amd64.msi nije pronadjen!"
$lblWarn.Font      = New-Object System.Drawing.Font("Segoe UI",8,[System.Drawing.FontStyle]::Bold)
$lblWarn.Location  = New-Object System.Drawing.Point(4,5)
$lblWarn.Size      = New-Object System.Drawing.Size(405,16)
$lblWarn.ForeColor = [System.Drawing.Color]::FromArgb(160,80,0)
$pnlWarn.Controls.Add($lblWarn)

# Progress
$progressBar = New-Object System.Windows.Forms.ProgressBar
$progressBar.Location = New-Object System.Drawing.Point(20,154)
$progressBar.Size     = New-Object System.Drawing.Size(415,14)
$progressBar.Style    = "Marquee"
$progressBar.Visible  = $false
$form.Controls.Add($progressBar)

$lblProgress = New-Object System.Windows.Forms.Label
$lblProgress.Location  = New-Object System.Drawing.Point(20,171)
$lblProgress.Size      = New-Object System.Drawing.Size(415,16)
$lblProgress.Font      = New-Object System.Drawing.Font("Segoe UI",8,[System.Drawing.FontStyle]::Italic)
$lblProgress.ForeColor = [System.Drawing.Color]::FromArgb(80,80,160)
$lblProgress.Visible   = $false
$form.Controls.Add($lblProgress)

# Korak 1
$lblStep1 = New-Object System.Windows.Forms.Label
$lblStep1.Text      = "KORAK 1 - Prije potpisivanja PDV prijave:"
$lblStep1.Font      = New-Object System.Drawing.Font("Segoe UI",9,[System.Drawing.FontStyle]::Bold)
$lblStep1.Location  = New-Object System.Drawing.Point(20,196)
$lblStep1.Size      = New-Object System.Drawing.Size(415,20)
$lblStep1.ForeColor = [System.Drawing.Color]::FromArgb(60,60,60)
$form.Controls.Add($lblStep1)

$btnUninstall = New-Object System.Windows.Forms.Button
$btnUninstall.Location  = New-Object System.Drawing.Point(20,219)
$btnUninstall.Size      = New-Object System.Drawing.Size(415,55)
$btnUninstall.Text      = "  ONEMOGUCI Nexus Personal  ->  Otvori Digitalni potpis"
$btnUninstall.Font      = New-Object System.Drawing.Font("Segoe UI",10,[System.Drawing.FontStyle]::Bold)
$btnUninstall.BackColor = [System.Drawing.Color]::FromArgb(200,60,40)
$btnUninstall.ForeColor = [System.Drawing.Color]::White
$btnUninstall.FlatStyle = "Flat"
$btnUninstall.FlatAppearance.BorderSize = 0
$btnUninstall.Cursor    = [System.Windows.Forms.Cursors]::Hand
$form.Controls.Add($btnUninstall)

# Korak 2
$lblStep2 = New-Object System.Windows.Forms.Label
$lblStep2.Text      = "KORAK 2 - Nakon sto ste potpisali PDV prijavu:"
$lblStep2.Font      = New-Object System.Drawing.Font("Segoe UI",9,[System.Drawing.FontStyle]::Bold)
$lblStep2.Location  = New-Object System.Drawing.Point(20,288)
$lblStep2.Size      = New-Object System.Drawing.Size(415,20)
$lblStep2.ForeColor = [System.Drawing.Color]::FromArgb(60,60,60)
$form.Controls.Add($lblStep2)

$btnInstall = New-Object System.Windows.Forms.Button
$btnInstall.Location  = New-Object System.Drawing.Point(20,311)
$btnInstall.Size      = New-Object System.Drawing.Size(415,55)
$btnInstall.Text      = "  VRATI Nexus Personal  (Halcom KEP ponovo aktivan)"
$btnInstall.Font      = New-Object System.Drawing.Font("Segoe UI",10,[System.Drawing.FontStyle]::Bold)
$btnInstall.BackColor = [System.Drawing.Color]::FromArgb(30,130,70)
$btnInstall.ForeColor = [System.Drawing.Color]::White
$btnInstall.FlatStyle = "Flat"
$btnInstall.FlatAppearance.BorderSize = 0
$btnInstall.Cursor    = [System.Windows.Forms.Cursors]::Hand
$form.Controls.Add($btnInstall)

# Footer sa Tehnoklik brendingom
$lblFooter = New-Object System.Windows.Forms.Label
$lblFooter.Text      = "TehnoKlik  |  www.tehnoklik.ba  |  v4.1"
$lblFooter.Font      = New-Object System.Drawing.Font("Segoe UI",8)
$lblFooter.Location  = New-Object System.Drawing.Point(20,378)
$lblFooter.Size      = New-Object System.Drawing.Size(415,18)
$lblFooter.ForeColor = [System.Drawing.Color]::FromArgb(210,210,215)
$lblFooter.TextAlign = "MiddleCenter"
$form.Controls.Add($lblFooter)

function Set-Busy($busy, $text) {
    $progressBar.Visible  = $busy
    $lblProgress.Visible  = $busy
    $lblProgress.Text     = $text
    $pnlWarn.Visible      = $false
    $btnUninstall.Enabled = -not $busy
    $btnInstall.Enabled   = -not $busy
    $form.Refresh()
}

function Update-UI {
    $msiOk = Test-Path $nexusMSI
    if (Get-NexusInstalled) {
        $picStatus.Image     = New-PenIcon 38 ([System.Drawing.Color]::FromArgb(30,130,70))
        $lblStatus.Text      = "Nexus Personal je AKTIVAN`nHalcom KEP radi | UINO moze imati problem"
        $lblStatus.ForeColor = [System.Drawing.Color]::FromArgb(20,100,20)
        $btnUninstall.Enabled = $true
        $btnInstall.Enabled   = $false
        $pnlWarn.Visible      = $false
    } else {
        $picStatus.Image     = New-PenIcon 38 ([System.Drawing.Color]::FromArgb(200,60,40))
        $lblStatus.Text      = "Nexus Personal NIJE aktivan`nUINO Digitalni potpis ce raditi normalno"
        $lblStatus.ForeColor = [System.Drawing.Color]::FromArgb(180,60,0)
        $btnUninstall.Enabled = $false
        $btnInstall.Enabled   = $msiOk
        $pnlWarn.Visible      = -not $msiOk
    }
}

$btnUninstall.Add_Click({
    $r = [System.Windows.Forms.MessageBox]::Show(
        "Ovo ce privremeno onemoguciti Nexus Personal.`n`nNakon sto potpišete PDV prijavu, kliknite KORAK 2.`n`nNastaviti?",
        "Potvrda", "YesNo", "Question")
    if ($r -ne "Yes") { return }
    Set-Busy $true "Onemogucujem Nexus Personal, molimo sacekajte..."
    try {
        $ok = Uninstall-Nexus
        Set-Busy $false ""
        Update-UI
        if ($ok) {
            $taxApp = Find-TaxApp
            $msg = "Nexus Personal je onemogucen!`n`nSada potpišite PDV prijavu u aplikaciji Digitalni potpis.`nNakon sto zavrsiste, kliknite KORAK 2."
            if (-not $taxApp) { $msg += "`n`nNisam pronasao TaxationDigitalSignature.exe - otvorite ga rucno." }
            [System.Windows.Forms.MessageBox]::Show($msg, "Uspjeh", "OK", "Information")
            if ($taxApp) { Start-Process $taxApp }
        } else {
            [System.Windows.Forms.MessageBox]::Show("Onemogucavanje nije uspjelo. Pokusajte ponovo.", "Greska", "OK", "Error")
        }
    } catch {
        Set-Busy $false ""
        Update-UI
        [System.Windows.Forms.MessageBox]::Show("Greska: $_", "Greska", "OK", "Error")
    }
})

$btnInstall.Add_Click({
    Set-Busy $true "Vracam Nexus Personal, molimo sacekajte..."
    try {
        $ok = Install-Nexus
        Set-Busy $false ""
        Update-UI
        if ($ok) {
            [System.Windows.Forms.MessageBox]::Show(
                "Nexus Personal je ponovo aktivan!`n`nHalcom KEP kartica je dostupna.",
                "Uspjeh", "OK", "Information")
        } else {
            [System.Windows.Forms.MessageBox]::Show(
                "Instalacija mozda nije uspjela.`nProvjerite da li Nexus Personal radi.",
                "Upozorenje", "OK", "Warning")
        }
    } catch {
        Set-Busy $false ""
        Update-UI
        [System.Windows.Forms.MessageBox]::Show("Greska: $_", "Greska", "OK", "Error")
    }
})

Update-UI
[void]$form.ShowDialog()
