<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveActionRepository;
use App\Repositories\ExecutiveActionReviewRepository;

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

echo "Executive Action Review Workflow Check\n";
echo "Phase: 10.6.3 — Review UI + Oracle Persistence QA\n";
echo "Hospital: " . strtoupper($hospital) . "\n\n";

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

    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: " . $operationalDate . "\n";
    echo "Review storage: " . (string)($workflow['storage'] ?? $repo->storageMode()) . "\n";
    echo "Audit trail: " . (!empty($workflow['audit_trail']) ? 'YES' : 'NO') . "\n";
    echo "Audit rows today: " . (string)($diag['audit_count_for_date'] ?? 0) . "\n\n";

    echo "Oracle audit table status:\n";
    echo "main_table       | " . (string)($diag['main_table'] ?? '-') . " | " . (!empty($diag['main_table_exists']) ? 'found' : 'not found') . "\n";
    echo "audit_table      | " . (string)($diag['audit_table'] ?? '-') . " | " . (!empty($diag['audit_table_exists']) ? 'found' : 'not found') . "\n";
    echo "active_storage   | " . (string)($diag['storage_mode'] ?? '-') . "\n";
    echo "json_fallback    | " . (string)($diag['json_fallback_path'] ?? '-') . "\n";
    if (!empty($diag['last_storage_error'])) { echo "storage_error    | " . (string)$diag['last_storage_error'] . "\n"; }
    echo "\n";

    echo "Review counts:\n";
    foreach (['open', 'reviewed', 'deferred'] as $status) {
        echo str_pad($status, 12) . " | " . (string)($reviewCounts[$status] ?? 0) . "\n";
    }

    echo "\nCurrent worklist review status:\n";
    foreach ((array)($center['actions'] ?? []) as $a) {
        if (!is_array($a)) { continue; }
        $review = is_array($a['review'] ?? null) ? $a['review'] : [];
        echo strtoupper((string)($a['severity'] ?? 'routine')) . ' | '
            . str_pad((string)($a['rule_id'] ?? '-'), 38) . ' | '
            . str_pad((string)($review['status'] ?? 'open'), 9) . ' | '
            . str_pad((string)($review['storage'] ?? $repo->storageMode()), 13) . ' | '
            . (string)($a['title'] ?? '-') . ' | '
            . (string)($review['updated_at'] ?? '-') . "\n";
    }

    echo "\nLatest audit rows:\n";
    $auditRows = is_array($diag['latest_audit_rows'] ?? null) ? $diag['latest_audit_rows'] : [];
    if (!$auditRows) {
        echo "No Oracle audit rows yet, or audit table is not installed.\n";
    } else {
        foreach ($auditRows as $row) {
            echo (string)($row['changed_at'] ?? '-') . ' | '
                . (string)($row['action_key'] ?? '-') . ' | '
                . (string)($row['old_status'] ?? '-') . ' -> '
                . (string)($row['new_status'] ?? '-') . ' | '
                . (string)($row['changed_by'] ?? '-') . "\n";
        }
    }

    echo "\nOpen a review page example:\n";
    $first = is_array(($center['actions'] ?? [])[0] ?? null) ? ($center['actions'] ?? [])[0] : null;
    if ($first) {
        echo "index.php?page=action-review&action=" . rawurlencode((string)($first['rule_id'] ?? '')) . "&lang=en\n";
    } else {
        echo "No active actions.\n";
    }

    echo "\nSQL install file:\n";
    echo "database/executive_action_review_audit_trail.sql\n";

    echo "\nWorkflow QA page:\n";
    echo "executive-action-review-workflow-qa.php?hospital=" . rawurlencode($hospital) . "\n";
} catch (Throwable $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
}
