<?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';
$layoutPath = $root . '/app/Views/layouts/main.php';
$cssPath = $root . '/public/assets/css/executive-ui-core.css';
$versionPath = $root . '/DDB_VERSION.json';

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

$layoutSource = is_file($layoutPath)
    ? (string)file_get_contents($layoutPath)
    : '';

$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 : [];
}

$browserMode = isset($_GET['browser']) && (string)$_GET['browser'] === '1';

if ($browserMode) {
    $viewport = trim((string)($_GET['viewport'] ?? 'desktop'));

    $viewportContract = [
        'desktop' => [
            'situation' => 4,
            'pulse' => 3,
            'main' => 2,
        ],
        'tablet' => [
            'situation' => 2,
            'pulse' => 2,
            'main' => 1,
        ],
        'mobile' => [
            'situation' => 1,
            'pulse' => 1,
            'main' => 1,
        ],
    ];

    if (!isset($viewportContract[$viewport])) {
        $viewport = 'desktop';
    }

    $expected = $viewportContract[$viewport];

    $executive = [
        'mode' => 'summary',
        'is_fast_mode' => false,
        'last_updated' => '2026-07-12 09:12',
        'today' => '2026-07-12',
        'operational' => [
            'operational_date' => '2026-07-12',
            'window_start' => '2026-07-12 07:00',
            'window_end' => '2026-07-13 07:00',
            'is_rollover' => false,
        ],
        'status' => [
            'status' => 'STABLE',
            'tone' => 'good',
            'text' => 'Operations normal',
        ],
        'flow' => [
            'opd' => 23,
            'er' => 0,
            'admissions' => 2,
            'discharges' => 0,
            'scheduled_operations' => 0,
            'performed_operations' => 0,
        ],
        'finance' => [
            'today_total' => 28100,
            'month_total' => 3050000,
            'cash' => 554600,
            'insurance' => 2500000,
            'moh' => 159700,
            'net' => 2890000,
        ],
        'capacity' => [
            'occupancy_rate' => 36,
            'available_beds' => 138,
            'total_beds' => 214,
            'expected_discharges' => 1,
            'units' => [
                ['unit_label' => 'ICU', 'occupancy_pct' => 66],
                ['unit_label' => 'Medical', 'occupancy_pct' => 52],
                ['unit_label' => 'Long-term Care', 'occupancy_pct' => 57],
            ],
        ],
        'clinical' => [
            'active_doctors' => 130,
            'op_mix' => 0,
            'ip_mix' => 0,
            'top_doctor' => [
                'label' => 'Ahmed Shawki Elsayed Farag',
                'value' => 28020000,
            ],
            'top_specialties' => [
                ['label' => 'Internal Medicine', 'value' => 139590000],
                ['label' => 'Pediatrics', 'value' => 82750000],
                ['label' => 'Surgery', 'value' => 62840000],
                ['label' => 'Obst/Gyne', 'value' => 58730000],
                ['label' => 'Orthopedics', 'value' => 42400000],
            ],
        ],
        'alerts' => [],
        'actions' => [],
    ];

    $hospital = ['name' => 'New Jeddah'];
    $executiveError = null;

    ob_start();
    require $viewPath;
    $dashboardHtml = (string)ob_get_clean();

    header('Content-Type: text/html; charset=UTF-8');

    ?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <meta
        name="viewport"
        content="width=device-width, initial-scale=1"
    >
    <title>Executive Dashboard Responsive QA</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <link
        rel="stylesheet"
        href="assets/css/executive-ui-core.css?v=h11-0-p10-1-executive-leadership-responsive-v3"
    >
    <style>
      html,body{
        margin:0;
        min-width:0;
        max-width:100%;
        overflow-x:hidden;
        background:#f5f7fb;
      }
      body{
        padding:18px;
      }
      @media(max-width:720px){
        body{padding:10px}
      }
      #responsive-probe{
        position:fixed;
        width:1px;
        height:1px;
        overflow:hidden;
        opacity:.001;
        pointer-events:none;
      }
    </style>
