<?php

declare(strict_types=1);

ob_start();
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$root = dirname(__DIR__);
$checks = [];

function h110p11r9_add(array &$checks, string $name, bool $passed, string $detail = ''): void
{
    $checks[] = ['name' => $name, 'status' => $passed ? 'PASS' : 'FAIL', 'detail' => $detail];
}

function h110p11r9_read(string $path): string
{
    if (!is_file($path)) {
        return '';
    }
    $value = @file_get_contents($path);
    return is_string($value) ? $value : '';
}

$versionPath = $root . '/DDB_VERSION.json';
$viewPath = $root . '/app/Views/revenue/index.php';
$layoutPath = $root . '/app/Views/layouts/main.php';
$cssPath = $root . '/public/assets/css/executive-ui-core.css';
$jsPath = $root . '/public/assets/js/executive-revenue-intelligence.js';
$dailyRevenueQaPath = $root . '/public/phase11-0-p10-4-inpatient-daily-revenue-qa.php';
$preservationQaPath = $root . '/public/phase11-0-p11-daily-revenue-preservation-qa.php';

$versionRaw = h110p11r9_read($versionPath);
$view = h110p11r9_read($viewPath);
$layout = h110p11r9_read($layoutPath);
$css = h110p11r9_read($cssPath);
$js = h110p11r9_read($jsPath);
$dailyRevenueQa = h110p11r9_read($dailyRevenueQaPath);
$versionData = json_decode($versionRaw, true);
$versionData = is_array($versionData) ? $versionData : [];
$release = (string)($versionData['release'] ?? '');
$phase = (string)($versionData['phase'] ?? '');

h110p11r9_add($checks, 'release_11_0_11_1_or_later', $release !== '' && version_compare($release, '11.0.11.1', '>='), $release);
h110p11r9_add($checks, 'phase_r9_or_later_contract', $phase === 'H11.0-P11-R9' || ($release !== '' && version_compare($release, '11.0.11.1', '>')), $phase);
h110p11r9_add($checks, 'production_revenue_view_present', is_file($viewPath), 'app/Views/revenue/index.php');
h110p11r9_add($checks, 'direct_executive_view_marker_present', strpos($view, 'H110_P11_R9_REVENUE_DIRECT_EXECUTIVE_VIEW') !== false, 'direct PHP view, no DOM overlay dependency');
h110p11r9_add($checks, 'shared_css_marker_present', strpos($css, 'EXEC_UI_REVENUE_INTELLIGENCE_H110_P11_R9_V2') !== false, 'executive-ui-core.css');
h110p11r9_add($checks, 'unsafe_r3_layout_injection_absent', strpos($layout, 'H110_P11_REVENUE_ASSET_V1') === false, 'global layout injection absent');
h110p11r9_add($checks, 'revenue_asset_scoped_to_revenue_view', strpos($view, 'executive-revenue-intelligence.js') !== false && strpos($layout, 'executive-revenue-intelligence.js') === false, 'Revenue view only');

$priorityCardOccurrences = substr_count($view, 'class="eri-v2-priority-card');
$legacyKpiGridOccurrences = substr_count($view, 'revenue109-kpis');
h110p11r9_add($checks, 'single_four_priority_kpi_contract', $priorityCardOccurrences === 4 && $legacyKpiGridOccurrences === 1, "priority_cards={$priorityCardOccurrences}; kpi_grids={$legacyKpiGridOccurrences}");
h110p11r9_add($checks, 'no_legacy_duplicate_kpi_section', strpos($view, 'workspace-grid revenue-summary revenue109-summary') === false, 'old duplicated KPI workspace absent');

$dataDrivenStatus = strpos($view, '$needsAttention = ($totalPercent !== null && $totalPercent <= -10) || $profitCurrent < 0;') !== false
    && strpos($view, "phase111_tr('Needs Attention', 'يحتاج إلى اهتمام')") !== false;
h110p11r9_add($checks, 'leadership_status_data_driven', $dataDrivenStatus, 'revenue decline/current loss derived state');
h110p11r9_add($checks, 'leadership_status_not_hardcoded_na', strpos($view, '>N/A</') === false && strpos($view, '>غير متاح</') === false, 'status card never hardcoded N/A');

