<?php
/** @var array<string,mixed> $report */
/** @var array<string,mixed> $hospital */
$summary = is_array($report['summary'] ?? null) ? $report['summary'] : [];
$patients = is_array($report['patients'] ?? null) ? $report['patients'] : [];
$units = is_array($report['units'] ?? null) ? $report['units'] : [];
$companies = is_array($report['companies'] ?? null) ? $report['companies'] : [];
$isAr = current_lang() === 'ar';
$tr = static fn(string $en, string $ar): string => $isAr ? $ar : $en;

$maxUnitRevenue = 0.0;
foreach ($units as $unit) {
    $maxUnitRevenue = max($maxUnitRevenue, (float)($unit['daily_revenue'] ?? 0));
}

$totalRevenue = (float)($summary['daily_revenue'] ?? 0);
$hasLoadError = (string)($errorMessage ?? '') !== '';
$topCompanies = array_slice($companies, 0, 5);
$topUnits = array_slice($units, 0, 7);
$displayPatients = $patients;
usort($displayPatients, static function (array $a, array $b): int {
    return ((float)($b['daily_revenue'] ?? 0)) <=> ((float)($a['daily_revenue'] ?? 0));
});
$initialPatientLimit = 5;
$patientPreviewCount = min(count($displayPatients), $initialPatientLimit);
$exportDate = date('Y-m-d');
$powerBiReportAvailable = is_array($powerBiReportStatus ?? null)
    && (($powerBiReportStatus['available'] ?? false) === true);
$generatedAt = (string)($summary['generated_at'] ?? date('Y-m-d H:i:s'));
$branchName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
$reviewCount = (int)($summary['review_count'] ?? 0);
$patientCount = (int)($summary['patient_count'] ?? 0);
$averageRevenue = (float)($summary['average_revenue'] ?? 0);
$topPayerName = (string)($topCompanies[0]['financial_class'] ?? '');
$topPayerRevenue = (float)($topCompanies[0]['daily_revenue'] ?? 0);
$topPayerShare = $totalRevenue > 0 ? ($topPayerRevenue / $totalRevenue) * 100 : 0.0;

$highestRevenueUnit = is_array($topUnits[0] ?? null) ? $topUnits[0] : [];
$highestOccupancyUnit = [];
$highestOccupancyPct = -1.0;
foreach ($units as $unit) {
    $beds = (int)($unit['beds'] ?? 0);
    $count = (int)($unit['patients'] ?? 0);
    if ($beds <= 0) {
        continue;
    }
    $occupancy = ($count / $beds) * 100;
    if ($occupancy > $highestOccupancyPct) {
        $highestOccupancyPct = $occupancy;
        $highestOccupancyUnit = $unit;
    }
}

$attentionItems = [];
if (!$hasLoadError) {
    if ($reviewCount > 0) {
        $attentionItems[] = [
            'class' => 'is-critical',
            'label' => $tr('Revenue review cases', 'حالات مراجعة الإيراد'),
            'value' => (string)$reviewCount,
            'message' => $tr(
                $reviewCount . ' active inpatient case' . ($reviewCount === 1 ? '' : 's') . ' require revenue validation.',
                'يوجد ' . $reviewCount . ' من حالات المرضى المنومين تحتاج إلى التحقق من الإيراد.'
            ),
        ];
    }
    if ($topPayerName !== '' && $topPayerShare >= 50.0) {
        $attentionItems[] = [
            'class' => 'is-watch',
            'label' => $tr('High payer concentration', 'تركيز مرتفع لجهة دفع'),
            'value' => number_format($topPayerShare, 1) . '%',
            'message' => $tr(
                number_format($topPayerShare, 1) . '% of current daily inpatient revenue is generated by one payer.',
                'تأتي نسبة ' . number_format($topPayerShare, 1) . '% من الإيراد اليومي الحالي للمرضى المنومين من جهة دفع واحدة.'
            ),
        ];
    }
    if ($highestOccupancyUnit !== [] && $highestOccupancyPct >= 90.0) {
        $unitName = (string)($highestOccupancyUnit['unit_name'] ?? '');
        $attentionItems[] = [
            'class' => 'is-watch',
            'label' => $tr('High occupancy', 'إشغال مرتفع'),
            'value' => number_format($highestOccupancyPct, 1) . '%',
            'message' => $tr(
                $unitName . ' is operating at ' . number_format($highestOccupancyPct, 1) . '% occupancy.',
                'تعمل ' . $unitName . ' حاليًا بنسبة إشغال تبلغ ' . number_format($highestOccupancyPct, 1) . '%.'
            ),
        ];
    }
}
$attentionItems = array_slice($attentionItems, 0, 3);

