<?php
require_once dirname(__DIR__) . '/components/executive/components.php';
require_once dirname(__DIR__, 2) . '/Executive/Language/ExecutiveLanguage.php';

$isAr = current_lang() === 'ar';
$tr = static function (string $en, string $ar) use ($isAr): string { return $isAr ? $ar : $en; };
$data = is_array($financeData ?? null) ? $financeData : null;
$cards = is_array($data['cards'] ?? null) ? $data['cards'] : [];
$matrix = is_array($data['matrix'] ?? null) ? $data['matrix'] : [];
$activity = is_array($data['activity'] ?? null) ? $data['activity'] : [];
$activityCards = is_array($activity['cards'] ?? null) ? $activity['cards'] : [];
$activityRows = is_array($activity['rows'] ?? null) ? $activity['rows'] : [];
$activitySignals = is_array($activity['signals'] ?? null) ? $activity['signals'] : [];
$activityChartConfigs = is_array($activity['chart_configs'] ?? null)
    ? $activity['chart_configs']
    : [];
$activityDefaultSpecialty = (string)($activity['default_specialty_id'] ?? '');
$activityDefaultMetric = (string)($activity['default_metric'] ?? 'outpatient');
$years = is_array($data['availableYears'] ?? null) ? $data['availableYears'] : [$year, $compareYear];
$movement = is_array($data['primaryMovement'] ?? null) ? $data['primaryMovement'] : null;
$coverage = is_array($data['coverage'] ?? null) ? $data['coverage'] : [];
$currentCoverage = is_array($coverage['current'] ?? null) ? $coverage['current'] : [];
$compareCoverage = is_array($coverage['compare'] ?? null) ? $coverage['compare'] : [];
$currentMonthCoverage = is_array($coverage['current_months'] ?? null) ? $coverage['current_months'] : [];
$compareMonthCoverage = is_array($coverage['compare_months'] ?? null) ? $coverage['compare_months'] : [];
$comparisonContract = is_array($data['comparisonContract'] ?? null)
    ? $data['comparisonContract']
    : (is_array($comparisonContract ?? null) ? $comparisonContract : []);
$periodLabels = is_array($data['periodLabels'] ?? null) ? $data['periodLabels'] : [];
$currentPeriodLabel = (string)($periodLabels['current'] ?? $year);
$comparePeriodLabel = (string)($periodLabels['compare'] ?? $compareYear);
$isFairCurrentYearComparison = !empty($comparisonContract['fair_current_year_comparison']);
$lastCompleteMonth = (int)($comparisonContract['last_complete_month'] ?? 12);
$currentYearHasData = !empty($currentCoverage['has_data']);
$compareYearHasData = !empty($compareCoverage['has_data']);
$currentYearHasPeriodData = $currentYearHasData
    && (!$isFairCurrentYearComparison || (int)($currentMonthCoverage['max_month'] ?? 0) >= $lastCompleteMonth);
$compareYearHasPeriodData = $compareYearHasData
    && (!$isFairCurrentYearComparison || (int)($compareMonthCoverage['max_month'] ?? 0) >= $lastCompleteMonth);
$topNet = is_array($data['topNetSpecialty'] ?? null) ? $data['topNetSpecialty'] : null;
$topTotalRevenue = is_array($data['topTotalRevenueSpecialty'] ?? null) ? $data['topTotalRevenueSpecialty'] : null;
$money = static function (float $v): string { return number_format($v, 0); };
$compact = static function (float $v): string {
    $a = abs($v);
    return $a >= 1000000 ? number_format($v / 1000000, 2) . 'M' : ($a >= 1000 ? number_format($v / 1000, 1) . 'K' : number_format($v, 0));
};
$pct = static function ($v): string { return $v === null ? '—' : number_format((float)$v, 1) . '%'; };
$trendClass = static function ($v): string { return $v !== null && (float)$v < 0 ? 'is-negative' : 'is-positive'; };
$trendArrow = static function ($v): string { return $v !== null && (float)$v < 0 ? '↓' : '↑'; };
$activityStateLabel = static function (string $state) use ($tr): string {
    switch ($state) {
        case 'new_activity':
            return $tr('New activity', 'نشاط جديد');
        case 'no_current_activity':
            return $tr('No current activity', 'لا يوجد نشاط حالي');
        case 'increased':
            return $tr('Increased', 'ارتفع');
        case 'decreased':
            return $tr('Decreased', 'انخفض');
        default:
            return $tr('Stable', 'مستقر');
    }
};
$activityStateClass = static function (string $state): string {
    switch ($state) {
        case 'new_activity':
        case 'increased':
            return 'is-positive';
        case 'no_current_activity':
        case 'decreased':
            return 'is-negative';
        default:
            return 'is-neutral';
    }
};
$activityChangeText = static function ($percent, string $state) use ($tr): string {
    if ($state === 'new_activity') {
        return $tr('New', 'جديد');
    }
    if ($state === 'no_current_activity') {
        return $tr('Stopped', 'متوقف');
    }
    if ($percent === null) {
        return '—';
    }
    $value = (float)$percent;
    if (abs($value) < 0.05) {
        return '0.0%';
    }
    return ($value > 0 ? '+' : '−') . number_format(abs($value), 1) . '%';
};

