<?php
/**
 * H11.0-P11.1-R24 — Executive Chart Readability Closure & Donut Center Fix
 * UI-only presentation layer. Existing PHP + Oracle reads are preserved.
 */

function phase109_card_icon(string $key): string {
    $icons = [
        'total' => '◈',
        'cash' => '●',
        'insurance' => '◐',
        'moh' => '◎',
        'profit_loss' => '◆',
    ];
    return $icons[$key] ?? '▦';
}

function phase109_total(array $cards, string $key, string $field): float {
    return isset($cards[$key][$field]) ? (float)$cards[$key][$field] : 0.0;
}

function phase109_card_title(string $key, array $card): string {
    $map = [
        'total' => 'revenue.total',
        'cash' => 'revenue.cash',
        'insurance' => 'revenue.insurance',
        'moh' => 'revenue.moh',
        'profit_loss' => 'revenue.profit_loss',
    ];
    return isset($map[$key]) ? t($map[$key]) : (string)($card['title'] ?? $key);
}

function phase109_chart_title(string $key, array $chart): string {
    $map = [
        'total' => 'chart.total',
        'cash' => 'chart.cash',
        'insurance' => 'chart.insurance',
        'moh' => 'chart.moh',
        'profit_loss' => 'chart.profit_loss',
    ];
    return isset($map[$key]) ? t($map[$key]) : (string)($chart['title'] ?? $key);
}

function phase119_chart_tab_title(string $key, array $chart): string {
    $labels = [
        'total' => ['Total Revenue', 'إجمالي الإيرادات'],
        'cash' => ['Cash Revenue', 'الإيرادات النقدية'],
        'insurance' => ['Insurance Revenue', 'إيرادات التأمين'],
        'moh' => ['MOH Revenue', 'إيرادات وزارة الصحة'],
        'profit_loss' => ['Profit / Loss', 'الربح / الخسارة'],
    ];
    if (isset($labels[$key])) {
        return phase111_tr($labels[$key][0], $labels[$key][1]);
    }
    return phase109_chart_title($key, $chart);
}

function phase1092_chart_has_data(array $rows): bool {
    if ($rows === []) {
        return false;
    }
    foreach ($rows as $row) {
        if (abs((float)($row['current_value'] ?? 0)) > 0.00001 || abs((float)($row['compare_value'] ?? 0)) > 0.00001) {
            return true;
        }
    }
    return false;
}

function phase1092_percent_text(?float $percent): string {
    return $percent === null ? '0.0' : number_format(abs($percent), 1);
}

function phase111_tr(string $en, string $ar): string {
    return current_lang() === 'ar' ? $ar : $en;
}

function phase111_change_class(?float $percent): string {
    if ($percent === null || abs($percent) < 0.00001) {
        return 'neutral';
    }
    return $percent > 0 ? 'positive' : 'negative';
}

function phase111_change_text(?float $percent): string {
    if ($percent === null) {
        return '—';
    }
    $arrow = $percent > 0 ? '↑' : ($percent < 0 ? '↓' : '→');
    return $arrow . ' ' . number_format(abs($percent), 2) . '%';
}

function phase111_month_extremes(array $rows): array {
    $points = [];
    foreach ($rows as $row) {
        $value = (float)($row['current_value'] ?? 0);
        if (abs($value) <= 0.00001) {
            continue;
        }
        $points[] = [
            'month' => (string)($row['month_name'] ?? ''),
            'value' => $value,
        ];
    }
    if ($points === []) {
        return ['best' => null, 'weakest' => null];
    }
    $best = $points[0];
    $weakest = $points[0];
    foreach ($points as $point) {
        if ($point['value'] > $best['value']) {
            $best = $point;
        }
        if ($point['value'] < $weakest['value']) {
            $weakest = $point;
        }
    }
    return ['best' => $best, 'weakest' => $weakest];
}

function phase111_extreme_text(?array $point): string {
    if ($point === null || trim((string)($point['month'] ?? '')) === '') {
        return phase111_tr('N/A', 'غير متاح');
    }
    return (string)$point['month'] . ' (' . compact_money((float)$point['value']) . ')';
}

$totalRevenue = phase109_total($cards, 'total', 'current_total');
$compareRevenue = phase109_total($cards, 'total', 'compare_total');
$cashRevenue = phase109_total($cards, 'cash', 'current_total');
$insuranceRevenue = phase109_total($cards, 'insurance', 'current_total');
$mohRevenue = phase109_total($cards, 'moh', 'current_total');
$profitCurrent = phase109_total($cards, 'profit_loss', 'current_total');
$profitCompare = phase109_total($cards, 'profit_loss', 'compare_total');
$totalPercent = isset($cards['total']['percent']) && $cards['total']['percent'] !== null
    ? (float)$cards['total']['percent']
    : null;
$profitPercent = isset($cards['profit_loss']['percent']) && $cards['profit_loss']['percent'] !== null
    ? (float)$cards['profit_loss']['percent']
    : null;
