<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

$root = dirname(__DIR__);
$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remote, ['127.0.0.1', '::1', 'localhost', ''], true);
$providedToken = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)env('DDB_QA_TOKEN', ''));
$tokenOk = $expectedToken !== '' && hash_equals($expectedToken, $providedToken);

if (!$isLocal && !$tokenOk) {
    http_response_code(403);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(['status' => 'FAIL', 'error' => 'Forbidden']);
    exit;
}

$viewPath = $root . '/app/Views/dashboard/index.php';
$cssPath = $root . '/public/assets/css/executive-ui-core.css';
$versionPath = $root . '/DDB_VERSION.json';

$viewSource = is_file($viewPath)
    ? (string)file_get_contents($viewPath)
    : '';

$cssSource = is_file($cssPath)
    ? (string)file_get_contents($cssPath)
    : '';

$version = [];
if (is_file($versionPath)) {
    $decoded = json_decode((string)file_get_contents($versionPath), true);
    $version = is_array($decoded) ? $decoded : [];
}

$release = (string)($version['release'] ?? '');

$checks = [];

$add = static function (
    string $name,
    bool $ok,
    string $detail = ''
) use (&$checks): void {
    $checks[] = [
        'name' => $name,
        'status' => $ok ? 'PASS' : 'FAIL',
        'detail' => $detail,
    ];
};

$technicalPhrases = [
    'Summary layer active',
    'Home KPIs are being read from the fast executive summary table.',
    'Key operational activity presented in a calm, readable three-card desktop grid.',
    'Two panels per row on desktop, one panel on tablet and mobile.',
    'Run the scheduled refresh job to update KPIs.',
    'Schema-aware queries',
    'storage/logs/app.log',
];

$technicalHits = [];

foreach ($technicalPhrases as $phrase) {
    if (stripos($viewSource, $phrase) !== false) {
        $technicalHits[] = $phrase;
    }
}

$add(
    'release_11_0_10_2_or_later',
    $release !== '' && version_compare($release, '11.0.10.2', '>='),
    $release
);

$add(
    'visible_technical_phrases_zero',
    count($technicalHits) === 0,
    implode(' | ', $technicalHits)
);

$add(
    'runtime_technical_alert_sanitizer_present',
    strpos($viewSource, '$technicalAlertPatterns = [') !== false
    && strpos($viewSource, '$sanitizeAlert = function') !== false
    && strpos(
        $viewSource,
        'No critical issues require executive attention'
    ) !== false,
    'technical alerts are normalized to executive wording'
);

$add(
    'executive_summary_copy_is_leadership_facing',
    strpos(
        $viewSource,
        'Leadership view of the hospital’s current operating position.'
    ) !== false,
    'no design explanation'
);

$add(
    'hospital_pulse_copy_is_leadership_facing',
    strpos(
        $viewSource,
        'Current-day activity across core hospital services.'
    ) !== false,
    'no desktop-grid wording'
);

$add(
    'decision_support_copy_is_leadership_facing',
    strpos(
        $viewSource,
        'Priority information supporting the next executive decision.'
    ) !== false,
    'no device/layout wording'
);

$add(
    'clinical_activity_top_3_contract',
    strpos(
        $viewSource,
        'array_slice($clinical[\'top_specialties\'], 0, 3)' 
    ) !== false
    && strpos(
        $viewSource,
        'data-top-specialty-limit="3"'
    ) !== false,
    'Top 3 specialties only'
);

$add(
    'critical_alerts_natural_height_contract',
    strpos(
        $viewSource,
        'data-critical-alerts-layout="natural-height"'
    ) !== false
    && strpos(
        $cssSource,
        '.exec-leadership-panel--content-fit'
    ) !== false
    && strpos(
        $cssSource,
        'align-self:start;'
    ) !== false,
    'content-fit alert panel'
);

$add(
    'main_grid_no_forced_equal_height',
    strpos(
        $cssSource,
        '.exec-leadership-main-grid'
    ) !== false
    && preg_match(
        '/\.exec-leadership-main-grid\s*\{[^}]*align-items\s*:\s*start\s*;/s',
        $cssSource
    ) === 1,
    'grid items align to start'
);

$add(
    'critical_alerts_full_width_compact',
    strpos(
        $viewSource,
        'data-attention-layout="full-width-compact"'
    ) !== false
    && strpos(
        $cssSource,
        '.exec-leadership-panel--attention-wide'
    ) !== false,
    'full-width compact executive attention strip'
);

$add(
    'recommended_actions_full_width_three_up',
    strpos(
        $viewSource,
        'data-actions-layout="full-width-three-up"'
    ) !== false
    && strpos(
        $cssSource,
        '.exec-leadership-panel--actions-wide'
    ) !== false
    && preg_match(
        '/\.exec-leadership-panel--actions-wide \.exec-leadership-actions\s*\{[^}]*grid-template-columns\s*:\s*repeat\(3,minmax\(0,1fr\)\)\s*;/s',
        $cssSource
    ) === 1,
    'desktop three-up actions'
);

$add(
    'shared_css_only',
    !is_file($root . '/public/assets/css/executive-home-p10-2.css'),
    'no page-specific stylesheet'
);

$add(
    'oracle_writes_none',
    true,
    'visual-only closure'
);

$failures = count(array_filter(
    $checks,
    static function (array $check): bool {
        return $check['status'] === 'FAIL';
    }
));

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P10.2',
    'title' => 'Executive Homepage Final Visual Closure',
    'production_view' => 'app/Views/dashboard/index.php',
    'shared_css' => 'public/assets/css/executive-ui-core.css',
    'technical_phrase_hits' => $technicalHits,
    'clinical_top_specialty_limit' => 3,
    'critical_alerts_layout' => 'NATURAL_HEIGHT',
    'main_grid_alignment' => 'START',
    'attention_layout' => 'FULL_WIDTH_COMPACT',
    'actions_layout' => 'FULL_WIDTH_THREE_UP',
    'new_page_specific_css_files' => 0,
    'new_page_specific_js_files' => 0,
    'oracle_reads_introduced' => 'NONE',
    'oracle_writes' => 'NONE',
    'checks' => $checks,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

header('Content-Type: application/json; charset=UTF-8');

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