<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Repositories\ExecutiveActionRepository;

$hospital = strtolower(trim((string)($_GET['hospital'] ?? 'njch'))) ?: 'njch';
header('Content-Type: text/plain; charset=utf-8');

echo "Executive Action Center Check\n";
echo "Phase: 10.6 — Action Drilldown & Review Workflow\n";
echo "Hospital: " . strtoupper($hospital) . "\n\n";

try {
    $center = (new ExecutiveActionRepository($hospital))->center();
    $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
    $counts = is_array($center['counts'] ?? null) ? $center['counts'] : [];
    $system = is_array($center['system'] ?? null) ? $center['system'] : [];
    $engine = is_array($center['engine'] ?? null) ? $center['engine'] : [];

    echo "Status: " . (string)($system['status'] ?? 'UNKNOWN') . "\n";
    echo "Engine: " . (string)($engine['name'] ?? 'Executive Alert Rules') . "\n";
    echo "Summary available: " . (!empty($center['summary_available']) ? 'YES' : 'NO') . "\n";
    echo "Stale: " . (!empty($center['is_stale']) ? 'YES' : 'NO') . "\n";
    echo "Last updated: " . (string)($center['last_updated'] ?? '-') . "\n";
    echo "Operational day: " . (string)($op['operational_date'] ?? '-') . "\n";
    echo "Window: " . (string)($op['window_start'] ?? '-') . " -> " . (string)($op['window_end'] ?? '-') . "\n\n";

    echo "Counts:\n";
    foreach (['critical', 'watch', 'routine', 'opportunity'] as $k) {
        echo str_pad($k, 14) . " | " . (string)($counts[$k] ?? 0) . "\n";
    }

    $cal = is_array($engine['revenue_calibration'] ?? null) ? $engine['revenue_calibration'] : [];
    if ($cal) {
        echo "
Revenue pace calibration:
";
        echo "elapsed_hours     | " . number_format((float)($cal['elapsed_hours'] ?? 0), 2) . "
";
        echo "check_due         | " . (!empty($cal['check_due']) ? 'YES' : 'NO') . "
";
        echo "skip_reason       | " . (string)($cal['skip_reason'] ?? '') . "
";
        echo "watch_floor       | " . number_format((float)($cal['watch_floor'] ?? 0), 2) . "
";
    }

    echo "\nActions:\n";
    foreach ((array)($center['actions'] ?? []) as $a) {
        echo strtoupper((string)($a['severity'] ?? 'routine')) . ' | '
            . str_pad((string)($a['rule_id'] ?? '-'), 28) . ' | '
            . (string)($a['category'] ?? '-') . ' | '
            . (string)($a['title'] ?? '-') . ' | '
            . (string)($a['metric'] ?? '-') . "\n";
    }
} catch (Throwable $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
}
