# Shared helper: resolve PHP 8.2+ for Laravel 11 (see serve.ps1 / migrate.ps1).
function Get-LaravelPhp {
    param(
        [Parameter(Mandatory)]
        [string] $ProjectRoot
    )

    $candidates = @(
        $env:LARAVEL_PHP
        (Join-Path $ProjectRoot "tools\php\php.exe")
        "C:\php82\php.exe"
        "C:\php83\php.exe"
        "C:\php\php.exe"
    ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }

    $phpExe = $null
    foreach ($c in $candidates) {
        $phpExe = $c
        break
    }

    if (-not $phpExe) {
        $phpExe = (Get-Command php -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source)
    }

    if (-not $phpExe -or -not (Test-Path -LiteralPath $phpExe)) {
        throw "No php.exe found. Install PHP 8.2+ and add it to PATH, or set LARAVEL_PHP to its full path."
    }

    $verLine = & $phpExe -r "echo PHP_VERSION;" 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "Could not run PHP at: $phpExe"
    }

    $m = if ($verLine -match '^(\d+\.\d+\.\d+)') { $Matches[1] } else { '0.0.0' }
    $ver = [Version]$m
    if ($ver -lt [Version]"8.2.0") {
        Write-Host "This project requires PHP >= 8.2.0 (Laravel 11). Current: $verLine" -ForegroundColor Red
        Write-Host "Path used: $phpExe" -ForegroundColor Yellow
        Write-Host ""
        Write-Host "Fix options:" -ForegroundColor Cyan
        Write-Host '  1) Install PHP 8.2+ from https://windows.php.net/download/ (VS16 x64). Extract to e.g. C:\php82\'
        Write-Host '  2) Enable openssl, mbstring, pdo_mysql, mysqli, curl, zip, fileinfo in php.ini'
        Write-Host '  3) Then set LARAVEL_PHP to that php.exe for this session, e.g.: $env:LARAVEL_PHP = "C:\php82\php.exe"'
        Write-Host "  4) Or copy that PHP folder into $(Join-Path $ProjectRoot 'tools\php')"
        exit 1
    }

    return @{ PhpExe = $phpExe; VersionLine = $verLine }
}
