<?php
$executive = is_array($executive ?? null) ? $executive : [];
$hospitalName = $hospital['name'] ?? 'New Jeddah';
$isAr = current_lang() === 'ar';
$txt = function (string $en, string $ar = '') use ($isAr): string { return $isAr && $ar !== '' ? $ar : $en; };
$num = function ($value): string { return number_format((float)$value, 0); };
$money = function ($value): string { return 'SAR ' . compact_money((float)$value); };
$get = function (array $arr, string $key) { return array_key_exists($key, $arr) ? $arr[$key] : null; };

$flow = is_array($executive['flow'] ?? null) ? $executive['flow'] : [];
$finance = is_array($executive['finance'] ?? null) ? $executive['finance'] : [];
$capacity = is_array($executive['capacity'] ?? null) ? $executive['capacity'] : [];
$clinical = is_array($executive['clinical'] ?? null) ? $executive['clinical'] : [];
$trends = is_array($executive['trends'] ?? null) ? $executive['trends'] : [];
$status = is_array($executive['status'] ?? null) ? $executive['status'] : ['status' => 'STABLE', 'tone' => 'good', 'text' => 'All systems normal'];
$alerts = is_array($executive['alerts'] ?? null) ? $executive['alerts'] : [];
$actions = is_array($executive['actions'] ?? null) ? $executive['actions'] : [];
$units = is_array($capacity['units'] ?? null) ? array_slice($capacity['units'], 0, 3) : [];
$topSpecialties = is_array($clinical['top_specialties'] ?? null) ? array_slice($clinical['top_specialties'], 0, 5) : [];
$topDoctor = is_array($clinical['top_doctor'] ?? null) ? $clinical['top_doctor'] : null;
$lastUpdated = (string)($executive['last_updated'] ?? date('Y-m-d H:i'));
$isFastMode = !empty($executive['is_fast_mode']);
$isSummaryMode = ((string)($executive['mode'] ?? '') === 'summary');
$modeName = $isSummaryMode ? $txt('Summary Layer', 'طبقة الملخصات') : ($isFastMode ? $txt('Fast Mode', 'الوضع السريع') : $txt('Live Mode', 'الوضع الحي'));
$operational = is_array($executive['operational'] ?? null) ? $executive['operational'] : [];
$operationalDate = (string)($operational['operational_date'] ?? ($executive['today'] ?? date('Y-m-d')));
$operationalWindow = trim((string)($operational['window_start'] ?? '') . ' → ' . (string)($operational['window_end'] ?? ''), ' →');
$isRollover = !empty($operational['is_rollover']);
$operationalModeText = $isRollover ? $txt('Night rollover active', 'تدوير ليلي مفعل') : $txt('Calendar day active', 'اليوم التقويمي مفعل');

$smartCount = function ($value, bool $trusted = true) use ($isFastMode, $num): string {
    if ($value === null || $value === '') { return '—'; }
    if ($isFastMode && !$trusted && (float)$value == 0.0) { return '—'; }
    return $num($value);
};
$smartMoney = function ($value, bool $trusted = true) use ($isFastMode, $money): string {
    if ($value === null || $value === '') { return '—'; }
    if ($isFastMode && !$trusted && (float)$value == 0.0) { return '—'; }
    return $money($value);
};
$smartPct = function ($value, bool $trusted = true) use ($isFastMode): string {
    if ($value === null || $value === '') { return '—'; }
    if ($isFastMode && !$trusted && (float)$value == 0.0) { return '—'; }
    return number_format((float)$value, 0) . '%';
};

$occupancyRate = $capacity['occupancy_rate'] ?? null;
$todayRevenue = $get($finance, 'today_total');
$monthRevenue = $get($finance, 'month_total');
$availableBeds = $get($capacity, 'available_beds');
$totalBeds = $get($capacity, 'total_beds');
$er = (int)($get($flow, 'er') ?? 0);
$erPressure = $er >= 50 ? $txt('HIGH', 'مرتفع') : ($er > 0 ? $txt('WATCH', 'متابعة') : $txt('LOW', 'منخفض'));
$erPressureClass = $er >= 50 ? 'high' : ($er > 0 ? 'watch' : 'low');
$opMix = (float)($clinical['op_mix'] ?? 0);
$ipMix = (float)($clinical['ip_mix'] ?? 0);

