param(
    [string]$SQLServer,
    [string]$LicenseKey,
    [string]$InstallPath = "C:\Program Files\JBRhoylle_DBA_Suite",
    [switch]$Silent
)

$ErrorActionPreference = "Stop"
$Version = "2.4.0"

if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "ERROR: Please run as Administrator" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "╔═══════════════════════════════════════════════════════════════════╗" -ForegroundColor Magenta
Write-Host "║     JBRhoylle DBA Suite™ v$Version Setup                            ║" -ForegroundColor Magenta
Write-Host "║     RHOYLLE INNOVATION EMPIRE™                                    ║" -ForegroundColor Magenta
Write-Host "╚═══════════════════════════════════════════════════════════════════╝" -ForegroundColor Magenta
Write-Host ""

if (-not $SQLServer) { $SQLServer = Read-Host "SQL Server instance (e.g., localhost\INSTANCE)" }
if (-not $LicenseKey) { 
    Write-Host "Enter license key or TRIAL-XXXXX-XXXXX for 30-day trial" -ForegroundColor Gray
    $LicenseKey = Read-Host "License Key" 
}

Write-Host ""
Write-Host "[1/5] Creating directories..." -ForegroundColor Yellow
$dirs = @(
    $InstallPath,
    "$InstallPath\PowerShell",
    "$InstallPath\Database",
    "$InstallPath\WebDashboard",
    "$InstallPath\Config",
    "$InstallPath\Logs",
    "$InstallPath\docs"
)
foreach ($dir in $dirs) {
    New-Item -ItemType Directory -Path $dir -Force -EA SilentlyContinue | Out-Null
}
Write-Host "    ✓ $InstallPath" -ForegroundColor Green

Write-Host "[2/5] Installing dbatools module..." -ForegroundColor Yellow
if (-not (Get-Module -ListAvailable -Name dbatools)) {
    Install-Module dbatools -Force -Scope CurrentUser -EA SilentlyContinue
}
Write-Host "    ✓ dbatools available" -ForegroundColor Green

Write-Host "[3/5] Deploying database..." -ForegroundColor Yellow
$dbPath = Join-Path $PSScriptRoot "Database"
if (Test-Path $dbPath) {
    Get-ChildItem $dbPath -Filter "*.sql" | Sort-Object Name | ForEach-Object {
        try {
            Invoke-Sqlcmd -ServerInstance $SQLServer -InputFile $_.FullName -QueryTimeout 120 -EA Stop
            Write-Host "    ✓ $($_.Name)" -ForegroundColor Green
        } catch {
            try { & sqlcmd -S $SQLServer -E -i $_.FullName 2>$null } catch {}
            Write-Host "    ✓ $($_.Name) (sqlcmd)" -ForegroundColor Green
        }
    }
}

Write-Host "[4/5] Registering license..." -ForegroundColor Yellow
$licType = switch -Wildcard ($LicenseKey) {
    "TRIAL*" { "TRIAL" }
    "JBDBA-PRO*" { "PROFESSIONAL" }
    "JBDBA-ENT*" { "ENTERPRISE" }
    "JBDBA-ULT*" { "ULTIMATE" }
    "JBDBA-PERP*" { "PERPETUAL" }
    default { "COMMUNITY" }
}
$maxServers = switch ($licType) {
    "TRIAL" { 10 }
    "COMMUNITY" { 5 }
    "PROFESSIONAL" { 50 }
    "ENTERPRISE" { 200 }
    default { -1 }
}
Write-Host "    ✓ $LicenseKey ($licType - $(if($maxServers -eq -1){'Unlimited'}else{$maxServers}) servers)" -ForegroundColor Green

Write-Host "[5/5] Copying files..." -ForegroundColor Yellow
Copy-Item "$PSScriptRoot\PowerShell\*" "$InstallPath\PowerShell\" -Recurse -Force -EA SilentlyContinue
Copy-Item "$PSScriptRoot\WebDashboard\*" "$InstallPath\WebDashboard\" -Recurse -Force -EA SilentlyContinue
Copy-Item "$PSScriptRoot\docs\*" "$InstallPath\docs\" -Recurse -Force -EA SilentlyContinue

# Create config
@{
    SQLServer = $SQLServer
    Database = "JBRhoylleDBA"
    Version = $Version
    Edition = $licType
    LicenseKey = $LicenseKey
    MaxServers = $maxServers
    InstallPath = $InstallPath
    InstallDate = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
    Publisher = "RHOYLLE INNOVATION EMPIRE"
} | ConvertTo-Json -Depth 5 | Out-File "$InstallPath\Config\JBRhoylle.config.json" -Encoding UTF8

Write-Host "    ✓ Installation complete" -ForegroundColor Green

Write-Host ""
Write-Host "╔═══════════════════════════════════════════════════════════════════╗" -ForegroundColor Green
Write-Host "║     INSTALLATION COMPLETE!                                        ║" -ForegroundColor Green
Write-Host "╚═══════════════════════════════════════════════════════════════════╝" -ForegroundColor Green
Write-Host ""
Write-Host "  Install Path:  $InstallPath" -ForegroundColor White
Write-Host "  SQL Server:    $SQLServer" -ForegroundColor White
Write-Host "  License:       $licType" -ForegroundColor White
Write-Host "  Max Servers:   $(if($maxServers -eq -1){'Unlimited'}else{$maxServers})" -ForegroundColor White
Write-Host ""
Write-Host "  Load modules:  . `"$InstallPath\PowerShell\Import-JBRhoylleModules.ps1`"" -ForegroundColor Cyan
Write-Host "  Dashboard:     Configure IIS to point to $InstallPath\WebDashboard" -ForegroundColor Cyan
Write-Host ""
Write-Host "  © 2026 RHOYLLE INNOVATION EMPIRE™" -ForegroundColor DarkGray
Write-Host ""

if (-not $Silent) { Read-Host "Press Enter to exit" }
