<#
.SYNOPSIS
    Yangquan Wedding - Start local PHP server
.DESCRIPTION
    First-run prompt for desktop install, then start PHP built-in web server
#>
#Requires -Version 2

[CmdletBinding()]
param(
    [switch]$Silent
)

$ErrorActionPreference = "Continue"

# ===== 基本信息 =====
$APP_NAME    = "阳泉婚礼宝典"
$APP_URL     = "http://127.0.0.1:{0}/index.php"
$APP_PORT    = 8080
$APP_TIMEOUT = 2

# ===== 路径解析 =====
$ScriptDir  = Split-Path -Parent $MyInvocation.MyCommand.Definition
$PhpExe     = Join-Path $ScriptDir "php\php.exe"
$InstallFlag = Join-Path $ScriptDir ".installed"
$InstallPs1  = Join-Path $ScriptDir "install.ps1"
$StopPs1     = Join-Path $ScriptDir "stop.ps1"
$TmpDir      = Join-Path $ScriptDir "tmp"

# ===== 颜色输出 =====
function Write-Color($Text, $Color) {
    if ($Color) {
        Write-Host -ForegroundColor $Color $Text
    } else {
        Write-Host $Text
    }
}

# ===== 主程序 =====
Write-Color "============================================" "Cyan"
Write-Color ("  " + $APP_NAME + " - Windows 便携版 / 桌面版") "Cyan"
Write-Color "============================================" "Cyan"
Write-Color ""

# ---------- 首次运行：询问是否安装桌面版 ----------
if (-not (Test-Path $InstallFlag) -and -not $Silent) {
    Write-Color "检测到这是您首次运行。" "Yellow"
    Write-Color ""
    Write-Color "  安装桌面版会创建以下内容："
    Write-Color "    - 桌面快捷方式（带自定义图标）"
    Write-Color "    - 开始菜单目录（启动/停止/卸载/直接访问）"
    Write-Color "    - 控制面板 -> 程序和功能 -> 卸载项"
    Write-Color ""
    Write-Color "  是否立即安装桌面版？(Y/n): " "White"
    $ans = Read-Host ""
    if ($ans -ne "n" -and $ans -ne "N") {
        Write-Color ""
        Write-Color "[信息] 正在启动桌面版安装程序..." "Cyan"
        & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $InstallPs1
        Write-Color "继续启动服务器..." "Green"
        Write-Color ""
    }
    Write-Color ""
}

# ---------- 检查 PHP ----------
if (-not (Test-Path $PhpExe)) {
    Write-Color "[错误] 未找到 php\php.exe" "Red"
    Write-Color "请确保本脚本在正确的目录中运行" "Red"
    if (-not $Silent) { Read-Host "按 Enter 键退出" }
    exit 1
}

# ---------- 端口检测 ----------
$port = $APP_PORT
foreach ($p in @(8080, 8088, 8090, 8092, 8094, 8096, 8098)) {
    $inUse = netstat -ano | Select-String (":$p\s+.*LISTENING")
    if (-not $inUse) {
        $port = $p
        break
    }
}
if ($port -ne $APP_PORT) {
    Write-Color ("[警告] 端口 " + $APP_PORT + " 已被占用，使用端口 " + $port) "Yellow"
}

# ---------- 创建临时目录 ----------
if (-not (Test-Path $TmpDir)) {
    New-Item -ItemType Directory -Path $TmpDir | Out-Null
}

# ---------- 设置 PHP 环境并启动 ----------
$env:PHPRC = Join-Path $ScriptDir "php"
$env:PHP_INI_SCAN_DIR = Join-Path $ScriptDir "php\conf.d"

Write-Color ("[信息] 正在启动 PHP 服务器 (端口 " + $port + ")...") "Cyan"
Write-Color ("[信息] 地址: http://127.0.0.1:" + $port) "Green"
Write-Color "[信息] 按 Ctrl+C 停止服务器" "Gray"
Write-Color ""

# 启动 PHP 服务器
$phpArgs = @(
    "-S", "127.0.0.1:$port",
    "-t", $ScriptDir,
    "-d", "display_errors=On",
    "-d", "date.timezone=Asia/Shanghai",
    "-d", "upload_max_filesize=50M",
    "-d", "post_max_size=50M",
    "-d", "memory_limit=256M"
)
$phpProc = Start-Process -FilePath $PhpExe -ArgumentList $phpArgs -PassThru -WindowStyle Hidden

# 等待服务器启动
Start-Sleep -Seconds 2

# 打开浏览器
$url = "http://127.0.0.1:" + $port + "/index.php"
Write-Color "[信息] 正在打开浏览器..." "Cyan"
Start-Process $url

Write-Color ""
Write-Color "============================================" "Green"
Write-Color "  服务器已启动！" "Green"
Write-Color ("  访问地址: http://127.0.0.1:" + $port) "Green"
Write-Color ""
Write-Color "  关闭此窗口将停止服务器" "Gray"
Write-Color "============================================" "Green"
Write-Color ""

# ---------- 等待用户输入后停止 ----------
if (-not $Silent) {
    Write-Color "  按任意键停止服务器..." "Yellow"
    # PS 2.0 兼容的等待方式
    $dummy = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}

# ---------- 停止服务器 ----------
Write-Color ""
Write-Color "[信息] 正在停止服务器..." "Cyan"
try {
    if (-not $phpProc.HasExited) {
        Stop-Process -Id $phpProc.Id -Force -ErrorAction SilentlyContinue
    }
} catch { }

# 确保所有 PHP 子进程也被清理
Get-Process php -ErrorAction SilentlyContinue | ForEach-Object {
    try { Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue } catch { }
}

Write-Color "[信息] 服务器已停止" "Green"
if (-not $Silent) {
    Start-Sleep -Seconds 2
}