$mohCard = $cards['moh'] ?? [];
$drugCard = $cards['drug'] ?? [];
$netCard = $cards['net'] ?? [];
$topFive = array_slice($matrix, 0, 5);
$specialtyCount = count($matrix);
$lowestNet = null;
if ($matrix) {
    $netCandidates = array_values(array_filter($matrix, static function ($row): bool {
        return array_key_exists('net_value', $row) && $row['net_value'] !== null;
    }));
    if ($netCandidates) {
        usort($netCandidates, static function ($a, $b): int {
            return ((float)$a['net_value']) <=> ((float)$b['net_value']);
        });
        $lowestNet = $netCandidates[0];
    }
}
$exactMoney = static function (float $v): string { return number_format($v, 2); };
?>
<div class="exec-page sf28-page" data-specialty-finance-executive="R30" data-specialty-activity-recovery="P12.1">
<?php if ($dataError || !$data): ?>
    <section class="exec-surface sf28-unavailable">
        <h2><?= e($tr('Specialty finance data is temporarily unavailable', 'بيانات المالية حسب التخصص غير متاحة مؤقتًا')) ?></h2>
        <p><?= e($tr('Try another year or branch.', 'جرّب سنة أو فرعًا آخر.')) ?></p>
    </section>
<?php else: ?>

<?php if (!$currentYearHasData): ?>
<section class="sf31-coverage-alert" role="status">
    <span class="sf31-coverage-alert__icon" aria-hidden="true">!</span>
    <div>
        <strong><?= e($tr(
            'The selected year is available, but Specialty Finance data has not been loaded yet.',
            'السنة المحددة متاحة للاختيار، لكن بيانات المالية حسب التخصص لم تُحمّل بعد.'
        )) ?></strong>
        <p><?= e($tr(
            '2026 is now visible as the current year. The page will not treat zero values as confirmed financial results until source coverage is available.',
            'أصبحت سنة 2026 ظاهرة كسنة حالية، ولن تعتبر الصفحة القيم الصفرية نتائج مالية مؤكدة حتى تتوفر تغطية المصدر.'
        )) ?></p>
    </div>
</section>
<?php endif; ?>

<section class="sf28-kpi-grid<?= !$currentYearHasData ? ' sf31-data-unavailable' : '' ?>" aria-label="<?= e($tr('Executive specialty finance summary', 'ملخص المالية التنفيذية حسب التخصص')) ?>">
    <?php
    $kpis = [
        ['moh', $tr('MOH Revenue', 'إيراد وزارة الصحة'), $mohCard, '▥'],
        ['drug', $tr('Drug Revenue', 'إيراد الأدوية'), $drugCard, '◇'],
        ['net', $tr('Net After Drug / MOH', 'الصافي بعد الأدوية ووزارة الصحة'), $netCard, '$'],
    ];
    foreach ($kpis as [$key, $label, $card, $icon]):
        $change = $card['percent'] ?? null;
    ?>
    <article class="sf28-kpi sf28-kpi--<?= e($key) ?>">
        <span class="sf28-kpi__icon" aria-hidden="true"><?= e($icon) ?></span>
        <div class="sf28-kpi__copy">
            <span><?= e($label) ?></span>
            <strong><?= e($currentYearHasPeriodData ? $compact((float)($card['current_total'] ?? 0)) : '—') ?></strong>
            <small>
                <?= e($tr('vs ', 'مقابل ') . $compareYear) ?>
                <?php if ($currentYearHasPeriodData && $compareYearHasPeriodData && $change !== null): ?><b class="<?= e($trendClass($change)) ?>"><?= e($trendArrow($change) . ' ' . $pct(abs((float)$change))) ?></b><?php endif; ?>
            </small>
        </div>
    </article>
    <?php endforeach; ?>

    <article class="sf28-kpi sf28-kpi--movement">
        <span class="sf28-kpi__icon" aria-hidden="true">↗</span>
        <div class="sf28-kpi__copy">
            <span><?= e($tr('Largest Movement', 'أكبر تحرك')) ?></span>
            <strong><?= e($currentYearHasPeriodData && $compareYearHasPeriodData && $movement ? $pct(abs((float)$movement['percent'])) : '—') ?></strong>
            <small><?= e($currentYearHasPeriodData && $compareYearHasPeriodData && $movement ? (string)$movement['title'] : $tr('No confirmed comparable movement', 'لا يوجد تحرك مقارن مؤكد')) ?></small>
        </div>
    </article>
