<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$controller = file_get_contents($root . '/app/Controllers/BedsController.php');
$view = file_get_contents($root . '/app/Views/beds/index.php');
$layout = file_get_contents($root . '/app/Views/layouts/main.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.81',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P8.3.1',
    'all_units_preserved_in_controller' => strpos($controller, '$isAllUnits = $unitId <= 0') !== false,
    'auto_select_removed' => strpos($controller, '$unitId = (int)($unitOptions[0]') === false,
    'scope_current_units' => strpos($controller, '$scopeCurrentUnits') !== false,
    'scope_compare_units' => strpos($controller, '$scopeCompareUnits') !== false,
    'scope_summary' => strpos($controller, '$this->weightedUtilization($scopeCurrentUnits)') !== false,
    'all_units_option' => strpos($view, "value=\"0\"") !== false
        && strpos($view, "All units") !== false,
    'all_units_selected_by_default' => strpos($view, "\$isAllUnits ? 'selected' : ''") !== false,
    'scope_label' => strpos($view, '$scopeLabel') !== false,
    'specific_unit_drilldown_conditional' => strpos($view, "<?php if (!\$isAllUnits): ?>") !== false,
    'bed_query_skipped_for_all_units' => strpos($controller, '$currentBeds = $isAllUnits') !== false
        && strpos($controller, '$compareBeds = $isAllUnits') !== false,
    'scope_chart' => strpos($view, '$isAllUnits ? $unitComparison : $scopeUnitComparison') !== false,
    'cache_identity' => strpos(
        $layout,
        'beds-executive-redesign.css?v=11.0.11.81-r45-p8-3-1-all-units-scope'
    ) !== false,
    'oracle_writes_none' => ($version['r45_p8_3_1']['oracle_writes'] ?? '') === 'NONE',
];

$failed = [];
foreach ($checks as $name => $ok) {
    if (!$ok) $failed[] = $name;
}

echo json_encode([
    'schema' => 'R45_P8_3_1_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;

exit(count($failed) === 0 ? 0 : 1);