$spark = function (array $rows, string $field = 'value', int $bars = 10): string {
    $values = [];
    foreach ($rows as $row) { $values[] = max(0.0, (float)($row[$field] ?? 0)); }
    if (!$values) { $values = [2,4,3,6,5,8,6,9,7,10]; }
    $max = max($values) ?: 1;
    $html = '';
    foreach (array_slice($values, -$bars) as $v) {
        $html .= '<span style="height:' . max(6, round(($v / $max) * 30)) . 'px"></span>';
    }
    return $html;
};

$todayCards = [
    ['label' => $txt('OPD Visits', 'زيارات العيادات'), 'value' => $get($flow, 'opd'), 'icon' => '♧', 'tone' => 'teal', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('ER Visits', 'زيارات الطوارئ'), 'value' => $get($flow, 'er'), 'icon' => '🚑', 'tone' => 'red', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('Admissions', 'الدخول'), 'value' => $get($flow, 'admissions'), 'icon' => '▤', 'tone' => 'purple', 'href' => url_to('visits'), 'trusted' => true],
    ['label' => $txt('Discharges', 'الخروج'), 'value' => $get($flow, 'discharges'), 'icon' => '⇥', 'tone' => 'green', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('Scheduled OR', 'عمليات مجدولة'), 'value' => $get($flow, 'scheduled_operations'), 'icon' => '▣', 'tone' => 'blue', 'href' => '#', 'trusted' => !$isFastMode],
    ['label' => $txt('Performed OR', 'عمليات منفذة'), 'value' => $get($flow, 'performed_operations'), 'icon' => '✎', 'tone' => 'teal', 'href' => '#', 'trusted' => !$isFastMode],
    ['label' => $txt('Revenue Today', 'إيراد اليوم'), 'value' => $todayRevenue, 'icon' => '◈', 'tone' => 'purple', 'href' => url_to('revenue'), 'money' => true, 'trusted' => true],
];

if (!$alerts) {
    $alerts = [[
        'severity' => 'summary',
        'title' => $isSummaryMode ? $txt('Summary Layer is Active', 'طبقة الملخصات مفعلة') : $txt('No critical alerts', 'لا توجد تنبيهات حرجة'),
        'text' => $isSummaryMode ? $txt('Home KPIs are being read from the fast executive summary table.', 'مؤشرات الصفحة الرئيسية تُقرأ من جدول الملخصات التنفيذي السريع.') : $txt('No high severity alert detected from current data.', 'لا توجد تنبيهات عالية الخطورة من البيانات الحالية.'),
    ]];
}
if (!$actions) {
    $actions = [
        ['tone' => 'teal', 'title' => $txt('Refresh Executive Summary', 'تحديث الملخص التنفيذي'), 'text' => $txt('Run the scheduled refresh job to update KPIs.', 'تشغيل مهمة التحديث لتحديث المؤشرات.')],
        ['tone' => 'purple', 'title' => $txt('Open Revenue Dashboard', 'فتح لوحة الإيرادات'), 'text' => $txt('Review detailed financial performance by month.', 'مراجعة الأداء المالي التفصيلي حسب الشهر.')],
        ['tone' => 'blue', 'title' => $txt('Review Capacity', 'مراجعة السعة'), 'text' => $txt('Open Beds dashboard for detailed capacity analysis.', 'فتح لوحة الأسرة لتحليل السعة بالتفصيل.')],
    ];
}

$unitFallback = [
    ['label' => 'ICU', 'value' => null],
    ['label' => 'Medical', 'value' => null],
    ['label' => 'Surgical', 'value' => null],
];
$unitsToRender = $units ?: $unitFallback;
?>