</head>
<body>
<div
    id="responsive-probe"
    data-browser-gate="PENDING"
    data-viewport="<?= htmlspecialchars($viewport, ENT_QUOTES, 'UTF-8') ?>"
    data-expected-situation="<?= (int)$expected['situation'] ?>"
    data-expected-pulse="<?= (int)$expected['pulse'] ?>"
    data-expected-main="<?= (int)$expected['main'] ?>"
    data-production-view="app/Views/dashboard/index.php"
></div>

<?= $dashboardHtml ?>

<script>
(function () {
    function columnCount(element) {
        if (!element) {
            return 0;
        }

        var value = window.getComputedStyle(element).gridTemplateColumns.trim();

        if (!value || value === 'none') {
            return 0;
        }

        return value.split(/\s+/).filter(Boolean).length;
    }

    function runResponsiveProbe() {
        var probe = document.getElementById('responsive-probe');
        var situation = document.querySelector('[data-grid-role="situation"]');
        var pulse = document.querySelector('[data-grid-role="pulse"]');
        var main = document.querySelector('[data-grid-role="main"]');

        var actualSituation = columnCount(situation);
        var actualPulse = columnCount(pulse);
        var actualMain = columnCount(main);

        var expectedSituation = parseInt(
            probe.getAttribute('data-expected-situation'),
            10
        );
        var expectedPulse = parseInt(
            probe.getAttribute('data-expected-pulse'),
            10
        );
        var expectedMain = parseInt(
            probe.getAttribute('data-expected-main'),
            10
        );

        var horizontalOverflow = (
            document.documentElement.scrollWidth > window.innerWidth + 1
            || document.body.scrollWidth > window.innerWidth + 1
        );

        var pass = (
            actualSituation === expectedSituation
            && actualPulse === expectedPulse
            && actualMain === expectedMain
            && !horizontalOverflow
        );

        probe.setAttribute(
            'data-browser-gate',
            pass ? 'PASS' : 'FAIL'
        );
        probe.setAttribute(
            'data-situation-columns',
            String(actualSituation)
        );
        probe.setAttribute(
            'data-pulse-columns',
            String(actualPulse)
        );
        probe.setAttribute(
            'data-main-columns',
            String(actualMain)
        );
        probe.setAttribute(
            'data-horizontal-overflow',
            horizontalOverflow ? 'YES' : 'NO'
        );
        probe.setAttribute(
            'data-window-width',
            String(window.innerWidth)
        );
        probe.setAttribute(
            'data-document-width',
            String(document.documentElement.scrollWidth)
        );
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', runResponsiveProbe);
    } else {
        runResponsiveProbe();
    }

    window.addEventListener('load', runResponsiveProbe);
    setTimeout(runResponsiveProbe, 250);
})();
</script>
</body>
</html>
    <?php
    exit;
}

$checks = [];

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

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

$add(
    'release_11_0_10_1_or_later',
    $release !== '' && version_compare($release, '11.0.10.1', '>='),
    $release
);

$add(
    'leadership_contract_v3_present',
    strpos(
        $viewSource,
        'data-exec-leadership-contract="v3"'
    ) !== false,
    'production dashboard view'
);

$add(
    'responsive_contract_4_3_2_2_2_1_1_1_1',
    strpos(
        $viewSource,
        'desktop:4-3-2;tablet:2-2-1;mobile:1-1-1'
    ) !== false,
    'desktop/tablet/mobile density contract'
);

$add(
    'desktop_situation_max_4',
    strpos(
        $cssSource,
        'grid-template-columns:repeat(4,minmax(0,1fr));'
    ) !== false,
    '4 situation cards'
);

$add(
    'desktop_pulse_max_3',
    strpos(
        $cssSource,
        '.exec-leadership-pulse-grid'
    ) !== false
    && strpos(
        $cssSource,
        'grid-template-columns:repeat(3,minmax(0,1fr));'
    ) !== false,
    '3 operational cards per row'
);

