<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveSummaryRepository;

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

$hospital = strtolower((string)($_GET['hospital'] ?? 'njch'));
$repo = new ExecutiveSummaryRepository($hospital);

echo "Beds Unit Mapping Check\n";
echo "Hospital: " . strtoupper($hospital) . "\n\n";

try {
    $preview = $repo->capacityUnitMappingPreview();
    $mapped = is_array($preview['mapped_units'] ?? null) ? $preview['mapped_units'] : [];
    $raw = is_array($preview['raw_units'] ?? null) ? $preview['raw_units'] : [];

    echo "Mapped executive slots:\n";
    foreach (['unit_icu' => 'ICU', 'unit_medical' => 'Medical', 'unit_surgical' => 'Surgical'] as $code => $fallback) {
        $slot = is_array($mapped[$code] ?? null) ? $mapped[$code] : [];
        $label = (string)($slot['label'] ?? $fallback);
        $value = $slot['value'] ?? null;
        $total = $slot['total_beds'] ?? null;
        $occupied = $slot['occupied_beds'] ?? null;
        echo "  {$code}: " . ($value === null ? 'pending' : number_format((float)$value, 2) . '%')
            . " | label=" . $label
            . " | beds=" . ($total === null ? '-' : number_format((float)$total, 0))
            . " | occupied=" . ($occupied === null ? '-' : number_format((float)$occupied, 0))
            . "\n";
    }

    echo "\nRaw unit rows from STP_BEDS/STP_PLACES/STP_HRC/RCP_BED_TRANS:\n";
    if (!$raw) {
        echo "  No unit rows returned.\n";
    } else {
        foreach ($raw as $idx => $row) {
            $label = (string)($row['label'] ?? 'Unknown unit');
            $id = (string)($row['id'] ?? '');
            $total = (float)($row['total_beds'] ?? 0);
            $occupied = (float)($row['occupied_beds'] ?? 0);
            $pct = (float)($row['value'] ?? 0);
            echo "  " . str_pad((string)($idx + 1), 2, ' ', STR_PAD_LEFT)
                . ") id=" . ($id !== '' ? $id : '-')
                . " | " . $label
                . " | beds=" . number_format($total, 0)
                . " | occupied=" . number_format($occupied, 0)
                . " | occupancy=" . number_format($pct, 2) . "%\n";
        }
    }

    echo "\nRecommended action:\n";
    echo "1) Run executive-summary-refresh.php?hospital={$hospital}&token=YOUR_TOKEN&force=1 after installing Phase 10.3.4.\n";
    echo "2) If a label is not what you prefer, send this output and we will pin the exact branch-specific mapping.\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
