<?php
$hospitalName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
$activeMode = $reportMode ?? 'year';
$isArabic = current_lang() === 'ar';
$dtx = static function (string $en, string $ar) use ($isArabic): string {
    return $isArabic ? $ar : $en;
};
$compactNumber = 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);
};
$percentChange = static function ($current, $compare): ?float {
    $current = (float)$current;
    $compare = (float)$compare;
    if (abs($compare) < 0.000001) return null;
    return (($current - $compare) / abs($compare)) * 100;
};
$deltaText = static function (?float $value, bool $points = false) use ($dtx): string {
    if ($value === null) return '—';
    if (abs($value) < 0.05) return $dtx('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';
};

$periodCurrent = is_array($diagnosticsData)
    ? (string)($diagnosticsData['current_period_label'] ?? $year)
    : (string)$year;
$periodCompare = is_array($diagnosticsData)
    ? (string)($diagnosticsData['compare_period_label'] ?? $compareYear)
    : (string)$compareYear;
$availableYears = is_array($diagnosticsData)
    ? array_values($diagnosticsData['availableYears'] ?? [])
    : [];
$contract = is_array($diagnosticsData['comparison_contract'] ?? null)
    ? $diagnosticsData['comparison_contract']
    : (is_array($comparisonContract ?? null) ? $comparisonContract : []);
$isFair = !empty($contract['fair_current_year_comparison']);
?>

<div class="diagnostics110-page" data-r45-p10-diagnostics-executive="true">
    <section class="diagnostics110-controls">
        <div class="diagnostics110-controls-copy">
            <span><?= e($dtx('DIAGNOSTIC COMPARISON', 'مقارنة النشاط التشخيصي')) ?></span>
            <strong><b><?= e($periodCurrent) ?></b><i>vs</i><b><?= e($periodCompare) ?></b></strong>
            <p><?= e($dtx(
                'Compare matched laboratory and radiology periods, then focus on the signals requiring leadership attention.',
                'قارن فترات المختبر والأشعة المتطابقة ثم ركز على مؤشرات المراجعة التي تتطلب انتباه الإدارة.'
            )) ?></p>
        </div>

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

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

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

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

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

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

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

        <div class="diagnostics110-contract <?= $isFair ? 'is-fair' : '' ?>">
            <span aria-hidden="true"><?= $isFair ? '✓' : '↔' ?></span>
            <p>
                <?php if ($isFair): ?>
                    <strong><?= e($dtx('Fair comparison:', 'مقارنة عادلة:')) ?></strong>
                    <?= e($dtx(
                        'the incomplete current month is excluded from laboratory and radiology in both periods.',
                        'تم استبعاد الشهر الحالي غير المكتمل من بيانات المختبر والأشعة في الفترتين.'
                    )) ?>
                <?php else: ?>
                    <strong><?= e($dtx('Matched comparison:', 'مقارنة متطابقة:')) ?></strong>
                    <?= e($periodCurrent . ' vs ' . $periodCompare) ?>
                <?php endif; ?>
            </p>
        </div>

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

    <?php if ($dataError || !is_array($diagnosticsData)): ?>
        <section class="diagnostics110-state">
            <strong><?= e($dtx('Diagnostic activity is not available for the selected view.', 'النشاط التشخيصي غير متاح للعرض المحدد.')) ?></strong>
            <p><?= e($dtx('Choose another period or branch and try again.', 'اختر فترة أو فرعًا آخر ثم حاول مرة أخرى.')) ?></p>
        </section>
    <?php else: ?>
        <?php
        $summary = $diagnosticsData['summary'] ?? [];
        $monthly = array_values($diagnosticsData['monthly'] ?? []);
        $labRows = array_values($diagnosticsData['charts']['lab']['rows'] ?? []);
        $radiologyRows = array_values($diagnosticsData['charts']['radiology']['rows'] ?? []);

        $labCurrent = (float)($summary['lab_current'] ?? 0);
        $labCompare = (float)($summary['lab_compare'] ?? 0);
        $radiologyCurrent = (float)($summary['radiology_current'] ?? 0);
        $radiologyCompare = (float)($summary['radiology_compare'] ?? 0);
        $combinedCurrent = (float)($summary['combined_current'] ?? 0);
        $combinedCompare = (float)($summary['combined_compare'] ?? 0);
        $labShareCurrent = isset($summary['lab_share_current']) ? (float)$summary['lab_share_current'] : null;
        $labShareCompare = isset($summary['lab_share_compare']) ? (float)$summary['lab_share_compare'] : null;
        $radiologyShareCurrent = isset($summary['radiology_share_current']) ? (float)$summary['radiology_share_current'] : null;
        $radiologyShareCompare = isset($summary['radiology_share_compare']) ? (float)$summary['radiology_share_compare'] : null;

        $labDelta = $percentChange($labCurrent, $labCompare);
        $radiologyDelta = $percentChange($radiologyCurrent, $radiologyCompare);
        $combinedDelta = $percentChange($combinedCurrent, $combinedCompare);
        $radiologyShareMovement = ($radiologyShareCurrent !== null && $radiologyShareCompare !== null)
            ? $radiologyShareCurrent - $radiologyShareCompare
            : null;

        $monthRows = [];
        $labByMonth = [];
        foreach ($labRows as $row) $labByMonth[(int)($row['month_id'] ?? 0)] = $row;
        $radiologyByMonth = [];
        foreach ($radiologyRows as $row) $radiologyByMonth[(int)($row['month_id'] ?? 0)] = $row;

        foreach ($monthly as $row) {
            $monthId = (int)($row['month_id'] ?? 0);
            $labRow = $labByMonth[$monthId] ?? [];
            $radiologyRow = $radiologyByMonth[$monthId] ?? [];
            $totalCurrent = (float)($row['current_value'] ?? 0);
            $totalCompare = (float)($row['compare_value'] ?? 0);
            $monthRows[] = [
                'month_id' => $monthId,
                'month_name' => (string)($row['month_name'] ?? ''),
                'lab_current' => (float)($labRow['current_value'] ?? 0),
                'lab_compare' => (float)($labRow['compare_value'] ?? 0),
                'radiology_current' => (float)($radiologyRow['current_value'] ?? 0),
                'radiology_compare' => (float)($radiologyRow['compare_value'] ?? 0),
                'total_current' => $totalCurrent,
                'total_compare' => $totalCompare,
                'total_delta' => $percentChange($totalCurrent, $totalCompare),
            ];
        }

        $comparableMonths = array_values(array_filter($monthRows, static function (array $row): bool {
            return $row['total_delta'] !== null;
        }));
        usort($comparableMonths, static function (array $a, array $b): int {
            return ((float)$a['total_delta']) <=> ((float)$b['total_delta']);
        });
        $weakestMonth = $comparableMonths[0] ?? null;
        $strongestMonth = $comparableMonths ? $comparableMonths[count($comparableMonths) - 1] : null;

        $peakRows = $monthRows;
        usort($peakRows, static function (array $a, array $b): int {
            return ((float)$b['total_current']) <=> ((float)$a['total_current']);
        });
        $peakMonth = $peakRows[0] ?? null;

        $currentCoverageRows = array_values(array_filter($monthRows, static function (array $row): bool {
            return (float)($row['total_current'] ?? 0) > 0.000001;
        }));
        $currentCoverageCount = count($currentCoverageRows);
        $lastCurrentMonth = $currentCoverageRows
            ? (string)$currentCoverageRows[count($currentCoverageRows) - 1]['month_name']
            : null;

        if ($combinedDelta === null) {
            $headline = $dtx('Comparison unavailable', 'المقارنة غير متاحة');
            $narrative = $dtx(
                'The comparison period does not contain enough diagnostic activity for a confirmed movement.',
                'لا تحتوي فترة المقارنة على نشاط تشخيصي كافٍ لتأكيد اتجاه الحركة.'
            );
        } elseif ($combinedDelta < -0.05) {
            $headline = $dtx('Diagnostic activity decreased', 'انخفض النشاط التشخيصي');
            $narrative = $dtx(
                'Total laboratory and radiology activity is ' . number_format(abs($combinedDelta), 1)
                . '% below the matched comparison period. '
                . ($weakestMonth ? (string)$weakestMonth['month_name'] . ' recorded the weakest movement.' : ''),
                'إجمالي نشاط المختبر والأشعة أقل بنسبة ' . number_format(abs($combinedDelta), 1)
                . '% من فترة المقارنة المتطابقة. '
                . ($weakestMonth ? 'سجل شهر ' . (string)$weakestMonth['month_name'] . ' أضعف تغير.' : '')
            );
        } elseif ($combinedDelta > 0.05) {
            $headline = $dtx('Diagnostic activity increased', 'ارتفع النشاط التشخيصي');
            $narrative = $dtx(
                'Total laboratory and radiology activity is ' . number_format($combinedDelta, 1)
                . '% above the matched comparison period. '
                . ($strongestMonth ? (string)$strongestMonth['month_name'] . ' recorded the strongest movement.' : ''),
                'إجمالي نشاط المختبر والأشعة أعلى بنسبة ' . number_format($combinedDelta, 1)
                . '% من فترة المقارنة المتطابقة. '
                . ($strongestMonth ? 'سجل شهر ' . (string)$strongestMonth['month_name'] . ' أقوى تغير.' : '')
            );
        } else {
            $headline = $dtx('Diagnostic activity remained stable', 'ظل النشاط التشخيصي مستقرًا');
            $narrative = $dtx(
                'Total laboratory and radiology activity is stable across the matched periods.',
                'إجمالي نشاط المختبر والأشعة مستقر بين الفترتين المتطابقتين.'
            );
        }

        $largestServiceMovement = abs((float)($labDelta ?? 0)) >= abs((float)($radiologyDelta ?? 0))
            ? ['label' => $dtx('Laboratory', 'المختبر'), 'value' => $labDelta]
            : ['label' => $dtx('Radiology', 'الأشعة'), 'value' => $radiologyDelta];

        $chartConfig = [
            'defaultMetric' => 'combined',
            'metrics' => [
                'combined' => [
                    'title' => $dtx('Total diagnostic activity', 'إجمالي النشاط التشخيصي'),
                    'payload' => $diagnosticsData['charts']['combined']['payload'] ?? [],
                ],
                'lab' => [
                    'title' => $dtx('Laboratory tests', 'فحوصات المختبر'),
                    'payload' => $diagnosticsData['charts']['lab']['payload'] ?? [],
                ],
                'radiology' => [
                    'title' => $dtx('Radiology tests', 'فحوصات الأشعة'),
                    'payload' => $diagnosticsData['charts']['radiology']['payload'] ?? [],
                ],
            ],
        ];
        ?>

        <section class="diagnostics110-kpi-grid" aria-label="<?= e($dtx('Key diagnostic indicators', 'مؤشرات النشاط التشخيصي الرئيسية')) ?>">
            <?php
            $diagnosticKpis = [
                [
                    'title' => $dtx('Laboratory tests', 'فحوصات المختبر'),
                    'value' => $labCurrent,
                    'compare' => $labCompare,
                    'delta' => $labDelta,
                    'mode' => 'count',
                    'tone' => 'teal',
                ],
                [
                    'title' => $dtx('Radiology tests', 'فحوصات الأشعة'),
                    'value' => $radiologyCurrent,
                    'compare' => $radiologyCompare,
                    'delta' => $radiologyDelta,
                    'mode' => 'count',
                    'tone' => 'blue',
                ],
                [
                    'title' => $dtx('Total diagnostic activity', 'إجمالي النشاط التشخيصي'),
                    'value' => $combinedCurrent,
                    'compare' => $combinedCompare,
                    'delta' => $combinedDelta,
                    'mode' => 'count',
                    'tone' => 'violet',
                ],
                [
                    'title' => $dtx('Radiology share', 'حصة الأشعة'),
                    'value' => $radiologyShareCurrent,
                    'compare' => $radiologyShareCompare,
                    'delta' => $radiologyShareMovement,
                    'mode' => 'percent',
                    'tone' => 'amber',
                ],
            ];
            ?>
            <?php foreach ($diagnosticKpis as $kpi): ?>
                <?php
                $isPercentKpi = $kpi['mode'] === 'percent';
                $semanticClass = $kpi['delta'] === null
                    ? 'neutral'
                    : ((float)$kpi['delta'] >= 0 ? 'up' : 'down');
                ?>
                <article class="diagnostics110-kpi tone-<?= e((string)$kpi['tone']) ?>">
                    <span class="diagnostics110-kpi-label"><?= e((string)$kpi['title']) ?></span>
                    <strong>
                        <?= $kpi['value'] === null
                            ? '—'
                            : e(number_format((float)$kpi['value'], $isPercentKpi ? 1 : 0) . ($isPercentKpi ? '%' : '')) ?>
                    </strong>
                    <small>
                        <?= e($dtx('Comparison period', 'فترة المقارنة')) ?> ·
                        <?= $kpi['compare'] === null
                            ? '—'
                            : e(number_format((float)$kpi['compare'], $isPercentKpi ? 1 : 0) . ($isPercentKpi ? '%' : '')) ?>
                    </small>
                    <?php if ($kpi['delta'] !== null): ?>
                        <em class="diagnostics110-delta <?= e($semanticClass) ?>">
                            <?= ((float)$kpi['delta'] >= 0 ? '↑ ' : '↓ ') ?>
                            <?= e(number_format(abs((float)$kpi['delta']), 1)) ?>
                            <?= $isPercentKpi ? ' pp' : '%' ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="diagnostics110-card diagnostics110-summary-card">
            <div class="diagnostics110-summary-intro">
                <span><?= e($dtx('EXECUTIVE INSIGHT', 'الرؤية التنفيذية')) ?></span>
                <h2><?= e($dtx('What leadership should know now', 'ما الذي يجب أن تعرفه الإدارة الآن')) ?></h2>
                <p><?= e($dtx(
                    'The most important laboratory and radiology signals are brought together for rapid review.',
                    'تم جمع أهم إشارات المختبر والأشعة في عرض واحد للمراجعة السريعة.'
                )) ?></p>
            </div>

            <div class="diagnostics110-summary-signals">
                <article>
                    <span><?= e($dtx('Total activity', 'إجمالي النشاط')) ?></span>
                    <strong><?= e(number_format($combinedCurrent, 0)) ?></strong>
                    <small><?= e($dtx('laboratory and radiology activities', 'نشاط مختبر وأشعة')) ?></small>
                </article>

                <article>
                    <span><?= e($dtx('Largest movement', 'أكبر تغير')) ?></span>
                    <strong><?= e((string)$largestServiceMovement['label']) ?></strong>
                    <small class="<?= e($largestServiceMovement['value'] === null
                        ? 'is-neutral'
                        : ((float)$largestServiceMovement['value'] >= 0 ? 'is-positive' : 'is-negative')) ?>">
                        <?= e($deltaText($largestServiceMovement['value'])) ?>
                    </small>
                </article>

                <article>
                    <span><?= e($dtx('Peak activity month', 'أعلى شهر نشاطًا')) ?></span>
                    <strong><?= e((string)($peakMonth['month_name'] ?? '—')) ?></strong>
                    <small>
                        <?= e($compactNumber($peakMonth['total_current'] ?? null)) ?>
                        <?= e($dtx('activities', 'نشاطًا')) ?>
                    </small>
                </article>

                <article>
                    <span><?= e($dtx('Current activity available through', 'النشاط الحالي متاح حتى')) ?></span>
                    <strong><?= e($lastCurrentMonth ?: '—') ?></strong>
                    <small>
                        <?= e((string)$currentCoverageCount) ?>
                        <?= e($dtx('matched months with activity', 'أشهر متطابقة بها نشاط')) ?>
                    </small>
                </article>
            </div>
        </section>

        <section class="diagnostics110-main-grid">
            <article class="diagnostics110-card diagnostics110-chart-card" data-diagnostics110-chart-state="pending">
                <header class="diagnostics110-card-head">
                    <div>
                        <span><?= e($dtx('MONTHLY COMPARISON', 'المقارنة الشهرية')) ?></span>
                        <h2 data-diagnostics110-chart-heading><?= e($dtx('Total diagnostic activity', 'إجمالي النشاط التشخيصي')) ?></h2>
                        <p><?= e($periodCurrent . ' vs ' . $periodCompare) ?></p>
                    </div>
                    <div class="diagnostics110-tabs">
                        <button type="button" class="is-active" data-diagnostics110-metric="combined"><?= e($dtx('Total', 'الإجمالي')) ?></button>
                        <button type="button" data-diagnostics110-metric="lab"><?= e($dtx('Laboratory', 'المختبر')) ?></button>
                        <button type="button" data-diagnostics110-metric="radiology"><?= e($dtx('Radiology', 'الأشعة')) ?></button>
                    </div>
                </header>
                <div class="diagnostics110-chart-stage">
                    <canvas id="diagnostics110_chart" height="170"></canvas>
                    <div class="diagnostics110-chart-state is-empty"><strong><?= e($dtx('No diagnostic activity is available for this metric.', 'لا يوجد نشاط تشخيصي متاح لهذا المؤشر.')) ?></strong></div>
                    <div class="diagnostics110-chart-state is-error"><strong><?= e($dtx('The monthly comparison chart is temporarily unavailable.', 'رسم المقارنة الشهرية غير متاح مؤقتًا.')) ?></strong></div>
                </div>
            </article>

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

                <article>
                    <i>1</i>
                    <div>
                        <small><?= e($dtx('Weakest monthly movement', 'أضعف تغير شهري')) ?></small>
                        <strong><?= e((string)($weakestMonth['month_name'] ?? '—')) ?></strong>
                        <b class="<?= e($deltaClass($weakestMonth['total_delta'] ?? null)) ?>"><?= e($deltaText($weakestMonth['total_delta'] ?? null)) ?></b>
                        <p><?= e($dtx('Review demand, referral flow, staffing and equipment availability.', 'راجع الطلب وتدفق الإحالات والكوادر وتوافر الأجهزة.')) ?></p>
                    </div>
                </article>

                <article>
                    <i>2</i>
                    <div>
                        <small><?= e($dtx('Largest service movement', 'أكبر تغير في خدمة')) ?></small>
                        <strong><?= e((string)$largestServiceMovement['label']) ?></strong>
                        <b class="<?= e($deltaClass($largestServiceMovement['value'])) ?>"><?= e($deltaText($largestServiceMovement['value'])) ?></b>
                        <p><?= e($dtx('Confirm whether the movement reflects demand, service transfer or source coverage.', 'تحقق مما إذا كان التغير يعكس الطلب أو انتقال الخدمة أو تغطية المصدر.')) ?></p>
                    </div>
                </article>

                <article>
                    <i>3</i>
                    <div>
                        <small><?= e($dtx('Service balance', 'توازن الخدمات')) ?></small>
                        <strong><?= e($dtx('Laboratory', 'المختبر')) ?> <?= $labShareCurrent === null ? '—' : e(number_format($labShareCurrent, 1)) ?>% · <?= e($dtx('Radiology', 'الأشعة')) ?> <?= $radiologyShareCurrent === null ? '—' : e(number_format($radiologyShareCurrent, 1)) ?>%</strong>
                        <b class="<?= e($deltaClass($radiologyShareMovement)) ?>"><?= e($deltaText($radiologyShareMovement, true)) ?></b>
                        <p><?= e($dtx('Monitor whether the workload mix is changing materially between services.', 'تابع ما إذا كان مزيج عبء العمل يتغير بصورة جوهرية بين الخدمتين.')) ?></p>
                    </div>
                </article>
            </aside>
        </section>

        <section class="diagnostics110-card diagnostics110-service-balance">
            <header class="diagnostics110-section-head">
                <div>
                    <span><?= e($dtx('SERVICE POSITION', 'وضع الخدمات')) ?></span>
                    <h2><?= e($dtx('Laboratory and radiology contribution', 'مساهمة المختبر والأشعة')) ?></h2>
                    <p><?= e($dtx('Both periods are shown together without repeating the executive summary.', 'تظهر الفترتان معًا دون تكرار الملخص التنفيذي.')) ?></p>
                </div>
            </header>

            <div class="diagnostics110-service-grid">
                <article>
                    <div>
                        <span><?= e($dtx('Laboratory', 'المختبر')) ?></span>
                        <strong><?= e($compactNumber($labCurrent)) ?></strong>
                        <small><?= e($periodCurrent) ?> · <?= e($labShareCurrent === null ? '—' : number_format($labShareCurrent, 1) . '%') ?></small>
                    </div>
                    <section>
                        <span><?= e($periodCompare) ?></span>
                        <b><?= e($compactNumber($labCompare)) ?></b>
                        <em class="<?= e($deltaClass($labDelta)) ?>"><?= e($deltaText($labDelta)) ?></em>
                    </section>
                </article>

                <article>
                    <div>
                        <span><?= e($dtx('Radiology', 'الأشعة')) ?></span>
                        <strong><?= e($compactNumber($radiologyCurrent)) ?></strong>
                        <small><?= e($periodCurrent) ?> · <?= e($radiologyShareCurrent === null ? '—' : number_format($radiologyShareCurrent, 1) . '%') ?></small>
                    </div>
                    <section>
                        <span><?= e($periodCompare) ?></span>
                        <b><?= e($compactNumber($radiologyCompare)) ?></b>
                        <em class="<?= e($deltaClass($radiologyDelta)) ?>"><?= e($deltaText($radiologyDelta)) ?></em>
                    </section>
                </article>
            </div>
        </section>

        <details class="diagnostics110-details" id="diagnostics110-details">
            <summary>
                <div>
                    <span><?= e($dtx('SUPPORTING DETAIL', 'التفاصيل الداعمة')) ?></span>
                    <strong><?= e($dtx('Open full monthly laboratory and radiology comparison', 'فتح المقارنة الشهرية الكاملة للمختبر والأشعة')) ?></strong>
                </div>
                <b><?= e($dtx('Open details', 'فتح التفاصيل')) ?></b>
            </summary>

            <div class="diagnostics110-detail-content">
                <header>
                    <h3><?= e($dtx('Monthly diagnostic activity', 'النشاط التشخيصي الشهري')) ?></h3>
                    <p><?= e($periodCurrent . ' vs ' . $periodCompare) ?></p>
                </header>
                <div class="diagnostics110-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th><?= e($dtx('Month', 'الشهر')) ?></th>
                                <th><?= e($dtx('Laboratory', 'المختبر')) ?> · <?= e($periodCurrent) ?></th>
                                <th><?= e($dtx('Laboratory', 'المختبر')) ?> · <?= e($periodCompare) ?></th>
                                <th><?= e($dtx('Radiology', 'الأشعة')) ?> · <?= e($periodCurrent) ?></th>
                                <th><?= e($dtx('Radiology', 'الأشعة')) ?> · <?= e($periodCompare) ?></th>
                                <th><?= e($dtx('Total movement', 'تغير الإجمالي')) ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($monthRows as $row): ?>
                                <tr>
                                    <td><strong><?= e((string)$row['month_name']) ?></strong></td>
                                    <td><?= e($compactNumber($row['lab_current'])) ?></td>
                                    <td><?= e($compactNumber($row['lab_compare'])) ?></td>
                                    <td><?= e($compactNumber($row['radiology_current'])) ?></td>
                                    <td><?= e($compactNumber($row['radiology_compare'])) ?></td>
                                    <td class="<?= e($deltaClass($row['total_delta'])) ?>"><?= e($deltaText($row['total_delta'])) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </details>

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