<?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';
$writeRequested = in_array(strtolower(trim((string)($_GET['write_test'] ?? '0'))), ['1', 'true', 'yes', 'on'], true);
$providedToken = (string)($_GET['token'] ?? '');
$configuredToken = trim((string)env('EXEC_ACTION_GOVERNANCE_QA_TOKEN', ''));

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

echo "Executive Action Governance & Follow-up QA\n";
echo "Phase: 10.6.6 — Executive Review Governance, Ownership & Follow-up Management\n";
echo "Hospital: " . strtoupper($hospital) . "\n";
echo "Write test requested: " . ($writeRequested ? 'YES' : 'NO') . "\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'));
    $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
    $repo = new ExecutiveActionGovernanceRepository($hospital);
    $diagnosticsBefore = $repo->diagnostics($operationalDate);
    $summaryBefore = $repo->managementSummary($actions, $operationalDate);

    $writeProof = [
        'requested' => $writeRequested,
        'performed' => false,
        'action_key' => '',
        'state_restored' => false,
        'audit_rows_added' => 0,
        'error' => '',
    ];

    if ($writeRequested) {
        if ($configuredToken === '' || !hash_equals($configuredToken, $providedToken)) {
            $writeProof['error'] = 'Invalid or missing EXEC_ACTION_GOVERNANCE_QA_TOKEN.';
        } elseif (!$actions) {
            $writeProof['error'] = 'No current action is available for controlled write proof.';
        } else {
            $selected = null;
            foreach ($actions as $candidate) {
                if (is_array($candidate) && trim((string)($candidate['rule_id'] ?? '')) !== '') { $selected = $candidate; break; }
            }
            if (!is_array($selected)) {
                $writeProof['error'] = 'No valid action key is available for controlled write proof.';
            } else {
                $key = (string)$selected['rule_id'];
                $writeProof['action_key'] = $key;
                $original = $repo->find($key, $operationalDate);
                $beforeHistory = $repo->auditHistory($key, 100);
                $testDue = date('Y-m-d', strtotime($operationalDate . ' +2 days'));
                $testFollow = $operationalDate;

                $testPayload = [
                    'owner_name' => 'phase10_6_6_qa_owner',
                    'assigned_to' => 'phase10_6_6_qa_executor',
                    'due_date' => $testDue,
                    'follow_up_date' => $testFollow,
                    'escalation_level' => 'watch',
                    'resolution_status' => 'active',
                    'resolution_note' => '',
                ];
                $repo->save($key, $operationalDate, $testPayload, 'phase10_6_6_qa', $selected);
                $testSaved = $repo->find($key, $operationalDate);

                $restorePayload = [
                    'owner_name' => (string)($original['owner_name'] ?? ''),
                    'assigned_to' => (string)($original['assigned_to'] ?? ''),
                    'due_date' => (string)($original['due_date'] ?? ''),
                    'follow_up_date' => (string)($original['follow_up_date'] ?? ''),
                    'escalation_level' => (string)($original['escalation_level'] ?? 'none'),
                    'resolution_status' => (string)($original['resolution_status'] ?? 'active'),
                    'resolution_note' => (string)($original['resolution_note'] ?? ''),
                ];
                $repo->save($key, $operationalDate, $restorePayload, 'phase10_6_6_qa_restore', $selected);
                $restored = $repo->find($key, $operationalDate);
                $afterHistory = $repo->auditHistory($key, 100);

                $writeProof['performed'] = true;
                $writeProof['test_saved'] =
                    (string)($testSaved['owner_name'] ?? '') === 'phase10_6_6_qa_owner' &&
                    (string)($testSaved['assigned_to'] ?? '') === 'phase10_6_6_qa_executor' &&
                    (string)($testSaved['escalation_level'] ?? '') === 'watch';
                $writeProof['state_restored'] =
                    (string)($restored['owner_name'] ?? '') === (string)($original['owner_name'] ?? '') &&
                    (string)($restored['assigned_to'] ?? '') === (string)($original['assigned_to'] ?? '') &&
                    (string)($restored['due_date'] ?? '') === (string)($original['due_date'] ?? '') &&
                    (string)($restored['follow_up_date'] ?? '') === (string)($original['follow_up_date'] ?? '') &&
                    (string)($restored['escalation_level'] ?? 'none') === (string)($original['escalation_level'] ?? 'none') &&
                    (string)($restored['resolution_status'] ?? 'active') === (string)($original['resolution_status'] ?? 'active') &&
                    (string)($restored['resolution_note'] ?? '') === (string)($original['resolution_note'] ?? '');
                $writeProof['audit_rows_added'] = max(0, count($afterHistory) - count($beforeHistory));
            }
        }
    }

    // Re-read after the optional controlled write proof.
    $centerAfter = (new ExecutiveActionRepository($hospital))->center();
    $actionsAfter = is_array($centerAfter['actions'] ?? null) ? $centerAfter['actions'] : [];
    $summary = $repo->managementSummary($actionsAfter, $operationalDate);
    $diagnostics = $repo->diagnostics($operationalDate);

    $passCount = 0;
    $failCount = 0;
    $pass = static function (bool $ok, string $label, string $detail = '') use (&$passCount, &$failCount): void {
        if ($ok) { $passCount++; } else { $failCount++; }
        echo ($ok ? '[PASS] ' : '[FAIL] ') . str_pad($label, 43) . ($detail !== '' ? ' | ' . $detail : '') . "\n";
    };

    $validStates = ['unassigned', 'assigned', 'due_soon', 'follow_up_due', 'overdue', 'escalated', 'resolved', 'on_track'];
    $allActionsHaveGovernance = true;
    $allDerivedStatesValid = true;
    foreach ($actionsAfter as $action) {
        if (!is_array($action) || !is_array($action['governance'] ?? null)) { $allActionsHaveGovernance = false; continue; }
        if (!in_array((string)($action['governance']['accountability_status'] ?? ''), $validStates, true)) { $allDerivedStatesValid = false; }
    }

    $queueActiveOnly = true;
    foreach ((array)($summary['accountability_queue'] ?? []) as $row) {
        if (!is_array($row) || (string)($row['accountability_status'] ?? '') === 'resolved') { $queueActiveOnly = false; break; }
    }

    $repoFile = dirname(__DIR__) . '/app/Repositories/ExecutiveActionGovernanceRepository.php';
    $controllerFile = dirname(__DIR__) . '/app/Controllers/ActionCenterController.php';
    $reviewViewFile = dirname(__DIR__) . '/app/Views/action_center/review.php';
    $dashboardViewFile = dirname(__DIR__) . '/app/Views/action_center/governance.php';
    $indexFile = __DIR__ . '/index.php';
    $cssFile = __DIR__ . '/assets/css/action-center.css';
    $sqlFile = dirname(__DIR__) . '/database/executive_action_governance.sql';
    $repoSource = is_file($repoFile) ? (string)file_get_contents($repoFile) : '';
    $controllerSource = is_file($controllerFile) ? (string)file_get_contents($controllerFile) : '';
    $reviewSource = is_file($reviewViewFile) ? (string)file_get_contents($reviewViewFile) : '';
    $dashboardSource = is_file($dashboardViewFile) ? (string)file_get_contents($dashboardViewFile) : '';
    $routeSource = is_file($indexFile) ? (string)file_get_contents($indexFile) : '';
    $cssSource = is_file($cssFile) ? (string)file_get_contents($cssFile) : '';
    $sqlSource = is_file($sqlFile) ? (string)file_get_contents($sqlFile) : '';

    echo "QA Gates:\n";
    $pass(!empty($centerAfter['summary_available']), 'summary_available', !empty($centerAfter['summary_available']) ? 'YES' : 'NO');
    $pass((string)($diagnostics['phase'] ?? '') === '10.6.6', 'governance_phase', (string)($diagnostics['phase'] ?? '-'));
    $pass((string)($diagnostics['storage_mode'] ?? '') === 'oracle', 'active_storage_is_oracle', (string)($diagnostics['storage_mode'] ?? '-'));
    $pass(!empty($diagnostics['main_table_exists']) && !empty($diagnostics['audit_table_exists']), 'oracle_governance_tables_ready', (string)($diagnostics['main_table'] ?? '-') . ' + ' . (string)($diagnostics['audit_table'] ?? '-'));
    $pass(count($actionsAfter) > 0, 'current_worklist_has_actions', (string)count($actionsAfter));
    $pass($allActionsHaveGovernance, 'governance_attached_to_every_action', (string)count($actionsAfter) . ' actions');
    $pass((int)($summary['total_actions'] ?? -1) === count($actionsAfter), 'summary_matches_current_worklist', (string)($summary['total_actions'] ?? 0) . ' / ' . count($actionsAfter));
    $pass(((int)($summary['active'] ?? 0) + (int)($summary['resolved'] ?? 0)) === count($actionsAfter), 'active_plus_resolved_equals_total', (string)($summary['active'] ?? 0) . ' + ' . (string)($summary['resolved'] ?? 0));
    $pass(((int)($summary['assigned'] ?? 0) + (int)($summary['unassigned'] ?? 0)) === count($actionsAfter), 'assigned_plus_unassigned_equals_total', (string)($summary['assigned'] ?? 0) . ' + ' . (string)($summary['unassigned'] ?? 0));
    $pass($allDerivedStatesValid, 'derived_accountability_states_valid', implode(', ', $validStates));
    $pass($queueActiveOnly, 'accountability_queue_excludes_resolved', (string)count((array)($summary['accountability_queue'] ?? [])) . ' active queued');
    $pass(is_array($summary['owner_workload'] ?? null), 'owner_workload_ready', (string)count((array)($summary['owner_workload'] ?? [])) . ' owners');
    $pass(strpos($sqlSource, 'PRIMARY KEY (HOSPITAL_CODE, ACTION_KEY)') !== false, 'ownership_persists_across_days', 'hospital + action key durable state');
    $pass(strpos($repoSource, 'Resolution note is required') !== false, 'resolution_note_guard_present', 'required when resolved');
    $pass(strpos($repoSource, 'EXEC_ACTION_GOVERNANCE_QA_ACTORS') !== false, 'qa_activity_exclusion_supported', 'management recent activity protected');
    $pass(strpos($controllerSource, 'governanceDashboard()') !== false && strpos($controllerSource, 'updateGovernance()') !== false, 'controller_governance_workflow_integrated', 'dashboard + save');
    $pass(strpos($routeSource, "case 'action-governance-dashboard'") !== false && strpos($routeSource, "case 'action-governance-update'") !== false, 'governance_routes_integrated', 'view + POST route');
    $pass(strpos($reviewSource, 'governance-editor-section') !== false && strpos($reviewSource, 'Save governance & follow-up') !== false, 'review_page_governance_editor_integrated', 'ownership + dates + escalation + resolution');
    $pass(strpos($dashboardSource, 'Accountability Queue') !== false && strpos($dashboardSource, 'Owner workload') !== false, 'governance_dashboard_integrated', 'queue + owner workload');
    $pass(strpos($cssSource, 'Phase 10.6.6') !== false && strpos($cssSource, '.governance-editor-section') !== false, 'governance_ui_css_integrated', 'responsive phase styles');
    $pass(is_file($sqlFile) && strpos($sqlSource, 'DASH_EXEC_ACTION_GOV_AUDIT') !== false, 'oracle_sql_install_ready', 'database/executive_action_governance.sql');
    $pass(is_array($diagnostics['latest_audit_rows'] ?? null), 'governance_audit_history_readable', (string)($diagnostics['audit_count'] ?? 0) . ' raw audit rows');

    if ($writeRequested) {
        $pass(empty($writeProof['error']), 'write_test_authorized', (string)($writeProof['error'] ?? 'OK'));
        $pass(!empty($writeProof['performed']) && !empty($writeProof['test_saved']), 'write_governance_saved', (string)($writeProof['action_key'] ?? '-'));
        $pass(!empty($writeProof['state_restored']), 'write_state_restored', !empty($writeProof['state_restored']) ? 'YES' : 'NO');
        $pass((int)($writeProof['audit_rows_added'] ?? 0) >= 2, 'write_audit_rows_added', (string)($writeProof['audit_rows_added'] ?? 0));
    }

    echo "\nGovernance Summary:\n";
    echo "operational_day       | " . $operationalDate . "\n";
    echo "storage               | " . (string)($summary['storage'] ?? '-') . "\n";
    echo "total_actions         | " . (string)($summary['total_actions'] ?? 0) . "\n";
    echo "active                | " . (string)($summary['active'] ?? 0) . "\n";
    echo "resolved              | " . (string)($summary['resolved'] ?? 0) . "\n";
    echo "assigned              | " . (string)($summary['assigned'] ?? 0) . "\n";
    echo "unassigned            | " . (string)($summary['unassigned'] ?? 0) . "\n";
    echo "overdue               | " . (string)($summary['overdue'] ?? 0) . "\n";
    echo "due_soon              | " . (string)($summary['due_soon'] ?? 0) . "\n";
    echo "follow_up_due         | " . (string)($summary['follow_up_due'] ?? 0) . "\n";
    echo "escalated             | " . (string)($summary['escalated'] ?? 0) . "\n";
    echo "governance_audit_rows | " . (string)($diagnostics['audit_count'] ?? 0) . "\n";

    if ($writeRequested) {
        echo "\nControlled Write Proof:\n";
        echo "action_key            | " . (string)($writeProof['action_key'] ?? '-') . "\n";
        echo "state_restored        | " . (!empty($writeProof['state_restored']) ? 'YES' : 'NO') . "\n";
        echo "audit_rows_added      | " . (string)($writeProof['audit_rows_added'] ?? 0) . "\n";
        if (!empty($writeProof['error'])) { echo "write_error           | " . (string)$writeProof['error'] . "\n"; }
    }

    echo "\nDashboard:\n";
    echo "index.php?page=action-governance-dashboard&lang=en\n";
    echo "\nQA result: " . ($failCount === 0 ? 'PASS' : 'FAIL') . "\n";
    echo "PASS gates: " . $passCount . "\n";
    echo "FAIL gates: " . $failCount . "\n";
    echo "Write proof is optional and controlled by EXEC_ACTION_GOVERNANCE_QA_TOKEN.\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
