<?php
require_once dirname(__DIR__) . '/components/executive/components.php';

$hospitalName = $hospital['name'] ?? strtoupper($hospitalCode);
$moduleTitle = t($moduleConfig['title_key']);
$moduleHero = t($moduleConfig['hero_key']);
$moduleText = t($moduleConfig['text_key'], ['hospital' => $hospitalName]);
$moduleIcon = $moduleConfig['icon'];
$moduleTone = $moduleConfig['tone'];
$steps = [
    ['title' => t('operations.step_1_title'), 'text' => t('operations.step_1_text')],
    ['title' => t('operations.step_2_title'), 'text' => t('operations.step_2_text')],
    ['title' => t('operations.step_3_title'), 'text' => t('operations.step_3_text')],
];
$isVisits = $module === 'visits';
$isDoctors = $module === 'doctors';
$isBeds = $module === 'beds';
$isOperations = $module === 'operations';
$isLiveModule = $isVisits || $isDoctors || $isBeds || $isOperations;
?>

<?php if ($isVisits || $isOperations): ?>
    <?php if ($isVisits): ?>
    <!-- H11_0_P11_1_R31_VISITS_GENERAL_MANAGER_EXECUTIVE_DECISION_REDESIGN -->
    <?php else: ?>
    <!-- H11_0_P11_1_R37_OPERATIONS_GENERAL_MANAGER_EXECUTIVE_DECISION_REDESIGN -->
    <?php endif; ?>
    <?php // The shared top layout already carries the page title and branch context. R31 intentionally avoids a duplicate hero. ?>
<?php else: ?>
<section class="operations-hero executive-hero compact-hero tone-<?= e($moduleTone) ?>">
    <div class="hero-copy">
        <span class="overline light"><?= e($isVisits ? t('visits.kicker_live') : ($isDoctors ? t('doctors.kicker_live') : ($isBeds ? t('beds.kicker_live') : ($isOperations ? t('operations.kicker_live') : t('operations.kicker'))))) ?></span>
        <h2><span><?= e($moduleIcon) ?></span> <?= e($moduleHero) ?></h2>
        <p><?= e($moduleText) ?></p>
        <div class="hero-actions">
            <button type="button" class="btn subtle" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
            <?php if ($isVisits): ?>
                <a class="btn primary" href="#visits-live-data"><?= e(t('visits.open_live_data')) ?></a>
            <?php elseif ($isDoctors): ?>
                <a class="btn primary" href="#doctors-live-data"><?= e(t('doctors.open_live_data')) ?></a>
            <?php elseif ($isBeds): ?>
                <a class="btn primary" href="#beds-live-data"><?= e(t('beds.open_live_data')) ?></a>
            <?php elseif ($isOperations): ?>
                <a class="btn primary" href="#operations-live-data"><?= e(t('operations.open_live_data')) ?></a>
            <?php else: ?>
                <a class="btn primary" href="<?= e(url_to('revenue')) ?>"><?= e(t('dashboard.open_revenue')) ?></a>
            <?php endif; ?>
        </div>
    </div>
    <div class="hero-command-card">
        <div class="command-topline"><span><?= e(t('layout.active_branch')) ?></span><i></i></div>
        <strong><?= e($hospitalName) ?></strong>
        <div class="operations-badge"><?= e($moduleIcon) ?></div>
        <h3><?= e($moduleTitle) ?></h3>
        <p><?= e($isVisits ? t('visits.module_live_text') : ($isDoctors ? t('doctors.module_live_text') : ($isBeds ? t('beds.module_live_text') : ($isOperations ? t('operations.module_live_text') : t('operations.module_ready_text'))))) ?></p>
    </div>
</section>
<?php endif; ?>

<?php if (!$isVisits && !$isOperations): ?>
<section class="metric-grid four">
    <?php foreach ($stats as $stat): ?>
        <article class="metric-card tone-<?= e($stat['tone']) ?>">
            <div class="metric-orb"></div>
            <span><?= e($stat['label']) ?></span>
            <strong><?= e($stat['value']) ?></strong>
            <small><?= e($stat['hint']) ?></small>
        </article>
    <?php endforeach; ?>
</section>
<?php endif; ?>

