<?php
$isArabic = current_lang() === 'ar';
$btx = static function (string $en, string $ar) use ($isArabic): string {
    return $isArabic ? $ar : $en;
};
$compact = static function ($value, int $decimals = 1): string {
    if ($value === null || $value === '') return '—';
    $number = (float)$value;
    $absolute = abs($number);
    if ($absolute >= 1000000) return rtrim(rtrim(number_format($number / 1000000, $decimals), '0'), '.') . 'M';
    if ($absolute >= 1000) return rtrim(rtrim(number_format($number / 1000, $decimals), '0'), '.') . 'K';
    return number_format($number, 0);
};
$percentText = static function (?float $value): string {
    if ($value === null) return '—';
    if (abs($value) < 0.05) return '0.0%';
    return ($value > 0 ? '+' : '−') . number_format(abs($value), 1) . '%';
};
$absoluteDeltaText = static function ($current, $compare) use ($compact): string {
    if ($current === null || $current === '' || $compare === null || $compare === '') return '—';
    $delta = (float)$current - (float)$compare;
    if (abs($delta) < 0.5) return '0';
    return ($delta > 0 ? '+' : '−') . $compact(abs($delta));
};
$movementClass = static function (?float $value): string {
    if ($value === null || abs($value) < 0.05) return 'is-neutral';
    return $value > 0 ? 'is-positive' : 'is-negative';
};
$stateLabel = static function (string $state) use ($btx): string {
    switch ($state) {
        case 'both_improved':
            return $btx('Increased in both branches', 'ارتفعت في الفرعين');
        case 'both_declined':
            return $btx('Decreased in both branches', 'انخفضت في الفرعين');
        case 'different_directions':
            return $btx('Different directions', 'اتجاهان مختلفان');
        case 'one_declined':
            return $btx('Decline in one branch', 'تراجع في أحد الفرعين');
        case 'one_improved':
            return $btx('Increase in one branch', 'ارتفاع في أحد الفرعين');
        case 'both_stable':
            return $btx('Stable in both branches', 'مستقرة في الفرعين');
        default:
            return $btx('Mixed movement', 'حركة مختلطة');
    }
};
$stateClass = static function (string $state): string {
    switch ($state) {
        case 'both_improved':
        case 'one_improved':
            return 'is-positive';
        case 'both_declined':
        case 'one_declined':
            return 'is-negative';
        case 'different_directions':
            return 'is-warning';
        default:
            return 'is-neutral';
    }
};

$currentPeriodLabel = (string)($periods['current_period_label'] ?? $year);
$comparePeriodLabel = (string)($periods['compare_period_label'] ?? $compareYear);
$isReady = is_array($comparison) && !empty($comparison['ready']);
$metrics = $isReady ? (array)($comparison['metrics'] ?? []) : [];
$summary = $isReady ? (array)($comparison['summary'] ?? []) : [];
$analysis = $isReady ? (array)($summary['service_first_analysis'] ?? []) : [];
$branchSignals = $isReady ? (array)($analysis['branch_signals'] ?? []) : [];
$prioritySignals = $isReady ? (array)($analysis['priority_signals'] ?? []) : [];
$positiveSignals = $isReady ? (array)($analysis['positive_signals'] ?? []) : [];
$serviceRows = $isReady ? (array)($analysis['service_rows'] ?? []) : [];
$latestMonth = $isReady ? (array)($analysis['latest_month'] ?? []) : [];
$defaultServiceKey = (string)($analysis['default_service_key'] ?? '');
$fairComparison = !empty($periods['fair_current_year_comparison']);
$leadPriority = is_array($prioritySignals[0] ?? null) ? $prioritySignals[0] : null;
?>