<section class="cmdx elite-command-best">
    <?php if (!empty($executiveError)): ?>
        <div class="cmdx-warning"><strong><?= e($txt('Executive data could not be fully loaded.', 'تعذر تحميل بيانات الصفحة التنفيذية بالكامل.')) ?></strong><span><?= e($txt('Details were logged in storage/logs/app.log.', 'تم تسجيل التفاصيل في storage/logs/app.log.')) ?></span></div>
    <?php endif; ?>

    <section class="cmdx-situation" aria-label="Executive hospital situation">
        <article class="cmdx-status-tile">
            <div class="cmdx-icon pulse">⌁</div>
            <div>
                <small><?= e($txt('Hospital Status', 'حالة المستشفى')) ?></small>
                <strong><?= e((string)($status['status'] ?? 'STABLE')) ?></strong>
                <em><?= e($isSummaryMode ? $txt('Summary layer active', 'طبقة الملخصات مفعلة') : (string)($status['text'] ?? 'All systems normal')) ?></em>
            </div>
            <span class="cmdx-live-chip">● <?= e($modeName) ?></span>
        </article>

        <article class="cmdx-mini-tile">
            <div class="cmdx-mini-ring" style="--p:<?= e((string)max(0, min(100, (float)($occupancyRate ?? 0)))) ?>"><span><?= e($smartPct($occupancyRate, !$isFastMode)) ?></span></div>
            <small><?= e($txt('Occupancy', 'الإشغال')) ?></small>
            <em><?= e($occupancyRate === null ? $txt('Awaiting bed summary', 'بانتظار ملخص الأسرة') : $txt('Current capacity', 'السعة الحالية')) ?></em>
        </article>

        <article class="cmdx-mini-tile revenue-tile">
            <div class="cmdx-square purple">◈</div>
            <small><?= e($txt('Today Revenue', 'إيراد اليوم')) ?></small>
            <strong><?= e($smartMoney($todayRevenue, true)) ?></strong>
            <div class="cmdx-spark purple"><?= $spark($trends['revenue'] ?? []) ?></div>
        </article>

        <article class="cmdx-mini-tile">
            <div class="cmdx-square orange">⚠</div>
            <small><?= e($txt('ER Pressure', 'ضغط الطوارئ')) ?></small>
            <strong class="cmdx-pressure-<?= e($erPressureClass) ?>"><?= e($erPressure) ?></strong>
            <div class="cmdx-pressure <?= e($erPressureClass) ?>"><i></i><i></i><i></i><i></i><i></i></div>
        </article>

        <article class="cmdx-mini-tile">
            <div class="cmdx-square bed">▱</div>
            <small><?= e($txt('Beds Available', 'أسرة متاحة')) ?></small>
            <strong><?= e($smartCount($availableBeds, !$isFastMode)) ?></strong>
            <em><?= e($txt('Total beds', 'إجمالي الأسرة')) ?>: <?= e($smartCount($totalBeds, !$isFastMode)) ?></em>
        </article>

        <article class="cmdx-mini-tile">
            <div class="cmdx-square shield">◇</div>
            <small><?= e($txt('Data Quality', 'جودة البيانات')) ?></small>
            <strong class="good"><?= e($txt('GOOD', 'جيدة')) ?></strong>
            <em><?= e($txt('All critical sources normal', 'المصادر الحرجة طبيعية')) ?></em>
        </article>
    </section>

    <div class="cmdx-section-head">
        <div>
            <span><?= e($isRollover ? $txt('Operational day at a glance', 'نظرة اليوم التشغيلي') : $txt('Today at a glance', 'نظرة اليوم')) ?></span>
            <h2><?= e($txt('Hospital Pulse', 'نبض المستشفى')) ?></h2>
        </div>
        <div class="cmdx-opday <?= $isRollover ? 'rollover' : '' ?>">
            <small><?= e($txt('Operational Day', 'اليوم التشغيلي')) ?></small>
            <strong><?= e($operationalDate) ?></strong>
            <em><?= e($operationalModeText) ?></em>
        </div>
        <div class="cmdx-updated"><small><?= e($txt('Last updated', 'آخر تحديث')) ?></small><strong><?= e($lastUpdated) ?></strong></div>
    </div>

    <section class="cmdx-pulse-row">
        <?php foreach ($todayCards as $card): ?>
            <a class="cmdx-pulse-card tone-<?= e($card['tone']) ?>" href="<?= e($card['href']) ?>">
                <span class="cmdx-pulse-icon"><?= e($card['icon']) ?></span>
                <div>
                    <small><?= e($card['label']) ?></small>
                    <strong><?= e(!empty($card['money']) ? $smartMoney($card['value'], (bool)($card['trusted'] ?? true)) : $smartCount($card['value'], (bool)($card['trusted'] ?? true))) ?></strong>
                    <em>▲ <?= e($isSummaryMode ? $txt('summary context', 'سياق ملخص') : $txt('live context', 'سياق حي')) ?></em>
                </div>
                <div class="cmdx-card-spark"><?= $spark([], 'value', 7) ?></div>
            </a>
        <?php endforeach; ?>
    </section>

    <section class="cmdx-grid">
        <article class="cmdx-panel flow-panel">
            <div class="cmdx-panel-title"><span>♧</span><h3><?= e($txt('Patient Flow Overview', 'ملخص تدفق المرضى')) ?></h3></div>
            <div class="cmdx-flow-line">
                <div class="cmdx-flow-node opd"><span>♧</span><b><?= e($smartCount($get($flow, 'opd'), !$isFastMode)) ?></b><small><?= e($txt('OPD', 'العيادات')) ?></small></div>
                <i></i>
                <div class="cmdx-flow-node er"><span>🚑</span><b><?= e($smartCount($get($flow, 'er'), !$isFastMode)) ?></b><small><?= e($txt('ER', 'الطوارئ')) ?></small></div>
                <i></i>
                <div class="cmdx-flow-node adm"><span>▤</span><b><?= e($smartCount($get($flow, 'admissions'), true)) ?></b><small><?= e($txt('Admissions', 'الدخول')) ?></small></div>
                <i></i>
                <div class="cmdx-flow-node occ primary"><span>▱</span><b><?= e($smartPct($occupancyRate, !$isFastMode)) ?></b><small><?= e($txt('Occupancy', 'الإشغال')) ?></small></div>
                <i></i>
                <div class="cmdx-flow-node dis"><span>⇥</span><b><?= e($smartCount($get($flow, 'discharges'), !$isFastMode)) ?></b><small><?= e($txt('Discharges', 'الخروج')) ?></small></div>
            </div>
            <footer><?= e($txt('Expected discharges in operational day', 'الخروج المتوقع في اليوم التشغيلي')) ?>: <b><?= e($smartCount($get($capacity, 'expected_discharges'), true)) ?></b><span>•</span><?= e($operationalWindow !== '' ? $operationalWindow : $txt('Real-time executive summary layer', 'طبقة الملخصات التنفيذية')) ?></footer>
        </article>

        <article class="cmdx-panel capacity-panel">
            <div class="cmdx-panel-title"><span>▱</span><h3><?= e($txt('Capacity & Occupancy', 'السعة والإشغال')) ?></h3></div>
            <div class="cmdx-capacity-body">
                <div class="cmdx-donut" style="--p:<?= e((string)max(0, min(100, (float)($occupancyRate ?? 0)))) ?>"><b><?= e($smartCount($totalBeds, !$isFastMode)) ?></b><small><?= e($txt('Total Beds', 'إجمالي الأسرة')) ?></small></div>
                <div class="cmdx-units">
                    <?php foreach ($unitsToRender as $unit): ?>
                        <?php $label=(string)($unit['unit_label'] ?? $unit['label'] ?? 'Unit'); $raw=$unit['occupancy_pct'] ?? $unit['value'] ?? null; $has=!($raw===null||$raw===''); $v=$has?(float)$raw:0; ?>
                        <div><span><?= e($label) ?></span><b style="--w:<?= e((string)max(0,min(100,$v))) ?>%"></b><em><?= e($has ? number_format($v, 0) . '%' : '—') ?></em></div>
                    <?php endforeach; ?>
                </div>
            </div>
            <a class="cmdx-soft-link" href="<?= e(url_to('beds')) ?>"><?= e($txt('View Beds Dashboard', 'فتح لوحة الأسرة')) ?> →</a>
        </article>

        <article class="cmdx-panel finance-panel">
            <div class="cmdx-panel-title"><span>◈</span><h3><?= e($txt('Finance Snapshot', 'لمحة مالية')) ?></h3><a href="<?= e(url_to('revenue')) ?>"><?= e($txt('Revenue', 'الإيرادات')) ?></a></div>
            <div class="cmdx-finance-grid">
                <div><small><?= e($txt('Today Revenue', 'إيراد اليوم')) ?></small><strong><?= e($smartMoney($todayRevenue, true)) ?></strong></div>
                <div><small><?= e($txt('Month Revenue', 'إيراد الشهر')) ?></small><strong><?= e($smartMoney($monthRevenue, true)) ?></strong></div>
                <div><small><?= e($txt('Cash', 'نقدي')) ?></small><strong><?= e($smartMoney($get($finance, 'cash'), true)) ?></strong></div>
                <div><small><?= e($txt('Insurance', 'تأمين')) ?></small><strong><?= e($smartMoney($get($finance, 'insurance'), true)) ?></strong></div>
                <div><small><?= e($txt('MOH', 'وزارة الصحة')) ?></small><strong><?= e($smartMoney($get($finance, 'moh'), true)) ?></strong></div>
                <div class="net"><small><?= e($txt('Net', 'الصافي')) ?></small><strong><?= e($smartMoney($get($finance, 'net'), true)) ?></strong></div>
            </div>
        </article>

        <article class="cmdx-panel clinical-panel">
            <div class="cmdx-panel-title"><span>♙</span><h3><?= e($txt('Clinical Activity', 'النشاط السريري')) ?></h3></div>
            <div class="cmdx-clinical-top">
                <div><small><?= e($txt('Active Doctors', 'الأطباء النشطون')) ?></small><strong><?= e($smartCount($get($clinical, 'active_doctors'), !$isFastMode)) ?></strong></div>
                <div class="wide"><small><?= e($txt('Top Doctor by Net Revenue', 'أعلى طبيب بالصافي')) ?></small><strong><?= e((string)($topDoctor['label'] ?? '—')) ?></strong><em><?= e(isset($topDoctor['value']) ? $money($topDoctor['value']) : '—') ?></em></div>
                <div><small><?= e($txt('OP / IP Mix', 'مزيج العيادات / التنويم')) ?></small><strong><?= e(($opMix == 0.0 && $ipMix == 0.0 && $isSummaryMode) ? '— / —' : (number_format($opMix, 0) . '% / ' . number_format($ipMix, 0) . '%')) ?></strong></div>
            </div>
            <ol class="cmdx-specialties">
                <?php if ($topSpecialties): ?>
                    <?php foreach ($topSpecialties as $idx => $spec): ?>
                        <?php $v=(float)($spec['value'] ?? 0); $max=max(1,(float)($topSpecialties[0]['value'] ?? 1)); ?>
                        <li><span><?= e((string)($idx + 1)) ?></span><b><?= e((string)($spec['label'] ?? 'Specialty')) ?></b><i style="--w:<?= e((string)max(8,min(100,($v/$max)*100))) ?>%"></i><em><?= e($money($v)) ?></em></li>
                    <?php endforeach; ?>
                <?php else: ?>
                    <li><span>1</span><b><?= e($txt('No specialty data yet', 'لا توجد بيانات تخصصات بعد')) ?></b><i style="--w:0%"></i><em>—</em></li>
                <?php endif; ?>
            </ol>
        </article>

        <aside class="cmdx-panel alerts-panel">
            <div class="cmdx-panel-title"><span>⚠</span><h3><?= e($txt('Critical Alerts', 'التنبيهات الحرجة')) ?></h3><a href="<?= e(url_to('action-center', ['section' => 'alerts'])) ?>"><?= e($txt('View all', 'عرض الكل')) ?></a></div>
            <div class="cmdx-alert-list">
                <?php foreach ($alerts as $alert): ?>
                    <div class="cmdx-alert severity-<?= e((string)($alert['severity'] ?? 'low')) ?>"><span>▧</span><b><?= e((string)($alert['title'] ?? 'Alert')) ?></b><p><?= e((string)($alert['text'] ?? '')) ?></p><em><?= e($txt('No critical data quality issues detected.', 'لا توجد مشكلات حرجة في جودة البيانات.')) ?></em></div>
                <?php endforeach; ?>
            </div>
        </aside>

        <aside class="cmdx-panel actions-panel">
            <div class="cmdx-panel-title"><span>▸</span><h3><?= e($txt('Recommended Actions', 'إجراءات مقترحة')) ?></h3></div>
            <div class="cmdx-actions">
                <?php foreach ($actions as $action): ?>
                    <div class="cmdx-action tone-<?= e((string)($action['tone'] ?? 'teal')) ?>"><div><b><?= e((string)($action['title'] ?? 'Action')) ?></b><span><?= e((string)($action['text'] ?? '')) ?></span></div><a href="<?= e(url_to('action-center')) ?>"><?= e($txt('Review', 'مراجعة')) ?></a></div>
                <?php endforeach; ?>
            </div>
            <a class="cmdx-action-center" href="<?= e(url_to('action-center')) ?>"><?= e($txt('Go to Action Center', 'فتح مركز الإجراءات')) ?> →</a>
        </aside>
    </section>

    <section class="cmdx-quick"><strong><?= e($txt('Quick Access', 'وصول سريع')) ?></strong><a href="<?= e(url_to('revenue')) ?>">◈ <?= e($txt('Revenue', 'الإيرادات')) ?></a><a href="<?= e(url_to('visits')) ?>">♧ <?= e($txt('Visits', 'الزيارات')) ?></a><a href="<?= e(url_to('doctors')) ?>">♙ <?= e($txt('Doctors', 'الأطباء')) ?></a><a href="<?= e(url_to('beds')) ?>">▱ <?= e($txt('Beds', 'الأسرة')) ?></a><a href="<?= e(url_to('action-center')) ?>">⚠ <?= e($txt('Action Center', 'مركز الإجراءات')) ?></a><a href="#">⌁ <?= e($txt('Metric Dictionary', 'قاموس المؤشرات')) ?></a></section>

    <section class="cmdx-trust">
        <div><span>▤</span><b><?= e($txt('Source', 'المصدر')) ?></b><strong>Oracle HIS</strong><em><?= e($isSummaryMode ? $txt('Executive summary layer', 'طبقة الملخصات التنفيذية') : $txt('Live connection', 'اتصال مباشر')) ?></em></div>
        <div><span>◷</span><b><?= e($txt('Operational Day', 'اليوم التشغيلي')) ?></b><strong><?= e($operationalDate) ?></strong><em><?= e($operationalModeText) ?></em></div>
        <div><span>◇</span><b><?= e($txt('Data Quality', 'جودة البيانات')) ?></b><strong><?= e($txt('Good', 'جيدة')) ?></strong><em><?= e($txt('Schema-aware queries', 'استعلامات تراعي اختلاف الجداول')) ?></em></div>
        <div><span>⚙</span><b><?= e($txt('System Status', 'حالة النظام')) ?></b><strong><?= e($txt('Operational', 'يعمل')) ?></strong><em><?= e($txt('No blocking issues', 'لا توجد مشكلات مانعة')) ?></em></div>
    </section>
</section>