$payerPalette = ['#5b21b6', '#2563eb', '#0f766e', '#f59e0b', '#db2777', '#64748b'];
$payerStops = [];
$payerSegments = [];
$cursor = 0.0;
$topPayerRevenueSum = 0.0;
foreach ($topCompanies as $idx => $company) {
    $value = (float)($company['daily_revenue'] ?? 0);
    $share = $totalRevenue > 0 ? max(0, min(100, ($value / $totalRevenue) * 100)) : 0;
    $start = $cursor;
    $cursor += $share;
    $color = $payerPalette[$idx % count($payerPalette)];
    $topPayerRevenueSum += $value;
    $payerSegments[] = [
        'label' => (string)($company['financial_class'] ?? ''),
        'value' => $value,
        'percentage' => $share,
        'prefix' => '',
        'suffix' => ' SR',
    ];
    $payerStops[] = $color . ' ' . number_format($start, 2, '.', '') . '% ' . number_format($cursor, 2, '.', '') . '%';
}
if ($cursor < 100) {
    $otherRevenue = max(0.0, $totalRevenue - $topPayerRevenueSum);
    $payerSegments[] = [
        'label' => $tr('Other payers', 'جهات دفع أخرى'),
        'value' => $otherRevenue,
        'percentage' => max(0.0, 100.0 - $cursor),
        'prefix' => '',
        'suffix' => ' SR',
    ];
    $payerStops[] = '#e5e7eb ' . number_format($cursor, 2, '.', '') . '% 100%';
}
$donutStyle = 'background:conic-gradient(' . implode(',', $payerStops) . ');';
$donutCenterValue = $hasLoadError ? 'N/A' : (($totalRevenue >= 1000000)
    ? number_format($totalRevenue / 1000000, 2) . 'M'
    : (($totalRevenue >= 1000) ? number_format($totalRevenue / 1000, 2) . 'K' : number_format($totalRevenue, 2)));
$donutCurrency = $tr('SR', 'ريال');
?>