h110p11r9_add($checks, 'semantic_change_colors_present', strpos($css, '.eri-v2-change--negative') !== false && strpos($css, '.eri-v2-change--positive') !== false && strpos($css, 'var(--eri-v2-red)') !== false && strpos($css, 'var(--eri-v2-green)') !== false, 'negative red / positive green');
h110p11r9_add($checks, 'change_direction_logic_data_driven', strpos($view, 'function phase111_change_class') !== false && strpos($view, 'return $percent > 0 ? \'positive\' : \'negative\';') !== false, 'semantic direction from actual percent');

h110p11r9_add($checks, 'compact_controls_direct_view', strpos($view, 'eri-v2-filter-grid') !== false && strpos($css, '.eri-v2-filter-grid') !== false, 'compact filter bar');
$yearFieldsServerHidden = substr_count($view, 'data-revenue-range-field') >= 2 && strpos($view, 'data-revenue-range-field <?= !$isRange ?') !== false;
$yearFieldsRuntimeGuard = strpos($js, 'syncModeFields') !== false && strpos($js, 'data-eri-year-fields-hidden') !== false;
h110p11r9_add($checks, 'year_mode_hides_range_fields_server_and_runtime', $yearFieldsServerHidden && $yearFieldsRuntimeGuard, 'From/To hidden in year mode');

h110p11r9_add($checks, 'revenue_mix_compact_direct_card', strpos($view, 'eri-v2-mix-layout') !== false && strpos($view, 'eri-v2-donut') !== false && strpos($view, 'eri-v2-mix-metrics') !== false, 'compact mix card');
h110p11r9_add($checks, 'executive_insight_data_driven', strpos($view, 'phase1092_executive_insights') !== false && strpos($view, 'data-executive-insight-source="selected-period-data"') !== false && strpos($view, 'Review revenue decline, payer concentration, and cost performance.') !== false, 'decision-oriented executive insight');
h110p11r9_add($checks, 'technical_executive_note_copy_removed', stripos($view, 'The executive insight below is generated') === false && stripos($view, 'Data Source: Executive Summary') === false && stripos($view, 'Data Status: Live') === false, '0 developer-facing copy');

$trendTabs = substr_count($view, 'class="eri-trend-tab eri-v2-tab"');
h110p11r9_add($checks, 'monthly_single_workspace_five_tabs', $trendTabs === 1 || strpos($view, 'foreach ($charts as $key => $chart)') !== false, 'five runtime tabs from existing chart set');
h110p11r9_add($checks, 'monthly_extremes_data_driven', strpos($view, 'function phase111_month_extremes') !== false && strpos($view, "'best' => " . '$best') !== false && strpos($view, "'weakest' => " . '$weakest') !== false, 'best/weakest derived from monthly rows');
h110p11r9_add($checks, 'monthly_chart_height_bounded', strpos($css, 'height: 430px !important') !== false && strpos($css, 'height: 390px !important') !== false && strpos($css, 'height: 350px !important') !== false, '430 desktop / 390 tablet / 350 mobile');
h110p11r9_add($checks, 'sticky_header_overlap_prevented_by_scope', strpos($css, 'body.page-revenue.eri-v2-active .elite-topbar') !== false && strpos($css, 'position: relative;') !== false && strpos($js, 'data-eri-sticky-overlap') !== false, 'Revenue page header non-sticky + runtime diagnostic');
h110p11r9_add($checks, 'horizontal_overflow_runtime_gate_present', strpos($js, 'data-eri-overflow-x') !== false, 'runtime overflow diagnostic');

h110p11r9_add($checks, 'executive_typography_contract', strpos($css, 'font-size: 40px') !== false && strpos($css, 'font-size: 28px') !== false && strpos($css, 'font-size: 16px') !== false, 'KPI 40 / section 28 / body 16');
h110p11r9_add($checks, 'arabic_17px_contract', strpos($css, 'html[lang="ar"] body.page-revenue.eri-v2-active') !== false && strpos($css, 'font-size: 17px') !== false, 'Arabic ~17px');
h110p11r9_add($checks, 'responsive_breakpoints_present', strpos($css, '@media (max-width: 1180px)') !== false && strpos($css, '@media (max-width: 900px)') !== false && strpos($css, '@media (max-width: 680px)') !== false, 'desktop/tablet/mobile');