<!-- BRANCH_COMPARISON_R1_EXECUTIVE_CLOSURE_START -->
<div class="branch113-page" data-r45-p11-3-service-first="true" data-branch-comparison-r1="true">
    <section class="branch113-controls">
        <div class="branch113-controls-copy">
            <span><?= e($btx('SERVICE-FIRST BRANCH COMPARISON', 'مقارنة الفروع حسب الخدمة')) ?></span>
            <strong><b><?= e($currentPeriodLabel) ?></b><i>vs</i><b><?= e($comparePeriodLabel) ?></b></strong>
            <p><?= e($btx(
                'Each service is compared separately with the same service in the matched period.',
                'تتم مقارنة كل خدمة بصورة مستقلة مع الخدمة نفسها في الفترة المتطابقة.'
            )) ?></p>
        </div>

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

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

            <label data-branch113-year-field>
                <span><?= e($btx('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($btx('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-branch113-range-field>
                <span><?= e($btx('From', 'من')) ?></span>
                <input type="date" name="from_date" value="<?= e($fromDate) ?>">
            </label>

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

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

        <div class="branch113-period-note">
            <span aria-hidden="true">✓</span>
            <p>
                <?php if ($fairComparison): ?>
                    <strong><?= e($btx('Comparable periods:', 'فترتان قابلتان للمقارنة:')) ?></strong>
                    <?= e($btx(
                        'July is not included because the month is still in progress.',
                        'لم يتم احتساب شهر يوليو لأنه لم يكتمل بعد.'
                    )) ?>
                <?php else: ?>
                    <strong><?= e($btx('Comparison period:', 'فترة المقارنة:')) ?></strong>
                    <?= e($currentPeriodLabel . ' vs ' . $comparePeriodLabel) ?>
                <?php endif; ?>
            </p>
        </div>

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

    <?php if ($dataError): ?>
        <section class="branch113-blocked">
            <h2><?= e($btx('The comparison is temporarily unavailable.', 'المقارنة غير متاحة مؤقتًا.')) ?></h2>
            <p><?= e($btx('Please try again after the branch data becomes available.', 'يرجى المحاولة مرة أخرى بعد اكتمال بيانات الفروع.')) ?></p>
        </section>
    <?php elseif (!$isReady): ?>
        <section class="branch113-blocked">
            <h2><?= e($btx('The comparison is temporarily unavailable.', 'المقارنة غير متاحة مؤقتًا.')) ?></h2>
            <p><?= e($btx('The comparison will appear when data from both branches is available.', 'ستظهر المقارنة عند اكتمال بيانات الفرعين.')) ?></p>
            <div class="branch113-unavailable-branches">
                <?php foreach ((array)($comparison['errors'] ?? []) as $branchCode => $error): ?>
                    <article>
                        <strong><?= e((string)($branchDefinitions[$branchCode]['name'] ?? strtoupper((string)$branchCode))) ?></strong>
                        <span><?= e($btx('Data is currently unavailable', 'البيانات غير متاحة حاليًا')) ?></span>
                    </article>
                <?php endforeach; ?>
            </div>
        </section>
    <?php else: ?>
        <section class="branch113-hero">
            <div>
                <span><?= e($btx('WHAT CHANGED', 'ما الذي تغير')) ?></span>
                <?php if ($leadPriority): ?>
                    <h1>
                        <?= e($btx('Largest decline:', 'أكبر تراجع:')) ?>
                        <?= e($isArabic ? (string)$leadPriority['metric_label_ar'] : (string)$leadPriority['metric_label_en']) ?>
                        · <?= e((string)$leadPriority['branch_name']) ?>
                    </h1>
                    <p class="branch113-hero-summary">
                        <strong class="is-negative"><?= e($percentText((float)$leadPriority['movement'])) ?></strong>
                        <b>
                            <?= e($absoluteDeltaText($leadPriority['current'] ?? null, $leadPriority['compare'] ?? null)) ?>
                            <?= e($btx('service units', 'وحدة خدمة')) ?>
                        </b>
                        <span><?= e($isArabic ? (string)$leadPriority['focus_ar'] : (string)$leadPriority['focus_en']) ?></span>
                        <a href="#branch113-priorities"><?= e($btx('Review priorities', 'مراجعة الأولويات')) ?> →</a>
                    </p>
                <?php else: ?>
                    <h1><?= e($btx('No service recorded a decline in the selected period.', 'لم تسجل أي خدمة تراجعًا خلال الفترة المحددة.')) ?></h1>
                    <p><?= e($btx('The service-by-service view below shows the exact movement in each branch.', 'يوضح العرض حسب الخدمة أدناه الحركة الدقيقة في كل فرع.')) ?></p>
                <?php endif; ?>
            </div>
            <aside>
                <strong><?= e($btx('How to read this page', 'طريقة قراءة الصفحة')) ?></strong>
                <p><?= e($btx(
                    'Services with different units are not added together. Every percentage belongs to one named service and one branch.',
                    'لا يتم جمع الخدمات ذات الوحدات المختلفة. كل نسبة تخص خدمة محددة وفرعًا محددًا.'
                )) ?></p>
            </aside>
        </section>

        <section class="branch113-branch-review" id="branch113-branch-review">
            <header class="branch113-section-heading">
                <span><?= e($btx('BRANCH REVIEW', 'مراجعة الفروع')) ?></span>
                <h2><?= e($btx('Service movement by branch', 'حركة الخدمات حسب الفرع')) ?></h2>
                <p><?= e($btx(
                    'A concise view of the services moving up or down in each branch.',
                    'عرض مختصر للخدمات التي ارتفعت أو انخفضت في كل فرع.'
                )) ?></p>
            </header>

            <div class="branch113-branch-grid">
                <?php foreach ($branchDefinitions as $branchCode => $branch): ?>
                    <?php $signals = (array)($branchSignals[$branchCode] ?? []); ?>
                    <article class="branch113-branch-card">
                        <header>
                            <span><?= e($btx('BRANCH', 'الفرع')) ?></span>
                            <h3><?= e((string)$branch['name']) ?></h3>
                        </header>

                        <div class="branch113-direction-block is-positive">
                            <h4><?= e($btx('Services that increased', 'الخدمات التي ارتفعت')) ?></h4>
                            <?php if ((array)($signals['improved'] ?? []) === []): ?>
                                <p class="branch113-empty"><?= e($btx('No service increased during the period.', 'لم ترتفع أي خدمة خلال الفترة.')) ?></p>
                            <?php else: ?>
                                <?php foreach ((array)$signals['improved'] as $signal): ?>
                                    <div class="branch113-signal-row">
                                        <div>
                                            <strong><?= e($isArabic ? (string)$signal['metric_label_ar'] : (string)$signal['metric_label_en']) ?></strong>
                                            <small>
                                                <?= e($btx('Current', 'الحالي')) ?> <?= e($compact($signal['current'])) ?>
                                                · <?= e($btx('Comparison', 'المقارنة')) ?> <?= e($compact($signal['compare'])) ?>
                                            </small>
                                        </div>
                                        <em><?= e($percentText((float)$signal['movement'])) ?></em>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <div class="branch113-direction-block is-negative">
                            <h4><?= e($btx('Services that decreased', 'الخدمات التي انخفضت')) ?></h4>
                            <?php if ((array)($signals['declined'] ?? []) === []): ?>
                                <p class="branch113-empty"><?= e($btx('No service decreased during the period.', 'لم تنخفض أي خدمة خلال الفترة.')) ?></p>
                            <?php else: ?>
                                <?php foreach ((array)$signals['declined'] as $signal): ?>
                                    <div class="branch113-signal-row">
                                        <div>
                                            <strong><?= e($isArabic ? (string)$signal['metric_label_ar'] : (string)$signal['metric_label_en']) ?></strong>
                                            <small>
                                                <?= e($btx('Current', 'الحالي')) ?> <?= e($compact($signal['current'])) ?>
                                                · <?= e($btx('Comparison', 'المقارنة')) ?> <?= e($compact($signal['compare'])) ?>
                                            </small>
                                        </div>
                                        <em><?= e($percentText((float)$signal['movement'])) ?></em>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        </section>

        <section class="branch113-priority-grid" id="branch113-priorities">
            <article class="branch113-card branch113-priorities">
                <header class="branch113-section-heading">
                    <span><?= e($btx('LEADERSHIP PRIORITIES', 'أولويات الإدارة')) ?></span>
                    <h2><?= e($btx('Largest service declines requiring review', 'أكبر تراجعات الخدمات التي تتطلب مراجعة')) ?></h2>
                </header>

                <?php if ($prioritySignals === []): ?>
                    <p class="branch113-empty"><?= e($btx('No declining service requires escalation.', 'لا توجد خدمة متراجعة تتطلب تصعيدًا.')) ?></p>
                <?php else: ?>
                    <div class="branch113-priority-list">
                        <?php foreach (array_slice($prioritySignals, 0, 4) as $index => $signal): ?>
                            <article>
                                <b><?= e((string)($index + 1)) ?></b>
                                <div>
                                    <span><?= e((string)$signal['branch_name']) ?></span>
                                    <h3><?= e($isArabic ? (string)$signal['metric_label_ar'] : (string)$signal['metric_label_en']) ?></h3>
                                    <p><?= e($isArabic ? (string)$signal['focus_ar'] : (string)$signal['focus_en']) ?></p>
                                </div>
                                <aside>
                                    <strong class="is-negative"><?= e($percentText((float)$signal['movement'])) ?></strong>
                                    <small>
                                        <?= e($compact($signal['current'])) ?>
                                        <?= e($btx('vs', 'مقابل')) ?>
                                        <?= e($compact($signal['compare'])) ?>
                                    </small>
                                </aside>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </article>

            <aside class="branch113-card branch113-positive-signals">
                <header class="branch113-section-heading">
                    <span><?= e($btx('POSITIVE SIGNALS', 'مؤشرات المراجعة الإيجابية')) ?></span>
                    <h2><?= e($btx('Strongest service increases', 'أقوى ارتفاعات الخدمات')) ?></h2>
                </header>

                <?php if ($positiveSignals === []): ?>
                    <p class="branch113-empty"><?= e($btx('No positive service movement was recorded.', 'لم يتم تسجيل حركة إيجابية في الخدمات.')) ?></p>
                <?php else: ?>
                    <?php foreach (array_slice($positiveSignals, 0, 3) as $signal): ?>
                        <article>
                            <div>
                                <span><?= e((string)$signal['branch_name']) ?></span>
                                <strong><?= e($isArabic ? (string)$signal['metric_label_ar'] : (string)$signal['metric_label_en']) ?></strong>
                                <small>
                                    <?= e($compact($signal['current'] ?? null)) ?>
                                    <?= e($btx('vs', 'مقابل')) ?>
                                    <?= e($compact($signal['compare'] ?? null)) ?>
                                </small>
                            </div>
                            <em class="is-positive"><?= e($percentText((float)$signal['movement'])) ?></em>
                        </article>
                    <?php endforeach; ?>
                <?php endif; ?>
            </aside>
        </section>

        <section class="branch113-card branch113-services" id="branch113-services">
            <header class="branch113-section-heading">
                <span><?= e($btx('SERVICE-BY-SERVICE COMPARISON', 'المقارنة خدمة بخدمة')) ?></span>
                <h2><?= e($btx('The complete comparison across all six services', 'المقارنة الكاملة عبر الخدمات الست')) ?></h2>
                <p><?= e($btx(
                    'Current and comparison values are shown separately for each branch and service.',
                    'تظهر القيم الحالية وقيم المقارنة بصورة مستقلة لكل فرع ولكل خدمة.'
                )) ?></p>
            </header>

            <div class="branch113-service-grid">
                <?php foreach ($serviceRows as $service): ?>
                    <?php
                    $executiveBranches = [];
                    foreach ($branchDefinitions as $executiveBranchCode => $executiveBranch) {
                        $executiveRow = (array)($service['branches'][$executiveBranchCode] ?? []);
                        $executiveMovement = isset($executiveRow['movement']) && $executiveRow['movement'] !== null
                            ? (float)$executiveRow['movement']
                            : null;
                        $executiveBranches[] = [
                            'code' => (string)$executiveBranchCode,
                            'name' => (string)($executiveBranch['name'] ?? $executiveBranchCode),
                            'current' => $executiveRow['current'] ?? null,
                            'compare' => $executiveRow['compare'] ?? null,
                            'movement' => $executiveMovement,
                        ];
                    }
                    usort($executiveBranches, static function (array $left, array $right): int {
                        $leftMovement = $left['movement'];
                        $rightMovement = $right['movement'];
                        if ($leftMovement === null && $rightMovement === null) {
                            return 0;
                        }
                        if ($leftMovement === null) {
                            return 1;
                        }
                        if ($rightMovement === null) {
                            return -1;
                        }
                        return abs((float)$rightMovement) <=> abs((float)$leftMovement);
                    });
                    $executiveLead = $executiveBranches[0] ?? [
                        'name' => '—',
                        'current' => null,
                        'compare' => null,
                        'movement' => null,
                    ];
                    ?>
                    <article class="branch113-service-card branch113-service-card--executive">
                        <header>
                            <div>
                                <span><?= e($btx('SERVICE', 'الخدمة')) ?></span>
                                <h3><?= e($isArabic ? (string)$service['label_ar'] : (string)$service['label_en']) ?></h3>
                            </div>
                            <em class="<?= e($stateClass((string)$service['comparison_state'])) ?>">
                                <?= e($stateLabel((string)$service['comparison_state'])) ?>
                            </em>
                        </header>

                        <section class="branch113-executive-result">
                            <div class="branch113-executive-result__context">
                                <span><?= e($btx('Most significant branch movement', 'أبرز تغير على مستوى الفروع')) ?></span>
                                <strong><?= e((string)$executiveLead['name']) ?></strong>
                                <small>
                                    <?= e($compact($executiveLead['current'] ?? null)) ?>
                                    <?= e($btx('vs', 'مقابل')) ?>
                                    <?= e($compact($executiveLead['compare'] ?? null)) ?>
                                </small>
                            </div>
                            <b class="branch113-executive-result__movement <?= e($movementClass($executiveLead['movement'])) ?>">
                                <?= e($percentText($executiveLead['movement'])) ?>
                            </b>
                        </section>

                        <div class="branch113-service-branches branch113-service-branches--secondary">
                            <?php foreach ($executiveBranches as $executiveBranchRow): ?>
                                <section>
                                    <div>
                                        <h4><?= e((string)$executiveBranchRow['name']) ?></h4>
                                        <small>
                                            <?= e($compact($executiveBranchRow['current'] ?? null)) ?>
                                            <?= e($btx('vs', 'مقابل')) ?>
                                            <?= e($compact($executiveBranchRow['compare'] ?? null)) ?>
                                        </small>
                                    </div>
                                    <b class="<?= e($movementClass($executiveBranchRow['movement'])) ?>">
                                        <?= e($percentText($executiveBranchRow['movement'])) ?>
                                    </b>
                                </section>
                            <?php endforeach; ?>
                        </div>

                        <?php if ((string)($service['focus_en'] ?? '') !== ''): ?>
                            <footer>
                                <strong><?= e($btx('Management attention', 'محور المراجعة الإدارية')) ?></strong>
                                <p><?= e($isArabic ? (string)$service['focus_ar'] : (string)$service['focus_en']) ?></p>
                            </footer>
                        <?php endif; ?>
                    </article>
                <?php endforeach; ?>
            </div>
        </section>

        <section class="branch113-card branch113-latest">
            <header class="branch113-section-heading">
                <span><?= e($btx('LATEST COMPLETED MONTH', 'أحدث شهر مكتمل')) ?></span>
                <h2>
                    <?= e((string)($latestMonth['month_name'] ?? '—')) ?>
                    — <?= e($btx('Services that changed', 'الخدمات التي تغيرت')) ?>
                </h2>
                <p><?= e($btx(
                    'This section names the services that increased or decreased compared with the same month last year.',
                    'يسمي هذا القسم الخدمات التي ارتفعت أو انخفضت مقارنة بالشهر نفسه من العام السابق.'
                )) ?></p>
                <div class="branch113-scope-note">
                    <strong><?= e($btx('Monthly view:', 'العرض الشهري:')) ?></strong>
                    <?= e($btx(
                        'This result is independent from the cumulative Jan–Jun comparison above.',
                        'هذه النتيجة مستقلة عن المقارنة التراكمية من يناير إلى يونيو المعروضة أعلاه.'
                    )) ?>
                </div>
            </header>

            <div class="branch113-latest-grid">
                <?php foreach ($branchDefinitions as $branchCode => $branch): ?>
                    <?php $latestBranch = (array)($latestMonth['branches'][$branchCode] ?? []); ?>
                    <article>
                        <h3><?= e((string)$branch['name']) ?></h3>

                        <div class="branch113-latest-column is-positive">
                            <h4><?= e($btx('Increased', 'ارتفعت')) ?></h4>
                            <?php if ((array)($latestBranch['improved'] ?? []) === []): ?>
                                <p class="branch113-empty"><?= e($btx('No service increased.', 'لم ترتفع أي خدمة.')) ?></p>
                            <?php else: ?>
                                <?php foreach ((array)$latestBranch['improved'] as $signal): ?>
                                    <div>
                                        <strong><?= e($isArabic ? (string)$signal['metric_label_ar'] : (string)$signal['metric_label_en']) ?></strong>
                                        <em><?= e($percentText((float)$signal['movement'])) ?></em>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <div class="branch113-latest-column is-negative">
                            <h4><?= e($btx('Decreased', 'انخفضت')) ?></h4>
                            <?php if ((array)($latestBranch['declined'] ?? []) === []): ?>
                                <p class="branch113-empty"><?= e($btx('No service decreased.', 'لم تنخفض أي خدمة.')) ?></p>
                            <?php else: ?>
                                <?php foreach ((array)$latestBranch['declined'] as $signal): ?>
                                    <div>
                                        <strong><?= e($isArabic ? (string)$signal['metric_label_ar'] : (string)$signal['metric_label_en']) ?></strong>
                                        <em><?= e($percentText((float)$signal['movement'])) ?></em>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        </section>

        <section class="branch113-card branch113-trend">
            <header class="branch113-section-heading">
                <span><?= e($btx('MONTHLY TREND BY SERVICE', 'الاتجاه الشهري حسب الخدمة')) ?></span>
                <h2 id="branch113_trend_title">
                    <?= e($btx('Select a service to review its monthly movement', 'اختر خدمة لمراجعة حركتها الشهرية')) ?>
                </h2>
                <p><?= e($btx(
                    'The chart compares the selected service only; no other services are included.',
                    'يقارن الرسم الخدمة المحددة فقط ولا يتضمن أي خدمات أخرى.'
                )) ?></p>
            </header>

            <div class="branch113-service-tabs" role="tablist" aria-label="<?= e($btx('Select service', 'اختيار الخدمة')) ?>">
                <?php foreach ($serviceRows as $serviceKey => $service): ?>
                    <button
                        type="button"
                        role="tab"
                        data-branch113-service-tab="<?= e((string)$serviceKey) ?>"
                        aria-selected="<?= $serviceKey === $defaultServiceKey ? 'true' : 'false' ?>"
                        class="<?= $serviceKey === $defaultServiceKey ? 'is-active' : '' ?>"
                    >
                        <?= e($isArabic ? (string)$service['short_ar'] : (string)$service['short_en']) ?>
                    </button>
                <?php endforeach; ?>
            </div>

            <div class="branch113-chart-legend" aria-label="<?= e($btx('Chart legend', 'دليل ألوان الرسم')) ?>">
                <?php
                $legendBranches = array_values($branchDefinitions);
                $legendBranchOne = (string)($legendBranches[0]['name'] ?? 'NJCH');
                $legendBranchTwo = (string)($legendBranches[1]['name'] ?? 'MNH');
                ?>
                <span class="series-one"><i></i><?= e($legendBranchOne . ' · ' . $currentPeriodLabel) ?></span>
                <span class="series-two"><i></i><?= e($legendBranchOne . ' · ' . $comparePeriodLabel) ?></span>
                <span class="series-three"><i></i><?= e($legendBranchTwo . ' · ' . $currentPeriodLabel) ?></span>
                <span class="series-four"><i></i><?= e($legendBranchTwo . ' · ' . $comparePeriodLabel) ?></span>
            </div>

            <div class="branch113-chart-wrap" data-branch113-chart-state="pending">
                <canvas id="branch113_service_chart" height="180"></canvas>
                <div class="branch113-chart-error">
                    <strong><?= e($btx('The selected service chart is unavailable.', 'رسم الخدمة المحددة غير متاح.')) ?></strong>
                </div>
            </div>

            <div class="branch113-monthly-panels">
                <?php foreach ($serviceRows as $serviceKey => $service): ?>
                    <section
                        data-branch113-service-panel="<?= e((string)$serviceKey) ?>"
                        class="<?= $serviceKey === $defaultServiceKey ? 'is-active' : '' ?>"
                    >
                        <header>
                            <strong><?= e($isArabic ? (string)$service['label_ar'] : (string)$service['label_en']) ?></strong>
                            <span><?= e($currentPeriodLabel . ' vs ' . $comparePeriodLabel) ?></span>
                        </header>
                        <div class="branch113-table-wrap">
                            <table>
                                <thead>
                                    <tr>
                                        <th><?= e($btx('Month', 'الشهر')) ?></th>
                                        <?php foreach ($branchDefinitions as $branch): ?>
                                            <th><?= e((string)$branch['short_name']) ?> · <?= e($currentPeriodLabel) ?></th>
                                            <th><?= e((string)$branch['short_name']) ?> · <?= e($comparePeriodLabel) ?></th>
                                            <th><?= e((string)$branch['short_name']) ?> · <?= e($btx('Change', 'التغير')) ?></th>
                                        <?php endforeach; ?>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ((array)$service['monthly_rows'] as $monthRow): ?>
                                        <tr>
                                            <td><strong><?= e((string)$monthRow['month_name']) ?></strong></td>
                                            <?php foreach ($branchDefinitions as $branchCode => $branch): ?>
                                                <?php $branchMonth = (array)($monthRow['branches'][$branchCode] ?? []); ?>
                                                <td><?= e(number_format((float)($branchMonth['current'] ?? 0), 0)) ?></td>
                                                <td><?= e(number_format((float)($branchMonth['compare'] ?? 0), 0)) ?></td>
                                                <td>
                                                    <b class="<?= e($movementClass(isset($branchMonth['movement']) ? (float)$branchMonth['movement'] : null)) ?>">
                                                        <?= e($percentText(isset($branchMonth['movement']) ? (float)$branchMonth['movement'] : null)) ?>
                                                    </b>
                                                </td>
                                            <?php endforeach; ?>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </section>
                <?php endforeach; ?>
            </div>
        </section>

        <script type="application/json" id="branch113_service_chart_config"><?= json_encode(
            array_map(
                static function (array $service): array {
                    return [
                        'key' => (string)$service['key'],
                        'label_en' => (string)$service['label_en'],
                        'label_ar' => (string)$service['label_ar'],
                        'payload' => (array)$service['chart_payload'],
                    ];
                },
                array_values($serviceRows)
            ),
            JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
        ) ?></script>
        <input type="hidden" id="branch113_default_service" value="<?= e($defaultServiceKey) ?>">
    <?php endif; ?>
</div>
<!-- BRANCH_COMPARISON_R1_EXECUTIVE_CLOSURE_END -->
