param(
  [string]$ProjectRoot = "C:\xampp\htdocs\ddb-new",
  [string]$PhpExe = "C:\xampp\php\php.exe",
  [string]$Hospital = "njch",
  [int]$IntervalMinutes = 15,
  [string]$TaskName = "HMH Executive Summary Refresh"
)

$ErrorActionPreference = "Stop"
$runnerPs1 = Join-Path $ProjectRoot "tools\run_executive_summary_refresh.ps1"
$runnerCmd = Join-Path $ProjectRoot "tools\run_executive_summary_refresh.cmd"

if (!(Test-Path $runnerPs1)) { throw "Runner not found: $runnerPs1" }
if (!(Test-Path $PhpExe)) { throw "php.exe not found: $PhpExe" }

$cmd = '@echo off' + [Environment]::NewLine +
       'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "' + $runnerPs1 + '" -ProjectRoot "' + $ProjectRoot + '" -PhpExe "' + $PhpExe + '" -Hospital "' + $Hospital + '"'
Set-Content -Path $runnerCmd -Value $cmd -Encoding ASCII

# Use schtasks because it is more tolerant across Windows editions and shows clear errors.
$createArgs = @('/Create','/TN',$TaskName,'/SC','MINUTE','/MO',[string]$IntervalMinutes,'/TR',$runnerCmd,'/F')
Write-Host "Creating task:" $TaskName
Write-Host "Runner:" $runnerCmd
$p = Start-Process -FilePath "schtasks.exe" -ArgumentList $createArgs -Wait -PassThru -NoNewWindow
if ($p.ExitCode -ne 0) {
  throw "schtasks failed with exit code $($p.ExitCode). Run PowerShell as Administrator."
}
Write-Host "Task created successfully."
Write-Host "Test now: schtasks /Run /TN `"$TaskName`""
Write-Host "Check: schtasks /Query /TN `"$TaskName`" /V /FO LIST"
