<?php
$isAr = current_lang() === 'ar';
$tr = static function (string $en, string $ar) use ($isAr): string { return $isAr ? $ar : $en; };
$hospitalName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
$data = is_array($bedsData ?? null) ? $bedsData : null;
$snapshot = is_array($data['snapshot'] ?? null) ? $data['snapshot'] : [];
$units = is_array($data['units'] ?? null) ? $data['units'] : [];
$beds = is_array($data['beds'] ?? null) ? $data['beds'] : [];
$selectedUnit = is_array($data['selected_unit'] ?? null) ? $data['selected_unit'] : null;
$periodLabel = $mode === 'range' ? ($fromDate . ' → ' . $toDate) : (string)$year;
?>
<div class="beds1014-shell">
    <section class="beds1014-hero">
        <div>
            <span class="beds1014-kicker"><?= e($tr('EXECUTIVE CAPACITY VIEW', 'عرض السعة التنفيذي')) ?></span>
            <h2><?= e($tr('Beds & Unit Capacity', 'الأسرة وسعة الوحدات')) ?></h2>
            <p><?= e($tr('See current bed availability, unit efficiency and bed-level utilization in one leadership view.', 'تابع توافر الأسرة الحالي وكفاءة الوحدات واستخدام كل سرير في عرض قيادي واحد.')) ?></p>
            <div class="beds1014-period-strip">
                <span><small><?= e($tr('Reporting period', 'فترة التقرير')) ?></small><strong><?= e($periodLabel) ?></strong></span>
                <span><small><?= e($tr('Active branch', 'الفرع النشط')) ?></small><strong><?= e($hospitalName) ?></strong></span>
                <span><small><?= e($tr('Selected unit', 'الوحدة المختارة')) ?></small><strong><?= e((string)($selectedUnit['bed_floor'] ?? $tr('Automatic', 'تلقائي'))) ?></strong></span>
            </div>
        </div>
        <div class="beds1014-hero-score">
            <span><?= e($tr('Current occupancy', 'الإشغال الحالي')) ?></span>
            <strong><?= e(number_format((float)($snapshot['occupancy_rate'] ?? 0), 1)) ?>%</strong>
            <small><?= e($tr('Live busy vs available bed snapshot', 'لقطة مباشرة للأسرة المشغولة والمتاحة')) ?></small>
        </div>
    </section>

    <section class="beds1014-controls">
        <div class="beds1014-section-head">
            <span><?= e($tr('REPORT CONTROLS', 'إعدادات التقرير')) ?></span>
            <h2><?= e($tr('Choose the period and unit', 'اختر الفترة والوحدة')) ?></h2>
        </div>
        <form method="get" action="index.php" class="beds1014-filter">
            <input type="hidden" name="page" value="beds"><input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <label><span><?= e($tr('Mode', 'الوضع')) ?></span><select name="mode"><option value="year" <?= $mode==='year'?'selected':'' ?>><?= e($tr('Year', 'سنة')) ?></option><option value="range" <?= $mode==='range'?'selected':'' ?>><?= e($tr('Date range', 'فترة مخصصة')) ?></option></select></label>
            <label><span><?= e($tr('Year', 'السنة')) ?></span><select name="year"><?php foreach (($data['years'] ?? [$year]) as $y): ?><option value="<?= e((string)$y) ?>" <?= (int)$y===(int)$year?'selected':'' ?>><?= e((string)$y) ?></option><?php endforeach; ?></select></label>
            <label><span><?= e($tr('From', 'من')) ?></span><input type="date" name="from_date" value="<?= e($fromDate) ?>"></label>
            <label><span><?= e($tr('To', 'إلى')) ?></span><input type="date" name="to_date" value="<?= e($toDate) ?>"></label>
            <label><span><?= e($tr('Unit', 'الوحدة')) ?></span><select name="unit_id"><option value="0"><?= e($tr('Automatic highest activity', 'تلقائيًا الأعلى نشاطًا')) ?></option><?php foreach ($units as $row): ?><option value="<?= e((string)$row['unit_id']) ?>" <?= (int)$row['unit_id']===(int)$unitId?'selected':'' ?>><?= e((string)$row['bed_floor']) ?></option><?php endforeach; ?></select></label>
            <button type="submit" class="beds1014-primary"><?= e($tr('Update view', 'تحديث العرض')) ?></button>
        </form>
        <?php if ($filterError): ?><p class="beds1014-inline-alert"><?= e($filterError) ?></p><?php endif; ?>
    </section>

    <?php if ($dataError || !$data): ?>
        <section class="beds1014-state beds1014-state-error"><strong><?= e($tr('Capacity data is temporarily unavailable', 'بيانات السعة غير متاحة مؤقتًا')) ?></strong><p><?= e($tr('The executive workspace remains available. Try another period or branch.', 'مساحة العمل التنفيذية متاحة. جرّب فترة أو فرعًا آخر.')) ?></p></section>
    <?php else: ?>
        <section class="beds1014-kpi-grid">
            <article class="beds1014-kpi"><span><?= e($tr('Occupancy rate', 'معدل الإشغال')) ?></span><strong><?= e(number_format((float)$snapshot['occupancy_rate'],1)) ?>%</strong><small><?= e($tr('Current snapshot', 'الوضع الحالي')) ?></small></article>
            <article class="beds1014-kpi"><span><?= e($tr('Occupied beds', 'الأسرة المشغولة')) ?></span><strong><?= e(number_format((float)$snapshot['busy'],0)) ?></strong><small><?= e($tr('Patients currently occupying beds', 'أسرة مشغولة حاليًا')) ?></small></article>
            <article class="beds1014-kpi"><span><?= e($tr('Available beds', 'الأسرة المتاحة')) ?></span><strong><?= e(number_format((float)$snapshot['empty'],0)) ?></strong><small><?= e($tr('Available capacity now', 'السعة المتاحة الآن')) ?></small></article>
            <article class="beds1014-kpi"><span><?= e($tr('Selected unit efficiency', 'كفاءة الوحدة المختارة')) ?></span><strong><?= e(number_format((float)($selectedUnit['bed_efficiency_percentage'] ?? 0),1)) ?>%</strong><small><?= e((string)($selectedUnit['bed_floor'] ?? $tr('No unit data', 'لا توجد بيانات وحدة'))) ?></small></article>
        </section>

        <section class="beds1014-insight-grid">
            <article class="beds1014-surface beds1014-insight"><span class="beds1014-kicker"><?= e($tr('EXECUTIVE INSIGHT', 'قراءة تنفيذية')) ?></span><h2><?= e($tr('What leadership should know now', 'ما الذي يجب أن تعرفه الإدارة الآن')) ?></h2>
                <p><?= e($tr('Current occupancy is ', 'معدل الإشغال الحالي هو ')) ?><strong><?= e(number_format((float)$snapshot['occupancy_rate'],1)) ?>%</strong><?= e($tr(', with ', '، مع ')) ?><strong><?= e(number_format((float)$snapshot['empty'],0)) ?></strong><?= e($tr(' beds available.', ' سريرًا متاحًا.')) ?></p>
                <?php if (!empty($units)): ?><p><?= e($tr('The highest-efficiency unit in the selected period is ', 'الوحدة الأعلى كفاءة في الفترة المحددة هي ')) ?><strong><?= e((string)$units[0]['bed_floor']) ?></strong> (<?= e(number_format((float)$units[0]['bed_efficiency_percentage'],1)) ?>%).</p><?php endif; ?>
            </article>
            <article class="beds1014-surface beds1014-capacity"><span class="beds1014-kicker"><?= e($tr('CAPACITY POSITION', 'وضع السعة')) ?></span><h2><?= e($tr('Busy vs available', 'مشغول مقابل متاح')) ?></h2><div class="beds1014-capacity-bar"><i style="width:<?= e(number_format(max(0,min(100,(float)$snapshot['occupancy_rate'])),2,'.','')) ?>%"></i></div><div class="beds1014-capacity-meta"><span><?= e($tr('Busy', 'مشغول')) ?> <strong><?= e(number_format((float)$snapshot['busy'],0)) ?></strong></span><span><?= e($tr('Available', 'متاح')) ?> <strong><?= e(number_format((float)$snapshot['empty'],0)) ?></strong></span></div></article>
        </section>

        <section class="beds1014-chart-grid">
            <?php foreach (['units','beds'] as $chartKey): $payload = $chartKey==='units' ? ($data['unit_payload'] ?? []) : ($data['bed_payload'] ?? []); ?>
                <article class="beds1014-surface beds1014-chart-card" data-beds-chart-shell="<?= e($chartKey) ?>" data-chart-state="pending"><div class="beds1014-section-head compact"><span><?= e($chartKey==='units'?$tr('UNIT EFFICIENCY','كفاءة الوحدات'):$tr('BED EFFICIENCY','كفاءة الأسرة')) ?></span><h2><?= e($chartKey==='units'?$tr('Efficiency by unit','الكفاءة حسب الوحدة'):$tr('Beds in the selected unit','الأسرة داخل الوحدة المختارة')) ?></h2></div><div class="beds1014-chart-stage"><canvas id="beds1014_chart_<?= e($chartKey) ?>" height="165"></canvas><div class="beds1014-chart-state beds1014-chart-empty"><strong><?= e($tr('No activity for this selection', 'لا يوجد نشاط لهذا الاختيار')) ?></strong><p><?= e($tr('Choose another period or unit.', 'اختر فترة أو وحدة أخرى.')) ?></p></div><div class="beds1014-chart-state beds1014-chart-error"><strong><?= e($tr('Chart temporarily unavailable', 'الرسم غير متاح مؤقتًا')) ?></strong><p><?= e($tr('The detailed table remains available below.', 'يبقى الجدول التفصيلي متاحًا أدناه.')) ?></p></div></div><script type="application/json" id="beds1014_data_<?= e($chartKey) ?>"><?= json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?></script></article>
            <?php endforeach; ?>
        </section>

        <section class="beds1014-surface beds1014-table-card"><div class="beds1014-section-head compact"><span><?= e($tr('UNIT DETAIL', 'تفاصيل الوحدات')) ?></span><h2><?= e($tr('Capacity efficiency matrix', 'مصفوفة كفاءة السعة')) ?></h2></div><div class="beds1014-table-wrap"><table><thead><tr><th><?= e($tr('Unit', 'الوحدة')) ?></th><th><?= e($tr('Beds', 'الأسرة')) ?></th><th><?= e($tr('Occupied hours', 'ساعات الإشغال')) ?></th><th><?= e($tr('Possible hours', 'الساعات الممكنة')) ?></th><th><?= e($tr('Efficiency', 'الكفاءة')) ?></th></tr></thead><tbody><?php foreach ($units as $row): ?><tr><td><strong><?= e((string)$row['bed_floor']) ?></strong></td><td><?= e(number_format((float)$row['bed_count'],0)) ?></td><td><?= e(number_format((float)$row['total_hours_occupied'],1)) ?></td><td><?= e(number_format((float)$row['total_hours_period'],1)) ?></td><td><?= e(number_format((float)$row['bed_efficiency_percentage'],1)) ?>%</td></tr><?php endforeach; ?><?php if (!$units): ?><tr><td colspan="5"><?= e($tr('No unit activity is available for this period.', 'لا يوجد نشاط وحدات متاح لهذه الفترة.')) ?></td></tr><?php endif; ?></tbody></table></div></section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            var gate = { expected: 2, rendered: 0, empty: 0, failed: 0, status: 'PENDING' };
            ['units','beds'].forEach(function (key) {
                var shell = document.querySelector('[data-beds-chart-shell="' + key + '"]');
                var node = document.getElementById('beds1014_data_' + key);
                try {
                    var payload = JSON.parse(node ? (node.textContent || '{}') : '{}');
                    var values = [];
                    (payload.series || []).forEach(function (series) { (series.values || []).forEach(function (value) { values.push(Number(value || 0)); }); });
                    if (!values.some(function (value) { return value !== 0; })) { if (shell) shell.setAttribute('data-chart-state','empty'); gate.empty += 1; return; }
                    var result = window.renderBarCompareChart('beds1014_chart_' + key, payload);
                    if (result && result.rendered) { if (shell) shell.setAttribute('data-chart-state','rendered'); gate.rendered += 1; } else { if (shell) shell.setAttribute('data-chart-state','error'); gate.failed += 1; }
                } catch (error) { if (shell) shell.setAttribute('data-chart-state','error'); gate.failed += 1; }
            });
            gate.status = gate.failed === 0 && (gate.rendered + gate.empty) === gate.expected ? 'PASS' : 'FAIL';
            window.__DDB_BEDS_CHART_GATE__ = gate;
            document.documentElement.setAttribute('data-beds-chart-expected', String(gate.expected));
            document.documentElement.setAttribute('data-beds-chart-rendered', String(gate.rendered));
            document.documentElement.setAttribute('data-beds-chart-empty', String(gate.empty));
            document.documentElement.setAttribute('data-beds-chart-failed', String(gate.failed));
            document.documentElement.setAttribute('data-beds-chart-gate', gate.status);
        });
        </script>
    <?php endif; ?>
</div>
