# iWifiMonitor - Windows Uninstall Script
# Run Uninstall.bat to uninstall (auto-elevates to Administrator)

$ErrorActionPreference = "Stop"

# Verify running as admin
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "ERROR: This script requires Administrator privileges." -ForegroundColor Red
    Write-Host "Please run Uninstall.bat instead." -ForegroundColor Yellow
    exit 1
}

$AppName = "iWiFiMonitor"
$ServiceName = "iWiFiMonitor"
$WebServiceName = "iWiFiMonitorWeb"
$InstallDir = "$env:ProgramFiles\$AppName"
$DataDir = "$env:ProgramData\$AppName"

Write-Host ""
Write-Host "=========================================="
Write-Host "   iWifiMonitor - Uninstaller"
Write-Host "=========================================="
Write-Host ""

# Stop services
Write-Host "Stopping services..."
Stop-Service -Name $WebServiceName -ErrorAction SilentlyContinue
Stop-Service -Name $ServiceName -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2

# Remove services
Write-Host "Removing services..."
sc.exe delete $WebServiceName 2>$null
sc.exe delete $ServiceName 2>$null
Start-Sleep -Seconds 1

# Remove firewall rule
Write-Host "Removing firewall rule..."
Remove-NetFirewallRule -DisplayName "iWifiMonitor Web UI" -ErrorAction SilentlyContinue

# Remove shortcuts
Write-Host "Removing shortcuts..."
$startMenuDir = "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\$AppName"
if (Test-Path $startMenuDir) {
    Remove-Item -Path $startMenuDir -Recurse -Force
}
$desktopShortcut = "$env:PUBLIC\Desktop\iWifiMonitor.url"
if (Test-Path $desktopShortcut) {
    Remove-Item -Path $desktopShortcut -Force
}

# Remove application files
Write-Host "Removing application files..."
if (Test-Path $InstallDir) {
    Remove-Item -Path $InstallDir -Recurse -Force
}

# Ask about data
Write-Host ""
$keepData = Read-Host "Keep your data (connection history, device list, settings)? (Y/n)"
if ($keepData -eq "n" -or $keepData -eq "N") {
    Write-Host "Removing data directory..."
    if (Test-Path $DataDir) {
        Remove-Item -Path $DataDir -Recurse -Force
    }
} else {
    Write-Host "Data preserved at: $DataDir"
}

Write-Host ""
Write-Host "=========================================="
Write-Host "   Uninstall Complete!"
Write-Host "=========================================="
Write-Host ""
