<?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';
$days = (int)($_GET['days'] ?? 30);
$days = max(7, min(90, $days));

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

echo "Executive Review Dashboard QA\n";
echo "Phase: 10.6.5 — Executive Review Dashboard & Management Summary\n";
echo "Hospital: " . strtoupper($hospital) . "\n";
echo "Analytics window: " . $days . " days\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'] : [];
    $analytics = $repo->managementDashboard($actions, $operationalDate, $days);
    $diag = $repo->diagnostics($operationalDate);

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

    $current = is_array($analytics['current'] ?? null) ? $analytics['current'] : [];
    $window = is_array($analytics['window'] ?? null) ? $analytics['window'] : [];
    $trend = is_array($analytics['trend'] ?? null) ? $analytics['trend'] : [];
    $matrix = is_array($analytics['severity_matrix'] ?? null) ? $analytics['severity_matrix'] : [];
    $queue = is_array($analytics['attention_queue'] ?? null) ? $analytics['attention_queue'] : [];
    $topActions = is_array($analytics['top_actions'] ?? null) ? $analytics['top_actions'] : [];
    $reviewers = is_array($analytics['reviewers'] ?? null) ? $analytics['reviewers'] : [];
    $recent = is_array($analytics['recent_activity'] ?? null) ? $analytics['recent_activity'] : [];

    $matrixTotal = 0;
    foreach ($matrix as $row) {
        if (is_array($row)) { $matrixTotal += (int)($row['total'] ?? 0); }
    }

    $queueValid = true;
    foreach ($queue as $item) {
        if (!is_array($item) || (string)($item['status'] ?? '') === 'reviewed') { $queueValid = false; break; }
    }

    $trendValid = count($trend) === $days;
    foreach ($trend as $row) {
        if (!is_array($row) || !isset($row['date'], $row['audit_count'], $row['reviewed'], $row['deferred'], $row['reopened'])) {
            $trendValid = false;
            break;
        }
    }

    $statusTotal = (int)($current['open'] ?? 0) + (int)($current['reviewed'] ?? 0) + (int)($current['deferred'] ?? 0);
    $dashboardFile = dirname(__DIR__) . '/app/Views/action_center/dashboard.php';
    $controllerFile = dirname(__DIR__) . '/app/Controllers/ActionCenterController.php';
    $routeFile = __DIR__ . '/index.php';
    $cssFile = __DIR__ . '/assets/css/action-center.css';
    $quickToolsFile = dirname(__DIR__) . '/app/Repositories/ExecutiveActionRepository.php';
    $dashboardView = is_file($dashboardFile) ? (string)file_get_contents($dashboardFile) : '';
    $controllerSource = is_file($controllerFile) ? (string)file_get_contents($controllerFile) : '';
    $routeSource = is_file($routeFile) ? (string)file_get_contents($routeFile) : '';
    $cssSource = is_file($cssFile) ? (string)file_get_contents($cssFile) : '';
    $quickToolsSource = is_file($quickToolsFile) ? (string)file_get_contents($quickToolsFile) : '';

    echo "QA Gates:\n";
    $pass(!empty($center['summary_available']), 'summary_available', !empty($center['summary_available']) ? 'YES' : 'NO');
    $pass(in_array((string)($analytics['phase'] ?? ''), ['10.6.5', '10.6.5.1'], true), 'analytics_phase', (string)($analytics['phase'] ?? '-'));
    $pass((int)($analytics['period_days'] ?? 0) === $days, 'selected_window_respected', (string)($analytics['period_days'] ?? 0) . ' days');
    $pass($statusTotal === count($actions), 'current_status_totals_match_worklist', $statusTotal . ' / ' . count($actions));
    $pass($matrixTotal === count($actions), 'severity_matrix_covers_worklist', $matrixTotal . ' / ' . count($actions));
    $pass($trendValid, 'cross_day_trend_buckets_ready', count($trend) . ' buckets');
    $pass($queueValid, 'attention_queue_unresolved_only', count($queue) . ' queued');
    $pass(isset($window['activity_7d'], $window['activity_previous_7d'], $window['velocity_trend_percent']), 'review_velocity_metrics_ready', '7d=' . (string)($window['activity_7d'] ?? 0));
    $pass(isset($current['completion_percent'], $current['pending_attention'], $current['risk_level']), 'management_kpis_ready', 'completion=' . (string)($current['completion_percent'] ?? 0) . '%');
    $pass(is_array($topActions), 'top_reviewed_actions_ready', (string)count($topActions));
    $pass(is_array($reviewers), 'reviewer_activity_ready', (string)count($reviewers));
    $pass(is_array($recent), 'recent_audit_timeline_ready', (string)count($recent));
    $pass((string)($diag['storage_mode'] ?? '') === 'oracle', 'active_storage_is_oracle', (string)($diag['storage_mode'] ?? '-'));
    $pass(is_file($dashboardFile) && strpos($dashboardView, 'executive-review-dashboard-v1065') !== false, 'dashboard_view_integrated', 'app/Views/action_center/dashboard.php');
    $pass(strpos($controllerSource, 'function reviewDashboard') !== false, 'dashboard_controller_integrated', 'reviewDashboard()');
    $pass(strpos($routeSource, "case 'action-review-dashboard'") !== false, 'dashboard_route_integrated', 'index.php?page=action-review-dashboard');
    $pass(strpos($cssSource, 'Phase 10.6.5 — Executive Review Dashboard') !== false, 'dashboard_css_integrated', 'action-center.css');
    $pass(strpos($quickToolsSource, "'target' => 'action-review-dashboard'") !== false, 'quick_tool_link_integrated', 'Review Dashboard');

    if ((int)($window['audit_count'] ?? 0) > 0) {
        $pass(count($recent) > 0, 'oracle_audit_history_visible', (string)($window['audit_count'] ?? 0) . ' events in window');
    } else {
        $pending('oracle_audit_history_visible', 'No audit events exist in the selected window yet.');
    }

    echo "\nManagement Summary:\n";
    echo "operational_day       | " . $operationalDate . "\n";
    echo "period                | " . (string)($analytics['period_start'] ?? '-') . ' -> ' . (string)($analytics['period_end'] ?? '-') . "\n";
    echo "storage               | " . (string)($analytics['storage'] ?? '-') . "\n";
    echo "total_actions         | " . (string)($current['total_actions'] ?? 0) . "\n";
    echo "open                  | " . (string)($current['open'] ?? 0) . "\n";
    echo "reviewed              | " . (string)($current['reviewed'] ?? 0) . "\n";
    echo "deferred              | " . (string)($current['deferred'] ?? 0) . "\n";
    echo "completion_percent    | " . (string)($current['completion_percent'] ?? 0) . "%\n";
    echo "pending_attention     | " . (string)($current['pending_attention'] ?? 0) . "\n";
    echo "critical_pending      | " . (string)($current['critical_pending'] ?? 0) . "\n";
    echo "oldest_pending_days   | " . (string)($current['oldest_pending_days'] ?? 0) . "\n";
    echo "risk_level            | " . (string)($current['risk_level'] ?? '-') . "\n";
    echo "audit_events_window   | " . (string)($window['audit_count'] ?? 0) . "\n";
    echo "active_reviewers      | " . (string)($window['active_reviewers'] ?? 0) . "\n";
    echo "activity_7d           | " . (string)($window['activity_7d'] ?? 0) . "\n";
    echo "velocity_trend        | " . (string)($window['velocity_trend_percent'] ?? 0) . "%\n";

    echo "\nDashboard:\n";
    echo "index.php?page=action-review-dashboard&lang=en&days=" . $days . "\n";
    echo "QA is read-only: no review status, note, Oracle row, or audit row is modified.\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