$cashPct = abs($totalRevenue) > 0.00001
    ? max(0, min(100, round(($cashRevenue / $totalRevenue) * 100)))
    : 0;
$insurancePct = abs($totalRevenue) > 0.00001
    ? max(0, min(100, round(($insuranceRevenue / $totalRevenue) * 100)))
    : 0;
$mohPct = abs($totalRevenue) > 0.00001
    ? max(0, min(100, round(($mohRevenue / $totalRevenue) * 100)))
    : 0;

$isRange = $mode === 'range';
$comparisonContract = is_array($comparisonContract ?? null) ? $comparisonContract : [];
$availableYears = is_array($availableYears ?? null) ? $availableYears : range((int)date('Y'), 2014);
$isFairCurrentYearComparison = !$isRange && !empty($comparisonContract['fair_current_year_comparison']);
$lastCompleteMonth = (int)($comparisonContract['last_complete_month'] ?? 12);
$currentMonthExcluded = (int)($comparisonContract['current_month_excluded'] ?? 0);
$monthNamesEn = [1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'May',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec'];
$monthNamesAr = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
$monthNames = current_lang() === 'ar' ? $monthNamesAr : $monthNamesEn;

if ($isRange) {
    $currentPeriodLabel = (string)$fromDate . ' → ' . (string)$toDate;
    $comparePeriodLabel = (string)$compareFromDate . ' → ' . (string)$compareToDate;
} elseif ($isFairCurrentYearComparison && $lastCompleteMonth > 0) {
    $rangeText = ($monthNames[1] ?? 'Jan') . '–' . ($monthNames[$lastCompleteMonth] ?? (string)$lastCompleteMonth);
    $currentPeriodLabel = $rangeText . ' ' . $year;
    $comparePeriodLabel = $rangeText . ' ' . $compareYear;
} elseif ($isFairCurrentYearComparison) {
    $currentPeriodLabel = phase111_tr('No completed months in ' . $year, 'لا توجد أشهر مكتملة في ' . $year);
    $comparePeriodLabel = phase111_tr('No comparable completed months', 'لا توجد أشهر مكتملة قابلة للمقارنة');
} else {
    $currentPeriodLabel = (string)$year;
    $comparePeriodLabel = (string)$compareYear;
}

function phase118_leadership_signals(?float $totalPercent, float $profitCurrent, int $insurancePct): array {
    $isArabic = current_lang() === 'ar';
    $signals = [];

    if ($profitCurrent < 0) {
        $signals[] = [
            'tone' => 'attention',
            'title' => $isArabic ? 'خسارة في الفترة الحالية' : 'Current-period loss',
            'detail' => $isArabic
                ? 'تسجل الفترة الحالية خسارة قدرها ' . compact_money(abs($profitCurrent)) . ' ريال.'
                : 'The current period is operating at a net loss of SAR ' . compact_money(abs($profitCurrent)) . '.',
        ];
    }

    if ($totalPercent !== null && $totalPercent <= -10) {
        $signals[] = [
            'tone' => 'attention',
            'title' => $isArabic ? 'انخفاض ملحوظ في الإيرادات' : 'Material revenue decline',
            'detail' => $isArabic
                ? 'انخفض إجمالي الإيرادات بنسبة ' . phase1092_percent_text($totalPercent) . '% مقارنة بفترة المقارنة.'
                : 'Total revenue is ' . phase1092_percent_text($totalPercent) . '% below the comparison period.',
        ];
    } elseif ($totalPercent !== null && $totalPercent >= 10) {
        $signals[] = [
            'tone' => 'positive',
            'title' => $isArabic ? 'نمو ملحوظ في الإيرادات' : 'Material revenue growth',
            'detail' => $isArabic
                ? 'ارتفع إجمالي الإيرادات بنسبة ' . phase1092_percent_text($totalPercent) . '% مقارنة بفترة المقارنة.'
                : 'Total revenue is ' . phase1092_percent_text($totalPercent) . '% above the comparison period.',
        ];
    }

    if ($insurancePct >= 80) {
        $signals[] = [
            'tone' => 'review',
            'title' => $isArabic ? 'اعتماد مرتفع على إيرادات التأمين' : 'High insurance concentration',
            'detail' => $isArabic
                ? 'يمثل التأمين ' . $insurancePct . '% من إجمالي الإيرادات الحالية.'
                : 'Insurance contributes ' . $insurancePct . '% of current total revenue.',
        ];
    }

    if ($signals === []) {
        $signals[] = [
            'tone' => 'positive',
            'title' => $isArabic
                ? 'لا توجد مشكلات مالية فورية تتطلب اهتمام الإدارة العليا'
                : 'No immediate financial issues require executive attention',
            'detail' => $isArabic
                ? 'لا تظهر المؤشرات الحالية إشارة مالية تستدعي تصعيدًا تنفيذيًا فوريًا.'
                : 'Current indicators show no immediate financial issue requiring executive escalation.',
        ];
    }

    return array_slice($signals, 0, 3);
}

$leadershipSignals = phase118_leadership_signals($totalPercent, $profitCurrent, $insurancePct);
$hasLeadershipAttention = false;
foreach ($leadershipSignals as $signal) {
    if (in_array((string)($signal['tone'] ?? ''), ['attention', 'review'], true)) {
        $hasLeadershipAttention = true;
        break;
    }
}

$primaryRevenueSource = $insuranceRevenue >= $cashRevenue
    ? [
        'label' => phase111_tr('Insurance', 'التأمين'),
        'value' => $insuranceRevenue,
        'share' => $insurancePct,
    ]
    : [
        'label' => phase111_tr('Cash', 'النقدي'),
        'value' => $cashRevenue,
        'share' => $cashPct,
    ];

$totalExtremes = phase111_month_extremes((array)($charts['total']['rows'] ?? []));
$strongestMonth = $totalExtremes['best'];
$weakestMonth = $totalExtremes['weakest'];

$currentDirection = $totalPercent === null
    ? phase111_tr('Comparison not available', 'المقارنة غير متاحة')
    : ($totalPercent > 0
        ? phase111_tr('Above comparison period', 'أعلى من فترة المقارنة')
        : ($totalPercent < 0
            ? phase111_tr('Below comparison period', 'أقل من فترة المقارنة')
            : phase111_tr('In line with comparison period', 'مماثل لفترة المقارنة')));

$chartSummary = [];
foreach ($charts as $chartKey => $chart) {
    $extremes = phase111_month_extremes((array)$chart['rows']);
    $card = $cards[$chartKey] ?? [];
    $chartSummary[$chartKey] = [
        'current' => compact_money((float)($card['current_total'] ?? 0)),
        'comparison' => compact_money((float)($card['compare_total'] ?? 0)),
        'change' => phase111_change_text(
            isset($card['percent']) && $card['percent'] !== null
                ? (float)$card['percent']
                : null
        ),
        'change_class' => phase111_change_class(
            isset($card['percent']) && $card['percent'] !== null
                ? (float)$card['percent']
                : null
        ),
        'best' => phase111_extreme_text($extremes['best']),
        'weakest' => phase111_extreme_text($extremes['weakest']),
    ];
}
?>

<section
    class="eri-v2-page eri-v3-page"
    data-executive-revenue-v2="true"
    data-executive-revenue-v3="true"
    data-revenue-mode="<?= e($mode) ?>"
>
    <section class="eri-v2-summary eri-v3-hero" aria-labelledby="eri-v2-summary-title">
        <div class="eri-v2-summary-head eri-v3-hero-head">
            <div class="eri-v2-summary-copy eri-v3-hero-copy">
                <span class="eri-eyebrow"><?= e(phase111_tr('Executive Financial View', 'الرؤية المالية التنفيذية')) ?></span>
                <h2 id="eri-v2-summary-title"><?= e(phase111_tr('Revenue & Financial Position', 'الإيرادات والوضع المالي')) ?></h2>
                <?php
                $revenueDataSource = (string)($revenueDataSource ?? 'batch');
                $revenueSummaryStatus = is_array($revenueSummaryStatus ?? null) ? $revenueSummaryStatus : [];
                $summaryFinishedAt = (string)($revenueSummaryStatus['finished_at'] ?? '');
                ?>
                <?php if ($revenueDataSource === 'summary'): ?>
                    <p class="muted eri-r45p3-source-note">
                        <?= e(phase111_tr('Monthly summary source', 'المصدر: الملخص الشهري')) ?>
                        <?php if ($summaryFinishedAt !== ''): ?>
                            · <?= e(phase111_tr('Refreshed ', 'آخر تحديث ')) ?><?= e($summaryFinishedAt) ?>
                        <?php endif; ?>
                    </p>
                <?php elseif ($revenueDataSource === 'batch_fallback'): ?>
                    <p class="muted eri-r45p3-source-note">
                        <?= e(phase111_tr(
                            'Live source fallback is active because the monthly summary is unavailable or stale.',
                            'تم استخدام المصدر المباشر لأن الملخص الشهري غير متاح أو قديم.'
                        )) ?>
                    </p>
                <?php endif; ?>
                <p><?= e(phase111_tr(
                    'A leadership view of current revenue, financial performance and the signals that matter for decision-making.',
                    'عرض تنفيذي للإيرادات الحالية والأداء المالي والمؤشرات الأكثر أهمية لصنع القرار.'
                )) ?></p>
            </div>

            <div class="eri-v2-context revenue109-period-strip eri-v3-context" aria-label="<?= e(phase111_tr('Current reporting context', 'سياق التقرير الحالي')) ?>">
                <span>
                    <b><?= e(phase111_tr('Current period', 'الفترة الحالية')) ?></b>
                    <strong><?= e($currentPeriodLabel) ?></strong>
                </span>
                <span>
                    <b><?= e(phase111_tr('Comparison period', 'فترة المقارنة')) ?></b>
                    <strong><?= e($comparePeriodLabel) ?></strong>
                </span>
                <span>
                    <b><?= e(phase111_tr('Branch', 'الفرع')) ?></b>
                    <strong><?= e((string)$hospital['name']) ?></strong>
                </span>
            </div>
        </div>

        <div class="eri-v2-priority-grid revenue109-kpis eri-v3-priority-grid" data-eri-priority-grid>
            <article class="eri-v2-priority-card eri-v2-priority-card--revenue eri-v3-priority-card">
                <span class="eri-v2-priority-icon" aria-hidden="true">◈</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase111_tr('Current Period Revenue', 'إيرادات الفترة الحالية')) ?></span>
                    <strong>SAR <?= e(compact_money($totalRevenue)) ?></strong>
                    <small><?= e(phase111_tr('Comparison period', 'فترة المقارنة')) ?>: SAR <?= e(compact_money($compareRevenue)) ?></small>
                    <em class="eri-v2-change eri-v2-change--<?= e(phase111_change_class($totalPercent)) ?>"><?= e(phase111_change_text($totalPercent)) ?></em>
                </div>
            </article>

            <article class="eri-v2-priority-card eri-v2-priority-card--profit eri-v3-priority-card <?= $profitCurrent < 0 ? 'is-attention' : '' ?>">
                <span class="eri-v2-priority-icon" aria-hidden="true">◆</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e($profitCurrent < 0
                        ? phase111_tr('Net Loss', 'صافي الخسارة')
                        : phase111_tr('Net Profit', 'صافي الربح')) ?></span>
                    <strong>SAR <?= e(compact_money(abs($profitCurrent))) ?></strong>
                    <small><?= e(phase111_tr('Comparison period', 'فترة المقارنة')) ?>: SAR <?= e(compact_money(abs($profitCompare))) ?></small>
                    <em class="eri-v2-change eri-v2-change--<?= e(phase111_change_class($profitPercent)) ?>"><?= e(phase111_change_text($profitPercent)) ?></em>
                </div>
            </article>

            <article class="eri-v2-priority-card eri-v2-priority-card--insurance eri-v3-priority-card">
                <span class="eri-v2-priority-icon" aria-hidden="true">◐</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase111_tr('Insurance Revenue', 'إيرادات التأمين')) ?></span>
                    <strong>SAR <?= e(compact_money($insuranceRevenue)) ?></strong>
                    <small><?= e((string)$insurancePct) ?>% <?= e(phase111_tr('of current revenue', 'من الإيرادات الحالية')) ?></small>
                </div>
            </article>

            <article class="eri-v2-priority-card eri-v3-priority-card eri-v3-priority-card--cash">
                <span class="eri-v2-priority-icon" aria-hidden="true">●</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase111_tr('Cash Revenue', 'الإيرادات النقدية')) ?></span>
                    <strong>SAR <?= e(compact_money($cashRevenue)) ?></strong>
                    <small><?= e((string)$cashPct) ?>% <?= e(phase111_tr('of current revenue', 'من الإيرادات الحالية')) ?></small>
                </div>
            </article>
        </div>
    </section>

    <section class="surface-card eri-v2-controls eri-v3-controls eri-r45p1-controls" aria-label="<?= e(phase111_tr('Year comparison controls', 'عناصر التحكم في مقارنة السنوات')) ?>">
        <div class="eri-r45p1-controls-head">
            <div>
                <span class="eri-eyebrow"><?= e(phase111_tr('Comparison controls', 'عناصر المقارنة')) ?></span>
                <h2><?= e(phase111_tr('Choose the years to compare', 'اختر السنوات المطلوب مقارنتها')) ?></h2>
                <p><?= e(phase111_tr(
                    'Select any two available years. The current year is compared only through the last completed month.',
                    'اختر أي سنتين متاحتين. تتم مقارنة السنة الحالية فقط حتى نهاية آخر شهر مكتمل.'
                )) ?></p>
            </div>
            <div class="eri-r45p1-active-comparison">
                <small><?= e(phase111_tr('Active comparison', 'المقارنة الحالية')) ?></small>
                <strong><?= e($currentPeriodLabel) ?> <span>vs</span> <?= e($comparePeriodLabel) ?></strong>
            </div>
        </div>

        <?php if ($filterError !== ''): ?>
            <div class="revenue109-alert" role="alert"><?= e($filterError) ?></div>
        <?php endif; ?>

        <?php if ($isFairCurrentYearComparison): ?>
            <div class="eri-r45p1-fair-notice" role="note">
                <span aria-hidden="true">✓</span>
                <div>
                    <strong><?= e(phase111_tr('Fair current-year comparison', 'مقارنة عادلة للسنة الحالية')) ?></strong>
                    <?php if ($lastCompleteMonth > 0): ?>
                        <p><?= e(phase111_tr(
                            'The comparison covers January through ' . ($monthNamesEn[$lastCompleteMonth] ?? '') . ' in both years. The incomplete current month, ' . ($monthNamesEn[$currentMonthExcluded] ?? '') . ', is excluded.',
                            'تشمل المقارنة الفترة من يناير حتى ' . ($monthNamesAr[$lastCompleteMonth] ?? '') . ' في السنتين. تم استثناء الشهر الحالي غير المكتمل: ' . ($monthNamesAr[$currentMonthExcluded] ?? '') . '.'
                        )) ?></p>
                    <?php else: ?>
                        <p><?= e(phase111_tr(
                            '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 else: ?>
            <div class="eri-r45p1-full-year-notice" role="note">
                <strong><?= e(phase111_tr('Full-year comparison', 'مقارنة سنة كاملة')) ?></strong>
                <span><?= e(phase111_tr('Both selected years are completed past years, so January through December are included.', 'السنتان المختارتان مكتملتان، لذلك تشمل المقارنة الفترة من يناير حتى ديسمبر.')) ?></span>
            </div>
        <?php endif; ?>

        <form method="get" action="index.php" class="eri-v2-filter-grid eri-v3-filter-grid eri-r45p1-filter-grid" data-revenue-filter-form>
            <input type="hidden" name="page" value="revenue">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">

            <label>
                <span><?= e(phase111_tr('Branch', 'الفرع')) ?></span>
                <select name="hospital">
                    <?php foreach ($hospitals as $code => $item): ?>
                        <option value="<?= e($code) ?>" <?= $code === $hospitalCode ? 'selected' : '' ?>><?= e($item['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                <span><?= e(phase111_tr('View', 'العرض')) ?></span>
                <select name="mode" data-revenue-mode-select>
                    <option value="year" <?= !$isRange ? 'selected' : '' ?>><?= e(phase111_tr('Year comparison', 'مقارنة السنوات')) ?></option>
                    <option value="range" <?= $isRange ? 'selected' : '' ?>><?= e(phase111_tr('Date range', 'نطاق زمني')) ?></option>
                </select>
            </label>

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

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

            <label data-revenue-range-field <?= !$isRange ? 'hidden aria-hidden="true"' : '' ?>>
                <span><?= e(phase111_tr('Start date', 'تاريخ البداية')) ?></span>
                <input type="date" name="from_date" value="<?= e((string)$fromDate) ?>">
            </label>

            <label data-revenue-range-field <?= !$isRange ? 'hidden aria-hidden="true"' : '' ?>>
                <span><?= e(phase111_tr('End date', 'تاريخ النهاية')) ?></span>
                <input type="date" name="to_date" value="<?= e((string)$toDate) ?>">
            </label>

            <button class="btn primary eri-v2-update" type="submit"><?= e(phase111_tr('Update comparison', 'تحديث المقارنة')) ?></button>
        </form>
    </section>

    <section class="eri-v2-decision-grid eri-v3-decision-grid" data-eri-decision-grid>
        <article class="eri-v2-card eri-v2-mix-card eri-v3-card eri-v3-composition-card">
            <div class="eri-v2-card-head eri-v3-card-head">
                <span class="eri-eyebrow"><?= e(phase111_tr('Revenue Composition', 'مكونات الإيرادات')) ?></span>
                <h2><?= e(phase111_tr('Current Revenue Composition', 'مكونات الإيرادات الحالية')) ?></h2>
                <p><?= e(phase111_tr(
                    'Insurance and cash form the primary revenue split. MOH revenue is shown separately for leadership visibility.',
                    'يمثل التأمين والنقدي التقسيم الرئيسي للإيرادات، مع عرض إيرادات وزارة الصحة بصورة مستقلة للوضوح التنفيذي.'
                )) ?></p>
            </div>

            <div class="eri-v2-mix-layout eri-v3-mix-layout">
                <div
                    class="eri-v2-donut eri-v3-donut"
                    style="--eri-v2-insurance: <?= e((string)$insurancePct) ?>%;"
                    data-ddb-chart-segments="<?= e(json_encode([
                        ['label' => phase111_tr('Insurance Revenue', 'إيرادات التأمين'), 'value' => $insuranceRevenue, 'percentage' => $insurancePct, 'prefix' => 'SAR '],
                        ['label' => phase111_tr('Cash Revenue', 'الإيرادات النقدية'), 'value' => $cashRevenue, 'percentage' => $cashPct, 'prefix' => 'SAR '],
                    ], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP)) ?>"
                    data-ddb-chart-inner-ratio="0.54"
                    data-ddb-chart-locale="<?= e(current_lang() === 'ar' ? 'ar-SA' : 'en-US') ?>"
                    role="img"
                    aria-label="<?= e(phase111_tr('Revenue composition', 'مكونات الإيرادات')) ?>"
                >
                    <div>
                        <strong>SAR <?= e(compact_money($totalRevenue)) ?></strong>
                        <span><?= e(phase111_tr('Current revenue', 'الإيرادات الحالية')) ?></span>
                    </div>
                </div>

                <div class="eri-v2-mix-metrics eri-v3-source-list">
                    <div class="eri-v3-source-item source-insurance">
                        <span><?= e(phase111_tr('Insurance Revenue', 'إيرادات التأمين')) ?></span>
                        <strong>SAR <?= e(compact_money($insuranceRevenue)) ?></strong>
                        <em><?= e((string)$insurancePct) ?>%</em>
                    </div>
                    <div class="eri-v3-source-item source-cash">
                        <span><?= e(phase111_tr('Cash Revenue', 'الإيرادات النقدية')) ?></span>
                        <strong>SAR <?= e(compact_money($cashRevenue)) ?></strong>
                        <em><?= e((string)$cashPct) ?>%</em>
                    </div>
                    <div class="eri-v3-source-item source-moh">
                        <span><?= e(phase111_tr('MOH Revenue', 'إيرادات وزارة الصحة')) ?></span>
                        <strong>SAR <?= e(compact_money($mohRevenue)) ?></strong>
                        <em><?= e((string)$mohPct) ?>%</em>
                    </div>
                </div>
            </div>
        </article>

        <article class="eri-v2-card eri-v3-card eri-v3-drivers-card">
            <div class="eri-v2-card-head eri-v3-card-head">
                <span class="eri-eyebrow"><?= e(phase111_tr('Revenue Drivers', 'محركات الإيرادات')) ?></span>
                <h2><?= e(phase111_tr('What is driving the current position', 'ما الذي يقود الوضع الحالي')) ?></h2>
                <p><?= e(phase111_tr(
                    'The strongest verified contributors and movement signals in the selected period.',
                    'أهم المساهمات والمؤشرات المؤكدة التي تفسر الوضع المالي خلال الفترة المحددة.'
                )) ?></p>
            </div>

            <div class="eri-v3-driver-grid">
                <article class="eri-v3-driver">
                    <small><?= e(phase111_tr('Primary revenue source', 'المصدر الرئيسي للإيرادات')) ?></small>
                    <strong><?= e((string)$primaryRevenueSource['label']) ?></strong>
                    <span>SAR <?= e(compact_money((float)$primaryRevenueSource['value'])) ?> · <?= e((string)$primaryRevenueSource['share']) ?>%</span>
                </article>

                <article class="eri-v3-driver">
                    <small><?= e(phase111_tr('Strongest month', 'أقوى شهر')) ?></small>
                    <strong><?= e($strongestMonth !== null && trim((string)($strongestMonth['month'] ?? '')) !== ''
                        ? (string)$strongestMonth['month']
                        : phase111_tr('Not available', 'غير متاح')) ?></strong>
                    <span><?= $strongestMonth !== null
                        ? 'SAR ' . e(compact_money((float)($strongestMonth['value'] ?? 0)))
                        : '—' ?></span>
                </article>

                <article class="eri-v3-driver">
                    <small><?= e(phase111_tr('Current direction', 'الاتجاه الحالي')) ?></small>
                    <strong class="direction-<?= e(phase111_change_class($totalPercent)) ?>"><?= e(phase111_change_text($totalPercent)) ?></strong>
                    <span><?= e($currentDirection) ?></span>
                </article>
            </div>
        </article>
    </section>

    <section
        class="eri-v2-card eri-v3-card eri-v3-attention <?= $hasLeadershipAttention ? 'has-attention' : 'is-clear' ?>"
        data-eri-leadership-status="<?= $hasLeadershipAttention ? 'attention' : 'stable' ?>"
        aria-labelledby="eri-v3-attention-title"
    >
        <div class="eri-v3-attention-head">
            <div>
                <span class="eri-eyebrow"><?= e(phase111_tr('Leadership Attention', 'اهتمام الإدارة العليا')) ?></span>
                <h2 id="eri-v3-attention-title"><?= e(phase111_tr('What requires executive awareness now', 'ما يستحق الانتباه التنفيذي الآن')) ?></h2>
            </div>
            <span class="eri-v3-attention-state">
                <?= e($hasLeadershipAttention
                    ? phase111_tr('Review required', 'تحتاج إلى مراجعة')
                    : phase111_tr('No immediate issue', 'لا توجد مشكلة فورية')) ?>
            </span>
        </div>

        <div class="eri-v3-attention-grid">
            <?php foreach ($leadershipSignals as $signal): ?>
                <article class="eri-v2-insight eri-v2-insight--<?= e((string)$signal['tone']) ?> eri-v3-attention-item">
                    <span aria-hidden="true"></span>
                    <div>
                        <strong><?= e((string)$signal['title']) ?></strong>
                        <p><?= e((string)$signal['detail']) ?></p>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="eri-v2-trend-workspace eri-trend-workspace eri-v3-trend-workspace" aria-labelledby="eri-v2-trend-title" data-eri-trend-workspace>
        <div class="eri-v2-trend-head eri-v3-trend-head">
            <div>
                <span class="eri-eyebrow"><?= e(phase111_tr('Financial Performance Trend', 'اتجاه الأداء المالي')) ?></span>
                <h2 id="eri-v2-trend-title"><?= e(phase111_tr('Current Period Performance', 'أداء الفترة الحالية')) ?></h2>
                <p><?= e(phase111_tr(
                    'Monthly revenue performance compared with the selected benchmark period.',
                    'أداء الإيرادات الشهري مقارنة بفترة المقارنة المحددة.'
                )) ?></p>
            </div>

            <div class="eri-v2-tabs" role="tablist" aria-label="<?= e(phase111_tr('Financial performance views', 'عروض الأداء المالي')) ?>">
                <?php $tabIndex = 0; ?>
                <?php foreach ($charts as $key => $chart): ?>
                    <button
                        type="button"
                        class="eri-trend-tab eri-v2-tab"
                        role="tab"
                        data-eri-trend-tab="<?= e((string)$key) ?>"
                        aria-selected="<?= $tabIndex === 0 ? 'true' : 'false' ?>"
                        tabindex="<?= $tabIndex === 0 ? '0' : '-1' ?>"
                    ><?= e(phase119_chart_tab_title((string)$key, $chart)) ?></button>
                    <?php $tabIndex++; ?>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="eri-v2-trend-layout">
            <div class="eri-v2-panel-host">
                <?php $panelIndex = 0; ?>
                <?php foreach ($charts as $key => $chart): ?>
                    <?php
                        $canvasId = 'chart_' . e((string)$key);
                        $jsonId = 'chart_data_' . e((string)$key);
                        $chartTitle = phase109_chart_title((string)$key, $chart);
                        $payload = $chart['payload'];
                        $payload['title'] = $chartTitle;
                        $payload['locale'] = current_lang() === 'ar' ? 'ar-SA' : 'en-US';
                        $payload['dir'] = current_dir();
                        $payload['showHeader'] = false;
                        $payload['showDataLabels'] = true;
                        $payload['valuePrefix'] = 'SAR ';
                        $payload['valueDecimals'] = 2;
                        $chartHasData = phase1092_chart_has_data($chart['rows']);
                        $summary = $chartSummary[$key];
                    ?>
                    <article
                        class="eri-v2-trend-panel revenue109-chart-card"
                        data-eri-trend-panel="<?= e((string)$key) ?>"
                        data-revenue-chart-shell
                        data-chart-key="<?= e((string)$key) ?>"
                        data-chart-data-state="<?= $chartHasData ? 'available' : 'empty' ?>"
                        data-chart-render-state="<?= $chartHasData ? 'pending' : 'empty' ?>"
                        data-summary-current="<?= e($summary['current']) ?>"
                        data-summary-comparison="<?= e($summary['comparison']) ?>"
                        data-summary-change="<?= e($summary['change']) ?>"
                        data-summary-change-class="<?= e($summary['change_class']) ?>"
                        data-summary-best="<?= e($summary['best']) ?>"
                        data-summary-weakest="<?= e($summary['weakest']) ?>"
                        <?= $panelIndex === 0 ? '' : 'hidden aria-hidden="true"' ?>
                    >
                        <div class="eri-v2-panel-title">
                            <div>
                                <span class="eri-eyebrow"><?= e(phase111_tr('Monthly View', 'العرض الشهري')) ?></span>
                                <h3><?= e($chartTitle) ?></h3>
                                <p><?= e((string)$hospital['name']) ?> · <?= e($currentPeriodLabel) ?> <?= e(phase111_tr('compared with', 'مقارنة بـ')) ?> <?= e($comparePeriodLabel) ?></p>
                            </div>
                            <div class="eri-v2-legend">
                                <span class="current"><?= e($year) ?></span>
                                <span class="comparison"><?= e($compareYear) ?></span>
                            </div>
                        </div>

                        <div class="revenue1092-chart-stage eri-v2-chart-stage" data-revenue-chart-stage>
                            <?php if ($chartHasData): ?>
                                <canvas id="<?= $canvasId ?>" class="chart revenue1092-chart-canvas eri-v2-chart-canvas" height="188" data-revenue-chart-canvas aria-label="<?= e($chartTitle) ?>"></canvas>
                                <div class="revenue1092-chart-message revenue1092-chart-error" data-revenue-chart-error hidden>
                                    <strong><?= e(t('revenue.chart_error_title')) ?></strong>
                                    <span><?= e(t('revenue.chart_error_text')) ?></span>
                                </div>
                            <?php else: ?>
                                <div class="revenue1092-chart-message revenue1092-chart-empty" data-revenue-chart-empty>
                                    <strong><?= e(t('revenue.chart_empty_title')) ?></strong>
                                    <span><?= e(t('revenue.chart_empty_text')) ?></span>
                                </div>
                            <?php endif; ?>
                        </div>

                        <script type="application/json" id="<?= $jsonId ?>" data-revenue-chart-payload><?= json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>

                        <details class="data-details revenue109-data-details eri-v2-monthly-details">
                            <summary><?= e(phase111_tr('Show monthly details', 'عرض التفاصيل الشهرية')) ?></summary>
                            <div class="table-wrap">
                                <table>
                                    <thead>
                                        <tr>
                                            <th><?= e(t('revenue.month')) ?></th>
                                            <th><?= e($year) ?></th>
                                            <th><?= e($compareYear) ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($chart['rows'] as $row): ?>
                                            <tr>
                                                <td><?= e($row['month_name']) ?></td>
                                                <td><?= e(money_number($row['current_value'])) ?></td>
                                                <td><?= e(money_number($row['compare_value'])) ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </details>
                    </article>
                    <?php $panelIndex++; ?>
                <?php endforeach; ?>
            </div>

            <?php $firstSummary = reset($chartSummary); ?>
            <aside class="eri-v2-trend-summary" aria-live="polite" data-eri-trend-summary>
                <div><span><?= e(phase111_tr('Current period', 'الفترة الحالية')) ?></span><strong data-eri-summary-current><?= e($firstSummary['current']) ?></strong></div>
                <div><span><?= e(phase111_tr('Comparison period', 'فترة المقارنة')) ?></span><strong data-eri-summary-comparison><?= e($firstSummary['comparison']) ?></strong></div>
                <div class="eri-v2-summary-change eri-v2-summary-change--<?= e($firstSummary['change_class']) ?>"><span><?= e(phase111_tr('Change', 'التغير')) ?></span><strong data-eri-summary-change><?= e($firstSummary['change']) ?></strong></div>
                <div><span><?= e(phase111_tr('Strongest month', 'أقوى شهر')) ?></span><strong data-eri-summary-best><?= e($firstSummary['best']) ?></strong></div>
                <div><span><?= e(phase111_tr('Weakest month', 'أضعف شهر')) ?></span><strong data-eri-summary-weakest><?= e($firstSummary['weakest']) ?></strong></div>
            </aside>
        </div>
    </section>

    <section class="eri-v2-card eri-v3-card eri-v3-actions" aria-labelledby="eri-v3-actions-title">
        <div class="eri-v3-actions-head">
            <div>
                <span class="eri-eyebrow"><?= e(phase111_tr('Recommended Actions', 'الإجراءات الموصى بها')) ?></span>
                <h2 id="eri-v3-actions-title"><?= e(phase111_tr('Next actions supporting executive review', 'الخطوات التالية لدعم المراجعة التنفيذية')) ?></h2>
            </div>
        </div>

        <div class="eri-v3-action-grid">
            <a class="eri-v3-action tone-teal" href="<?= e(url_to('action-center')) ?>">
                <span>◇</span>
                <div>
                    <strong><?= e(phase111_tr('Review financial priorities', 'مراجعة الأولويات المالية')) ?></strong>
                    <p><?= e(phase111_tr('Review items requiring leadership attention and confirm the next action.', 'مراجعة البنود التي تحتاج اهتمام الإدارة العليا وتحديد الإجراء التالي.')) ?></p>
                </div>
                <em>→</em>
            </a>

            <a class="eri-v3-action tone-purple" href="<?= e(url_to('specialty-finance')) ?>">
                <span>◈</span>
                <div>
                    <strong><?= e(phase111_tr('Review specialty contribution', 'مراجعة مساهمة التخصصات')) ?></strong>
                    <p><?= e(phase111_tr('Examine financial contribution across specialties when deeper analysis is needed.', 'مراجعة المساهمة المالية حسب التخصص عند الحاجة إلى تحليل أعمق.')) ?></p>
                </div>
                <em>→</em>
            </a>

            <a class="eri-v3-action tone-blue" href="<?= e(url_to('inpatient-daily-revenue')) ?>">
                <span>▱</span>
                <div>
                    <strong><?= e(phase111_tr('Review daily inpatient revenue', 'مراجعة إيرادات المرضى الداخليين اليومية')) ?></strong>
                    <p><?= e(phase111_tr('Open the current inpatient revenue position, care-area performance and patient highlights.', 'فتح الوضع الحالي لإيرادات المرضى الداخليين وأداء مناطق الرعاية وأبرز الحالات.')) ?></p>
                </div>
                <em>→</em>
            </a>
        </div>
    </section>
</section>

<!-- data-revenue-chart-gate __DDB_REVENUE_CHART_GATE__ -->
<!-- H110_P11_1_R18_REVENUE_GENERAL_MANAGER_EXECUTIVE_VIEW -->
<script src="assets/js/executive-revenue-intelligence.js?v=11.0.11.29" defer></script>

<!-- H110_P11_1_R22_PROFESSIONAL_CHART_ENGINE_MIGRATION_ALL_SITE_CHARTS -->