</section>

<section class="sf28-insight-band sf29-decision-lens" aria-labelledby="sf28-insight-title">
    <div class="sf28-insight-main">
        <span class="sf28-insight-icon" aria-hidden="true">★</span>
        <div>
            <span class="sf28-eyebrow"><?= e($tr('EXECUTIVE SPECIALTY VIEW', 'نظرة تنفيذية حسب التخصص')) ?></span>
            <h2 id="sf28-insight-title"><?= e($tr('What leadership should know now', 'ما الذي يجب أن تعرفه الإدارة الآن')) ?></h2>
            <p>
                <?php if ($topTotalRevenue && $topNet): ?>
                    <strong><?= e((string)$topTotalRevenue['label']) ?></strong>
                    <?= e($tr('leads total revenue, while ', 'يتصدر إجمالي الإيرادات، بينما يتصدر ')) ?>
                    <strong><?= e((string)$topNet['label']) ?></strong>
                    <?= e($tr('leads net contribution in the selected period.', 'المساهمة الصافية في الفترة المحددة.')) ?>
                <?php else: ?>
                    <?= e($tr('Current specialty performance is available for executive review.', 'أداء التخصصات الحالي متاح للمراجعة التنفيذية.')) ?>
                <?php endif; ?>
            </p>
        </div>
    </div>
    <div class="sf28-signal-grid sf29-signal-grid">
        <article class="sf29-signal sf29-signal--lead">
            <small><?= e($tr('Top performer', 'الأعلى أداءً')) ?></small>
            <strong><?= e($topNet ? (string)$topNet['label'] : '—') ?></strong>
            <span><?= e($topNet ? $compact((float)$topNet['value']) : '—') ?></span>
        </article>
        <article class="sf29-signal sf29-signal--movement">
            <small><?= e($tr('Strongest movement', 'أقوى تحرك')) ?></small>
            <strong><?= e($movement ? (string)$movement['title'] : '—') ?></strong>
            <span class="<?= e($movement ? $trendClass($movement['percent']) : '') ?>"><?= e($movement ? $trendArrow($movement['percent']) . ' ' . $pct(abs((float)$movement['percent'])) : '—') ?></span>
        </article>
        <article class="sf29-signal sf29-signal--attention">
            <small><?= e($tr('Review opportunity', 'فرصة للمراجعة')) ?></small>
            <strong><?= e($lowestNet ? (string)$lowestNet['label'] : '—') ?></strong>
            <span><?= e($lowestNet ? $compact((float)$lowestNet['net_value']) : '—') ?></span>
        </article>
        <article class="sf29-signal sf29-signal--coverage">
            <small><?= e($tr('Specialties reviewed', 'التخصصات المشمولة')) ?></small>
            <strong><?= e((string)$specialtyCount) ?></strong>
            <span><?= e($tr('Current comparison', 'المقارنة الحالية')) ?></span>
        </article>
    </div>
</section>

<form method="get" action="index.php" class="sf28-period-controls">
    <input type="hidden" name="page" value="specialty-finance">
    <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
    <div class="sf28-period-label">
        <span class="sf28-eyebrow"><?= e($tr('COMPARISON PERIOD', 'فترة المقارنة')) ?></span>
        <strong><?= e($currentPeriodLabel . ' · ' . ($hospital['name'] ?? $hospitalCode ?? '')) ?></strong>
        <?php if (!$currentYearHasData): ?>
            <small><?= e($tr('Awaiting source coverage', 'بانتظار تغطية المصدر')) ?></small>
        <?php endif; ?>
    </div>
    <label>
        <span><?= e($tr('Current year', 'السنة الحالية')) ?></span>
        <select name="year"><?php foreach ($years as $y): ?><option value="<?= e((string)$y) ?>" <?= (int)$y === (int)$year ? 'selected' : '' ?>><?= e((string)$y) ?></option><?php endforeach; ?></select>
    </label>
    <label>
        <span><?= e($tr('Comparison year', 'سنة المقارنة')) ?></span>
        <select name="compare_year"><?php foreach ($years as $y): ?><option value="<?= e((string)$y) ?>" <?= (int)$y === (int)$compareYear ? 'selected' : '' ?>><?= e((string)$y) ?></option><?php endforeach; ?></select>
    </label>
    <button type="submit"><?= e($tr('Update comparison', 'تحديث المقارنة')) ?></button>
    <?php if ($isFairCurrentYearComparison): ?>
        <div class="sf61-fair-comparison" role="note">
            <span class="sf61-fair-comparison__icon" aria-hidden="true">✓</span>
            <div>
                <strong><?= e($tr('Fair current-year comparison', 'مقارنة عادلة للسنة الحالية')) ?></strong>
                <p><?= e($tr(
                    $currentPeriodLabel . ' is compared with ' . $comparePeriodLabel . '. The incomplete current month is excluded.',
                    'تتم مقارنة ' . $currentPeriodLabel . ' مع ' . $comparePeriodLabel . '، مع استبعاد الشهر الحالي غير المكتمل.'
                )) ?></p>
            </div>
        </div>
    <?php endif; ?>