$add(
    'desktop_main_max_2',
    strpos(
        $cssSource,
        '.exec-leadership-main-grid'
    ) !== false
    && strpos(
        $cssSource,
        'grid-template-columns:repeat(2,minmax(0,1fr));'
    ) !== false,
    '2 decision-support panels per row'
);

$add(
    'tablet_breakpoint_present',
    strpos($cssSource, '@media (max-width:1180px)') !== false,
    'tablet responsive contract'
);

$add(
    'mobile_breakpoint_present',
    strpos($cssSource, '@media (max-width:720px)') !== false,
    'mobile responsive contract'
);

$add(
    'narrow_phone_overflow_guard_present',
    strpos($cssSource, '@media (max-width:420px)') !== false,
    'narrow-phone overflow guard'
);

$add(
    'typography_contract_present',
    strpos(
        $cssSource,
        '--exec-v3-page-title:clamp(34px,2.7vw,44px)'
    ) !== false
    && strpos(
        $cssSource,
        '--exec-v3-section-title:clamp(24px,1.85vw,28px)'
    ) !== false
    && strpos(
        $cssSource,
        '--exec-v3-kpi-value:clamp(32px,2.7vw,48px)'
    ) !== false
    && strpos($cssSource, '--exec-v3-body:16px') !== false
    && strpos($cssSource, '--exec-v3-body-ar:17px') !== false,
    'leadership typography'
);

$add(
    'operational_cards_exactly_6',
    strpos(
        $viewSource,
        'data-operational-card-count="6"'
    ) !== false,
    '6 operational cards'
);

$technicalPhrases = [
    'Phase 10.4 — Executive Action Center Enabled',
    'المرحلة 10.4 — تفعيل مركز الإجراءات التنفيذي',
    'Summary Layer is Active',
    'طبقة الملخصات مفعلة',
    'Home KPIs are being read from the fast executive summary table.',
    'storage/logs/app.log',
    'Run the scheduled refresh job to update KPIs.',
    'Schema-aware queries',
];

$technicalHits = [];

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

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

$add(
    'dashboard_subtitle_is_executive_facing',
    strpos(
        $layoutSource,
        'Hospital performance, risk and decision priorities at a glance.'
    ) !== false
    && strpos(
        $layoutSource,
        'أداء المستشفى والمخاطر وأولويات القرار بنظرة واحدة.'
    ) !== false,
    'leadership-facing subtitle'
);

$add(
    'shared_css_only_no_new_page_stylesheet',
    strpos(
        $layoutSource,
        'executive-ui-core.css?v=h11-0-p10-1-executive-leadership-responsive-v3'
    ) !== false,
    'shared executive-ui-core.css'
);

$add(
    'branch_status_panel_absent',
    stripos($viewSource, 'Branch Status') === false
    && stripos($viewSource, 'حالة الفرع') === false
    && stripos($viewSource, 'exec-leadership-branch-status') === false,
    'no branch-status panel'
);

$add(
    'production_dashboard_view_is_reused_by_browser_probe',
    strpos(
        (string)file_get_contents(__FILE__),
        'require $viewPath;'
    ) !== false,
    'same app/Views/dashboard/index.php'
);

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

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P10.1',
    'title' => 'Executive Command Center Leadership-First Responsive Redesign',
    'production_view' => 'app/Views/dashboard/index.php',
    'shared_css' => 'public/assets/css/executive-ui-core.css',
    'responsive_contract' => [
        'desktop' => [
            'window' => '1600x1000',
            'situation_columns' => 4,
            'pulse_columns' => 3,
            'main_columns' => 2,
        ],
        'tablet' => [
            'window' => '900x1200',
            'situation_columns' => 2,
            'pulse_columns' => 2,
            'main_columns' => 1,
        ],
        'mobile' => [
            'window' => '390x844',
            'situation_columns' => 1,
            'pulse_columns' => 1,
            'main_columns' => 1,
        ],
    ],
    'visible_technical_phrase_hits' => $technicalHits,
    '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
);