<section class="idr-page idr-r16-page" data-idr-root data-initial-limit="<?= e((string)$initialPatientLimit) ?>">
    <section class="idr-v11-hero idr-r15-hero" aria-label="<?= e($tr('Daily inpatient revenue summary', 'ملخص الإيراد اليومي للمرضى المنومين')) ?>">
        <div class="idr-v11-hero-copy">
            <span class="idr-v11-overline"><?= e($tr('Executive revenue snapshot', 'لقطة الإيراد التنفيذي')) ?></span>
            <h2><?= e($tr("Today's Inpatient Revenue Position", 'وضع إيراد المرضى المنومين اليوم')) ?></h2>
            <p><?= e($tr(
                "Today's inpatient revenue, payer concentration, care-area performance and highest-impact cases in one decision view.",
                'إيراد المرضى المنومين اليوم، وتركيز جهات الدفع، وأداء مناطق الرعاية، وأعلى الحالات تأثيرًا في عرض واحد للقرار.'
            )) ?></p>
            <div class="idr-v11-context">
                <span><b><?= e($tr('Branch', 'الفرع')) ?></b><strong><?= e($branchName) ?></strong></span>
                <span><b><?= e($tr('Updated', 'آخر تحديث')) ?></b><strong><?= e($generatedAt) ?></strong></span>
            </div>
        </div>
        <div class="idr-v11-export-card">
            <span><?= e($tr('Exports', 'التصدير')) ?></span>
            <strong><?= e($tr('Executive reporting', 'التقارير التنفيذية')) ?></strong>
            <div class="idr-v11-export-actions <?= $powerBiReportAvailable ? 'has-three' : 'has-two' ?>">
                <a class="idr-v11-btn" href="<?= e(url_to('inpatient-daily-revenue-export')) ?>"><?= e($tr('Excel', 'Excel')) ?></a>
                <?php if ($powerBiReportAvailable): ?>
                    <a class="idr-v11-btn secondary" href="<?= e(url_to('inpatient-daily-revenue-powerbi-export')) ?>"><?= e($tr('Power BI', 'Power BI')) ?></a>
                <?php endif; ?>
                <a class="idr-v11-btn secondary" href="<?= e(url_to('inpatient-daily-revenue-powerpoint-export')) ?>"><?= e($tr('PowerPoint', 'PowerPoint')) ?></a>
            </div>
            <small><?= e($powerBiReportAvailable
                ? $tr('Export the latest Excel workbook, Power BI package or PowerPoint brief.', 'تصدير أحدث ملف Excel أو حزمة Power BI أو موجز PowerPoint.')
                : $tr('Export the latest Excel workbook or PowerPoint brief.', 'تصدير أحدث ملف Excel أو موجز PowerPoint.')) ?></small>
        </div>
    </section>

    <?php if ($hasLoadError): ?>
        <section class="surface-card idr-alert" role="alert">
            <strong><?= e($tr('Daily revenue is temporarily unavailable', 'الإيراد اليومي غير متاح مؤقتًا')) ?></strong>
            <p><?= e((string)$errorMessage) ?></p>
        </section>
    <?php endif; ?>

    <section class="idr-v11-kpis idr-r15-kpis" aria-label="<?= e($tr('Daily inpatient revenue indicators', 'مؤشرات الإيراد اليومي للمرضى المنومين')) ?>">
        <article class="idr-v11-kpi is-purple idr-r15-primary-kpi">
            <span class="idr-v11-icon idr-icon-revenue">SR</span>
            <div>
                <p><?= e($tr('Total daily revenue', 'إجمالي الإيراد اليومي')) ?></p>
                <strong><?= $hasLoadError ? 'N/A' : e(money_number($totalRevenue)) ?> <em>SR</em></strong>
                <small><?= e($tr('Current active inpatient census', 'للتعداد النشط الحالي للمرضى المنومين')) ?></small>
            </div>
        </article>
        <article class="idr-v11-kpi is-teal">
            <span class="idr-v11-icon idr-icon-census">◎</span>
            <div>
                <p><?= e($tr('Patients in rooms', 'المرضى في الغرف')) ?></p>
                <strong><?= $hasLoadError ? 'N/A' : e((string)$patientCount) ?></strong>
                <small><?= e($tr('Current active census', 'التعداد النشط الحالي')) ?></small>
            </div>
        </article>
        <article class="idr-v11-kpi is-blue">
            <span class="idr-v11-icon idr-icon-average">◇</span>
            <div>
                <p><?= e($tr('Average per patient', 'المتوسط لكل مريض')) ?></p>
                <strong><?= $hasLoadError ? 'N/A' : e(money_number($averageRevenue)) ?> <em>SR</em></strong>
                <small><?= e($tr('Daily revenue average', 'متوسط الإيراد اليومي')) ?></small>
            </div>
        </article>
        <article class="idr-v11-kpi is-rose <?= $reviewCount > 0 ? 'needs-attention' : '' ?>">
            <span class="idr-v11-icon idr-icon-review">!</span>
            <div>
                <p><?= e($tr('Needs review', 'يحتاج مراجعة')) ?></p>
                <strong><?= $hasLoadError ? 'N/A' : e((string)$reviewCount) ?></strong>
                <small><?= e($reviewCount > 0
                    ? $tr('Cases requiring financial validation', 'حالات تحتاج إلى تحقق مالي')
                    : $tr('No cases currently flagged for review', 'لا توجد حالات محددة للمراجعة حاليًا')) ?></small>
            </div>
        </article>
    </section>

    <section class="idr-v11-insight-grid idr-r15-insight-grid">
        <article class="idr-v11-card idr-v11-payer-card">
            <div class="idr-v11-section-head idr-r15-section-head">
                <div>
                    <span><?= e($tr('Revenue concentration by payer', 'تركيز الإيراد حسب جهة الدفع')) ?></span>
                    <h3><?= e($tr('Current revenue concentration', 'تركيز الإيراد الحالي')) ?></h3>
                </div>
                <?php if ($topPayerName !== ''): ?>
                    <div class="idr-r15-head-stat">
                        <span><?= e($tr('Largest payer', 'أكبر جهة دفع')) ?></span>
                        <strong><?= e(number_format($topPayerShare, 1)) ?>%</strong>
                    </div>
                <?php endif; ?>
            </div>
            <div class="idr-v11-payer-body">
                <div class="idr-v11-donut" style="<?= e($donutStyle) ?>"
                    data-ddb-chart-segments="<?= e(json_encode($payerSegments, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP)) ?>"
                    data-ddb-chart-inner-ratio="0.64"
                    data-ddb-chart-locale="<?= e($isAr ? 'ar-SA' : 'en-US') ?>"
                    data-ddb-center-value="<?= e($donutCenterValue) ?>"
                    data-ddb-center-currency="<?= e($donutCurrency) ?>"
                    data-ddb-center-exact="<?= $hasLoadError ? 'N/A' : e(money_number($totalRevenue)) ?>">
                    <div>
                        <strong><?= e($donutCenterValue) ?></strong>
                        <span><?= e($donutCurrency) ?></span>
                    </div>
                </div>
                <div class="idr-v11-payer-list">
                    <?php foreach ($topCompanies as $idx => $company): ?>
                        <?php
                            $value = (float)($company['daily_revenue'] ?? 0);
                            $pct = $totalRevenue > 0 ? min(100, ($value / $totalRevenue) * 100) : 0;
                            $color = $payerPalette[$idx % count($payerPalette)];
                        ?>
                        <div class="idr-v11-payer-item">
                            <i style="background:<?= e($color) ?>"></i>
                            <span><?= e((string)($company['financial_class'] ?? '')) ?></span>
                            <strong><?= e(money_number($value)) ?> SR</strong>
                            <em><?= e(number_format($pct, 1)) ?>%</em>
                        </div>
                    <?php endforeach; ?>
                    <?php if ($topCompanies === []): ?>
                        <p class="idr-empty-copy"><?= e($tr('No payer data is available for this snapshot.', 'لا تتوفر بيانات جهات دفع لهذه اللقطة.')) ?></p>
                    <?php endif; ?>
                </div>
            </div>
            <?php if (!$hasLoadError && $topPayerName !== ''): ?>
                <div class="idr-r15-payer-insight <?= $topPayerShare >= 50.0 ? 'is-watch' : '' ?>">
                    <strong><?= e($tr('Leadership insight', 'رؤية للإدارة العليا')) ?></strong>
                    <span><?= e($tr(
                        'One payer accounts for ' . number_format($topPayerShare, 1) . '% of current daily inpatient revenue.',
                        'تمثل جهة دفع واحدة نسبة ' . number_format($topPayerShare, 1) . '% من الإيراد اليومي الحالي للمرضى المنومين.'
                    )) ?></span>
                </div>
            <?php endif; ?>
        </article>

        <article class="idr-v11-card idr-v11-care-card">
            <div class="idr-v11-section-head idr-r15-section-head">
                <div>
                    <span><?= e($tr('Care area performance', 'أداء مناطق الرعاية')) ?></span>
                    <h3><?= e($tr('Revenue and occupancy performance by care area', 'أداء الإيراد والإشغال حسب منطقة الرعاية')) ?></h3>
                </div>
            </div>
            <?php if ($topUnits !== []): ?>
                <div class="idr-r15-care-summary">
                    <div>
                        <span><?= e($tr('Highest revenue unit', 'أعلى وحدة من حيث الإيراد')) ?></span>
                        <strong><?= e((string)($highestRevenueUnit['unit_name'] ?? '')) ?></strong>
                        <small><?= e(money_number((float)($highestRevenueUnit['daily_revenue'] ?? 0))) ?> SR</small>
                    </div>
                    <?php if ($highestOccupancyUnit !== []): ?>
                        <div>
                            <span><?= e($tr('Highest occupancy', 'أعلى نسبة إشغال')) ?></span>
                            <strong><?= e((string)($highestOccupancyUnit['unit_name'] ?? '')) ?></strong>
                            <small><?= e(number_format($highestOccupancyPct, 1)) ?>%</small>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <div class="idr-v11-care-list">
                <?php foreach ($topUnits as $idx => $unit): ?>
                    <?php
                        $unitRevenue = (float)($unit['daily_revenue'] ?? 0);
                        $width = $maxUnitRevenue > 0 ? max(2, ($unitRevenue / $maxUnitRevenue) * 100) : 0;
                        $beds = (int)($unit['beds'] ?? 0);
                        $count = (int)($unit['patients'] ?? 0);
                        $occupancy = $beds > 0 ? ($count / $beds) * 100 : null;
                        $unitAverage = $count > 0 ? $unitRevenue / $count : 0.0;
                        $unitRevenueCompact = ($unitRevenue >= 1000000)
                            ? number_format($unitRevenue / 1000000, 2) . 'M'
                            : (($unitRevenue >= 1000) ? number_format($unitRevenue / 1000, 2) . 'K' : number_format($unitRevenue, 2));
                        $color = $payerPalette[$idx % count($payerPalette)];
                    ?>
                    <div class="idr-v11-care-row idr-r15-care-row" data-ddb-chart-display-value="<?= e($unitRevenueCompact) ?> SR" data-ddb-chart-exact-value="<?= e(money_number($unitRevenue)) ?> SR">
                        <div>
                            <strong><?= e((string)($unit['unit_name'] ?? '')) ?></strong>
                            <span>
                                <?= e((string)$count) ?> <?= e($tr('patients', 'مريض')) ?>
                                <?php if ($occupancy !== null): ?>
                                    · <?= e(number_format($occupancy, 1)) ?>% <?= e($tr('occupancy', 'إشغال')) ?>
                                <?php else: ?>
                                    · <?= e($tr('Occupancy N/A', 'الإشغال غير متاح')) ?>
                                <?php endif; ?>
                            </span>
                        </div>
                        <div class="idr-v11-care-track"><i style="width:<?= e(number_format($width, 2, '.', '')) ?>%;background:<?= e($color) ?>"></i></div>
                        <div class="idr-r15-care-value">
                            <strong><?= e(money_number($unitRevenue)) ?> SR</strong>
                            <small><?= e(money_number($unitAverage)) ?> <?= e($tr('SR / patient', 'ريال / مريض')) ?></small>
                        </div>
                    </div>
                <?php endforeach; ?>
                <?php if ($topUnits === []): ?>
                    <p class="idr-empty-copy"><?= e($tr('No unit data is available for this snapshot.', 'لا تتوفر بيانات وحدات لهذه اللقطة.')) ?></p>
                <?php endif; ?>
            </div>
        </article>
    </section>

    <section class="idr-v11-card idr-r15-attention-card" aria-label="<?= e($tr('Decision signals', 'إشارات القرار')) ?>">
        <div class="idr-v11-section-head idr-r15-section-head">
            <div>
                <span><?= e($tr('Decision signals', 'إشارات القرار')) ?></span>
                <h3><?= e($tr('Leadership Attention', 'اهتمام الإدارة العليا')) ?></h3>
            </div>
        </div>
        <?php if ($attentionItems !== []): ?>
            <div class="idr-r15-attention-grid">
                <?php foreach ($attentionItems as $item): ?>
                    <article class="idr-r15-attention-item <?= e((string)$item['class']) ?>">
                        <div>
                            <span><?= e((string)$item['label']) ?></span>
                            <strong><?= e((string)$item['value']) ?></strong>
                        </div>
                        <p><?= e((string)$item['message']) ?></p>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="idr-r15-attention-clear">
                <strong><?= e($tr('No immediate leadership attention required', 'لا توجد نقاط تتطلب اهتمامًا فوريًا من الإدارة العليا')) ?></strong>
                <span><?= e($tr(
                    'No immediate revenue issues are currently flagged for leadership attention.',
                    'لا توجد حاليًا مؤشرات إيراد فورية تستدعي اهتمام الإدارة العليا.'
                )) ?></span>
            </div>
        <?php endif; ?>
    </section>

    <section class="idr-v11-card idr-v11-table-card idr-r15-table-card">
        <div class="idr-v11-table-head">
            <div>
                <span><?= e($tr('Patient-level highlights', 'أبرز حالات المرضى')) ?></span>
                <h3><?= e($tr('Top Inpatients by Daily Revenue', 'أعلى المرضى حسب الإيراد اليومي')) ?></h3>
                <p class="idr-r15-table-subtitle"><?= e($tr(
                    'Top 5 current inpatients by daily revenue. Search or view all patients for the complete active census.',
                    'تعرض الصفوف الخمسة الأولى أعلى المرضى حسب الإيراد اليومي. استخدم البحث أو عرض جميع المرضى لرؤية التعداد النشط الكامل.'
                )) ?></p>
            </div>
            <div class="idr-table-controls">
                <input type="search" placeholder="<?= e($tr('Search patient, room or payer', 'بحث بالمريض أو الغرفة أو جهة الدفع')) ?>" data-idr-search>
                <select data-idr-status>
                    <option value="all"><?= e($tr('All statuses', 'كل الحالات')) ?></option>
                    <option value="calculated"><?= e($tr('Calculated', 'محسوب')) ?></option>
                    <option value="review"><?= e($tr('Needs review', 'يحتاج مراجعة')) ?></option>
                </select>
            </div>
        </div>
        <div class="idr-table-wrap">
            <table class="idr-table">
                <thead>
                    <tr>
                        <th><?= e($tr('Patient', 'المريض')) ?></th>
                        <th><?= e($tr('Location', 'الموقع')) ?></th>
                        <th><?= e($tr('Care area', 'منطقة الرعاية')) ?></th>
                        <th><?= e($tr('Financial class', 'الفئة المالية')) ?></th>
                        <th><?= e($tr('Daily revenue', 'الإيراد اليومي')) ?></th>
                    </tr>
                </thead>
                <tbody data-idr-table-body>
                    <?php foreach ($displayPatients as $patient): ?>
                        <?php
                            $needsReview = !empty($patient['needs_review']);
                            $searchText = strtolower(trim(implode(' ', [
                                (string)($patient['patient_name'] ?? ''),
                                (string)($patient['patientid'] ?? ''),
                                (string)($patient['room'] ?? ''),
                                (string)($patient['bed'] ?? ''),
                                (string)($patient['financial_class'] ?? ''),
                                (string)($patient['unit_name'] ?? ''),
                            ])));
                        ?>
                        <tr data-idr-row data-status="<?= $needsReview ? 'review' : 'calculated' ?>" data-search="<?= e($searchText) ?>">
                            <td>
                                <strong><?= e((string)($patient['patient_name'] ?? '')) ?></strong>
                                <small>#<?= e(trim((string)($patient['patientid'] ?? ''))) ?> · <?= e((string)($patient['attending_doctor'] ?? '')) ?></small>
                            </td>
                            <td>
                                <strong><?= e((string)($patient['room'] ?? '')) ?> / <?= e((string)($patient['bed'] ?? '')) ?></strong>
                                <small><?= e($tr('LOS', 'مدة الإقامة')) ?> <?= e((string)($patient['los'] ?? 0)) ?> · <?= e($tr('Total LOS', 'إجمالي الإقامة')) ?> <?= e((string)($patient['total_los'] ?? 0)) ?></small>
                            </td>
                            <td><strong><?= e((string)($patient['unit_name'] ?? '')) ?></strong></td>
                            <td><strong><?= e((string)($patient['financial_class'] ?? '')) ?></strong></td>
                            <td class="idr-revenue-cell"><strong><?= e(money_number((float)($patient['daily_revenue'] ?? 0))) ?> SR</strong></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="idr-table-footer">
            <span><b data-idr-visible-count><?= e((string)$patientPreviewCount) ?></b> <?= e($tr('of', 'من')) ?> <b data-idr-total-count><?= e((string)count($displayPatients)) ?></b> <?= e($tr('patients shown', 'مريض معروض')) ?></span>
            <?php if (count($displayPatients) > $initialPatientLimit): ?>
                <button type="button" class="idr-v11-link-btn" data-idr-show-all><?= e($tr('View all patients', 'عرض جميع المرضى')) ?></button>
            <?php endif; ?>
        </div>
    </section>
</section>
