# K_Recycle - one-click install (same pattern as RentRoom 2026)
# v1.0.4 - PostInstall runs from ZIP\install\ (never stale Program Files scripts)
$ErrorActionPreference = 'Stop'

function Test-IsAdmin {
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    $p = New-Object Security.Principal.WindowsPrincipal($id)
    return $p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Show-LogTail {
    param([string]$LogFile)
    if (Test-Path $LogFile) {
        Write-Host ''
        Write-Host '--- install.log (last 30 lines) ---'
        Get-Content -LiteralPath $LogFile -Tail 30 -Encoding UTF8
        Write-Host "--- Full log: $LogFile ---"
    }
    else {
        Write-Host "Log not found: $LogFile"
    }
}

if (-not (Test-IsAdmin)) {
    $arg = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`""
    $proc = Start-Process powershell.exe -Verb RunAs -ArgumentList $arg -Wait -PassThru
    exit $proc.ExitCode
}

$setupDir = $PSScriptRoot
$setupExe = Join-Path $setupDir 'K_Recycle_Setup.exe'
$postInstall = Join-Path $setupDir 'install\PostInstall.ps1'
$appDir = Join-Path ${env:ProgramFiles} 'K_Recycle'
$logFile = Join-Path $appDir 'install\install.log'

Write-Host ''
Write-Host '============================================'
Write-Host ' K_Recycle - Full Install (OneClick v1.0.4)'
Write-Host '============================================'
if (Test-Path (Join-Path $setupDir 'VERSION.txt')) {
    Get-Content (Join-Path $setupDir 'VERSION.txt') -Encoding UTF8 | ForEach-Object { Write-Host " $_" }
}
Write-Host ''

if (-not (Test-Path $setupExe)) {
    Write-Host 'ERROR: K_Recycle_Setup.exe not found in this folder.'
    Write-Host 'Download K_Recycle_OneClick.zip from the website and extract ALL files.'
    Read-Host 'Press Enter to exit'
    exit 1
}

if (-not (Test-Path $postInstall)) {
    Write-Host 'ERROR: install\PostInstall.ps1 not found in this folder.'
    Write-Host 'Your ZIP is incomplete or outdated. Download fresh ZIP from website.'
    Write-Host 'The ZIP must contain: install\, sql\, K_Recycle_Setup.exe, Install-OneClick.ps1'
    Read-Host 'Press Enter to exit'
    exit 1
}

$sqlScript = Join-Path $setupDir 'install\Install-SqlExpress.ps1'
if (-not (Test-Path $sqlScript)) {
    Write-Host "ERROR: Missing $sqlScript"
    Read-Host 'Press Enter to exit'
    exit 1
}
$sqlText = Get-Content $sqlScript -Raw -Encoding UTF8
if ($sqlText -match 'MEDIATYPE=ENU') {
    Write-Host 'ERROR: Old SQL script (ENU). Download fresh K_Recycle_OneClick.zip from website.'
    Read-Host 'Press Enter to exit'
    exit 1
}

Write-Host '[1/2] Installing program files...'
$setup = Start-Process -FilePath $setupExe -ArgumentList @(
    '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/MERGETASKS=desktopicon'
) -Wait -PassThru -NoNewWindow
if ($setup.ExitCode -ne 0) {
    Write-Host "ERROR: Setup failed (code $($setup.ExitCode))"
    Show-LogTail -LogFile $logFile
    Read-Host 'Press Enter to exit'
    exit 1
}

Write-Host ''
Write-Host '[2/2] .NET 4.8 + SQL Server + Database...'
Write-Host '      (scripts from this ZIP folder - same as RentRoom)'
Write-Host '      Needs Internet. 15-45 minutes. Do not close.'
Write-Host ''

& $postInstall -AppDir $appDir
if ($LASTEXITCODE -ne 0) {
    Write-Host "ERROR: PostInstall failed (code $LASTEXITCODE)"
    Show-LogTail -LogFile $logFile
    Read-Host 'Press Enter to exit'
    exit 1
}

$svc = Get-Service -Name 'MSSQL$SQLEXPRESS' -ErrorAction SilentlyContinue
if (-not $svc -or $svc.Status -ne 'Running') {
    Write-Host 'ERROR: SQL Server SQLEXPRESS is not running.'
    Show-LogTail -LogFile $logFile
    Read-Host 'Press Enter to exit'
    exit 1
}

Write-Host ''
Write-Host 'SUCCESS - Installation complete.'
$exe = Join-Path $appDir 'K_Recycle.exe'
if (Test-Path $exe) {
    Write-Host 'Starting K_Recycle...'
    Start-Process $exe
}
Read-Host 'Press Enter to exit'
exit 0
