<?php
/**
 * H11.0-P11-R9 — Revenue Intelligence Executive Visual Closure
 * 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 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 phase1092_executive_insights(array $cards, float $totalRevenue, float $cashRevenue, float $insuranceRevenue): array {
    $isArabic = current_lang() === 'ar';
    $insights = [];
    $totalPercent = isset($cards['total']['percent']) && $cards['total']['percent'] !== null ? (float)$cards['total']['percent'] : null;
    $profitCurrent = (float)($cards['profit_loss']['current_total'] ?? 0);
    $profitCompare = (float)($cards['profit_loss']['compare_total'] ?? 0);
    $insuranceShare = abs($totalRevenue) > 0.00001 ? max(0, min(100, round(($insuranceRevenue / $totalRevenue) * 100))) : null;

    if ($totalPercent === null || abs($totalPercent) < 0.5) {
        $insights[] = [
            'title' => $isArabic ? 'استقرار الإيرادات' : 'Revenue stability',
            'detail' => $isArabic ? 'لم يظهر تغير جوهري مقارنة بفترة المقارنة.' : 'No material change is visible versus the comparison period.',
            'tone' => 'neutral',
        ];
    } elseif ($totalPercent > 0) {
        $insights[] = [
            'title' => $isArabic ? 'نمو الإيرادات' : 'Revenue growth',
            'detail' => $isArabic
                ? 'ارتفع إجمالي الإيرادات بنسبة ' . phase1092_percent_text($totalPercent) . '% مقارنة بفترة المقارنة.'
                : 'Total revenue is ' . phase1092_percent_text($totalPercent) . '% above the comparison period.',
            'tone' => 'positive',
        ];
    } else {
        $insights[] = [
            'title' => $isArabic ? 'انخفاض الإيرادات' : 'Revenue decline',
            'detail' => $isArabic
                ? 'انخفض إجمالي الإيرادات بنسبة ' . phase1092_percent_text($totalPercent) . '% مقارنة بفترة المقارنة.'
                : 'Total revenue is ' . phase1092_percent_text($totalPercent) . '% below the comparison period.',
            'tone' => 'attention',
        ];
    }

    if ($insuranceShare !== null) {
        $insights[] = [
            'title' => $insuranceShare >= 80
                ? ($isArabic ? 'تركيز مرتفع في التأمين' : 'High insurance concentration')
                : ($isArabic ? 'مزيج الإيرادات' : 'Revenue mix'),
            'detail' => $isArabic
                ? 'يمثل التأمين ' . $insuranceShare . '% من إجمالي الإيرادات.'
                : 'Insurance represents ' . $insuranceShare . '% of total revenue.',
            'tone' => $insuranceShare >= 80 ? 'review' : 'neutral',
        ];
    }

    if ($profitCurrent < 0) {
        $insights[] = [
            'title' => $isArabic ? 'تراجع الربحية' : 'Profitability deterioration',
            'detail' => $isArabic
                ? 'تسجل الفترة الحالية خسارة قدرها ' . compact_money(abs($profitCurrent)) . ' مقابل ' . compact_money($profitCompare) . ' في فترة المقارنة.'
                : 'The current period reports a ' . compact_money(abs($profitCurrent)) . ' loss versus ' . compact_money($profitCompare) . ' in the comparison period.',
            'tone' => 'attention',
        ];
    } else {
        $insights[] = [
            'title' => $isArabic ? 'الربحية الحالية' : 'Current profitability',
            'detail' => $isArabic
                ? 'تسجل الفترة الحالية ربحًا قدره ' . compact_money($profitCurrent) . ' مقابل ' . compact_money($profitCompare) . ' في فترة المقارنة.'
                : 'The current period reports ' . compact_money($profitCurrent) . ' profit versus ' . compact_money($profitCompare) . ' in the comparison period.',
            'tone' => 'positive',
        ];
    }

    $needsAttention = ($totalPercent !== null && $totalPercent <= -10) || $profitCurrent < 0;
    $insights[] = [
        'title' => $needsAttention
            ? ($isArabic ? 'يتطلب اهتمام الإدارة العليا' : 'Leadership attention')
            : ($isArabic ? 'الأداء ضمن نطاق مستقر' : 'Performance remains stable'),
        'detail' => $needsAttention
            ? ($isArabic
                ? 'يرجى مراجعة انخفاض الإيرادات وتركيز جهات الدفع وأداء التكاليف.'
                : 'Review revenue decline, payer concentration, and cost performance.')
            : ($isArabic
                ? 'لا توجد إشارة مالية حرجة تتطلب تصعيدًا تنفيذيًا فوريًا.'
                : 'No critical financial signal requires immediate executive escalation.'),
        'tone' => $needsAttention ? 'attention' : 'positive',
    ];

    return array_slice($insights, 0, 4);
}

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;
$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;
$isRange = $mode === 'range';
$currentPeriodLabel = $isRange ? ((string)$fromDate . ' → ' . (string)$toDate) : (string)$year;
$comparePeriodLabel = $isRange ? ((string)$compareFromDate . ' → ' . (string)$compareToDate) : (string)$compareYear;
$executiveInsights = phase1092_executive_insights($cards, $totalRevenue, $cashRevenue, $insuranceRevenue);
$needsAttention = ($totalPercent !== null && $totalPercent <= -10) || $profitCurrent < 0;
$leadershipStatus = $needsAttention ? phase111_tr('Needs Attention', 'يحتاج إلى اهتمام') : phase111_tr('Stable', 'مستقر');
$leadershipSupport = $needsAttention
    ? phase111_tr('Revenue decline or current-period loss requires review.', 'انخفاض الإيرادات أو خسارة الفترة الحالية يتطلب المراجعة.')
    : phase111_tr('No critical financial signal requires immediate escalation.', 'لا توجد إشارة مالية حرجة تتطلب تصعيدًا فوريًا.');

$chartSummary = [];
foreach ($charts as $chartKey => $chart) {
    $extremes = phase111_month_extremes((array)$chart['rows']);
    $cardKey = $chartKey === 'profit_loss' ? 'profit_loss' : $chartKey;
    $card = $cards[$cardKey] ?? [];
    $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" data-executive-revenue-v2="true" data-revenue-mode="<?= e($mode) ?>">
    <section class="eri-v2-summary" aria-labelledby="eri-v2-summary-title">
        <div class="eri-v2-summary-head">
            <div class="eri-v2-summary-copy">
                <span class="eri-eyebrow"><?= e(phase111_tr('Executive Summary', 'الملخص التنفيذي')) ?></span>
                <h2 id="eri-v2-summary-title"><?= e(phase111_tr('Revenue performance at a glance', 'أداء الإيرادات في لمحة')) ?></h2>
                <p><?= e(phase111_tr('The most important financial signals for leadership, with detail available below when needed.', 'أهم المؤشرات المالية للإدارة العليا، مع إتاحة التفاصيل أدناه عند الحاجة.')) ?></p>
            </div>
            <div class="eri-v2-context revenue109-period-strip" aria-label="<?= e(phase111_tr('Period in focus', 'الفترة محل التركيز')) ?>">
                <span><b><?= e(t('revenue.current_period')) ?></b><strong><?= e($currentPeriodLabel) ?></strong></span>
                <span><b><?= e(t('revenue.compare_period')) ?></b><strong><?= e($comparePeriodLabel) ?></strong></span>
                <span><b><?= e(t('revenue.active_branch')) ?></b><strong><?= e((string)$hospital['name']) ?></strong></span>
            </div>
        </div>

        <div class="eri-v2-priority-grid revenue109-kpis" data-eri-priority-grid>
            <article class="eri-v2-priority-card eri-v2-priority-card--revenue">
                <span class="eri-v2-priority-icon" aria-hidden="true">◈</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase109_card_title('total', $cards['total'])) ?></span>
                    <strong><?= e(compact_money($totalRevenue)) ?></strong>
                    <small><?= e(phase111_tr('vs ', 'مقارنة بـ ')) ?><?= 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>

            <?php $profitPercent = isset($cards['profit_loss']['percent']) && $cards['profit_loss']['percent'] !== null ? (float)$cards['profit_loss']['percent'] : null; ?>
            <article class="eri-v2-priority-card eri-v2-priority-card--profit <?= $profitCurrent < 0 ? 'is-attention' : '' ?>">
                <span class="eri-v2-priority-icon" aria-hidden="true">◆</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase109_card_title('profit_loss', $cards['profit_loss'])) ?></span>
                    <strong><?= e(compact_money($profitCurrent)) ?></strong>
                    <small><?= e(phase111_tr('vs ', 'مقارنة بـ ')) ?><?= e(compact_money($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">
                <span class="eri-v2-priority-icon" aria-hidden="true">◐</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase111_tr('Insurance Share', 'حصة التأمين')) ?></span>
                    <strong><?= e((string)$insurancePct) ?>%</strong>
                    <small><?= e(compact_money($insuranceRevenue)) ?></small>
                    <em class="eri-v2-priority-note"><?= e(phase111_tr('of total revenue', 'من إجمالي الإيرادات')) ?></em>
                </div>
            </article>

            <article class="eri-v2-priority-card eri-v2-priority-card--status <?= $needsAttention ? 'is-attention' : 'is-stable' ?>" data-eri-leadership-status="<?= $needsAttention ? 'attention' : 'stable' ?>">
                <span class="eri-v2-priority-icon" aria-hidden="true">!</span>
                <div>
                    <span class="eri-v2-priority-label"><?= e(phase111_tr('Leadership Status', 'حالة المتابعة التنفيذية')) ?></span>
                    <strong class="eri-v2-status-value"><?= e($leadershipStatus) ?></strong>
                    <small><?= e($leadershipSupport) ?></small>
                </div>
            </article>
        </div>
    </section>

    <section class="surface-card eri-v2-controls" data-eri-controls aria-labelledby="eri-v2-controls-title">
        <div class="eri-v2-controls-head">
            <span class="eri-eyebrow"><?= e(t('revenue.filter_title')) ?></span>
            <strong id="eri-v2-controls-title"><?= e($isRange ? t('revenue.mode_range') : t('revenue.mode_year')) ?></strong>
        </div>

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

        <form method="get" action="index.php" class="eri-v2-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(t('revenue.hospital')) ?></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(t('revenue.mode')) ?></span>
                <select name="mode" data-revenue-mode-select>
                    <option value="year" <?= !$isRange ? 'selected' : '' ?>><?= e(t('revenue.mode_year')) ?></option>
                    <option value="range" <?= $isRange ? 'selected' : '' ?>><?= e(t('revenue.mode_range')) ?></option>
                </select>
            </label>

            <label data-revenue-year-field <?= $isRange ? 'hidden aria-hidden="true"' : '' ?>>
                <span><?= e(t('revenue.current_year')) ?></span>
                <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
            </label>

            <label data-revenue-range-field <?= !$isRange ? 'hidden aria-hidden="true"' : '' ?>>
                <span><?= e(t('revenue.from_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(t('revenue.to_date')) ?></span>
                <input type="date" name="to_date" value="<?= e((string)$toDate) ?>">
            </label>

            <label>
                <span><?= e(t('revenue.compare_year')) ?></span>
                <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
            </label>

            <button class="btn primary eri-v2-update" type="submit"><?= e(t('revenue.update')) ?></button>
        </form>
    </section>

    <section class="eri-v2-decision-grid" data-eri-decision-grid>
        <article class="eri-v2-card eri-v2-mix-card">
            <div class="eri-v2-card-head">
                <span class="eri-eyebrow"><?= e(phase111_tr('Revenue Mix', 'مزيج الإيرادات')) ?></span>
            </div>
            <div class="eri-v2-mix-layout">
                <div class="eri-v2-donut" style="--eri-v2-insurance: <?= e((string)$insurancePct) ?>%;" role="img" aria-label="<?= e(phase111_tr('Insurance share ', 'حصة التأمين ')) ?><?= e((string)$insurancePct) ?>%">
                    <div><strong><?= e((string)$insurancePct) ?>%</strong><span><?= e(phase111_tr('Insurance', 'التأمين')) ?></span></div>
                </div>
                <div class="eri-v2-mix-metrics">
                    <div class="eri-v2-mix-row">
                        <span><i class="insurance"></i><?= e(phase111_tr('Insurance Revenue', 'إيرادات التأمين')) ?></span>
                        <strong><?= e(compact_money($insuranceRevenue)) ?></strong>
                        <em><?= e((string)$insurancePct) ?>%</em>
                    </div>
                    <div class="eri-v2-progress"><i class="insurance" style="width: <?= e((string)$insurancePct) ?>%"></i></div>

                    <div class="eri-v2-mix-row">
                        <span><i class="cash"></i><?= e(phase111_tr('Cash Revenue', 'الإيرادات النقدية')) ?></span>
                        <strong><?= e(compact_money($cashRevenue)) ?></strong>
                        <em><?= e((string)$cashPct) ?>%</em>
                    </div>
                    <div class="eri-v2-progress"><i class="cash" style="width: <?= e((string)$cashPct) ?>%"></i></div>

                    <div class="eri-v2-moh-row">
                        <span><?= e(phase111_tr('MOH Revenue', 'إيرادات وزارة الصحة')) ?></span>
                        <strong><?= e(compact_money($mohRevenue)) ?></strong>
                    </div>
                </div>
            </div>
        </article>

        <article class="eri-v2-card eri-v2-insight-card" data-executive-insight-source="selected-period-data">
            <div class="eri-v2-card-head">
                <span class="eri-eyebrow"><?= e(phase111_tr('Executive Insight', 'أبرز النتائج التنفيذية')) ?></span>
            </div>
            <div class="eri-v2-insights">
                <?php foreach ($executiveInsights as $insight): ?>
                    <div class="eri-v2-insight eri-v2-insight--<?= e((string)$insight['tone']) ?>">
                        <span aria-hidden="true"></span>
                        <div>
                            <strong><?= e((string)$insight['title']) ?></strong>
                            <p><?= e((string)$insight['detail']) ?></p>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>
    </section>

    <section class="eri-v2-trend-workspace eri-trend-workspace" aria-labelledby="eri-v2-trend-title" data-eri-trend-workspace>
        <div class="eri-v2-trend-head">
            <div>
                <span class="eri-eyebrow"><?= e(phase111_tr('Monthly Financial Trend', 'الاتجاه المالي الشهري')) ?></span>
                <h2 id="eri-v2-trend-title"><?= e(phase111_tr('Monthly Financial Trend', 'الاتجاه المالي الشهري')) ?></h2>
            </div>
            <div class="eri-v2-tabs" role="tablist" aria-label="<?= e(phase111_tr('Monthly financial 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(phase109_chart_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();
                        $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(t('revenue.monthly_trend')) ?></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(t('revenue.show_months')) ?></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 total', 'الإجمالي الحالي')) ?></span><strong data-eri-summary-current><?= e($firstSummary['current']) ?></strong></div>
                <div><span><?= e(phase111_tr('Comparison total', 'إجمالي المقارنة')) ?></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('Best 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>

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