</form>

<?php if (!empty($activity['ready'])): ?>
<section
    class="sf121-activity"
    id="specialty-activity"
    data-sf121-root
    data-view-all-label="<?= e($tr('View all specialties', 'عرض كل التخصصات')) ?>"
    data-view-top-label="<?= e($tr('Show first 5 specialties', 'عرض أول 5 تخصصات')) ?>"
    data-sf121-active-metric="<?= e($activityDefaultMetric) ?>"
>
    <header class="sf121-heading">
        <div>
            <span class="sf28-eyebrow"><?= e($tr('PATIENT ACTIVITY', 'نشاط المرضى')) ?></span>
            <h2><?= e($tr('Patient Activity by Specialty', 'نشاط المرضى حسب التخصص')) ?></h2>
            <p><?= e($tr(
                'Review outpatient visits and admissions across the matched comparison period.',
                'مراجعة زيارات العيادات الخارجية وحالات الدخول خلال فترة المقارنة المتطابقة.'
            )) ?></p>
        </div>
        <span class="sf121-period-chip">
            <?= e($currentPeriodLabel) ?> · <?= e($tr('vs', 'مقابل')) ?> · <?= e($comparePeriodLabel) ?>
        </span>
    </header>

    <?php
    $outpatientActivityCard = $activityCards['outpatient'] ?? [];
    $admissionsActivityCard = $activityCards['admissions'] ?? [];
    $activityKpis = [
        [
            'key' => 'outpatient',
            'label' => $tr('Outpatient Visits', 'زيارات العيادات الخارجية'),
            'card' => $outpatientActivityCard,
            'icon' => 'OP',
        ],
        [
            'key' => 'admissions',
            'label' => $tr('Admissions', 'حالات الدخول'),
            'card' => $admissionsActivityCard,
            'icon' => 'IP',
        ],
    ];
    ?>
    <div class="sf121-kpi-grid">
        <?php foreach ($activityKpis as $activityKpi): ?>
            <?php
            $activityCard = (array)$activityKpi['card'];
            $activityPercent = $activityCard['percent'] ?? null;
            $activityCurrent = (float)($activityCard['current_total'] ?? 0);
            $activityCompare = (float)($activityCard['compare_total'] ?? 0);
            ?>
            <article class="sf121-kpi sf121-kpi--<?= e((string)$activityKpi['key']) ?>">
                <span class="sf121-kpi__icon"><?= e((string)$activityKpi['icon']) ?></span>
                <div>
                    <span><?= e((string)$activityKpi['label']) ?></span>
                    <strong><?= e(number_format($activityCurrent, 0)) ?></strong>
                    <small>
                        <?= e($comparePeriodLabel) ?>:
                        <b><?= e(number_format($activityCompare, 0)) ?></b>
                    </small>
                </div>
                <em class="<?= e($trendClass($activityPercent)) ?>">
                    <?= e($activityChangeText(
                        $activityPercent,
                        $activityCurrent > $activityCompare
                            ? 'increased'
                            : ($activityCurrent < $activityCompare ? 'decreased' : 'stable')
                    )) ?>
                </em>
            </article>
        <?php endforeach; ?>
    </div>

    <?php
    $topOutpatient = is_array($activitySignals['top_outpatient'] ?? null)
        ? $activitySignals['top_outpatient']
        : null;
    $topAdmissions = is_array($activitySignals['top_admissions'] ?? null)
        ? $activitySignals['top_admissions']
        : null;
    $outpatientDecline = is_array($activitySignals['largest_outpatient_decline'] ?? null)
        ? $activitySignals['largest_outpatient_decline']
        : null;
    $admissionsDecline = is_array($activitySignals['largest_admissions_decline'] ?? null)
        ? $activitySignals['largest_admissions_decline']
        : null;
    ?>
    <div class="sf121-view-toolbar">
        <div>
            <span><?= e($tr('Activity view', 'عرض النشاط')) ?></span>
            <strong id="sf121_activity_view_title"><?= e($tr('Outpatient Visits', 'زيارات العيادات الخارجية')) ?></strong>
        </div>
        <div class="sf121-metric-tabs" role="tablist">
            <button
                type="button"
                data-sf121-metric="outpatient"
                class="<?= $activityDefaultMetric === 'outpatient' ? 'is-active' : '' ?>"
                aria-selected="<?= $activityDefaultMetric === 'outpatient' ? 'true' : 'false' ?>"
            >
                <?= e($tr('Outpatient Visits', 'زيارات العيادات الخارجية')) ?>
            </button>
            <button
                type="button"
                data-sf121-metric="admissions"
                class="<?= $activityDefaultMetric === 'admissions' ? 'is-active' : '' ?>"
                aria-selected="<?= $activityDefaultMetric === 'admissions' ? 'true' : 'false' ?>"
            >
                <?= e($tr('Admissions', 'حالات الدخول')) ?>
            </button>
        </div>
    </div>

    <div class="sf121-signal-grid">
        <article data-sf121-signal-metric="outpatient">
            <small><?= e($tr('Highest volume', 'أعلى حجم')) ?></small>
            <strong><?= e($topOutpatient ? (string)$topOutpatient['label'] : '—') ?></strong>
            <span><?= e($topOutpatient ? number_format((float)$topOutpatient['current_outpatient_visits'], 0) : '—') ?></span>
        </article>
        <article class="is-attention" data-sf121-signal-metric="outpatient">
            <small><?= e($tr('Largest decline', 'أكبر انخفاض')) ?></small>
            <strong><?= e($outpatientDecline ? (string)$outpatientDecline['label'] : $tr('No decline', 'لا يوجد انخفاض')) ?></strong>
            <span class="<?= e($outpatientDecline ? 'is-negative' : 'is-positive') ?>">
                <?= e($outpatientDecline
                    ? number_format(abs((float)$outpatientDecline['outpatient_difference']), 0) . ' '
                        . $tr('fewer visits', 'زيارة أقل')
                    : $tr('Stable or increasing', 'مستقر أو مرتفع')
                ) ?>
            </span>
        </article>
        <article data-sf121-signal-metric="admissions">
            <small><?= e($tr('Highest volume', 'أعلى حجم')) ?></small>
            <strong><?= e($topAdmissions ? (string)$topAdmissions['label'] : '—') ?></strong>
            <span><?= e($topAdmissions ? number_format((float)$topAdmissions['current_admissions'], 0) : '—') ?></span>
        </article>
        <article class="is-attention" data-sf121-signal-metric="admissions">
            <small><?= e($tr('Largest decline', 'أكبر انخفاض')) ?></small>
            <strong><?= e($admissionsDecline ? (string)$admissionsDecline['label'] : $tr('No decline', 'لا يوجد انخفاض')) ?></strong>
            <span class="<?= e($admissionsDecline ? 'is-negative' : 'is-positive') ?>">
                <?= e($admissionsDecline
                    ? number_format(abs((float)$admissionsDecline['admissions_difference']), 0) . ' '
                        . $tr('fewer admissions', 'حالة دخول أقل')
                    : $tr('Stable or increasing', 'مستقر أو مرتفع')
                ) ?>
            </span>
        </article>
    </div>

    <div class="sf121-workspace">
        <article class="sf121-table-card">
            <header>
                <div>
                    <span class="sf28-eyebrow"><?= e($tr('SPECIALTY DETAIL', 'تفاصيل التخصصات')) ?></span>
                    <h3 id="sf121_activity_table_title"><?= e($tr('Outpatient Visits by Specialty', 'زيارات العيادات الخارجية حسب التخصص')) ?></h3>
                </div>
            </header>

            <div class="sf121-table-wrap">
                <table class="sf121-table">
                    <thead>
                        <tr>
                            <th><?= e($tr('Specialty', 'التخصص')) ?></th>
                            <th><?= e($currentPeriodLabel) ?></th>
                            <th><?= e($comparePeriodLabel) ?></th>
                            <th><?= e($tr('Change', 'التغير')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($activityRows as $activityIndex => $activityRow): ?>
                            <tr
                                data-sf121-activity-row
                                <?= $activityIndex >= 5 ? 'hidden data-sf121-extra-row="true"' : '' ?>
                            >
                                <td>
                                    <strong><?= e((string)$activityRow['label']) ?></strong>
                                </td>
                                <td data-sf121-metric-cell="outpatient"><?= e(number_format((float)$activityRow['current_outpatient_visits'], 0)) ?></td>
                                <td data-sf121-metric-cell="outpatient"><?= e(number_format((float)$activityRow['compare_outpatient_visits'], 0)) ?></td>
                                <td data-sf121-metric-cell="outpatient">
                                    <span class="<?= e($activityStateClass((string)$activityRow['outpatient_state'])) ?>">
                                        <?= e($activityChangeText(
                                            $activityRow['outpatient_percent'],
                                            (string)$activityRow['outpatient_state']
                                        )) ?>
                                    </span>
                                </td>
                                <td data-sf121-metric-cell="admissions"><?= e(number_format((float)$activityRow['current_admissions'], 0)) ?></td>
                                <td data-sf121-metric-cell="admissions"><?= e(number_format((float)$activityRow['compare_admissions'], 0)) ?></td>
                                <td data-sf121-metric-cell="admissions">
                                    <span class="<?= e($activityStateClass((string)$activityRow['admissions_state'])) ?>">
                                        <?= e($activityChangeText(
                                            $activityRow['admissions_percent'],
                                            (string)$activityRow['admissions_state']
                                        )) ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if (count($activityRows) > 5): ?>
                <button type="button" class="sf121-view-all" data-sf121-view-all aria-expanded="false">
                    <?= e($tr('View all specialties', 'عرض كل التخصصات')) ?>
                </button>
            <?php endif; ?>
        </article>

        <article class="sf121-trend-card">
            <header>
                <div>
                    <span class="sf28-eyebrow"><?= e($tr('MONTHLY ACTIVITY TREND', 'الاتجاه الشهري للنشاط')) ?></span>
                    <h3 id="sf121_activity_chart_title"><?= e($tr('Monthly comparison', 'المقارنة الشهرية')) ?></h3>
                </div>
                <label>
                    <span><?= e($tr('Scope', 'النطاق')) ?></span>
                    <select data-sf121-specialty-select>
                        <option value="__all__" <?= $activityDefaultSpecialty === '__all__' ? 'selected' : '' ?>>
                            <?= e($tr('All Specialties', 'جميع التخصصات')) ?>
                        </option>
                        <?php foreach ($activityRows as $activityRow): ?>
                            <option
                                value="<?= e((string)$activityRow['id']) ?>"
                                <?= (string)$activityRow['id'] === $activityDefaultSpecialty ? 'selected' : '' ?>
                            >
                                <?= e((string)$activityRow['label']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </label>
            </header>

            <div class="sf121-chart-stage" data-sf121-chart-state="pending">
                <canvas id="sf121_activity_chart" height="180"></canvas>
                <div class="sf121-chart-error">
                    <?= e($tr('The activity chart is temporarily unavailable.', 'رسم النشاط غير متاح مؤقتًا.')) ?>
                </div>
            </div>

        </article>
    </div>

    <script type="application/json" id="sf121_activity_chart_config"><?= json_encode(
        $activityChartConfigs,
        JSON_UNESCAPED_UNICODE
        | JSON_UNESCAPED_SLASHES
        | JSON_HEX_TAG
        | JSON_HEX_APOS
        | JSON_HEX_QUOT
        | JSON_HEX_AMP
    ) ?></script>
    <input type="hidden" id="sf121_default_specialty" value="<?= e($activityDefaultSpecialty) ?>">
    <input type="hidden" id="sf121_default_metric" value="<?= e($activityDefaultMetric) ?>">
</section>
<?php endif; ?>

<section class="sf28-charts" id="specialty-charts" data-legacy-aliases="special_net_rev net_rev" data-legacy-function="get_net_rev" data-source-boundary="FULL_HISTORICAL_FUNCTION_BODY_AND_DISPATCHER_ALIAS_MAPPING_RECOVERED">
<?php
$chartMeta = [
    'moh' => [$tr('MOH contribution by specialty', 'مساهمة وزارة الصحة حسب التخصص'), 'moh'],
    'drug' => [$tr('Drug revenue by specialty', 'إيراد الأدوية حسب التخصص'), 'drug'],
    'net' => [$tr('Net revenue by specialty', 'صافي الإيراد حسب التخصص'), 'net'],
];
foreach (['moh', 'drug', 'net'] as $key):
    $chart = $data['charts'][$key] ?? [];
    $payload = $chart['payload'] ?? [];
    $values = (array)(($payload['series'][0]['values'] ?? []));
    $labels = (array)($payload['labels'] ?? []);
    $rows = [];
    foreach ($labels as $i => $label) { $rows[] = ['label' => (string)$label, 'value' => (float)($values[$i] ?? 0)]; }
?>
    <article class="sf28-chart-card sf28-chart-card--<?= e($key) ?>" data-exec-chart-card="<?= e($key) ?>" data-chart-state="pending">
        <header>
            <div>
                <span class="sf28-eyebrow"><?= e($tr('SPECIALTY PERFORMANCE', 'أداء التخصصات')) ?></span>
                <h3><?= e($chartMeta[$key][0]) ?></h3>
            </div>
            <div class="sf28-chart-total">
                <small><?= e($tr('Total', 'الإجمالي')) ?></small>
                <strong><?= e($compact((float)($cards[$key]['current_total'] ?? 0))) ?></strong>
            </div>
        </header>
        <div class="sf28-chart-stage">
            <canvas id="exec_chart_<?= e($key) ?>" width="760" height="440"></canvas>
            <div class="exec-chart-state exec-chart-empty"><?= e($tr('No activity for this year', 'لا توجد بيانات لهذه السنة')) ?></div>
            <div class="exec-chart-state exec-chart-error"><?= e($tr('Chart temporarily unavailable', 'الرسم غير متاح مؤقتًا')) ?></div>
        </div>
    </article>
    <script type="application/json" id="exec_chart_data_<?= e($key) ?>"><?= json_encode(['tone' => $chartMeta[$key][1], 'rows' => $rows, 'limit' => 10, 'fitParent' => true, 'preferredHeight' => 320, 'locale' => $isAr ? 'ar-SA' : 'en-US'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
<?php endforeach; ?>
</section>

<section class="sf28-lower" id="specialty-table" data-legacy-function="special_prof" data-source-boundary="FULL_HISTORICAL_FUNCTION_BODY_RECOVERED">
    <article class="sf28-table-card">
        <header class="sf28-section-head">
            <div>
                <span class="sf28-eyebrow"><?= e($tr('SPECIALTY PERFORMANCE DETAIL', 'تفاصيل أداء التخصصات')) ?></span>
                <h2><?= e($tr('Specialty Performance Overview', 'نظرة عامة على أداء التخصصات')) ?></h2>
                <p><?= e($tr('Top specialties first, with the full list available when deeper review is needed.', 'تظهر التخصصات الأعلى أولًا، مع إتاحة القائمة الكاملة عند الحاجة إلى مراجعة أعمق.')) ?></p>
            </div>
        </header>
        <div class="sf28-table-wrap">
            <table class="sf28-table" data-exec-table>
                <thead><tr>
                    <th>#</th>
                    <th><?= e($tr('Specialty', 'التخصص')) ?></th>
                    <th><?= e(exec_lang('total_revenue')) ?></th>
                    <th><?= e($tr('MOH revenue', 'إيراد وزارة الصحة')) ?></th>
                    <th><?= e($tr('Drug revenue', 'إيراد الأدوية')) ?></th>
                    <th><?= e($tr('Net after drug / MOH', 'الصافي بعد الأدوية ووزارة الصحة')) ?></th>
                </tr></thead>
                <tbody>
                <?php foreach ($matrix as $i => $row): ?>
                    <tr class="<?= $i >= 5 ? 'sf28-extra-row' : '' ?>" <?= $i >= 5 ? 'hidden' : '' ?>>
                        <td><span class="exec-rank"><?= e((string)($i + 1)) ?></span></td>
                        <td><strong><?= e((string)$row['label']) ?></strong></td>
                        <td><?= array_key_exists('total_revenue_value', $row) && $row['total_revenue_value'] !== null ? '<span class="sf29-money" title="' . e($exactMoney((float)$row['total_revenue_value'])) . '">' . e($compact((float)$row['total_revenue_value'])) . '</span>' : '—' ?></td>
                        <td><span class="sf29-money" title="<?= e($exactMoney((float)$row['moh_value'])) ?>"><?= e($compact((float)$row['moh_value'])) ?></span></td>
                        <td><span class="sf29-money" title="<?= e($exactMoney((float)$row['drug_value'])) ?>"><?= e($compact((float)$row['drug_value'])) ?></span></td>
                        <td><?= array_key_exists('net_value', $row) && $row['net_value'] !== null ? '<span class="sf29-money" title="' . e($exactMoney((float)$row['net_value'])) . '">' . e($compact((float)$row['net_value'])) . '</span>' : '—' ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php if (count($matrix) > 5): ?>
            <button type="button" class="sf28-view-all" data-sf28-view-all><?= e($tr('View all specialties', 'عرض كل التخصصات')) ?></button>
        <?php endif; ?>
    </article>

    <aside class="sf28-summary-card">
        <span class="sf28-eyebrow"><?= e($tr('LEADERSHIP SIGNALS', 'إشارات الإدارة العليا')) ?></span>
        <h2><?= e($tr('Leadership Review indicators', 'إشارات الإدارة العليا')) ?></h2>
        <div class="sf28-summary-list">
            <?php if ($topTotalRevenue): ?>
            <article class="tone-blue"><i>🏆</i><div><small><?= e($tr('Leading total revenue specialty', 'أعلى تخصص في إجمالي الإيراد')) ?></small><strong><?= e((string)$topTotalRevenue['label']) ?></strong><span><?= e($compact((float)$topTotalRevenue['value'])) ?></span></div></article>
            <?php endif; ?>
            <?php if ($topNet): ?>
            <article class="tone-purple"><i>◆</i><div><small><?= e($tr('Leading net-revenue specialty', 'أعلى تخصص في صافي الإيراد')) ?></small><strong><?= e((string)$topNet['label']) ?></strong><span><?= e($compact((float)$topNet['value'])) ?></span></div></article>
            <?php endif; ?>
            <?php if ($movement): ?>
            <article class="tone-teal"><i>↗</i><div><small><?= e($tr('Strongest year-over-year movement', 'أقوى تحرك سنوي')) ?></small><strong><?= e((string)$movement['title']) ?></strong><span class="<?= e($trendClass($movement['percent'])) ?>"><?= e($trendArrow($movement['percent']) . ' ' . $pct(abs((float)$movement['percent']))) ?></span></div></article>
            <?php endif; ?>
            <article class="tone-gold"><i>◇</i><div><small><?= e($tr('Leadership consideration', 'اعتبار للإدارة العليا')) ?></small><strong><?= e($topNet ? $tr('Protect the strongest net contribution and verify its sustainability', 'حافظ على أقوى مساهمة صافية وتحقق من استدامتها') : $tr('Review current specialty contribution and sustainability', 'راجع مساهمات التخصصات الحالية واستدامتها')) ?></strong></div></article>
        </div>
    </aside>
</section>

<section class="sf28-actions" aria-labelledby="sf28-actions-title">
    <div class="sf28-actions-intro">
        <span class="sf28-actions-icon" aria-hidden="true">◎</span>
        <div>
            <span class="sf28-eyebrow"><?= e($tr('RECOMMENDED ACTIONS', 'الإجراءات الموصى بها')) ?></span>
            <h2 id="sf28-actions-title"><?= e($tr('Next actions for leadership review', 'الخطوات التالية لمراجعة الإدارة العليا')) ?></h2>
        </div>
    </div>
    <div class="sf28-actions-grid">
        <a href="#specialty-charts" class="tone-blue"><i>⌕</i><div><strong><?= e($tr('Review the leading specialties', 'راجع التخصصات المتصدرة')) ?></strong><span><?= e($tr('Confirm what is sustaining the strongest revenue contribution.', 'تحقق من العوامل التي تدعم أقوى مساهمة في الإيرادات.')) ?></span></div><b>→</b></a>
        <a href="#specialty-table" class="tone-purple"><i>◇</i><div><strong><?= e($tr('Validate MOH contribution sustainability', 'تحقق من استدامة مساهمة وزارة الصحة')) ?></strong><span><?= e($tr('Review whether the strongest year-over-year movement is sustainable.', 'راجع ما إذا كان أقوى تحرك سنوي قابلًا للاستمرار.')) ?></span></div><b>→</b></a>
        <a href="#specialty-table" class="tone-teal"><i>▥</i><div><strong><?= e($tr('Review lower net contributors', 'راجع التخصصات الأقل مساهمة صافية')) ?></strong><span><?= e($tr('Identify where focused management attention may improve contribution.', 'حدد أين يمكن للتركيز الإداري أن يحسن المساهمة.')) ?></span></div><b>→</b></a>
    </div>
</section>

<script>
(function(){'use strict';
var gate={expected:3,rendered:0,empty:0,failed:0,status:'PENDING',runtime:'H11.0-P11.1-R29'};
function publish(){gate.status=gate.failed===0&&(gate.rendered+gate.empty)===gate.expected?'PASS':'FAIL';window.__DDB_SPECIALTY_FINANCE_CHART_GATE__=gate;document.documentElement.dataset.specialtyFinanceChartGate=gate.status;document.documentElement.dataset.specialtyFinanceChartRuntime='H11.0-P11.1-R30';}
function run(){if(!window.ExecutiveUI||!window.ExecutiveUI.Charts){gate.failed=3;publish();return;}['moh','drug','net'].forEach(function(key){var card=document.querySelector('[data-exec-chart-card="'+key+'"]'),node=document.getElementById('exec_chart_data_'+key);try{var cfg=JSON.parse(node.textContent||'{}'),result=window.ExecutiveUI.Charts.renderHorizontalBar('exec_chart_'+key,cfg);if(result.empty){gate.empty++;card.dataset.chartState='empty';}else if(result.rendered){gate.rendered++;card.dataset.chartState='rendered';}else{gate.failed++;card.dataset.chartState='error';}}catch(e){gate.failed++;if(card)card.dataset.chartState='error';}});publish();}
function initViewAll(){var btn=document.querySelector('[data-sf28-view-all]');if(!btn)return;btn.addEventListener('click',function(){document.querySelectorAll('.sf28-extra-row').forEach(function(row){row.hidden=!row.hidden;});var expanded=btn.getAttribute('aria-expanded')==='true';btn.setAttribute('aria-expanded',expanded?'false':'true');btn.textContent=expanded?'<?= e($tr('View all specialties', 'عرض كل التخصصات')) ?>':'<?= e($tr('Show top 5 only', 'عرض أعلى 5 فقط')) ?>';});}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',function(){run();initViewAll();},{once:true});else{run();initViewAll();}
})();
</script>
<?php endif; ?>
</div>