<?php if ($isVisits): ?>
    <?php
        $activeMode = $reportMode ?? 'year';
        $periodCurrent = is_array($visitData) ? (string)($visitData['current_period_label'] ?? $year) : ($activeMode === 'range' ? ($fromDate . ' - ' . $toDate) : (string)$year);
        $periodCompare = is_array($visitData) ? (string)($visitData['compare_period_label'] ?? $compareYear) : (string)$compareYear;
        $visitsComparisonContract = is_array($visitsComparisonContract ?? null)
            ? $visitsComparisonContract
            : (is_array($visitData['comparison_contract'] ?? null) ? $visitData['comparison_contract'] : []);
        $visitsFairCurrentYear = $activeMode === 'year'
            && !empty($visitsComparisonContract['fair_current_year_comparison']);
        $visitsLastCompleteMonth = (int)($visitsComparisonContract['last_complete_month'] ?? 12);
        $visitsExcludedMonth = (int)($visitsComparisonContract['current_month_excluded'] ?? 0);
        $visitMonthsEn = [1=>'January',2=>'February',3=>'March',4=>'April',5=>'May',6=>'June',7=>'July',8=>'August',9=>'September',10=>'October',11=>'November',12=>'December'];
        $visitMonthsAr = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
        $visitsIsArabic = current_lang() === 'ar';
        $vtxt = static function (string $en, string $ar) use ($visitsIsArabic): string { return $visitsIsArabic ? $ar : $en; };
        $compactVisitNumber = static function ($value): string {
            $n = (float)$value;
            $abs = abs($n);
            if ($abs >= 1000000) return number_format($n / 1000000, 2) . 'M';
            if ($abs >= 1000) return number_format($n / 1000, 1) . 'K';
            return number_format($n, 0);
        };
        $deltaPct = static function ($current, $compare): ?float {
            $c = (float)$current; $p = (float)$compare;
            if (abs($p) < 0.000001) return null;
            return (($c - $p) / abs($p)) * 100.0;
        };
        $topFivePayload = static function (array $chart): array {
            $rows = array_values($chart['rows'] ?? []);
            if (!$rows) return $chart['payload'] ?? [];
            $ranked = $rows;
            usort($ranked, static function (array $a, array $b): int {
                return ((float)($b['current_value'] ?? 0)) <=> ((float)($a['current_value'] ?? 0));
            });
            $selected = array_slice($ranked, 0, 5);
            $order = [];
            foreach ($rows as $idx => $row) $order[(string)($row['month_name'] ?? $idx)] = $idx;
            usort($selected, static function (array $a, array $b) use ($order): int {
                return ($order[(string)($a['month_name'] ?? '')] ?? 999) <=> ($order[(string)($b['month_name'] ?? '')] ?? 999);
            });
            $payload = $chart['payload'] ?? [];
            $payload['labels'] = array_map(static fn(array $r): string => (string)($r['month_name'] ?? ''), $selected);
            if (!empty($payload['series']) && is_array($payload['series'])) {
                foreach ($payload['series'] as $seriesIndex => $series) {
                    $isCurrent = $seriesIndex === 0;
                    $payload['series'][$seriesIndex]['values'] = array_map(static function (array $r) use ($isCurrent): float {
                        return (float)($r[$isCurrent ? 'current_value' : 'compare_value'] ?? 0);
                    }, $selected);
                }
            }
            $payload['showHeader'] = false;
            $payload['showDataLabels'] = true;
            return $payload;
        };
    ?>

    <?php if ($dataError): ?>
        <section class="surface-card visits31-state visits31-state--attention">
            <span class="overline"><?= e($vtxt('Information unavailable', 'المعلومات غير متاحة')) ?></span>
            <h2><?= e($vtxt('The selected visit view is not available right now.', 'العرض المحدد للزيارات غير متاح حاليًا.')) ?></h2>
            <p><?= e($vtxt('Please choose another period or branch and try again.', 'يرجى اختيار فترة أو فرع آخر ثم المحاولة مرة أخرى.')) ?></p>
        </section>
    <?php elseif (is_array($visitData)): ?>
        <?php
            $visitCards = $visitData['cards'] ?? [];
            $visitIcons = ['opd' => '♧', 'er' => '✚', 'admissions' => '▣', 'followup' => '♟'];
            $visitTones = ['opd' => 'blue', 'er' => 'violet', 'admissions' => 'teal', 'followup' => 'purple'];

            $changeItems = [];
            foreach (['opd', 'er', 'admissions'] as $metricKey) {
                $card = $visitCards[$metricKey] ?? null;
                if (!is_array($card) || ($card['percent'] ?? null) === null) continue;
                $changeItems[] = ['key' => $metricKey, 'title' => (string)$card['title'], 'percent' => (float)$card['percent']];
            }
            usort($changeItems, static fn(array $a, array $b): int => abs($b['percent']) <=> abs($a['percent']));
            $primaryChange = $changeItems[0] ?? null;

            $visitChartPayloads = [];
            foreach (['opd', 'er', 'admissions'] as $chartKey) {
                $visitChartPayloads[$chartKey] = $topFivePayload($visitData['charts'][$chartKey] ?? []);
            }

            $opdRows = array_values($visitData['charts']['opd']['rows'] ?? []);
            $rankedMonths = $opdRows;
            usort($rankedMonths, static fn(array $a, array $b): int => ((float)($b['current_value'] ?? 0)) <=> ((float)($a['current_value'] ?? 0)));
            $matrixRows = array_slice($rankedMonths, 0, 5);

            $erRowsByMonth = [];
            foreach (($visitData['charts']['er']['rows'] ?? []) as $row) $erRowsByMonth[(string)($row['month_name'] ?? '')] = $row;
            $admRowsByMonth = [];
            foreach (($visitData['charts']['admissions']['rows'] ?? []) as $row) $admRowsByMonth[(string)($row['month_name'] ?? '')] = $row;

            $mix = $visitData['followup'] ?? [];
            $followupPct = max(0.0, min(100.0, (float)($mix['ratio'] ?? 0)));
            $newPct = max(0.0, min(100.0, (float)($mix['new_ratio'] ?? 0)));
            $totalVisits = (float)($mix['new'] ?? 0) + (float)($mix['followup'] ?? 0);

            $admissionCategories = array_slice(array_values($visitData['admissionCategories'] ?? []), 0, 4);
            $specialties = array_slice(array_values($visitData['specialties'] ?? []), 0, 5);
            $specialtyMax = 1.0;
            foreach ($specialties as $row) $specialtyMax = max($specialtyMax, (float)($row['value'] ?? 0));
        ?>

        <section id="visits-live-data" class="surface-card visits31-comparison" data-patient-activity-controls>
            <div class="visits31-comparison-copy">
                <span class="overline"><?= e($vtxt('Comparison period', 'فترة المقارنة')) ?></span>
                <strong><?= e($periodCurrent) ?> · <?= e($hospitalName) ?></strong>
                <small><?= e($vtxt('Adjust the comparison only when a different leadership view is needed.', 'غيّر المقارنة فقط عند الحاجة إلى منظور إداري مختلف.')) ?></small>
            </div>
            <form method="get" action="index.php" class="visits31-filter <?= $activeMode === 'range' ? 'is-range' : 'is-year' ?>" data-patient-filter>
                <input type="hidden" name="page" value="visits">
                <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
                <label class="visits31-mode-field">
                    <span><?= e($vtxt('Report mode', 'نمط العرض')) ?></span>
                    <select name="mode" data-patient-mode>
                        <option value="year" <?= $activeMode === 'year' ? 'selected' : '' ?>><?= e($vtxt('Year comparison', 'مقارنة سنوية')) ?></option>
                        <option value="range" <?= $activeMode === 'range' ? 'selected' : '' ?>><?= e($vtxt('Custom date range', 'فترة زمنية مخصصة')) ?></option>
                    </select>
                </label>
                <label data-year-field><span><?= e($vtxt('Current year', 'السنة الحالية')) ?></span><input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>"></label>
                <label data-range-field><span><?= e($vtxt('From', 'من')) ?></span><input type="date" name="from_date" value="<?= e($fromDate ?? '') ?>"></label>
                <label data-range-field><span><?= e($vtxt('To', 'إلى')) ?></span><input type="date" name="to_date" value="<?= e($toDate ?? '') ?>"></label>
                <label><span><?= e($vtxt('Comparison year', 'سنة المقارنة')) ?></span><input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>"></label>
                <button class="btn primary visits31-apply" type="submit"><?= e($vtxt('Apply comparison', 'تطبيق المقارنة')) ?></button>
            </form>
            <?php if ($visitsFairCurrentYear): ?>
                <div class="visits31-fair-comparison" role="note">
                    <span class="visits31-fair-icon" aria-hidden="true">✓</span>
                    <div>
                        <strong><?= e($vtxt('Fair current-year comparison', 'مقارنة عادلة للسنة الحالية')) ?></strong>
                        <?php if ($visitsLastCompleteMonth > 0): ?>
                            <p><?= e($vtxt(
                                'The comparison covers January through ' . ($visitMonthsEn[$visitsLastCompleteMonth] ?? '') . ' in both years. The incomplete current month, ' . ($visitMonthsEn[$visitsExcludedMonth] ?? '') . ', is excluded.',
                                'تشمل المقارنة الفترة من يناير حتى ' . ($visitMonthsAr[$visitsLastCompleteMonth] ?? '') . ' في السنتين. تم استبعاد الشهر الحالي غير المكتمل، ' . ($visitMonthsAr[$visitsExcludedMonth] ?? '') . '.'
                            )) ?></p>
                        <?php else: ?>
                            <p><?= e($vtxt(
                                'The current month is the first month of the year, so no completed month is available for a fair comparison yet.',
                                'الشهر الحالي هو أول شهر في السنة، لذلك لا يوجد شهر مكتمل متاح للمقارنة العادلة حتى الآن.'
                            )) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
            <?php if (!empty($visitsFilterError)): ?><div class="visits31-filter-message" role="alert"><?= e($visitsFilterError) ?></div><?php endif; ?>
        </section>

        <?php if (!empty($visitData['warnings'])): ?>
            <section class="surface-card visits31-state visits31-state--notice">
                <strong><?= e($vtxt('Some indicators are not available for the selected view.', 'بعض المؤشرات غير متاحة للعرض المحدد.')) ?></strong>
                <span><?= e($vtxt('Available measures are shown below without substituting missing values.', 'يتم عرض المؤشرات المتاحة أدناه دون استبدال القيم غير المتوفرة.')) ?></span>
            </section>
        <?php endif; ?>

        <section class="visits31-kpi-grid" aria-label="<?= e($vtxt('Executive visit indicators', 'مؤشرات الزيارات التنفيذية')) ?>">
            <?php foreach ($visitCards as $key => $card): ?>
                <?php
                    $isRatio = ($card['mode'] ?? '') === 'ratio';
                    $pct = $card['percent'] ?? null;
                    $tone = $visitTones[$key] ?? 'blue';
                ?>
                <article class="visits31-kpi visits31-kpi--<?= e($tone) ?>">
                    <div class="visits31-kpi-icon"><?= e($visitIcons[$key] ?? '◇') ?></div>
                    <div class="visits31-kpi-copy">
                        <span><?= e($card['title']) ?></span>
                        <strong><?= e(number_format((float)$card['current_total'], 0)) ?></strong>
                        <?php if ($isRatio): ?>
                            <small><?= e($vtxt('Follow-up share', 'نسبة المتابعة')) ?> · <?= $pct === null ? e($vtxt('Not available', 'غير متاح')) : e(number_format((float)$pct, 1) . '%') ?></small>
                        <?php else: ?>
                            <small><?= e($vtxt('Previous period', 'الفترة السابقة')) ?> · <?= e(number_format((float)$card['compare_total'], 0)) ?></small>
                        <?php endif; ?>
                    </div>
                    <?php if (!$isRatio && $pct !== null): ?>
                        <em class="visits31-delta <?= (float)$pct >= 0 ? 'up' : 'down' ?>"><?= e(((float)$pct >= 0 ? '↑ ' : '↓ ') . number_format(abs((float)$pct), 1) . '%') ?></em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="surface-card visits31-insight">
            <div class="visits31-insight-icon">✦</div>
            <div>
                <span class="overline"><?= e($vtxt('Executive insight', 'الرؤية التنفيذية')) ?></span>
                <h2><?= e($vtxt('What leadership should know now', 'ما الذي يجب أن تعرفه الإدارة الآن')) ?></h2>
            </div>
            <p>
                <?php if (is_array($primaryChange)): ?>
                    <?= e($primaryChange['title']) ?> <?= e($primaryChange['percent'] >= 0 ? $vtxt('is up by', 'ارتفع بنسبة') : $vtxt('is down by', 'انخفض بنسبة')) ?> <strong><?= e(number_format(abs((float)$primaryChange['percent']), 1)) ?>%</strong> <?= e($vtxt('versus the comparison period.', 'مقارنة بفترة المقارنة.')) ?>
                <?php else: ?>
                    <?= e($vtxt('No material movement requires immediate leadership attention in the selected view.', 'لا توجد حركة جوهرية تتطلب اهتمامًا فوريًا من الإدارة في العرض المحدد.')) ?>
                <?php endif; ?>
            </p>
        </section>

        <section class="visits31-primary-grid">
            <article class="surface-card visits31-main-chart" id="visits31-monthly-movement">
                <div class="visits31-card-head">
                    <div>
                        <span class="overline"><?= e($vtxt('Patient movement', 'حركة المرضى')) ?></span>
                        <h2><?= e($vtxt('Monthly activity at a glance', 'النشاط الشهري بنظرة سريعة')) ?></h2>
                        <p><?= e($vtxt('Top five months are shown by default to keep the comparison clear.', 'يتم عرض أهم خمسة أشهر افتراضيًا للحفاظ على وضوح المقارنة.')) ?></p>
                    </div>
                    <div class="visits31-chart-tabs" role="tablist" aria-label="<?= e($vtxt('Visit trend metric', 'مؤشر اتجاه الزيارات')) ?>">
                        <button type="button" class="active" data-visits31-chart-tab="opd"><?= e($vtxt('Outpatient', 'العيادات الخارجية')) ?></button>
                        <button type="button" data-visits31-chart-tab="er"><?= e($vtxt('Emergency', 'الطوارئ')) ?></button>
                        <button type="button" data-visits31-chart-tab="admissions"><?= e($vtxt('Admissions', 'الدخول')) ?></button>
                    </div>
                </div>
                <?php foreach (['opd', 'er', 'admissions'] as $chartKey): ?>
                    <?php $chart = $visitData['charts'][$chartKey] ?? []; ?>
                    <div class="visits31-chart-panel <?= $chartKey === 'opd' ? 'active' : '' ?>" data-visits31-chart-panel="<?= e($chartKey) ?>" <?= $chartKey === 'opd' ? '' : 'hidden' ?>>
                        <div class="visits31-chart-meta"><strong><?= e($chart['title'] ?? '') ?></strong><span><?= e($periodCurrent) ?> · <?= e($vtxt('vs', 'مقابل')) ?> · <?= e($periodCompare) ?></span></div>
                        <div class="visits31-chart-stage" data-patient-chart-card="<?= e($chartKey) ?>" data-chart-state="pending">
                            <canvas id="visits_chart_<?= e($chartKey) ?>" class="chart visits-chart" height="184" data-patient-activity-chart="<?= e($chartKey) ?>" data-chart-rendered="false"></canvas>
                            <div class="patient1010-chart-state patient1010-chart-empty" hidden><?= e($vtxt('No activity is available for this view.', 'لا يتوفر نشاط لهذا العرض.')) ?></div>
                            <div class="patient1010-chart-state patient1010-chart-error" hidden><?= e($vtxt('This trend is not available right now.', 'هذا الاتجاه غير متاح حاليًا.')) ?></div>
                        </div>
                        <script type="application/json" id="visits_chart_data_<?= e($chartKey) ?>"><?= json_encode($visitChartPayloads[$chartKey], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
                    </div>
                <?php endforeach; ?>
            </article>

            <article class="surface-card visits31-balance-card">
                <div class="visits31-card-head visits31-card-head--stacked">
                    <div>
                        <span class="overline"><?= e($vtxt('Visit profile', 'ملف الزيارات')) ?></span>
                        <h2><?= e($vtxt('New vs follow-up balance', 'التوازن بين الزيارات الجديدة والمتابعة')) ?></h2>
                        <p><?= e($vtxt('How outpatient activity is divided between new and returning patients.', 'توزيع نشاط العيادات الخارجية بين المرضى الجدد ومرضى المتابعة.')) ?></p>
                    </div>
                </div>
                <div class="visits31-balance-numbers">
                    <div><i class="new"></i><strong><?= e(number_format((float)($mix['new'] ?? 0), 0)) ?></strong><span><?= e($vtxt('New patients', 'مرضى جدد')) ?></span><em><?= e(number_format($newPct, 1)) ?>%</em></div>
                    <div><i class="follow"></i><strong><?= e(number_format((float)($mix['followup'] ?? 0), 0)) ?></strong><span><?= e($vtxt('Follow-up patients', 'مرضى متابعة')) ?></span><em><?= e(number_format($followupPct, 1)) ?>%</em></div>
                </div>
                <div class="visits31-balance-bar" aria-label="<?= e($vtxt('New and follow-up visit balance', 'توازن الزيارات الجديدة والمتابعة')) ?>">
                    <span style="width: <?= e(number_format($newPct, 2, '.', '')) ?>%"><b><?= $newPct >= 12 ? e(number_format($newPct, 1) . '%') : '' ?></b></span>
                    <i style="width: <?= e(number_format($followupPct, 2, '.', '')) ?>%"><b><?= $followupPct >= 12 ? e(number_format($followupPct, 1) . '%') : '' ?></b></i>
                </div>
                <small class="visits31-total-visits"><?= e($vtxt('Total outpatient visits', 'إجمالي زيارات العيادات الخارجية')) ?> · <strong><?= e(number_format($totalVisits, 0)) ?></strong></small>
            </article>
        </section>

        <section class="visits31-secondary-grid">
            <article class="surface-card visits31-funding-card" id="visits31-funding-profile">
                <div class="visits31-card-head visits31-card-head--stacked">
                    <div>
                        <span class="overline"><?= e($vtxt('Admission profile', 'ملف الدخول')) ?></span>
                        <h2><?= e($vtxt('Admission funding profile', 'توزيع تمويل حالات الدخول')) ?></h2>
                        <p><?= e($vtxt('The principal funding categories for admissions in the selected period.', 'الفئات الرئيسية لتمويل حالات الدخول خلال الفترة المحددة.')) ?></p>
                    </div>
                </div>
                <div class="visits31-profile-list">
                    <?php foreach ($admissionCategories as $row): ?>
                        <?php $pct = max(0.0, min(100.0, (float)($row['percent'] ?? 0))); $categoryKey = (string)($row['category'] ?? 'other'); ?>
                        <div class="visits31-profile-row">
                            <div><strong><?= e(t('visits.admission_category_' . $categoryKey)) ?></strong><span><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></span></div>
                            <b><i style="width: <?= e(number_format($pct, 2, '.', '')) ?>%"></i></b>
                            <em><?= e(number_format($pct, 1)) ?>%</em>
                        </div>
                    <?php endforeach; ?>
                    <?php if (!$admissionCategories): ?><div class="visits31-empty"><?= e($vtxt('Admission funding information is not available for the selected view.', 'معلومات تمويل حالات الدخول غير متاحة للعرض المحدد.')) ?></div><?php endif; ?>
                </div>
            </article>

            <article class="surface-card visits31-specialty-card" id="visits31-top-specialties">
                <div class="visits31-card-head visits31-card-head--stacked">
                    <div>
                        <span class="overline"><?= e($vtxt('Demand concentration', 'تركيز الطلب')) ?></span>
                        <h2><?= e($vtxt('Top outpatient specialties', 'أعلى التخصصات في طلب العيادات الخارجية')) ?></h2>
                        <p><?= e($vtxt('The five specialties with the highest outpatient demand in the selected view.', 'أعلى خمسة تخصصات من حيث طلب العيادات الخارجية في العرض المحدد.')) ?></p>
                    </div>
                </div>
                <?php if ($specialties): ?>
                    <div class="visits31-specialty-list">
                        <?php foreach ($specialties as $idx => $row): ?>
                            <?php $width = max(4.0, ((float)($row['value'] ?? 0) / $specialtyMax) * 100.0); ?>
                            <div class="visits31-specialty-row">
                                <em><?= e($idx + 1) ?></em>
                                <strong><?= e((string)($row['label'] ?? '')) ?></strong>
                                <span><i style="width: <?= e(number_format($width, 2, '.', '')) ?>%"></i></span>
                                <b><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></b>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="visits31-empty visits31-empty--large">
                        <strong><?= e($vtxt('Specialty demand is not available for the selected view.', 'بيانات الطلب حسب التخصص غير متاحة للعرض المحدد.')) ?></strong>
                        <span><?= e($vtxt('The rest of the patient-flow indicators remain available.', 'تظل بقية مؤشرات تدفق المرضى متاحة.')) ?></span>
                    </div>
                <?php endif; ?>
            </article>
        </section>

        <section class="surface-card visits31-matrix-card" id="visits31-matrix">
            <div class="visits31-card-head">
                <div>
                    <span class="overline"><?= e($vtxt('Decision table', 'جدول القرار')) ?></span>
                    <h2><?= e($vtxt('Monthly visit matrix', 'مصفوفة الزيارات الشهرية')) ?></h2>
                    <p><?= e($vtxt('Five highest-demand months are shown first for rapid executive review.', 'يتم عرض أعلى خمسة أشهر من حيث الطلب أولًا للمراجعة التنفيذية السريعة.')) ?></p>
                </div>
                <a href="#visits31-full-matrix" class="visits31-text-link" data-visits31-full-matrix-link aria-controls="visits31-full-details" aria-expanded="false"><?= e($vtxt('View full matrix', 'عرض المصفوفة الكاملة')) ?> →</a>
            </div>
            <div class="visits31-table-wrap">
                <table>
                    <thead><tr>
                        <th><?= e($vtxt('Month', 'الشهر')) ?></th>
                        <th><?= e($vtxt('Outpatient visits', 'زيارات العيادات')) ?></th>
                        <th><?= e($vtxt('vs comparison', 'مقابل المقارنة')) ?></th>
                        <th><?= e($vtxt('Emergency visits', 'زيارات الطوارئ')) ?></th>
                        <th><?= e($vtxt('vs comparison', 'مقابل المقارنة')) ?></th>
                        <th><?= e($vtxt('Admissions', 'الدخول')) ?></th>
                        <th><?= e($vtxt('vs comparison', 'مقابل المقارنة')) ?></th>
                    </tr></thead>
                    <tbody>
                        <?php foreach ($matrixRows as $row): ?>
                            <?php
                                $month = (string)($row['month_name'] ?? '');
                                $erRow = $erRowsByMonth[$month] ?? [];
                                $admRow = $admRowsByMonth[$month] ?? [];
                                $opdDelta = $deltaPct($row['current_value'] ?? 0, $row['compare_value'] ?? 0);
                                $erDelta = $deltaPct($erRow['current_value'] ?? 0, $erRow['compare_value'] ?? 0);
                                $admDelta = $deltaPct($admRow['current_value'] ?? 0, $admRow['compare_value'] ?? 0);
                            ?>
                            <tr>
                                <td><strong><?= e($month) ?></strong></td>
                                <td><?= e(number_format((float)($row['current_value'] ?? 0), 0)) ?></td>
                                <td><?= $opdDelta === null ? '—' : '<span class="visits31-table-delta ' . ($opdDelta >= 0 ? 'up' : 'down') . '">' . e(($opdDelta >= 0 ? '↑ ' : '↓ ') . number_format(abs($opdDelta), 1) . '%') . '</span>' ?></td>
                                <td><?= e(number_format((float)($erRow['current_value'] ?? 0), 0)) ?></td>
                                <td><?= $erDelta === null ? '—' : '<span class="visits31-table-delta ' . ($erDelta >= 0 ? 'up' : 'down') . '">' . e(($erDelta >= 0 ? '↑ ' : '↓ ') . number_format(abs($erDelta), 1) . '%') . '</span>' ?></td>
                                <td><?= e(number_format((float)($admRow['current_value'] ?? 0), 0)) ?></td>
                                <td><?= $admDelta === null ? '—' : '<span class="visits31-table-delta ' . ($admDelta >= 0 ? 'up' : 'down') . '">' . e(($admDelta >= 0 ? '↑ ' : '↓ ') . number_format(abs($admDelta), 1) . '%') . '</span>' ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <details class="surface-card visits31-supporting-details" id="visits31-full-details">
            <summary><span><?= e($vtxt('Supporting operational details', 'التفاصيل التشغيلية الداعمة')) ?></span><small><?= e($vtxt('Open only when deeper review is needed', 'افتح عند الحاجة إلى مراجعة أعمق فقط')) ?></small></summary>
            <div class="visits31-supporting-grid">
                <article class="visits31-support-card">
                    <span class="overline"><?= e($vtxt('Last 14 days', 'آخر 14 يومًا')) ?></span>
                    <h3><?= e($vtxt('Daily scheduled visit trend', 'اتجاه الزيارات المجدولة يوميًا')) ?></h3>
                    <?php $dailyRows = array_slice(array_values($visitData['daily'] ?? []), -14); $dailyMax = 1.0; foreach ($dailyRows as $row) $dailyMax = max($dailyMax, (float)($row['value'] ?? 0)); ?>
                    <div class="visits31-daily-bars">
                        <?php foreach ($dailyRows as $row): ?>
                            <?php $height = max(8.0, ((float)($row['value'] ?? 0) / $dailyMax) * 100.0); ?>
                            <div title="<?= e((string)($row['label'] ?? '') . ': ' . number_format((float)($row['value'] ?? 0), 0)) ?>"><b><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></b><span style="height: <?= e(number_format($height, 2, '.', '')) ?>%"></span><small><?= e((string)($row['label'] ?? '')) ?></small></div>
                        <?php endforeach; ?>
                    </div>
                </article>

                <article class="visits31-support-card">
                    <span class="overline"><?= e($vtxt('Payment profile', 'ملف الدفع')) ?></span>
                    <h3><?= e($vtxt('Scheduled outpatient visits by payment type', 'الزيارات المجدولة للعيادات حسب نوع الدفع')) ?></h3>
                    <?php $outpatientPayerMix = array_values($visitData['outpatientPayerMix'] ?? []); ?>
                    <div class="visits31-profile-list visits31-profile-list--compact">
                        <?php foreach ($outpatientPayerMix as $row): ?>
                            <?php $pct = max(0.0, min(100.0, (float)($row['percent'] ?? 0))); $categoryKey = (string)($row['category'] ?? 'credit'); ?>
                            <div class="visits31-profile-row"><div><strong><?= e(t('visits.outpatient_payer_' . $categoryKey)) ?></strong><span><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></span></div><b><i style="width: <?= e(number_format($pct, 2, '.', '')) ?>%"></i></b><em><?= e(number_format($pct, 1)) ?>%</em></div>
                        <?php endforeach; ?>
                    </div>
                </article>

                <?php $multiBranchRows = array_values($visitData['multiBranchOutpatient'] ?? []); ?>
                <?php if ($multiBranchRows): ?>
                    <article class="visits31-support-card visits31-support-card--wide">
                        <span class="overline"><?= e($vtxt('Branch comparison', 'مقارنة الفروع')) ?></span>
                        <h3><?= e($vtxt('Outpatient visits across branches', 'زيارات العيادات الخارجية عبر الفروع')) ?></h3>
                        <div class="visits31-table-wrap"><table><thead><tr><th><?= e($vtxt('Month', 'الشهر')) ?></th><th><?= e(t('visits.branch_new_jeddah')) ?></th><th><?= e(t('visits.branch_madina')) ?></th><th><?= e($vtxt('Total', 'الإجمالي')) ?></th></tr></thead><tbody>
                            <?php foreach (array_slice($multiBranchRows, 0, 6) as $row): ?><tr><td><strong><?= e((string)($row['month_name'] ?? '')) ?></strong></td><td><?= e(number_format((float)($row['njch'] ?? 0), 0)) ?></td><td><?= e(number_format((float)($row['mnh'] ?? 0), 0)) ?></td><td><strong><?= e(number_format((float)($row['total'] ?? 0), 0)) ?></strong></td></tr><?php endforeach; ?>
                        </tbody></table></div>
                    </article>
                <?php endif; ?>

                <article class="visits31-support-card visits31-support-card--wide" id="visits31-full-matrix" tabindex="-1">
                    <span class="overline"><?= e($vtxt('Full matrix', 'المصفوفة الكاملة')) ?></span>
                    <h3><?= e($vtxt('All monthly visit values', 'جميع قيم الزيارات الشهرية')) ?></h3>
                    <div class="visits31-table-wrap"><table><thead><tr><th><?= e($vtxt('Month', 'الشهر')) ?></th><th><?= e($vtxt('Outpatient', 'العيادات')) ?> · <?= e($periodCurrent) ?></th><th><?= e($vtxt('Outpatient', 'العيادات')) ?> · <?= e($periodCompare) ?></th><th><?= e($vtxt('Emergency', 'الطوارئ')) ?> · <?= e($periodCurrent) ?></th><th><?= e($vtxt('Emergency', 'الطوارئ')) ?> · <?= e($periodCompare) ?></th><th><?= e($vtxt('Admissions', 'الدخول')) ?> · <?= e($periodCurrent) ?></th><th><?= e($vtxt('Admissions', 'الدخول')) ?> · <?= e($periodCompare) ?></th></tr></thead><tbody>
                        <?php foreach ($opdRows as $row): ?>
                            <?php $month = (string)($row['month_name'] ?? ''); $erRow = $erRowsByMonth[$month] ?? []; $admRow = $admRowsByMonth[$month] ?? []; ?>
                            <tr><td><strong><?= e($month) ?></strong></td><td><?= e(number_format((float)($row['current_value'] ?? 0),0)) ?></td><td><?= e(number_format((float)($row['compare_value'] ?? 0),0)) ?></td><td><?= e(number_format((float)($erRow['current_value'] ?? 0),0)) ?></td><td><?= e(number_format((float)($erRow['compare_value'] ?? 0),0)) ?></td><td><?= e(number_format((float)($admRow['current_value'] ?? 0),0)) ?></td><td><?= e(number_format((float)($admRow['compare_value'] ?? 0),0)) ?></td></tr>
                        <?php endforeach; ?>
                    </tbody></table></div>
                </article>
            </div>
        </details>

        <section class="surface-card visits31-actions">
            <div class="visits31-actions-title"><span class="overline"><?= e($vtxt('Recommended actions', 'الإجراءات المقترحة')) ?></span><h2><?= e($vtxt('Next actions for leadership review', 'الخطوات التالية للمراجعة الإدارية')) ?></h2></div>
            <a href="#visits31-monthly-movement"><i>♧</i><div><strong><?= e($vtxt('Review outpatient demand', 'مراجعة طلب العيادات الخارجية')) ?></strong><span><?= e($vtxt('Focus on the strongest and weakest demand months before allocating resources.', 'ركز على أقوى وأضعف أشهر الطلب قبل توزيع الموارد.')) ?></span></div><em>→</em></a>
            <a href="#visits31-funding-profile"><i>◇</i><div><strong><?= e($vtxt('Review admission funding', 'مراجعة تمويل حالات الدخول')) ?></strong><span><?= e($vtxt('Understand the funding concentration behind current admissions.', 'افهم تركّز التمويل وراء حالات الدخول الحالية.')) ?></span></div><em>→</em></a>
            <a href="#visits31-top-specialties"><i>◎</i><div><strong><?= e($vtxt('Monitor specialty demand', 'متابعة الطلب حسب التخصص')) ?></strong><span><?= e($vtxt('Use the top five specialties to guide a deeper capacity review when needed.', 'استخدم أعلى خمسة تخصصات لتوجيه مراجعة أعمق للسعة عند الحاجة.')) ?></span></div><em>→</em></a>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            document.body.classList.add('visits31-active');
            var modeSelect = document.querySelector('[data-patient-mode]');
            var filter = document.querySelector('[data-patient-filter]');
            if (modeSelect && filter) {
                var refreshMode = function () {
                    filter.classList.toggle('is-range', modeSelect.value === 'range');
                    filter.classList.toggle('is-year', modeSelect.value !== 'range');
                };
                modeSelect.addEventListener('change', refreshMode);
                refreshMode();
            }

            var gate = { expected: 3, rendered: 0, empty: 0, failed: 0, status: 'PENDING' };
            var renderedKeys = {};
            var renderKey = function (key) {
                if (renderedKeys[key]) {
                    window.setTimeout(function () { window.dispatchEvent(new Event('resize')); }, 50);
                    return true;
                }
                var node = document.getElementById('visits_chart_data_' + key);
                var stage = document.querySelector('[data-patient-chart-card="' + key + '"]');
                var canvas = document.getElementById('visits_chart_' + key);
                if (!node || !stage || !canvas) return false;
                try {
                    var payload = JSON.parse(node.textContent || '{}');
                    var values = [];
                    (payload.series || []).forEach(function (series) { (series.values || []).forEach(function (value) { values.push(Number(value || 0)); }); });
                    if (!values.some(function (value) { return value !== 0; })) {
                        stage.setAttribute('data-chart-state', 'empty');
                        var emptyState = stage.querySelector('.patient1010-chart-empty');
                        if (emptyState) emptyState.hidden = false;
                        canvas.hidden = true;
                        gate.empty += 1;
                        renderedKeys[key] = true;
                        return true;
                    }
                    var result = window.renderBarCompareChart('visits_chart_' + key, payload);
                    if (!result || !result.rendered) throw new Error('Chart renderer did not confirm success.');
                    stage.setAttribute('data-chart-state', 'rendered');
                    gate.rendered += 1;
                    renderedKeys[key] = true;
                    return true;
                } catch (error) {
                    stage.setAttribute('data-chart-state', 'error');
                    var errorState = stage.querySelector('.patient1010-chart-error');
                    if (errorState) errorState.hidden = false;
                    canvas.hidden = true;
                    gate.failed += 1;
                    renderedKeys[key] = true;
                    return false;
                }
            };

            renderKey('opd');
            document.querySelectorAll('[data-visits31-chart-tab]').forEach(function (button) {
                button.addEventListener('click', function () {
                    var key = button.getAttribute('data-visits31-chart-tab');
                    document.querySelectorAll('[data-visits31-chart-tab]').forEach(function (item) { item.classList.toggle('active', item === button); });
                    document.querySelectorAll('[data-visits31-chart-panel]').forEach(function (panel) {
                        var active = panel.getAttribute('data-visits31-chart-panel') === key;
                        panel.hidden = !active;
                        panel.classList.toggle('active', active);
                    });
                    window.setTimeout(function () { renderKey(key); window.dispatchEvent(new Event('resize')); }, 30);
                });
            });

            var fullDetails = document.getElementById('visits31-full-details');
            var fullMatrix = document.getElementById('visits31-full-matrix');
            var fullMatrixLinks = Array.prototype.slice.call(document.querySelectorAll('[data-visits31-full-matrix-link]'));

            var syncFullMatrixLinkState = function () {
                var expanded = !!(fullDetails && fullDetails.open);
                fullMatrixLinks.forEach(function (link) {
                    link.setAttribute('aria-expanded', expanded ? 'true' : 'false');
                });
            };

            var openFullMatrix = function (updateHash) {
                if (!fullDetails || !fullMatrix) return false;
                fullDetails.open = true;
                syncFullMatrixLinkState();
                if (updateHash && window.history && window.history.replaceState) {
                    window.history.replaceState(null, '', '#visits31-full-matrix');
                }
                window.setTimeout(function () {
                    fullMatrix.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    try { fullMatrix.focus({ preventScroll: true }); } catch (error) { fullMatrix.focus(); }
                }, 40);
                return true;
            };

            fullMatrixLinks.forEach(function (link) {
                link.addEventListener('click', function (event) {
                    event.preventDefault();
                    openFullMatrix(true);
                });
            });

            if (fullDetails) {
                fullDetails.addEventListener('toggle', syncFullMatrixLinkState);
                syncFullMatrixLinkState();
            }

            if (window.location.hash === '#visits31-full-matrix' || window.location.hash === '#visits31-full-details') {
                openFullMatrix(false);
            }

            gate.status = gate.failed === 0 ? 'PASS' : 'FAIL';
            window.__DDB_PATIENT_ACTIVITY_CHART_GATE__ = gate;
            document.documentElement.setAttribute('data-patient-chart-expected', String(gate.expected));
            document.documentElement.setAttribute('data-patient-chart-rendered', String(gate.rendered));
            document.documentElement.setAttribute('data-patient-chart-empty', String(gate.empty));
            document.documentElement.setAttribute('data-patient-chart-failed', String(gate.failed));
            document.documentElement.setAttribute('data-patient-chart-gate', gate.status);
        });
        </script>
    <?php endif; ?>

