<?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';
$requestedAction = strtolower(trim((string)($_GET['action'] ?? '')));
$writeTest = (string)($_GET['write_test'] ?? '') === '1';
$token = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)(env('EXEC_ACTION_REVIEW_QA_TOKEN', '') ?: env('EXECUTIVE_REFRESH_TOKEN', '')));

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

echo "Executive Action Review Workflow QA\n";
echo "Phase: 10.6.3 — Review UI + Oracle Persistence QA\n";
echo "Hospital: " . strtoupper($hospital) . "\n";
echo "Write test requested: " . ($writeTest ? 'YES' : 'NO') . "\n\n";

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

    $selected = null;
    foreach ($actions as $candidate) {
        if (!is_array($candidate)) { continue; }
        $rule = strtolower((string)($candidate['rule_id'] ?? ''));
        if ($requestedAction !== '' && $rule === $requestedAction) {
            $selected = $candidate;
            break;
        }
        if ($selected === null) { $selected = $candidate; }
    }

    if ($writeTest) {
        if ($expectedToken === '' || !hash_equals($expectedToken, $token)) {
            http_response_code(403);
            echo "FORBIDDEN: set EXEC_ACTION_REVIEW_QA_TOKEN or EXECUTIVE_REFRESH_TOKEN in .env and pass ?token=YOUR_TOKEN.\n";
            exit;
        }
        if (!$selected) {
            echo "WRITE TEST SKIPPED: no active action found in the worklist.\n\n";
        } else {
            $review = is_array($selected['review'] ?? null) ? $selected['review'] : [];
            $currentStatus = strtolower((string)($review['status'] ?? 'open'));
            if (!in_array($currentStatus, ['open', 'reviewed', 'deferred'], true)) { $currentStatus = 'open'; }
            $requestedStatus = strtolower(trim((string)($_GET['status'] ?? '')));
            $targetStatus = in_array($requestedStatus, ['open', 'reviewed', 'deferred'], true) ? $requestedStatus : $currentStatus;
            $note = trim((string)($_GET['note'] ?? ''));
            if ($note === '') {
                $note = 'Phase 10.6.3 QA proof - transaction-safe review save at ' . date('Y-m-d H:i:s');
            }
            $saved = $repo->save((string)($selected['rule_id'] ?? ''), $operationalDate, $targetStatus, $note, 'phase10_6_3_qa', $selected);
            echo "WRITE TEST RESULT: saved\n";
            echo "action_key       | " . (string)($saved['rule_id'] ?? $selected['rule_id'] ?? '-') . "\n";
            echo "status           | " . (string)($saved['status'] ?? '-') . "\n";
            echo "storage          | " . (string)($saved['storage'] ?? '-') . "\n";
            echo "review_count     | " . (string)($saved['review_count'] ?? '-') . "\n\n";

            $center = (new ExecutiveActionRepository($hospital))->center();
            $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
            $selectedRule = (string)($selected['rule_id'] ?? '');
            $selected = null;
            foreach ($actions as $candidate) {
                if (is_array($candidate) && (string)($candidate['rule_id'] ?? '') === $selectedRule) {
                    $selected = $candidate;
                    break;
                }
            }
        }
    }

    $workflow = is_array($center['review_workflow'] ?? null) ? $center['review_workflow'] : [];
    $reviewCounts = is_array($workflow['counts'] ?? null) ? $workflow['counts'] : [];
    $diag = $repo->diagnostics($operationalDate);
    $selectedRule = $selected ? (string)($selected['rule_id'] ?? '') : '';
    $history = $selectedRule !== '' ? $repo->auditHistory($selectedRule, $operationalDate, 10) : [];

    $pass = function (bool $ok, string $label, string $detail = ''): void {
        echo ($ok ? '[PASS] ' : '[FAIL] ') . str_pad($label, 32) . ($detail !== '' ? ' | ' . $detail : '') . "\n";
    };
    $pending = function (string $label, string $detail = ''): void {
        echo '[PENDING] ' . str_pad($label, 29) . ($detail !== '' ? ' | ' . $detail : '') . "\n";
    };

    echo "QA Gates:\n";
    $pass(!empty($center['summary_available']), 'summary_available', !empty($center['summary_available']) ? 'YES' : 'NO');
    $pass((string)($diag['storage_mode'] ?? '') === 'oracle', 'active_storage_is_oracle', (string)($diag['storage_mode'] ?? '-'));
    $pass(!empty($diag['main_table_exists']), 'main_table_found', (string)($diag['main_table'] ?? '-'));
    $pass(!empty($diag['audit_table_exists']), 'audit_table_found', (string)($diag['audit_table'] ?? '-'));
    $pass(count($actions) > 0, 'worklist_has_actions', (string)count($actions));
    $pass(isset($reviewCounts['open'], $reviewCounts['reviewed'], $reviewCounts['deferred']), 'review_counts_available', 'open=' . (string)($reviewCounts['open'] ?? 0) . ', reviewed=' . (string)($reviewCounts['reviewed'] ?? 0) . ', deferred=' . (string)($reviewCounts['deferred'] ?? 0));
    if ((int)($diag['audit_count_for_date'] ?? 0) > 0) {
        $pass(true, 'audit_rows_exist_for_day', (string)$diag['audit_count_for_date']);
    } else {
        $pending('audit_rows_exist_for_day', 'Run one UI save or use write_test=1 with token.');
    }
    if ($selectedRule !== '') {
        if (count($history) > 0) {
            $pass(true, 'selected_action_audit_history', $selectedRule . ' rows=' . count($history));
        } else {
            $pending('selected_action_audit_history', $selectedRule . ' has no audit rows yet.');
        }
    }

    if (!empty($diag['last_storage_error'])) {
        echo "\nStorage error:\n" . (string)$diag['last_storage_error'] . "\n";
    }

    echo "\nOperational day: " . $operationalDate . "\n";
    echo "Review storage: " . (string)($workflow['storage'] ?? $repo->storageMode()) . "\n";
    echo "Audit rows today: " . (string)($diag['audit_count_for_date'] ?? 0) . "\n";
    echo "JSON fallback path: " . (string)($diag['json_fallback_path'] ?? '-') . "\n";

    echo "\nSelected action:\n";
    if ($selected) {
        $review = is_array($selected['review'] ?? null) ? $selected['review'] : [];
        echo "rule_id          | " . (string)($selected['rule_id'] ?? '-') . "\n";
        echo "title            | " . (string)($selected['title'] ?? '-') . "\n";
        echo "status           | " . (string)($review['status'] ?? 'open') . "\n";
        echo "storage          | " . (string)($review['storage'] ?? $repo->storageMode()) . "\n";
        echo "review_count     | " . (string)($review['review_count'] ?? 0) . "\n";
        echo "review_page      | index.php?page=action-review&action=" . rawurlencode((string)($selected['rule_id'] ?? '')) . "&lang=en\n";
    } else {
        echo "No active action selected.\n";
    }

    echo "\nLatest selected-action audit history:\n";
    if (!$history) {
        echo "No audit history for selected action yet.\n";
    } else {
        foreach ($history as $row) {
            echo (string)($row['changed_at'] ?? '-') . ' | '
                . (string)($row['action_key'] ?? '-') . ' | '
                . (string)($row['old_status'] ?? '-') . ' -> '
                . (string)($row['new_status'] ?? '-') . ' | '
                . (string)($row['changed_by'] ?? '-') . ' | '
                . (string)($row['storage'] ?? '-') . "\n";
        }
    }

    echo "\nOptional automated write proof:\n";
    if ($expectedToken === '') {
        echo "Set EXEC_ACTION_REVIEW_QA_TOKEN in .env first.\n";
    } else {
        echo "Open: executive-action-review-workflow-qa.php?hospital=" . rawurlencode($hospital) . "&write_test=1&token=YOUR_TOKEN\n";
        echo "This writes one controlled audit row for the selected/current action.\n";
    }
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
