param(
  [string]$ProjectRoot = "C:\xampp\htdocs\ddb-new",
  [string]$PhpExe = "C:\xampp\php\php.exe",
  [string]$Hospital = "all"
)

$ErrorActionPreference = "Stop"
$logDir = Join-Path $ProjectRoot "storage\logs"
if (!(Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }

$script = Join-Path $ProjectRoot "public\executive-summary-refresh.php"
$latest = Join-Path $logDir "executive-summary-refresh-latest.log"
$history = Join-Path $logDir "executive-summary-refresh-history.log"

$stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"[$stamp] START hospital=$Hospital" | Out-File -FilePath $latest -Encoding UTF8 -Append
"[$stamp] START hospital=$Hospital" | Out-File -FilePath $history -Encoding UTF8 -Append

if (!(Test-Path $PhpExe)) {
  "[$stamp] ERROR php.exe not found: $PhpExe" | Out-File -FilePath $latest -Encoding UTF8 -Append
  exit 2
}
if (!(Test-Path $script)) {
  "[$stamp] ERROR refresh script not found: $script" | Out-File -FilePath $latest -Encoding UTF8 -Append
  exit 3
}

$output = & $PhpExe $script $Hospital 2>&1
$code = $LASTEXITCODE
$output | Out-File -FilePath $latest -Encoding UTF8 -Append
$output | Out-File -FilePath $history -Encoding UTF8 -Append
$end = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"[$end] END exit=$code" | Out-File -FilePath $latest -Encoding UTF8 -Append
"[$end] END exit=$code" | Out-File -FilePath $history -Encoding UTF8 -Append
exit $code