<?php elseif ($isOperations): ?>
    <?php
        $activeMode = $reportMode ?? 'year';
        $periodCurrent = is_array($operationData)
            ? (string)($operationData['current_period_label'] ?? $year)
            : (string)$year;
        $periodCompare = is_array($operationData)
            ? (string)($operationData['compare_period_label'] ?? $compareYear)
            : (string)$compareYear;
        $operationsIsArabic = current_lang() === 'ar';
        $otxt = static function (string $en, string $ar) use ($operationsIsArabic): string {
            return $operationsIsArabic ? $ar : $en;
        };
        $compactOperationsNumber = static function ($value, int $decimals = 1): string {
            if ($value === null || $value === '') return '—';
            $n = (float)$value;
            $abs = abs($n);
            if ($abs >= 1000000) return rtrim(rtrim(number_format($n / 1000000, $decimals), '0'), '.') . 'M';
            if ($abs >= 1000) return rtrim(rtrim(number_format($n / 1000, $decimals), '0'), '.') . 'K';
            return number_format($n, 0);
        };
        $operationsDelta = static function ($current, $compare): ?float {
            $current = (float)$current;
            $compare = (float)$compare;
            if (abs($compare) < 0.000001) return null;
            return (($current - $compare) / abs($compare)) * 100.0;
        };
        $deltaText = static function (?float $value, bool $points = false) use ($otxt): string {
            if ($value === null) return '—';
            if (abs($value) < 0.05) return $otxt('No material change', 'لا يوجد تغير جوهري');
            return ($value > 0 ? '↑ +' : '↓ ') . number_format(abs($value), 1) . ($points ? ' pp' : '%');
        };
        $deltaClass = static function (?float $value): string {
            if ($value === null || abs($value) < 0.05) return 'is-neutral';
            return $value > 0 ? 'is-up' : 'is-down';
        };
    ?>

    <div class="operations91-page" data-r45-p9-operations-executive="true">
        <section class="operations91-controls">
            <div class="operations91-controls-copy">
                <span><?= e($otxt('SURGICAL COMPARISON', 'مقارنة النشاط الجراحي')) ?></span>
                <strong><?= e($periodCurrent) ?> <i>vs</i> <?= e($periodCompare) ?></strong>
                <p><?= e($otxt(
                    'Compare matched periods and focus on the operational decisions that require attention.',
                    'قارن الفترات المتطابقة وركز على القرارات التشغيلية التي تتطلب الانتباه.'
                )) ?></p>
            </div>

            <form method="get" action="index.php" class="operations91-filter <?= $activeMode === 'range' ? 'is-range' : 'is-year' ?>" data-operations91-filter>
                <input type="hidden" name="page" value="operations">
                <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">

                <label>
                    <span><?= e($otxt('View', 'العرض')) ?></span>
                    <select name="mode" data-operations91-mode>
                        <option value="year" <?= $activeMode === 'year' ? 'selected' : '' ?>><?= e($otxt('Year comparison', 'مقارنة السنوات')) ?></option>
                        <option value="range" <?= $activeMode === 'range' ? 'selected' : '' ?>><?= e($otxt('Custom period', 'فترة مخصصة')) ?></option>
                    </select>
                </label>

                <?php $operationYears = is_array($operationData) ? ($operationData['availableYears'] ?? []) : []; ?>
                <label data-operations91-year-field>
                    <span><?= e($otxt('Primary year', 'السنة الأساسية')) ?></span>
                    <select name="year">
                        <?php foreach ($operationYears ?: [$year] as $availableYear): ?>
                            <option value="<?= e((string)$availableYear) ?>" <?= (int)$availableYear === (int)$year ? 'selected' : '' ?>><?= e((string)$availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>

                <label>
                    <span><?= e($otxt('Comparison year', 'سنة المقارنة')) ?></span>
                    <select name="compare_year">
                        <?php foreach ($operationYears ?: [$compareYear] as $availableYear): ?>
                            <option value="<?= e((string)$availableYear) ?>" <?= (int)$availableYear === (int)$compareYear ? 'selected' : '' ?>><?= e((string)$availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>

                <label data-operations91-range-field>
                    <span><?= e($otxt('From', 'من')) ?></span>
                    <input type="date" name="from_date" value="<?= e($fromDate ?? '') ?>">
                </label>

                <label data-operations91-range-field>
                    <span><?= e($otxt('To', 'إلى')) ?></span>
                    <input type="date" name="to_date" value="<?= e($toDate ?? '') ?>">
                </label>

                <button type="submit"><?= e($otxt('Update', 'تحديث')) ?></button>
            </form>

            <?php
                $operationsContract = is_array($operationData['comparison_contract'] ?? null)
                    ? $operationData['comparison_contract']
                    : (is_array($operationsComparisonContract ?? null) ? $operationsComparisonContract : []);
                $operationsFair = !empty($operationsContract['fair_current_year_comparison']);
            ?>
            <div class="operations91-contract <?= $operationsFair ? 'is-fair' : '' ?>">
                <span aria-hidden="true"><?= $operationsFair ? '✓' : '↔' ?></span>
                <p>
                    <?php if ($operationsFair): ?>
                        <strong><?= e($otxt('Fair comparison:', 'مقارنة عادلة:')) ?></strong>
                        <?= e($otxt(
                            'the incomplete current month is excluded from both periods.',
                            'تم استبعاد الشهر الحالي غير المكتمل من الفترتين.'
                        )) ?>
                    <?php else: ?>
                        <strong><?= e($otxt('Matched comparison:', 'مقارنة متطابقة:')) ?></strong>
                        <?= e($periodCurrent . ' vs ' . $periodCompare) ?>
                    <?php endif; ?>
                </p>
            </div>

            <?php if (!empty($operationsFilterError)): ?>
                <p class="operations91-alert"><?= e($operationsFilterError) ?></p>
            <?php endif; ?>
        </section>

        <?php if ($dataError || !is_array($operationData)): ?>
            <section class="operations91-state">
                <strong><?= e($otxt('Surgical activity is not available for the selected view.', 'النشاط الجراحي غير متاح للعرض المحدد.')) ?></strong>
                <p><?= e($otxt('Choose another period or branch and try again.', 'اختر فترة أو فرعًا آخر ثم حاول مرة أخرى.')) ?></p>
            </section>
        <?php else: ?>
            <?php
                $summary = $operationData['summary'] ?? [];
                $scheduledCurrent = (float)($summary['scheduled_current'] ?? 0);
                $scheduledCompare = (float)($summary['scheduled_compare'] ?? 0);
                $performedCurrent = (float)($summary['performed_current'] ?? 0);
                $performedCompare = (float)($summary['performed_compare'] ?? 0);
                $cancelledCurrent = (float)($summary['cancelled_current'] ?? 0);
                $cancelledCompare = (float)($summary['cancelled_compare'] ?? 0);
                $completionCurrent = isset($summary['completion_rate_current']) ? (float)$summary['completion_rate_current'] : null;
                $completionCompare = isset($summary['completion_rate_compare']) ? (float)$summary['completion_rate_compare'] : null;
                $cancellationRateCurrent = isset($summary['cancellation_rate_current']) ? (float)$summary['cancellation_rate_current'] : null;
                $cancellationRateCompare = isset($summary['cancellation_rate_compare']) ? (float)$summary['cancellation_rate_compare'] : null;

                $performedDelta = $operationsDelta($performedCurrent, $performedCompare);
                $scheduledDelta = $operationsDelta($scheduledCurrent, $scheduledCompare);
                $cancelledDelta = $operationsDelta($cancelledCurrent, $cancelledCompare);
                $completionPointChange = ($completionCurrent !== null && $completionCompare !== null)
                    ? $completionCurrent - $completionCompare
                    : null;

                $performedRows = array_values($operationData['charts']['performed']['rows'] ?? []);
                $scheduledRows = array_values($operationData['charts']['scheduled']['rows'] ?? []);
                $cancelledRows = array_values($operationData['charts']['cancelled']['rows'] ?? []);

                $performedMovements = [];
                foreach ($performedRows as $row) {
                    $compareValue = (float)($row['compare_value'] ?? 0);
                    $currentValue = (float)($row['current_value'] ?? 0);
                    $delta = abs($compareValue) > 0.000001
                        ? (($currentValue - $compareValue) / abs($compareValue)) * 100
                        : null;
                    $performedMovements[] = $row + ['delta_percent' => $delta];
                }
                $comparablePerformedMonths = array_values(array_filter($performedMovements, static function (array $row): bool {
                    return $row['delta_percent'] !== null;
                }));
                usort($comparablePerformedMonths, static function (array $a, array $b): int {
                    return ((float)$a['delta_percent']) <=> ((float)$b['delta_percent']);
                });
                $weakestMonth = $comparablePerformedMonths[0] ?? null;
                $strongestMonth = $comparablePerformedMonths ? $comparablePerformedMonths[count($comparablePerformedMonths) - 1] : null;

                $specialtyComparisons = array_values($operationData['specialtyComparisons'] ?? []);
                $doctorComparisons = array_values($operationData['doctorComparisons'] ?? []);
                $roomComparisons = array_values($operationData['roomComparisons'] ?? []);

                $currentSpecialtyLeaders = array_values(array_filter(
                    $specialtyComparisons,
                    static function (array $row): bool {
                        return (float)($row['current_value'] ?? 0) > 0.000001;
                    }
                ));
                $currentDoctorLeaders = array_values(array_filter(
                    $doctorComparisons,
                    static function (array $row): bool {
                        return (float)($row['current_value'] ?? 0) > 0.000001;
                    }
                ));

                $topSpecialties = array_slice($currentSpecialtyLeaders, 0, 5);
                $topDoctors = array_slice($currentDoctorLeaders, 0, 5);
                $leadingSpecialty = $topSpecialties[0] ?? null;

                $zeroCurrentLosses = [];
                foreach ($doctorComparisons as $row) {
                    if (!empty($row['zero_current_loss'])) {
                        $zeroCurrentLosses[] = $row + ['entity_type' => $otxt('Doctor', 'طبيب')];
                    }
                }
                foreach ($specialtyComparisons as $row) {
                    if (!empty($row['zero_current_loss'])) {
                        $zeroCurrentLosses[] = $row + ['entity_type' => $otxt('Specialty', 'تخصص')];
                    }
                }
                usort($zeroCurrentLosses, static function (array $a, array $b): int {
                    return ((float)($b['compare_value'] ?? 0)) <=> ((float)($a['compare_value'] ?? 0));
                });

                $negativeActivityMovements = [];
                foreach ($doctorComparisons as $row) {
                    if ((float)($row['volume_change'] ?? 0) < -0.000001) {
                        $negativeActivityMovements[] = $row + ['entity_type' => $otxt('Doctor', 'طبيب')];
                    }
                }
                foreach ($specialtyComparisons as $row) {
                    if ((float)($row['volume_change'] ?? 0) < -0.000001) {
                        $negativeActivityMovements[] = $row + ['entity_type' => $otxt('Specialty', 'تخصص')];
                    }
                }
                usort($negativeActivityMovements, static function (array $a, array $b): int {
                    return ((float)($a['volume_change'] ?? 0)) <=> ((float)($b['volume_change'] ?? 0));
                });

                $largestActivityLoss = $zeroCurrentLosses[0] ?? ($negativeActivityMovements[0] ?? null);
                $activityLossIsZeroCurrent = $largestActivityLoss !== null
                    && !empty($largestActivityLoss['zero_current_loss']);

                if ($performedDelta === null) {
                    $operationsHeadline = $otxt('Comparison unavailable', 'المقارنة غير متاحة');
                    $operationsNarrative = $otxt(
                        'The comparison period does not contain enough performed-operation activity.',
                        'لا تحتوي فترة المقارنة على نشاط كافٍ للعمليات المنفذة.'
                    );
                } elseif ($performedDelta < -0.05) {
                    $operationsHeadline = $otxt('Surgical throughput decreased', 'انخفض حجم النشاط الجراحي');
                    $operationsNarrative = $otxt(
                        'Performed operations are ' . number_format(abs($performedDelta), 1) . '% below the matched comparison period. '
                        . ($weakestMonth ? (string)$weakestMonth['month_name'] . ' recorded the weakest movement.' : ''),
                        'العمليات المنفذة أقل بنسبة ' . number_format(abs($performedDelta), 1) . '% من فترة المقارنة المتطابقة. '
                        . ($weakestMonth ? 'سجل شهر ' . (string)$weakestMonth['month_name'] . ' أضعف تغير.' : '')
                    );
                } elseif ($performedDelta > 0.05) {
                    $operationsHeadline = $otxt('Surgical throughput increased', 'ارتفع حجم النشاط الجراحي');
                    $operationsNarrative = $otxt(
                        'Performed operations are ' . number_format($performedDelta, 1) . '% above the matched comparison period. '
                        . ($strongestMonth ? (string)$strongestMonth['month_name'] . ' recorded the strongest movement.' : ''),
                        'العمليات المنفذة أعلى بنسبة ' . number_format($performedDelta, 1) . '% من فترة المقارنة المتطابقة. '
                        . ($strongestMonth ? 'سجل شهر ' . (string)$strongestMonth['month_name'] . ' أقوى تغير.' : '')
                    );
                } else {
                    $operationsHeadline = $otxt('Surgical throughput remained stable', 'ظل حجم النشاط الجراحي مستقرًا');
                    $operationsNarrative = $otxt(
                        'Performed operations are stable across the matched periods.',
                        'العمليات المنفذة مستقرة بين الفترتين المتطابقتين.'
                    );
                }

                $operationsChartConfig = [
                    'defaultMetric' => 'performed',
                    'metrics' => [
                        'scheduled' => [
                            'title' => $otxt('Scheduled operations', 'العمليات المجدولة'),
                            'payload' => array_merge(
                                $operationData['charts']['scheduled']['payload'] ?? [],
                                ['stableHover' => true, 'showDataLabels' => true]
                            ),
                        ],
                        'performed' => [
                            'title' => $otxt('Performed operations', 'العمليات المنفذة'),
                            'payload' => array_merge(
                                $operationData['charts']['performed']['payload'] ?? [],
                                ['stableHover' => true, 'showDataLabels' => true]
                            ),
                        ],
                        'cancelled' => [
                            'title' => $otxt('Cancelled operations', 'العمليات الملغاة'),
                            'payload' => array_merge(
                                $operationData['charts']['cancelled']['payload'] ?? [],
                                ['stableHover' => true, 'showDataLabels' => true]
                            ),
                        ],
                    ],
                ];
            ?>

            <?php
                $cancelledSemanticClass = $cancelledDelta === null || abs($cancelledDelta) < 0.05
                    ? 'neutral'
                    : ($cancelledDelta > 0 ? 'negative' : 'positive');

                $operationsKpis = [
                    [
                        'title' => $otxt('Scheduled operations', 'العمليات المجدولة'),
                        'value' => $scheduledCurrent,
                        'compare' => $scheduledCompare,
                        'delta' => $scheduledDelta,
                        'mode' => 'count',
                        'tone' => 'blue',
                        'semantic' => $scheduledDelta === null || abs($scheduledDelta) < 0.05
                            ? 'neutral'
                            : ($scheduledDelta > 0 ? 'positive' : 'negative'),
                    ],
                    [
                        'title' => $otxt('Performed operations', 'العمليات المنفذة'),
                        'value' => $performedCurrent,
                        'compare' => $performedCompare,
                        'delta' => $performedDelta,
                        'mode' => 'count',
                        'tone' => 'teal',
                        'semantic' => $performedDelta === null || abs($performedDelta) < 0.05
                            ? 'neutral'
                            : ($performedDelta > 0 ? 'positive' : 'negative'),
                    ],
                    [
                        'title' => $otxt('Completion rate', 'معدل الإتمام'),
                        'value' => $completionCurrent,
                        'compare' => $completionCompare,
                        'delta' => $completionPointChange,
                        'mode' => 'percent',
                        'points' => true,
                        'tone' => 'violet',
                        'semantic' => $completionPointChange === null || abs($completionPointChange) < 0.05
                            ? 'neutral'
                            : ($completionPointChange > 0 ? 'positive' : 'negative'),
                    ],
                    [
                        'title' => $otxt('Cancelled operations', 'العمليات الملغاة'),
                        'value' => $cancelledCurrent,
                        'compare' => $cancelledCompare,
                        'delta' => $cancelledDelta,
                        'mode' => 'count',
                        'tone' => 'amber',
                        'semantic' => $cancelledSemanticClass,
                    ],
                ];
            ?>

            <section class="operations91-kpi-grid" aria-label="<?= e($otxt('Key surgical indicators', 'مؤشرات النشاط الجراحي الرئيسية')) ?>">
                <?php foreach ($operationsKpis as $kpi): ?>
                    <?php
                        $isPercentKpi = $kpi['mode'] === 'percent';
                        $isPoints = !empty($kpi['points']);
                    ?>
                    <article class="operations91-kpi tone-<?= e((string)$kpi['tone']) ?>">
                        <span class="operations91-kpi-label"><?= e((string)$kpi['title']) ?></span>
                        <strong>
                            <?= $kpi['value'] === null
                                ? '—'
                                : e(
                                    $isPercentKpi
                                        ? number_format((float)$kpi['value'], 1) . '%'
                                        : number_format((float)$kpi['value'], 0)
                                ) ?>
                        </strong>
                        <small>
                            <?= e($otxt('Comparison period', 'فترة المقارنة')) ?> ·
                            <?= $kpi['compare'] === null
                                ? '—'
                                : e(
                                    $isPercentKpi
                                        ? number_format((float)$kpi['compare'], 1) . '%'
                                        : number_format((float)$kpi['compare'], 0)
                                ) ?>
                        </small>
                        <?php if ($kpi['delta'] !== null): ?>
                            <em class="operations91-delta <?= e((string)$kpi['semantic']) ?>">
                                <?= e($deltaText((float)$kpi['delta'], $isPoints)) ?>
                            </em>
                        <?php endif; ?>
                    </article>
                <?php endforeach; ?>
            </section>

            <section class="operations91-card operations91-summary-card">
                <div class="operations91-summary-intro">
                    <span><?= e($otxt('EXECUTIVE INSIGHT', 'الرؤية التنفيذية')) ?></span>
                    <h2><?= e($otxt('What leadership should know now', 'ما الذي يجب أن تعرفه الإدارة الآن')) ?></h2>
                    <strong class="<?= e(
                        $performedDelta === null || abs($performedDelta) < 0.05
                            ? 'is-neutral'
                            : ($performedDelta > 0 ? 'is-positive' : 'is-negative')
                    ) ?>"><?= e($operationsHeadline) ?></strong>
                    <p><?= e($operationsNarrative) ?></p>
                </div>

                <div class="operations91-summary-signals">
                    <article>
                        <span><?= e($otxt('Performed operations', 'العمليات المنفذة')) ?></span>
                        <strong><?= e(number_format($performedCurrent, 0)) ?></strong>
                        <small class="<?= e(
                            $performedDelta === null || abs($performedDelta) < 0.05
                                ? 'is-neutral'
                                : ($performedDelta > 0 ? 'is-positive' : 'is-negative')
                        ) ?>"><?= e($deltaText($performedDelta)) ?></small>
                    </article>

                    <article>
                        <span><?= e($otxt('Weakest movement', 'أضعف تغير')) ?></span>
                        <strong><?= e((string)($weakestMonth['month_name'] ?? '—')) ?></strong>
                        <?php $weakestDelta = isset($weakestMonth['delta_percent']) ? (float)$weakestMonth['delta_percent'] : null; ?>
                        <small class="<?= e(
                            $weakestDelta === null || abs($weakestDelta) < 0.05
                                ? 'is-neutral'
                                : ($weakestDelta > 0 ? 'is-positive' : 'is-negative')
                        ) ?>"><?= e($deltaText($weakestDelta)) ?></small>
                    </article>

                    <article>
                        <span><?= e($otxt('Leading specialty', 'التخصص المتصدر')) ?></span>
                        <strong><?= e((string)($leadingSpecialty['label'] ?? '—')) ?></strong>
                        <small>
                            <?= e($compactOperationsNumber($leadingSpecialty['current_value'] ?? null)) ?>
                            <?= e($otxt('operations', 'عملية')) ?>
                        </small>
                    </article>

                    <article>
                        <span><?= e($otxt('Completion control', 'ضبط الإتمام')) ?></span>
                        <strong><?= $completionCurrent === null ? '—' : e(number_format($completionCurrent, 1)) . '%' ?></strong>
                        <small class="<?= e(
                            $completionPointChange === null || abs($completionPointChange) < 0.05
                                ? 'is-neutral'
                                : ($completionPointChange > 0 ? 'is-positive' : 'is-negative')
                        ) ?>"><?= e($deltaText($completionPointChange, true)) ?></small>
                    </article>
                </div>
            </section>

            <section class="operations91-main-grid">
                <article class="operations91-card operations91-chart-card" data-operations91-chart-state="pending">
                    <header class="operations91-card-head">
                        <div>
                            <span><?= e($otxt('MONTHLY COMPARISON', 'المقارنة الشهرية')) ?></span>
                            <h2 data-operations91-chart-heading><?= e($otxt('Performed operations', 'العمليات المنفذة')) ?></h2>
                            <p><?= e($periodCurrent . ' vs ' . $periodCompare) ?></p>
                        </div>
                        <div class="operations91-tabs">
                            <button type="button" data-operations91-metric="performed" class="is-active"><?= e($otxt('Performed', 'المنفذة')) ?></button>
                            <button type="button" data-operations91-metric="scheduled"><?= e($otxt('Scheduled', 'المجدولة')) ?></button>
                            <button type="button" data-operations91-metric="cancelled"><?= e($otxt('Cancelled', 'الملغاة')) ?></button>
                        </div>
                    </header>
                    <div class="operations91-chart-stage">
                        <canvas id="operations91_chart" height="170"></canvas>
                        <div class="operations91-chart-state is-empty">
                            <strong><?= e($otxt('No activity is available for this metric.', 'لا يوجد نشاط متاح لهذا المؤشر.')) ?></strong>
                        </div>
                        <div class="operations91-chart-state is-error">
                            <strong><?= e($otxt('The monthly comparison chart is temporarily unavailable.', 'رسم المقارنة الشهرية غير متاح مؤقتًا.')) ?></strong>
                        </div>
                    </div>
                </article>

                <aside class="operations91-card operations91-agenda">
                    <header>
                        <span><?= e($otxt('DECISION AGENDA', 'أجندة القرار')) ?></span>
                        <h2><?= e($otxt('What needs attention', 'ما الذي يحتاج إلى انتباه')) ?></h2>
                    </header>

                    <article>
                        <i>1</i>
                        <div>
                            <small><?= e($otxt('Weakest monthly movement', 'أضعف تغير شهري')) ?></small>
                            <strong><?= e((string)($weakestMonth['month_name'] ?? '—')) ?></strong>
                            <b class="<?= e($deltaClass(isset($weakestMonth['delta_percent']) ? (float)$weakestMonth['delta_percent'] : null)) ?>">
                                <?= e($deltaText(isset($weakestMonth['delta_percent']) ? (float)$weakestMonth['delta_percent'] : null)) ?>
                            </b>
                            <p><?= e($otxt('Review demand, scheduling and theatre availability.', 'راجع الطلب والجدولة وتوافر غرف العمليات.')) ?></p>
                        </div>
                    </article>

                    <article>
                        <i>2</i>
                        <div>
                            <small><?= e($activityLossIsZeroCurrent
                                ? $otxt('No current-period activity', 'لا يوجد نشاط في الفترة الحالية')
                                : $otxt('Largest activity loss', 'أكبر فقد في النشاط')
                            ) ?></small>
                            <strong><?= e((string)($largestActivityLoss['label'] ?? '—')) ?></strong>
                            <?php if ($largestActivityLoss): ?>
                                <b class="is-down">
                                    <?= e($compactOperationsNumber($largestActivityLoss['current_value'] ?? 0)) ?>
                                    <?= e($otxt(' vs ', ' مقابل ')) ?>
                                    <?= e($compactOperationsNumber($largestActivityLoss['compare_value'] ?? 0)) ?>
                                </b>
                                <p>
                                    <?= e((string)($largestActivityLoss['entity_type'] ?? '')) ?> ·
                                    <?= e($activityLossIsZeroCurrent
                                        ? $otxt('confirm whether the activity stopped, moved or is missing from the current-period source.', 'تحقق مما إذا كان النشاط قد توقف أو انتقل أو لم يصل من مصدر الفترة الحالية.')
                                        : $otxt('review the operational reason behind the largest volume reduction.', 'راجع السبب التشغيلي وراء أكبر انخفاض في الحجم.')
                                    ) ?>
                                </p>
                            <?php else: ?>
                                <b>—</b>
                                <p><?= e($otxt('No material activity loss was identified.', 'لم يتم تحديد فقد جوهري في النشاط.')) ?></p>
                            <?php endif; ?>
                        </div>
                    </article>

                    <article>
                        <i>3</i>
                        <div>
                            <small><?= e($otxt('Completion control', 'ضبط الإتمام')) ?></small>
                            <strong><?= $completionCurrent === null ? '—' : e(number_format($completionCurrent, 1)) . '%' ?></strong>
                            <b class="<?= e($deltaClass($completionPointChange)) ?>"><?= e($deltaText($completionPointChange, true)) ?></b>
                            <p><?= e($otxt('Maintain cancellation control while recovering throughput.', 'حافظ على ضبط الإلغاءات أثناء استعادة حجم النشاط.')) ?></p>
                        </div>
                    </article>
                </aside>
            </section>

            <section class="operations91-card operations91-concentration">
                <header class="operations91-section-head">
                    <div>
                        <span><?= e($otxt('ACTIVITY CONCENTRATION', 'تركز النشاط')) ?></span>
                        <h2><?= e($otxt('Who is driving surgical volume', 'من يقود حجم النشاط الجراحي')) ?></h2>
                        <p><?= e($otxt(
                            'Ranked by current-period volume. Comparison values and movement are shown beside each leader.',
                            'تم الترتيب حسب حجم الفترة الحالية، مع إظهار قيمة المقارنة والتغير بجوار كل متصدر.'
                        )) ?></p>
                    </div>
                </header>

                <div class="operations91-concentration-grid">
                    <article>
                        <h3><?= e($otxt('Leading specialties — current period', 'التخصصات المتصدرة — الفترة الحالية')) ?></h3>
                        <div class="operations91-rank-list">
                            <?php foreach ($topSpecialties as $index => $row): ?>
                                <div>
                                    <i><?= e((string)($index + 1)) ?></i>
                                    <section>
                                        <strong><?= e((string)$row['label']) ?></strong>
                                        <small><?= e($periodCurrent) ?>: <?= e($compactOperationsNumber($row['current_value'])) ?> · <?= e($periodCompare) ?>: <?= e($compactOperationsNumber($row['compare_value'])) ?></small>
                                    </section>
                                    <b class="<?= e($deltaClass($row['delta_percent'])) ?>"><?= e($deltaText($row['delta_percent'])) ?></b>
                                </div>
                            <?php endforeach; ?>
                            <?php if (!$topSpecialties): ?><p>—</p><?php endif; ?>
                        </div>
                    </article>

                    <article>
                        <h3><?= e($otxt('Leading doctors — current period', 'الأطباء المتصدرون — الفترة الحالية')) ?></h3>
                        <div class="operations91-rank-list">
                            <?php foreach ($topDoctors as $index => $row): ?>
                                <div>
                                    <i><?= e((string)($index + 1)) ?></i>
                                    <section>
                                        <strong title="<?= e((string)$row['label']) ?>"><?= e((string)$row['label']) ?></strong>
                                        <small><?= e($periodCurrent) ?>: <?= e($compactOperationsNumber($row['current_value'])) ?> · <?= e($periodCompare) ?>: <?= e($compactOperationsNumber($row['compare_value'])) ?></small>
                                    </section>
                                    <b class="<?= e($deltaClass($row['delta_percent'])) ?>"><?= e($deltaText($row['delta_percent'])) ?></b>
                                </div>
                            <?php endforeach; ?>
                            <?php if (!$topDoctors): ?><p>—</p><?php endif; ?>
                        </div>
                    </article>
                </div>
            </section>

            <details class="operations91-details" id="operations91-details">
                <summary>
                    <div>
                        <span><?= e($otxt('SUPPORTING DETAIL', 'التفاصيل الداعمة')) ?></span>
                        <strong><?= e($otxt('Open monthly, specialty, doctor and room details', 'فتح تفاصيل الأشهر والتخصصات والأطباء والغرف')) ?></strong>
                    </div>
                    <b><?= e($otxt('Open details', 'فتح التفاصيل')) ?></b>
                </summary>

                <div class="operations91-detail-content">
                    <section>
                        <header><h3><?= e($otxt('Monthly surgical activity', 'النشاط الجراحي الشهري')) ?></h3><p><?= e($periodCurrent . ' vs ' . $periodCompare) ?></p></header>
                        <div class="operations91-table-wrap">
                            <table>
                                <thead><tr>
                                    <th><?= e($otxt('Month', 'الشهر')) ?></th>
                                    <th><?= e($otxt('Scheduled', 'المجدولة')) ?></th>
                                    <th><?= e($otxt('Comparison', 'المقارنة')) ?></th>
                                    <th><?= e($otxt('Performed', 'المنفذة')) ?></th>
                                    <th><?= e($otxt('Comparison', 'المقارنة')) ?></th>
                                    <th><?= e($otxt('Cancelled', 'الملغاة')) ?></th>
                                    <th><?= e($otxt('Completion', 'الإتمام')) ?></th>
                                </tr></thead>
                                <tbody>
                                <?php
                                    $performedByMonth = [];
                                    foreach ($performedRows as $row) $performedByMonth[(int)$row['month_id']] = $row;
                                    $cancelledByMonth = [];
                                    foreach ($cancelledRows as $row) $cancelledByMonth[(int)$row['month_id']] = $row;
                                ?>
                                <?php foreach ($scheduledRows as $row): ?>
                                    <?php
                                        $monthId = (int)($row['month_id'] ?? 0);
                                        $performedRow = $performedByMonth[$monthId] ?? [];
                                        $cancelledRow = $cancelledByMonth[$monthId] ?? [];
                                        $monthScheduled = (float)($row['current_value'] ?? 0);
                                        $monthPerformed = (float)($performedRow['current_value'] ?? 0);
                                        $monthCompletion = $monthScheduled > 0 ? ($monthPerformed / $monthScheduled) * 100 : null;
                                    ?>
                                    <tr>
                                        <td><strong><?= e((string)($row['month_name'] ?? '')) ?></strong></td>
                                        <td><?= e($compactOperationsNumber($monthScheduled)) ?></td>
                                        <td><?= e($compactOperationsNumber($row['compare_value'] ?? 0)) ?></td>
                                        <td><?= e($compactOperationsNumber($monthPerformed)) ?></td>
                                        <td><?= e($compactOperationsNumber($performedRow['compare_value'] ?? 0)) ?></td>
                                        <td><?= e($compactOperationsNumber($cancelledRow['current_value'] ?? 0)) ?></td>
                                        <td><?= $monthCompletion === null ? '—' : e(number_format($monthCompletion, 1)) . '%' ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </section>

                    <section>
                        <header><h3><?= e($otxt('Operating rooms', 'غرف العمليات')) ?></h3><p><?= e($otxt('Available where the legacy schema exposes room data.', 'متاحة عندما يوفر النظام القديم بيانات الغرف.')) ?></p></header>
                        <div class="operations91-table-wrap">
                            <table>
                                <thead><tr>
                                    <th><?= e($otxt('Room', 'الغرفة')) ?></th>
                                    <th><?= e($periodCurrent) ?></th>
                                    <th><?= e($periodCompare) ?></th>
                                    <th><?= e($otxt('Movement', 'التغير')) ?></th>
                                </tr></thead>
                                <tbody>
                                <?php foreach ($roomComparisons as $row): ?>
                                    <tr>
                                        <td><strong><?= e((string)$row['label']) ?></strong></td>
                                        <td><?= e($compactOperationsNumber($row['current_value'])) ?></td>
                                        <td><?= e($compactOperationsNumber($row['compare_value'])) ?></td>
                                        <td class="<?= e($deltaClass($row['delta_percent'])) ?>"><?= e($deltaText($row['delta_percent'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$roomComparisons): ?><tr><td colspan="4">—</td></tr><?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </section>
                </div>
            </details>

            <script type="application/json" id="operations91_chart_config"><?= json_encode(
                $operationsChartConfig,
                JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
            ) ?></script>
        <?php endif; ?>
    </div>

<?php elseif ($isDoctors): ?>
    <section id="doctors-live-data" class="surface-card visits-control-panel doctors-control-panel">
        <form method="get" action="index.php" class="visits-filter doctors-filter">
            <input type="hidden" name="page" value="doctors">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <?php $doctorYears = $doctorData['availableYears'] ?? []; ?>
            <label>
                <span><?= e(t('visits.year')) ?></span>
                <?php if (!empty($doctorYears)): ?>
                    <select name="year">
                        <?php foreach ($doctorYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$year) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('visits.compare_year')) ?></span>
                <?php if (!empty($doctorYears)): ?>
                    <select name="compare_year">
                        <?php foreach ($doctorYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$compareYear) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('doctors.metric')) ?></span>
                <select name="metric">
                    <?php foreach (($doctorData['availableMetrics'] ?? []) as $m): ?>
                        <option value="<?= e($m['key']) ?>" <?= (($doctorData['metric'] ?? $metric) === $m['key']) ? 'selected' : '' ?>><?= e(t($m['label_key'])) ?></option>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['availableMetrics'])): ?>
                        <option value="TOT_REV"><?= e(t('doctors.metric_revenue')) ?></option>
                    <?php endif; ?>
                </select>
            </label>
            <button class="btn primary" type="submit"><?= e(t('visits.apply_filter')) ?></button>
            <button class="btn ghost" type="button" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
        </form>
        <?php if (!empty($doctorYears)): ?>
            <p class="filter-hint"><?= e(t('doctors.available_years_hint', ['years' => implode(', ', $doctorYears)])) ?></p>
        <?php endif; ?>
    </section>

    <?php if ($dataError): ?>
        <section class="surface-card data-alert">
            <span class="overline"><?= e(t('doctors.data_error_label')) ?></span>
            <h2><?= e(t('doctors.data_error_title')) ?></h2>
            <p><?= e(t('doctors.data_error_text')) ?></p>
            <pre><?= e($dataError) ?></pre>
        </section>
    <?php elseif (is_array($doctorData)): ?>
        <?php if (!empty($doctorData['warnings'])): ?>
            <section class="surface-card data-alert soft-alert">
                <span class="overline"><?= e(t('visits.data_warning_label')) ?></span>
                <h2><?= e(t('doctors.data_warning_title')) ?></h2>
                <p><?= e(t('doctors.data_warning_text')) ?></p>
                <pre><?= e(implode("\n", $doctorData['warnings'])) ?></pre>
            </section>
        <?php endif; ?>

        <section class="metric-grid four visits-kpi-grid doctors-kpi-grid">
            <?php foreach ($doctorData['cards'] as $key => $card): ?>
                <article class="metric-card visits-kpi tone-<?= e($key === 'opd' ? 'blue' : ($key === 'inpatient' ? 'violet' : ($key === 'active' ? 'amber' : 'green'))) ?>">
                    <div class="metric-orb"></div>
                    <span><?= e($card['title']) ?></span>
                    <strong><?= e(number_format((float)$card['current_total'], 0)) ?></strong>
                    <small><?= e($card['hint']) ?><?php if (($card['mode'] ?? '') === 'compare'): ?> · <?= e(t('visits.previous')) ?>: <?= e(number_format((float)$card['compare_total'], 0)) ?><?php endif; ?></small>
                    <?php if (($card['mode'] ?? '') === 'compare'): ?>
                        <em class="delta <?= ($card['percent'] ?? 0) >= 0 ? 'up' : 'down' ?>">
                            <?= $card['percent'] === null ? e(t('common.not_available')) : e(number_format((float)$card['percent'], 1) . '%') ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="workspace-grid visits-insight-grid doctors-insight-grid">
            <article class="surface-card operations-card wide">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.top_doctors_kicker')) ?></span>
                    <h2><?= e(t('doctors.top_doctors_title')) ?></h2>
                    <p><?= e(t('doctors.top_doctors_text', ['year' => $year])) ?></p>
                </div>
                <canvas id="doctors_chart_top" class="chart visits-chart doctors-chart" height="145"></canvas>
                <script type="application/json" id="doctors_chart_data_top"><?= json_encode($doctorData['topDoctorsPayload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
            </article>

            <article class="surface-card operations-card visits-mix-card doctors-mix-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.revenue_mix_kicker')) ?></span>
                    <h2><?= e(t('doctors.revenue_mix_title')) ?></h2>
                    <p><?= e(t('doctors.revenue_mix_text')) ?></p>
                </div>
                <?php $mixTotal = 0.0; foreach (($doctorData['mix'] ?? []) as $row) { $mixTotal += max(0, (float)$row['value']); } ?>
                <div class="doctor-mix-stack">
                    <?php foreach (($doctorData['mix'] ?? []) as $row): ?>
                        <?php $pct = $mixTotal > 0 ? (((float)$row['value'] / $mixTotal) * 100) : 0; ?>
                        <div>
                            <span><?= e($row['label']) ?></span>
                            <strong><?= e(number_format((float)$row['value'], 0)) ?></strong>
                            <i><b style="width: <?= e(number_format(max(2, $pct), 2, '.', '')) ?>%"></b></i>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['mix'])): ?>
                        <p class="muted-line"><?= e(t('doctors.no_mix')) ?></p>
                    <?php endif; ?>
                </div>
            </article>
        </section>

        <section class="workspace-grid visits-detail-grid doctors-detail-grid">
            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.specialty_kicker')) ?></span>
                    <h2><?= e(t('doctors.specialty_title')) ?></h2>
                    <p><?= e(t('doctors.specialty_text')) ?></p>
                </div>
                <?php $maxSpec = 1; foreach (($doctorData['specialties'] ?? []) as $row) { $maxSpec = max($maxSpec, (float)$row['value']); } ?>
                <div class="rank-list">
                    <?php foreach (($doctorData['specialties'] ?? []) as $idx => $row): ?>
                        <?php $width = max(5, ((float)$row['value'] / $maxSpec) * 100); ?>
                        <div class="rank-row">
                            <em><?= e($idx + 1) ?></em>
                            <div>
                                <strong><?= e($row['label']) ?></strong>
                                <span><i style="width: <?= e(number_format($width, 2, '.', '')) ?>%"></i></span>
                            </div>
                            <b><?= e(number_format((float)$row['value'], 0)) ?></b>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['specialties'])): ?>
                        <p class="muted-line"><?= e(t('doctors.no_specialties')) ?></p>
                    <?php endif; ?>
                </div>
            </article>

            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.table_kicker')) ?></span>
                    <h2><?= e(t('doctors.table_title')) ?></h2>
                    <p><?= e(t('doctors.table_text')) ?></p>
                </div>
                <div class="table-wrap visits-table-wrap doctors-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th><?= e(t('doctors.doctor')) ?></th>
                                <th><?= e(t('doctors.specialty')) ?></th>
                                <th><?= e(t('doctors.value')) ?></th>
                                <th><?= e(t('doctors.opd')) ?></th>
                                <th><?= e(t('doctors.inpatient')) ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($doctorData['topDoctors'] ?? []) as $row): ?>
                                <tr>
                                    <td><?= e($row['label']) ?></td>
                                    <td><?= e($row['secondary'] ?: t('common.not_available')) ?></td>
                                    <td><?= e(number_format((float)$row['value'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['op_visits'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['inpat_visits'], 0)) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($doctorData['topDoctors'])): ?>
                                <tr><td colspan="5"><?= e(t('doctors.no_doctors')) ?></td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </article>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('script[type="application/json"][id^="doctors_chart_data_"]').forEach(function (node) {
                var key = node.id.replace('doctors_chart_data_', '');
                var payload = JSON.parse(node.textContent || '{}');
                window.renderBarCompareChart('doctors_chart_' + key, payload);
            });
        });
        </script>
    <?php endif; ?>