h110p11r9_add($checks, 'daily_revenue_gate_forward_compatible', strpos($dailyRevenueQa, 'release_11_0_10_5_1_or_later') !== false && strpos($dailyRevenueQa, 'daily_revenue_baseline_provenance_preserved') !== false && strpos($dailyRevenueQa, "version_compare(\$currentRelease, '11.0.10.5.1', '>=')") !== false, 'stale exact-version equality removed');
h110p11r9_add($checks, 'daily_revenue_preservation_gate_present', is_file($preservationQaPath), 'H11.0-P10.5-R1 critical hash preservation');
h110p11r9_add($checks, 'daily_revenue_provenance_preserved_in_version', (string)($versionData['preserved_daily_revenue_release'] ?? '') === '11.0.10.5.1' && (string)($versionData['preserved_daily_revenue_phase'] ?? '') === 'H11.0-P10.5-R1' && (string)($versionData['preserved_daily_revenue_contract'] ?? '') === 'UNCHANGED', '11.0.10.5.1 / H11.0-P10.5-R1 / UNCHANGED');

$sqlPatternFound = preg_match('/\b(?:SELECT\s+.+\s+FROM|INSERT\s+INTO|UPDATE\s+[A-Za-z0-9_$#.]+\s+SET|DELETE\s+FROM|MERGE\s+INTO)\b/i', $js . "\n" . $view) === 1;
h110p11r9_add($checks, 'no_oracle_logic_in_ui_payload', stripos($js, 'oci_') === false && stripos($view, 'oci_') === false && !$sqlPatternFound, 'UI-only; existing Oracle reads remain controller/repository-owned');
h110p11r9_add($checks, 'oracle_writes_none', (string)($versionData['oracle_write_operations'] ?? '') === 'NONE', 'NONE');
h110p11r9_add($checks, 'legacy_parity_unchanged', (string)($versionData['legacy_parity_impact'] ?? '') === 'UNCHANGED', 'Population 29 / MATCHED 23 / PARTIAL 6 / MISSING 0 unchanged');
h110p11r9_add($checks, 'jckh_policy_unchanged', (string)($versionData['branch_policy'] ?? '') === 'READY_BRANCHES_ONLY_JCKH_DEFERRED', 'NJCH+MNH blocking; JCKH deferred non-blocking; DB scope unchanged');
h110p11r9_add($checks, 'legacy_chart_gate_compatibility_tokens_preserved', strpos($view, 'data-revenue-chart-gate') !== false && strpos($view, '__DDB_REVENUE_CHART_GATE__') !== false && strpos($js, '__DDB_REVENUE_CHART_GATE__') !== false, 'inherited H10.9.2 chart contract preserved');

$forbiddenVisible = [
    'Summary layer active',
    'Fast executive summary table',
    'Schema-aware queries',
    'Run scheduled refresh job',
    'Two panels per row on desktop',
    'Data Source: Executive Summary',
    'Data Status: Live',
];
$forbiddenHits = [];
foreach ($forbiddenVisible as $phrase) {
    if (stripos($view, $phrase) !== false || stripos($js, $phrase) !== false || stripos($css, $phrase) !== false) {
        $forbiddenHits[] = $phrase;
    }
}
h110p11r9_add($checks, 'no_developer_facing_visible_phrases', $forbiddenHits === [], $forbiddenHits === [] ? '0 hits' : implode(', ', $forbiddenHits));

$failed = array_values(array_filter($checks, static fn(array $check): bool => $check['status'] !== 'PASS'));
$result = [
    'status' => $failed === [] ? 'PASS' : 'FAIL',
    'phase' => 'H11.0-P11-R9',
    'version' => $release,
    'title' => 'Revenue Intelligence Executive Visual Closure + Daily Revenue Inherited Gate Compatibility',
    'package_revision' => 'R9',
    'oracle_writes' => 'NONE',
    'legacy_parity_impact' => 'UNCHANGED',
    'branch_policy' => 'READY_BRANCHES_ONLY_JCKH_DEFERRED',
    'preserved_daily_revenue' => '11.0.10.5.1 / H11.0-P10.5-R1 / UNCHANGED',
    'checks_total' => count($checks),
    'checks_pass' => count($checks) - count($failed),
    'checks_fail' => count($failed),
    'checks' => $checks,
];

ob_clean();
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
