<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveActionGovernanceRepository;
use App\Repositories\ExecutiveActionRepository;

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

echo "Executive Action Governance Storage Check\n";
echo "Phase: 10.6.6 — Governance, Ownership & Follow-up Management\n";
echo "Hospital: " . strtoupper($hospital) . "\n\n";

try {
    $center = (new ExecutiveActionRepository($hospital))->center();
    $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
    $operationalDate = (string)($op['operational_date'] ?? date('Y-m-d'));
    $repo = new ExecutiveActionGovernanceRepository($hospital);
    $diag = $repo->diagnostics($operationalDate);

    echo "Oracle governance table status:\n";
    echo "main_table       | " . (string)($diag['main_table'] ?? '-') . " | " . (!empty($diag['main_table_exists']) ? 'found' : 'missing') . "\n";
    echo "audit_table      | " . (string)($diag['audit_table'] ?? '-') . " | " . (!empty($diag['audit_table_exists']) ? 'found' : 'missing') . "\n";
    echo "active_storage   | " . (string)($diag['storage_mode'] ?? '-') . "\n";
    echo "state_rows       | " . (string)($diag['state_count'] ?? 0) . "\n";
    echo "audit_rows       | " . (string)($diag['audit_count'] ?? 0) . "\n";
    echo "json_fallback    | " . (string)($diag['json_fallback_path'] ?? '-') . "\n";
    if (!empty($diag['last_storage_error'])) {
        echo "last_error       | " . (string)$diag['last_storage_error'] . "\n";
    }

    echo "\nRequired Oracle SQL install file:\n";
    echo "database/executive_action_governance.sql\n";

    echo "\nExpected production state after SQL install:\n";
    echo "main_table       | DASH_EXEC_ACTION_GOV | found\n";
    echo "audit_table      | DASH_EXEC_ACTION_GOV_AUDIT | found\n";
    echo "active_storage   | oracle\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
