<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveSummaryRepository;

header('Content-Type: text/plain; charset=utf-8');

$hospital = strtolower((string)($_GET['hospital'] ?? 'njch'));
$mode = (string)env('EXECUTIVE_DASHBOARD_MODE', 'summary');

try {
    $repo = new ExecutiveSummaryRepository($hospital);
    $op = $repo->operationalDayInfo();

    echo "Executive Summary Layer Check\n";
    echo "Hospital: " . strtoupper($hospital) . "\n";
    echo "EXECUTIVE_DASHBOARD_MODE: " . $mode . "\n";
    echo "Operational day start hour: " . (string)($op['start_hour'] ?? '-') . "\n";
    echo "Operational date: " . (string)($op['operational_date'] ?? '-') . "\n";
    echo "Operational window: " . (string)($op['window_start'] ?? '-') . " -> " . (string)($op['window_end'] ?? '-') . "\n";
    echo "Night rollover: " . (!empty($op['is_rollover']) ? 'YES' : 'NO') . "\n\n";

    $summary = $repo->latestForToday();
    if (!$summary) {
        echo "Status: NO SUMMARY ROWS FOR OPERATIONAL DAY\n";
        echo "Action: run executive-summary-refresh.php?hospital={$hospital}&token=YOUR_TOKEN&force=1\n";
        exit;
    }

    echo "Status: SUMMARY ACTIVE\n";
    echo "Last updated: " . ($summary['last_updated'] ?? '-') . "\n";
    echo "Stale: " . (!empty($summary['is_stale']) ? 'YES' : 'NO') . "\n";
    echo "Rows: " . count((array)($summary['rows'] ?? [])) . "\n\n";

    $rows = (array)($summary['rows'] ?? []);
    ksort($rows);
    foreach ($rows as $code => $row) {
        echo str_pad((string)$code, 28) . " | "
            . str_pad((string)($row['kpi_value'] ?? 'NULL'), 12) . " | "
            . (string)($row['kpi_text'] ?? '') . " | "
            . (string)($row['kpi_status'] ?? '') . "\n";
    }
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