<?php elseif ($isBeds): ?>
    <section id="beds-live-data" class="surface-card visits-control-panel beds-control-panel">
        <form method="get" action="index.php" class="visits-filter">
            <input type="hidden" name="page" value="beds">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <?php $bedYears = $bedsData['availableYears'] ?? []; ?>
            <label>
                <span><?= e(t('visits.year')) ?></span>
                <?php if (!empty($bedYears)): ?>
                    <select name="year">
                        <?php foreach ($bedYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$year) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('visits.compare_year')) ?></span>
                <?php if (!empty($bedYears)): ?>
                    <select name="compare_year">
                        <?php foreach ($bedYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$compareYear) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
                <?php endif; ?>
            </label>
            <button class="btn primary" type="submit"><?= e(t('visits.apply_filter')) ?></button>
            <button class="btn ghost" type="button" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
        </form>
        <?php if (!empty($bedYears)): ?>
            <p class="filter-hint"><?= e(t('beds.available_years_hint', ['years' => implode(', ', $bedYears)])) ?></p>
        <?php endif; ?>
    </section>

    <?php if ($dataError): ?>
        <section class="surface-card data-alert">
            <span class="overline"><?= e(t('beds.data_error_label')) ?></span>
            <h2><?= e(t('beds.data_error_title')) ?></h2>
            <p><?= e(t('beds.data_error_text')) ?></p>
            <pre><?= e($dataError) ?></pre>
        </section>
    <?php elseif (is_array($bedsData)): ?>
        <?php if (!empty($bedsData['warnings'])): ?>
            <section class="surface-card data-alert soft-alert">
                <span class="overline"><?= e(t('visits.data_warning_label')) ?></span>
                <h2><?= e(t('beds.data_warning_title')) ?></h2>
                <p><?= e(t('beds.data_warning_text')) ?></p>
                <pre><?= e(implode("\n", $bedsData['warnings'])) ?></pre>
            </section>
        <?php endif; ?>

        <section class="metric-grid four visits-kpi-grid beds-kpi-grid">
            <?php foreach ($bedsData['cards'] as $key => $card): ?>
                <article class="metric-card visits-kpi tone-<?= e($key === 'available' ? 'green' : ($key === 'hours' ? 'violet' : ($key === 'occupied' ? 'amber' : 'blue'))) ?>">
                    <div class="metric-orb"></div>
                    <span><?= e($card['title']) ?></span>
                    <strong><?= e(($card['mode'] ?? '') === 'percent' ? number_format((float)$card['current_total'], 1) . '%' : number_format((float)$card['current_total'], 0)) ?></strong>
                    <small><?= e($card['hint']) ?><?php if (($card['mode'] ?? '') === 'compare'): ?> · <?= e(t('visits.previous')) ?>: <?= e(number_format((float)$card['compare_total'], 0)) ?><?php endif; ?></small>
                    <?php if (($card['mode'] ?? '') === 'compare'): ?>
                        <em class="delta <?= ($card['percent'] ?? 0) >= 0 ? 'up' : 'down' ?>">
                            <?= $card['percent'] === null ? e(t('common.not_available')) : e(number_format((float)$card['percent'], 1) . '%') ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="workspace-grid visits-insight-grid beds-insight-grid">
            <article class="surface-card operations-card wide">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.unit_kicker')) ?></span>
                    <h2><?= e(t('beds.unit_chart_title')) ?></h2>
                    <p><?= e(t('beds.unit_chart_text', ['year' => $year])) ?></p>
                </div>
                <canvas id="beds_chart_units" class="chart visits-chart beds-chart" height="145"></canvas>
                <script type="application/json" id="beds_chart_data_units"><?= json_encode($bedsData['unitsPayload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
            </article>

            <article class="surface-card operations-card visits-mix-card beds-mix-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.live_kicker')) ?></span>
                    <h2><?= e(t('beds.live_title')) ?></h2>
                    <p><?= e(t('beds.live_text')) ?></p>
                </div>
                <?php $current = $bedsData['current'] ?? []; $totalBeds = max(1, (float)($current['total_beds'] ?? 0)); $occPct = ((float)($current['occupied_beds'] ?? 0) / $totalBeds) * 100; $freePct = ((float)($current['available_beds'] ?? 0) / $totalBeds) * 100; ?>
                <div class="mix-meter beds-meter" aria-label="<?= e(t('beds.live_title')) ?>">
                    <span style="width: <?= e(number_format($occPct, 2, '.', '')) ?>%"></span>
                    <b style="width: <?= e(number_format($freePct, 2, '.', '')) ?>%"></b>
                </div>
                <div class="mix-legend">
                    <div><i class="new"></i><strong><?= e(number_format((float)($current['occupied_beds'] ?? 0), 0)) ?></strong><span><?= e(t('beds.occupied')) ?></span></div>
                    <div><i class="follow"></i><strong><?= e(number_format((float)($current['available_beds'] ?? 0), 0)) ?></strong><span><?= e(t('beds.available')) ?></span></div>
                </div>
                <p class="muted-line"><?= e(t('beds.total_beds_hint', ['total' => number_format((float)($current['total_beds'] ?? 0), 0)])) ?></p>
            </article>
        </section>

        <section class="workspace-grid visits-detail-grid beds-detail-grid">
            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.top_beds_kicker')) ?></span>
                    <h2><?= e(t('beds.top_beds_title')) ?></h2>
                    <p><?= e(t('beds.top_beds_text', ['year' => $year])) ?></p>
                </div>
                <canvas id="beds_chart_top_beds" class="chart visits-chart beds-chart" height="132"></canvas>
                <script type="application/json" id="beds_chart_data_top_beds"><?= json_encode($bedsData['topBedsPayload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
            </article>

            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.table_kicker')) ?></span>
                    <h2><?= e(t('beds.table_title')) ?></h2>
                    <p><?= e(t('beds.table_text')) ?></p>
                </div>
                <div class="table-wrap visits-table-wrap beds-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th><?= e(t('beds.unit')) ?></th>
                                <th><?= e(t('beds.beds_count')) ?></th>
                                <th><?= e(t('beds.occupied_hours')) ?></th>
                                <th><?= e(t('beds.occupancy_percent')) ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($bedsData['units'] ?? []) as $row): ?>
                                <tr>
                                    <td><?= e($row['label']) ?></td>
                                    <td><?= e(number_format((float)$row['bed_count'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['occupied_hours'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['value'], 1)) ?>%</td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($bedsData['units'])): ?>
                                <tr><td colspan="4"><?= e(t('beds.no_units')) ?></td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </article>
        </section>

        <section class="surface-card operations-card beds-table-card">
            <div class="section-head compact">
                <span class="overline"><?= e(t('beds.bed_table_kicker')) ?></span>
                <h2><?= e(t('beds.bed_table_title')) ?></h2>
                <p><?= e(t('beds.bed_table_text')) ?></p>
            </div>
            <div class="table-wrap visits-table-wrap beds-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?= e(t('beds.bed')) ?></th>
                            <th><?= e(t('beds.unit')) ?></th>
                            <th><?= e(t('beds.occupied_hours')) ?></th>
                            <th><?= e(t('beds.occupancy_percent')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (($bedsData['topBeds'] ?? []) as $row): ?>
                            <tr>
                                <td><?= e($row['label']) ?></td>
                                <td><?= e($row['secondary'] ?: t('common.not_available')) ?></td>
                                <td><?= e(number_format((float)$row['occupied_hours'], 0)) ?></td>
                                <td><?= e(number_format((float)$row['value'], 1)) ?>%</td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($bedsData['topBeds'])): ?>
                            <tr><td colspan="4"><?= e(t('beds.no_beds')) ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('script[type="application/json"][id^="beds_chart_data_"]').forEach(function (node) {
                var key = node.id.replace('beds_chart_data_', '');
                var payload = JSON.parse(node.textContent || '{}');
                window.renderBarCompareChart('beds_chart_' + key, payload);
            });
        });
        </script>
    <?php endif; ?>

<?php else: ?>
    <section class="workspace-grid operations-grid">
        <article class="surface-card operations-card wide">
            <div class="section-head">
                <span class="overline"><?= e(t('operations.blueprint')) ?></span>
                <h2><?= e(t('operations.blueprint_title')) ?></h2>
                <p><?= e(t('operations.blueprint_text')) ?></p>
            </div>
            <div class="operations-steps">
                <?php foreach ($steps as $index => $step): ?>
                    <div>
                        <b><?= e('0' . ($index + 1)) ?></b>
                        <strong><?= e($step['title']) ?></strong>
                        <span><?= e($step['text']) ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="surface-card operations-card">
            <div class="section-head compact">
                <span class="overline"><?= e(t('operations.branch_scope')) ?></span>
                <h2><?= e($hospitalName) ?></h2>
                <p><?= e(t('operations.branch_scope_text')) ?></p>
            </div>
            <div class="branch-scope-actions">
                <button type="button" class="btn primary full" data-branch-open><?= e(t('layout.branch_matrix')) ?></button>
                <a class="btn ghost full" href="<?= e(url_to('dashboard')) ?>"><?= e(t('nav.home')) ?></a>
            </div>
        </article>
    </section>
<?php endif; ?>
