<?php
use App\Core\AccessControl;
use App\Core\Auth;
use App\Core\BranchReadiness;
use App\Core\Csrf;

$user = Auth::user();
$canAccessRevenue = AccessControl::allows('revenue.view');
$canViewDailyInpatientRevenue = AccessControl::allows('daily_inpatient_revenue.view');
$canViewSpecialtyFinance = AccessControl::allows('specialty_finance.view');
$canManageDailyRevenueSettings = AccessControl::allows('daily_revenue_settings.view');
$canManageAccessControl = AccessControl::allows('security.access_control.manage');
$canViewDiarRules = AccessControl::allows('diar.rules.view');
$canViewDiarInvestigations = AccessControl::allows('diar.investigation.view');
$canViewDiarCommandCenter = AccessControl::allows('diar.command.view'); // DIAR_UI1_LAYOUT_CAPABILITY_V1 // DIAR4B_LAYOUT_CAPABILITY_V1
$canViewDiarPortal = \App\Services\DiarWorkspaceNavigation::canOpenPortal(); // DIAR_6B_2_R2_LAYOUT_CAPABILITY
$appName = config('app.name', 'HMH Dashboard');
$activePage = $activePage ?? '';
$diarSidebarItems = \App\Services\DiarWorkspaceNavigation::sidebarItems(); // DIAR_6B_2_R3_1_ROLE_AWARE_SIDEBAR
$diarSidebarPages = \App\Services\DiarWorkspaceNavigation::sidebarPages();
$diarActivePages = \App\Services\DiarWorkspaceNavigation::allActivePages();
$isDiarPremiumPage = \App\Services\DiarWorkspaceNavigation::isPremiumPage((string)$activePage);
$diarContextTabs = \App\Services\DiarWorkspaceNavigation::contextTabs((string)$activePage); // DIAR_6B_2_R3_1_3_CONTEXT_SERVICE
$hospitals = config('hospitals', []);
$liveHospitals = AccessControl::allowedHospitals(is_array($hospitals) ? $hospitals : []);
$currentHospitalCode = Auth::hospital();
$currentHospital = $hospitals[$currentHospitalCode] ?? config('hospitals.' . $currentHospitalCode, []);
$lang = current_lang();
$dir = current_dir();
$isAr = $lang === 'ar';
$currentHospitalDisplay = (string)($isAr ? ($currentHospital['name_ar'] ?? $currentHospital['name'] ?? strtoupper($currentHospitalCode)) : ($currentHospital['name_en'] ?? $currentHospital['name'] ?? strtoupper($currentHospitalCode)));
$tr = function (string $en, string $ar = '') use ($isAr): string {
    return $isAr && $ar !== '' ? $ar : $en;
};
$branchLogoMap = [
    'njch' => 'assets/img/brand/njch.png',
    'jckh' => 'assets/img/brand/jckh.png',
    'mnh' => 'assets/img/brand/mnh.png',
];
$corporateLogo = 'assets/img/brand/logo-half.png';
$wideLogo = 'assets/img/brand/hmh-wide.png';
$hospitalLogo = $branchLogoMap[strtolower((string)$currentHospitalCode)] ?? $corporateLogo;
$pageTitleMap = [
    'dashboard' => $tr('Executive Command Center', 'مركز القيادة التنفيذي'),
    'revenue' => t('revenue.title'),
    'inpatient-daily-revenue' => $tr('Daily Inpatient Revenue', 'الإيراد اليومي للمرضى المنومين'),
    'inpatient-daily-revenue-settings' => $tr('Daily Revenue Settings', 'إعدادات الإيراد اليومي'),
    'specialty-finance' => $tr('Specialty Finance', 'المالية حسب التخصص'),
    'visits' => t('operations.visits.title'),
    'doctors' => t('doctors.page_title'),
    'beds' => t('operations.beds.title'),
    'operations' => t('operations.operations.title'),
    'lab' => t('diagnostics.title'),
    'branch-comparison' => $tr('Branch Comparison', 'مقارنة الفروع'),
    'action-center' => $tr('Executive Action Center', 'مركز الإجراءات التنفيذي'),
    'access-control' => $tr('Users & Roles', 'المستخدمون والأدوار'),
    'diar-rules' => $tr('Detection Policy & Thresholds', 'سياسة وحدود الاكتشاف'),
    'diar-investigations' => $tr('Investigation Cases', 'قضايا التحقيق'),
    'diar-investigation' => $tr('Investigation Case Review', 'مراجعة قضية التحقيق'), // DIAR_6B_2_R3_1_3_DETAIL_TITLE
    'diar-case-evidence' => $tr('Case Details & Preserved Evidence', 'تفاصيل الحالة والأدلة المحفوظة'), // DIAR_6B_3_CASE_EVIDENCE_TITLE
    // DIAR_6B_2_R2_PAGE_TITLES
    'diar-portal' => $tr('Medication Risk Intelligence', 'منظومة ذكاء مخاطر الأدوية'),
    'diar-executive-overview' => $tr('DIAR Executive Dashboard', 'لوحة DIAR للإدارة العليا'),
    'diar-statistics' => $tr('DIAR Annual Statistics', 'إحصاءات DIAR السنوية'),
    'diar-cases' => $tr('DIAR Suspicious Cases', 'حالات DIAR المشتبه بها'),
    'diar-investigation-workspace' => $tr('Investigation Management', 'إدارة تحقيقات DIAR'),
    'diar-reports' => $tr('DIAR Reports & Presentations', 'تقارير DIAR والعروض'),
    'diar-governance' => $tr('DIAR Administration & Controls', 'إدارة وضوابط DIAR'),
    // DIAR_UI1_PAGE_TITLES_V1
    'diar-command-center' => $tr('Medication Movement Intelligence', 'ذكاء حركات مخزون الأدوية'),
    'diar-engine-runs' => $tr('DIAR Processing Status', 'حالة معالجة مخاطر الأدوية'),
    'diar-movement-dictionary' => $tr('Movement Types', 'قاموس أنواع الحركات'),
    'diar-daily-facts' => $tr('Daily Medication Movements', 'حركات الأدوية اليومية'),
    'diar-statistical-profiles' => $tr('Expected Movement Patterns', 'الأنماط المتوقعة للحركة'),
    'diar-anomaly-candidates' => $tr('Unusual Movements', 'الحركات غير المعتادة'),
    'leadership-huddle' => $tr('Leadership Huddle', 'اجتماع القيادة'),
];
$pageTitle = $pageTitleMap[$activePage] ?? ($title ?? $appName);
$diarLayoutDescriptions = [
    // DIAR_6B_2_R3_1_LAYOUT_DESCRIPTIONS
    'diar-portal' => $tr('Access to executive, analytical, investigation, reporting and administration functions according to each user’s responsibilities.', 'وصول إلى وظائف الإدارة والتحليل والتحقيق والتقارير والإدارة وفق مسؤوليات كل مستخدم.'),
    'diar-executive-overview' => $tr('Executive decisions, risk exposure, key findings and hospital readiness.', 'القرارات التنفيذية وقيمة المخاطر والنتائج المهمة وجاهزية المستشفيات.'),
    'diar-statistics' => $tr('Annual item, store and movement statistics separated from investigation decisions.', 'إحصاءات سنوية للأصناف والمخازن والحركات منفصلة عن قرارات التحقيق.'),
    'diar-cases' => $tr('Search recorded unusual movements and prioritize the cases that require review.', 'البحث في الحركات غير المعتادة المسجلة وترتيب الحالات التي تتطلب المراجعة.'),
    'diar-investigation-workspace' => $tr('Assignments, evidence, findings, approvals and corrective actions.', 'التعيينات والأدلة والنتائج والاعتمادات والإجراءات التصحيحية.'),
    'diar-reports' => $tr('Executive reports, report preview and approved monthly downloads.', 'التقارير التنفيذية ومعاينة التقرير والتصدير المحكوم للنسخ.'),
    'diar-governance' => $tr('Review policies, users, processing status, data quality and audit oversight.', 'سياسات المراجعة والمستخدمون وحالة المعالجة وجودة البيانات والإشراف الرقابي.'),
    'diar-command-center' => $tr('Learn the normal movement pattern for every medication and prioritize meaningful deviations.', 'تعلّم النمط الطبيعي لحركة كل دواء وترتيب الانحرافات المهمة للمراجعة.'),
    'diar-statistical-profiles' => $tr('Expected historical movement patterns for each item, store, recorded unit and movement type.', 'الأنماط المتوقعة للحركة الطبيعية لكل صنف ومخزن ووحدة ونوع حركة دقيق.'),
    'diar-anomaly-candidates' => $tr('Medication movements that differ materially from their expected historical pattern.', 'حركات الأدوية التي تختلف بصورة جوهرية عن نمطها التاريخي المتوقع.'),
    'diar-investigations' => $tr('Evidence-based review of statistically unusual medication movements.', 'مراجعة قائمة على الأدلة للحركات الدوائية غير المعتادة إحصائيًا.'),
    'diar-investigation' => $tr('Review one investigation case, its evidence, assignment and decision history.', 'مراجعة قضية تحقيق واحدة وأدلتها وتعيينها وسجل قراراتها.'), // DIAR_6B_2_R3_1_3_DETAIL_DESCRIPTION
    'diar-case-evidence' => $tr('Protected case evidence linked to the hospital, reporting month and case record.', 'أدلة حالة محمية مرتبطة بالمستشفى وشهر التقرير وسجل الحالة.'), // DIAR_6B_3_CASE_EVIDENCE_DESCRIPTION
    'diar-rules' => $tr('Govern how statistical deviations are interpreted and prioritized.', 'حوكمة طريقة تفسير الانحرافات الإحصائية وترتيب أولويتها.'),
];
$userName = (string)($user['name'] ?? 'Admin');
$userInitial = function_exists('mb_substr') ? mb_substr($userName, 0, 1, 'UTF-8') : substr($userName, 0, 1);
$currentRelativeUrl = 'index.php' . current_url(['lang' => current_lang()]);
$navItems = [
    ['page' => 'dashboard', 'label' => $tr('Overview', 'نظرة عامة'), 'icon' => '▦', 'live' => true, 'visible' => AccessControl::allows('overview.view')],
    ['page' => 'revenue', 'label' => $tr('Revenue', 'الإيرادات'), 'icon' => '◈', 'live' => true, 'visible' => $canAccessRevenue],
    ['page' => 'inpatient-daily-revenue', 'label' => $tr('Daily Inpatient Revenue', 'الإيراد اليومي للمنومين'), 'icon' => '◉', 'live' => true, 'visible' => $canViewDailyInpatientRevenue],
    ['page' => 'inpatient-daily-revenue-settings', 'label' => $tr('Daily Revenue Settings', 'إعدادات الإيراد اليومي'), 'icon' => '⚙', 'live' => true, 'visible' => $canManageDailyRevenueSettings],
    ['page' => 'specialty-finance', 'label' => $tr('Specialty Finance', 'المالية حسب التخصص'), 'icon' => '◆', 'live' => true, 'visible' => $canViewSpecialtyFinance],
    ['page' => 'visits', 'label' => $tr('Visits', 'الزيارات'), 'icon' => '♧', 'live' => true, 'visible' => AccessControl::allows('visits.view')],
    ['page' => 'doctors', 'label' => $tr('Doctors', 'الأطباء'), 'icon' => '♙', 'live' => true, 'visible' => AccessControl::allows('doctors.view')],
    ['page' => 'beds', 'label' => $tr('Beds & Capacity', 'الأسرة والسعة'), 'icon' => '▱', 'live' => true, 'visible' => AccessControl::allows('beds.view')],
    ['page' => 'operations', 'label' => $tr('Operations', 'العمليات'), 'icon' => '✦', 'live' => true, 'visible' => AccessControl::allows('operations.view')],
    ['page' => 'lab', 'label' => $tr('Lab & Radiology', 'المختبر والأشعة'), 'icon' => '⌬', 'live' => true, 'visible' => AccessControl::allows('lab_radiology.view')],
    ['page' => 'quality', 'label' => $tr('Quality & Safety', 'الجودة والسلامة'), 'icon' => '◇', 'live' => false],
    ['page' => 'branch-comparison', 'label' => $tr('Branch Comparison', 'مقارنة الفروع'), 'icon' => '▥', 'live' => true, 'visible' => AccessControl::allows('branch_comparison.view')],
    ['page' => 'leadership-huddle', 'label' => $tr('Daily Huddle', 'الاجتماع اليومي'), 'icon' => '☷', 'live' => true, 'visible' => AccessControl::allows('leadership_huddle.view')],
    ['page' => 'action-center', 'label' => $tr('Action Center', 'مركز الإجراءات'), 'icon' => '⚠', 'live' => true, 'visible' => AccessControl::allows('action_center.view')],
    ...$diarSidebarItems, // DIAR_6B_2_R3_1_SIDEBAR_ITEMS
    ['page' => 'access-control', 'label' => $tr('Users & Roles', 'المستخدمون والأدوار'), 'icon' => '⚿', 'live' => true, 'visible' => $canManageAccessControl],
];

$nativeSidebarGroups = [
    [
        'key' => 'leadership',
        'label' => $tr('Leadership', 'القيادة والمتابعة'),
        'icon' => '⌂',
        'pages' => ['dashboard', 'branch-comparison', 'leadership-huddle', 'action-center'],
        'active_pages' => ['dashboard', 'branch-comparison', 'leadership-huddle', 'action-center'],
    ],
    [
        'key' => 'finance',
        'label' => $tr('Finance & Revenue', 'المالية والإيرادات'),
        'icon' => '▥',
        'pages' => ['revenue', 'inpatient-daily-revenue', 'inpatient-daily-revenue-settings', 'specialty-finance'],
        'active_pages' => ['revenue', 'inpatient-daily-revenue', 'inpatient-daily-revenue-settings', 'specialty-finance'],
    ],
    [
        'key' => 'clinical',
        'label' => $tr('Clinical Operations', 'العمليات السريرية'),
        'icon' => '✚',
        'pages' => ['visits', 'doctors', 'beds', 'operations', 'lab', 'quality'],
        'active_pages' => ['visits', 'doctors', 'beds', 'operations', 'lab', 'quality'],
    ],
    [
        'key' => 'medication',
        'label' => $tr('Medication Movement Intelligence', 'ذكاء حركات مخزون الأدوية'),
        'icon' => '◇',
        'pages' => $diarSidebarPages, // DIAR_6B_2_R3_1_SIDEBAR_GROUP
        'active_pages' => $diarActivePages, // DIAR_6B_2_R3_1_SIDEBAR_GROUP
    ],
    [
        'key' => 'system',
        'label' => $tr('System', 'النظام والإعدادات'),
        'icon' => '⚙',
        'pages' => ['access-control'],
        'active_pages' => ['access-control'],
    ],
];
$nativeSidebarActiveGroup = 'leadership';
foreach ($nativeSidebarGroups as $nativeSidebarGroup) {
    if (in_array((string)$activePage, $nativeSidebarGroup['active_pages'], true)) {
        $nativeSidebarActiveGroup = (string)$nativeSidebarGroup['key'];
        break;
    }
}

$layoutLastUpdatedRaw = '';
if ((string)$activePage === 'action-center') {
    if (isset($center) && is_array($center) && !empty($center['last_updated'])) {
        $layoutLastUpdatedRaw = (string)$center['last_updated'];
    } elseif (isset($lastUpdated) && (string)$lastUpdated !== '') {
        $layoutLastUpdatedRaw = (string)$lastUpdated;
    }
} elseif ((string)$activePage === 'leadership-huddle') {
    if (isset($huddle) && is_array($huddle) && !empty($huddle['last_updated'])) {
        $layoutLastUpdatedRaw = (string)$huddle['last_updated'];
    }
}
$layoutLastUpdatedDisplay = date('H:i');
if ($layoutLastUpdatedRaw !== '' && $layoutLastUpdatedRaw !== '—') {
    $layoutLastUpdatedTs = strtotime($layoutLastUpdatedRaw);
    if ($layoutLastUpdatedTs !== false) {
        $layoutLastUpdatedDisplay = date('H:i', $layoutLastUpdatedTs);
    } elseif (preg_match('/(\d{1,2}):(\d{2})/', $layoutLastUpdatedRaw, $layoutLastUpdatedMatch)) {
        $layoutLastUpdatedDisplay = str_pad($layoutLastUpdatedMatch[1], 2, '0', STR_PAD_LEFT) . ':' . $layoutLastUpdatedMatch[2];
    }
}
$diarInitialHtmlClass = $isDiarPremiumPage
    ? 'native-sidebar-enhanced diar-sidebar-r5-stable diar-initial-render-r1-3'
    : '';
$diarInitialRenderState = $isDiarPremiumPage ? 'SERVER_READY' : 'NA';
?>
<!doctype html>
<html lang="<?= e($lang) ?>" dir="<?= e($dir) ?>" class="<?= e($diarInitialHtmlClass) ?>" data-diar-initial-render="<?= e($diarInitialRenderState) ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($pageTitle) ?> - <?= e($appName) ?></title>
    <?php if ($isDiarPremiumPage): ?>
    <style id="diar-initial-render-critical-r1-3">
    @media (min-width:761px){
      html.diar-initial-render-r1-3 body[data-native-sidebar-page^="diar-"] .elite-shell[data-native-shell-contract="R4"]{display:grid!important;grid-template-rows:auto!important;align-items:start!important;width:100%!important;min-width:0!important;min-height:100vh!important;margin:0!important;padding:0!important;gap:0!important;overflow:visible!important}
      html[dir="ltr"].diar-initial-render-r1-3 body[data-native-sidebar-page^="diar-"] .elite-shell[data-native-shell-contract="R4"]{grid-template-columns:296px minmax(0,1fr)!important;grid-template-areas:"native-sidebar native-main"!important;direction:ltr!important}
      html[dir="rtl"].diar-initial-render-r1-3 body[data-native-sidebar-page^="diar-"] .elite-shell[data-native-shell-contract="R4"]{grid-template-columns:minmax(0,1fr) 296px!important;grid-template-areas:"native-main native-sidebar"!important;direction:ltr!important}
      html.diar-initial-render-r1-3 body[data-native-sidebar-page^="diar-"] .elite-shell[data-native-shell-contract="R4"]>.elite-main[data-native-main-contract="R4"]{grid-area:native-main!important;grid-row:1!important;align-self:start!important;position:relative!important;top:0!important;inset-block-start:0!important;width:auto!important;min-width:0!important;max-width:none!important;margin:0!important;padding-block-start:0!important;transform:none!important;translate:none!important;overflow-x:clip!important}
      html.diar-initial-render-r1-3 body[data-native-sidebar-page^="diar-"] .elite-main[data-native-main-contract="R4"]>.elite-topbar--diar-premium:first-child{margin-block-start:0!important;top:0!important}
    }
    </style>
    <?php endif; ?> <!-- DIAR_6B_4_R1_3_SERVER_PREPAINT_GEOMETRY -->
    <link rel="stylesheet" href="assets/css/app.css?v=phase10-2-5-elite-reference-ui">
    <link rel="stylesheet" href="assets/css/command-responsive-fix.css?v=phase10-2-6-responsive-command-ui">
    <link rel="stylesheet" href="assets/css/command-laptop-compact-fix.css?v=phase10-2-7-laptop-compact-ui">
    <link rel="stylesheet" href="assets/css/command-clean-executive-refinement.css?v=phase10-2-9-clean-executive-ui">
    <link rel="stylesheet" href="assets/css/command-pixel-perfect-final.css?v=phase10-2-10-pixel-perfect-layout">
    <link rel="stylesheet" href="assets/css/command-patient-flow-no-overlap.css?v=phase10-2-11-flow-no-overlap">
    <link rel="stylesheet" href="assets/css/command-phase10-3-4-final-polish.css?v=phase10-3-4-beds-unit-header-polish">
    <link rel="stylesheet" href="assets/css/command-operational-day.css?v=phase10-3-5-operational-day">
    <link rel="stylesheet" href="assets/css/action-center.css?v=phase10-6-6-governance-ownership-followup">
    <link rel="stylesheet" href="assets/css/leadership-huddle.css?v=phase10-7-2-executive-leadership-readability">
    <link rel="stylesheet" href="assets/css/revenue-executive-parity.css?v=phase10-9-2-revenue-chart-executive-closure">
    <link rel="stylesheet" href="assets/css/patient-activity-executive-parity.css?v=h11-0-p11-1-r32-visits-full-matrix-hotfix">
    <link rel="stylesheet" href="assets/css/operations-executive-parity.css?v=h11-0-p11-1-r37-operations-executive-decision-redesign">
    <?php if ($activePage === 'operations'): ?>
        <link rel="stylesheet" href="assets/css/operations-executive-redesign.css?v=11.0.11.86-r45-p9-2-light-summary-semantic-colors">
    <?php endif; ?>
    <link rel="stylesheet" href="assets/css/diagnostics-executive-parity.css?v=h11-0-p11-1-r38-diagnostics-executive-decision-redesign">
    <?php if ($activePage === 'lab'): ?>
        <link rel="stylesheet" href="assets/css/diagnostics-executive-redesign.css?v=11.0.11.85-r45-p10-1-light-summary-semantic-colors">
    <?php endif; ?>
    <link rel="stylesheet" href="assets/css/doctors-executive-parity.css?v=11.0.13.1-p13-0-1-specialty-recovery">
    <link rel="stylesheet" href="assets/css/beds-executive-parity.css?v=11.0.11.79-r45-p8-2-full-comparison-view">
    <?php if ($activePage === 'beds'): ?>
        <link rel="stylesheet" href="assets/css/beds-executive-redesign.css?v=11.0.11.87-r45-p8-4-light-summary-semantic-colors">
    <?php endif; ?>
    <link rel="stylesheet" href="assets/css/specialty-finance-executive-parity.css?v=11.0.12.4-p12-1-2-all-specialties">
    <?php if ($activePage === 'branch-comparison'): ?>
        <link rel="stylesheet" href="assets/css/branch-comparison.css?v=11.0.11.99-r45-p11-3-1-php7-hotfix">
    <?php endif; ?>
    <?php if ($activePage === 'access-control'): ?>
        <link rel="stylesheet" href="assets/css/access-control.css?v=11.0.14.2-p14-2-role-management">
    <?php endif; ?>
    <?php if ($activePage === 'diar-rules'): ?>
        <link rel="stylesheet" href="assets/css/diar-rules.css?v=diar-ui3-r1-workspace">
    <?php endif; ?>
    <?php if (in_array($activePage, ['diar-investigations','diar-investigation','diar-case-evidence'], true)): ?>
        <link rel="stylesheet" href="assets/css/diar-investigations.css?v=diar-6b3-r3">
        <link rel="stylesheet" href="assets/css/diar-investigation-workflow-r4.css?v=diar-6b4-r1">
    <?php endif; ?>
    <?php if ($activePage === 'diar-case-evidence'): ?>
        <link rel="stylesheet" href="assets/css/diar-case-evidence.css?v=diar-6b3-r3">
    <?php endif; ?>
    <?php if (in_array($activePage, ['diar-command-center','diar-engine-runs','diar-movement-dictionary','diar-daily-facts','diar-statistical-profiles','diar-anomaly-candidates','diar-investigations','diar-investigation','diar-case-evidence','diar-rules'], true)): ?>
        <link rel="stylesheet" href="assets/css/diar-command-center.css?v=diar-ui4-r1">
        <link rel="stylesheet" href="assets/css/diar-functional-clarity.css?v=diar-ui4-r1">
    <?php endif; ?> <!-- DIAR_UI1_CSS_V1 --> <!-- DIAR4B_CSS_V1 -->
    <?php if ($isDiarPremiumPage): ?>
        <link rel="stylesheet" href="assets/css/diar-premium-shell.css?v=diar-6b-2-r3-1">
    <?php endif; ?> <!-- DIAR_6B_2_R3_1_PREMIUM_SHELL_CSS -->
    <link rel="stylesheet" href="assets/css/executive-ui-core.css?v=11.0.11.77-r45-p7-1-2-doctors-layout">
    <link rel="stylesheet" href="assets/css/dashboard-executive-command.css?v=h11-0-p11-1-r42-legacy-kpi-parity-live-reconciliation-closure">
    <link rel="stylesheet" href="assets/css/ddb-echarts.css?v=h11-0-p11-1-r27">
    <?php if (in_array($activePage, ['inpatient-daily-revenue', 'inpatient-daily-revenue-settings'], true)): ?>
        <link rel="stylesheet" href="assets/css/inpatient-daily-revenue.css?v=h11-0-p11-1-r27">
    <?php endif; ?>
    <script src="assets/vendor/echarts/echarts.min.js?v=6.1.0" defer></script>
    <script src="assets/js/ddb-echarts-adapter.js?v=11.0.11.83-r45-p9-1-compare-hover-stability" defer></script>
    <script src="assets/js/charts.js?v=h11-0-p11-1-r22" defer></script>
    <script src="assets/js/executive-ui.js?v=h11-0-p11-1-r22-professional-chart-engine" defer></script>
    <?php if ($activePage === 'inpatient-daily-revenue'): ?>
        <script src="assets/js/inpatient-daily-revenue.js?v=h11-0-p11-1-r12" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'beds'): ?>
        <script src="assets/js/beds-comparison.js?v=11.0.11.80-r45-p8-3-executive-redesign" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'operations'): ?>
        <script src="assets/js/operations-comparison.js?v=11.0.11.83-r45-p9-1-ranking-header" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'lab'): ?>
        <script src="assets/js/diagnostics-comparison.js?v=11.0.11.84-r45-p10-fair-executive" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'branch-comparison'): ?>
        <script src="assets/js/branch-comparison.js?v=11.0.11.99-r45-p11-3-1-php7-hotfix" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'specialty-finance'): ?>
        <script src="assets/js/specialty-finance-activity.js?v=11.0.12.4-p12-1-2-all-specialties" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'doctors'): ?>
        <script src="assets/js/doctors-specialty-filter.js?v=11.0.13.1-p13-0-1-specialty-recovery" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'access-control'): ?>
        <script src="assets/js/access-control.js?v=11.0.14.2-p14-2-role-management" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'diar-rules'): ?>
        <script src="assets/js/diar-rules.js?v=diar-ui3-r1-workspace" defer></script>
    <?php endif; ?>
    <?php if (in_array($activePage, ['diar-investigations','diar-investigation'], true)): ?>
        <script src="assets/js/diar-investigations.js?v=diar-6b3-r3" defer></script>
        <script src="assets/js/diar-investigation-workflow-r4.js?v=diar-6b4-r1" defer></script>
    <?php endif; ?>
    <?php if ($activePage === 'diar-case-evidence'): ?>
        <script src="assets/js/diar-case-evidence.js?v=diar-6b3-r3" defer></script>
    <?php endif; ?>
    <?php if (in_array($activePage, ['diar-command-center','diar-engine-runs','diar-movement-dictionary','diar-daily-facts','diar-statistical-profiles','diar-anomaly-candidates'], true)): ?>
        <script src="assets/js/diar-command-center.js?v=diar-ui3-r0" defer></script>
    <?php endif; ?> <!-- DIAR_UI1_JS_V1 DIAR_UI1_R2_ASSET_CLOSURE_V1 DIAR_UI1_R3_MODULE_NAVIGATION_CLOSURE_V1 DIAR_UI1_R3_ARABIC_RTL_SIDEBAR_CLOSURE_V1 --> <!-- DIAR4B_JS_V1 -->
    <link rel="stylesheet" href="assets/css/native-executive-sidebar.css?v=native-sidebar-r4"> <!-- NATIVE_EXECUTIVE_SIDEBAR_R4_CSS -->
    <?php if ($isDiarPremiumPage): ?>
        <link rel="stylesheet" href="assets/css/diar-premium-stabilization.css?v=diar-6b-2-r3-1-1">
        <link rel="stylesheet" href="assets/css/diar-sidebar-r5-root-stability.css?v=diar-6b-2-r3-1-2">
        <link rel="stylesheet" href="assets/css/diar-navigation-closure.css?v=diar-6b-2-r3-1-3">
        <link rel="stylesheet" href="assets/css/diar-evidence-rtl-closure.css?v=diar-6b3-r3">
        <link rel="stylesheet" href="assets/css/diar-rtl-physical-placement-r3-1.css?v=diar-6b3-r3-1">
        <link rel="stylesheet" href="assets/css/diar-ltr-top-gap-closure-r1-2.css?v=diar-6b4-r1-2"> <!-- DIAR_6B_4_R1_2_LTR_TOP_GAP_CLOSURE -->
        <link rel="stylesheet" href="assets/css/diar-initial-render-evidence-r1-3.css?v=diar-6b4-r1-3"> <!-- DIAR_6B_4_R1_3_INITIAL_RENDER_EVIDENCE_CSS -->
    <?php endif; ?> <!-- DIAR_6B_2_R3_1_1_STABILIZATION_CSS --> <!-- DIAR_6B_2_R3_1_2_ROOT_STABILITY_CSS --> <!-- DIAR_6B_2_R3_1_3_NAV_CSS -->
    <?php if ($isDiarPremiumPage): ?>
    <link rel="stylesheet" href="assets/css/diar-user-language-r26.css?v=diar-6b5-r2-6"> <!-- DIAR_6B_5_R2_6_EXECUTIVE_LANGUAGE_CSS -->
    <?php endif; ?>
</head>
<body class="app-body elite-body exec-shell-v2 page-<?= e((string)$activePage) ?>" data-exec-ui-contract="v2" data-native-sidebar-page="<?= e((string)$activePage) ?>" data-native-sidebar-release="R4" data-diar-direction="<?= e($dir) ?>" data-diar-browser-contract="6B.4-R1.3">
<div class="elite-mobile-bar">
    <button type="button" class="elite-icon-button" data-sidebar-toggle aria-label="Menu">☰</button>
    <img src="<?= e($wideLogo) ?>" alt="HMH" class="elite-mobile-logo">
    <a class="elite-lang-small" href="<?= e(lang_url(opposite_lang())) ?>"><?= e(strtoupper(opposite_lang())) ?></a>
</div>

<div class="elite-shell" data-native-shell data-native-shell-contract="R4">
    <aside class="elite-sidebar native-sidebar-skin" data-sidebar data-native-sidebar data-native-sidebar-release="R4" data-native-sidebar-contract="R4">
        <a class="elite-brand" href="<?= e(url_to('dashboard')) ?>">
            <span class="elite-brand-mark"><img src="<?= e($corporateLogo) ?>" alt="HMH"></span>
            <span>
                <strong>HMH</strong>
                <small><?= e($tr('Executive Healthcare Platform', 'منصة الرعاية الصحية التنفيذية')) ?></small>
            </span>
        </a>

        <nav class="elite-nav native-nav" aria-label="<?= e($tr('Main navigation', 'التنقل الرئيسي')) ?>" data-native-nav>
            <?php foreach ($nativeSidebarGroups as $group): ?>
                <?php
                $groupItems = array_values(array_filter($navItems, static function (array $item) use ($group): bool {
                    if (!in_array((string)($item['page'] ?? ''), $group['pages'], true)) return false;
                    return !isset($item['visible']) || (bool)$item['visible'];
                }));
                if ($groupItems === []) continue;
                $groupOpen = $nativeSidebarActiveGroup === $group['key'];
                $groupId = 'native-nav-group-' . $group['key'];
                ?>
                <section class="native-nav-group native-nav-group--<?= e($group['key']) ?><?= $groupOpen ? ' is-open' : '' ?>" data-nav-group="<?= e($group['key']) ?>">
                    <button type="button"
                            class="native-nav-group-toggle"
                            aria-expanded="<?= $groupOpen ? 'true' : 'false' ?>"
                            aria-controls="<?= e($groupId) ?>"
                            data-nav-group-toggle>
                        <span class="native-nav-group-icon" aria-hidden="true"><?= e($group['icon']) ?></span>
                        <b><?= e($group['label']) ?></b>
                        <span class="native-nav-count"><?= count($groupItems) ?></span>
                        <span class="native-nav-chevron" aria-hidden="true">⌄</span>
                    </button>
                    <div class="native-nav-group-items" id="<?= e($groupId) ?>" data-nav-group-items>
                        <?php foreach ($groupItems as $item): ?>
                            <?php if ($item['live']): ?>
                                <a class="native-nav-item<?= $activePage === $item['page'] ? ' active' : '' ?>"
                                   href="<?= e(url_to($item['page'])) ?>"
                                   <?= $activePage === $item['page'] ? 'aria-current="page"' : '' ?>>
                                    <span class="native-nav-item-icon" aria-hidden="true"><?= e($item['icon']) ?></span>
                                    <b><?= e($item['label']) ?></b>
                                    <?php if ($activePage === $item['page']): ?><i aria-hidden="true"></i><?php endif; ?>
                                </a>
                            <?php else: ?>
                                <a class="native-nav-item disabled" href="#" aria-disabled="true" tabindex="-1">
                                    <span class="native-nav-item-icon" aria-hidden="true"><?= e($item['icon']) ?></span>
                                    <b><?= e($item['label']) ?></b>
                                    <em><?= e($tr('Soon', 'قريبًا')) ?></em>
                                </a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>
        </nav>

        <section class="elite-sidebar-card">
            <span><?= e($tr('Active Branch', 'الفرع النشط')) ?></span>
            <strong><?= e($currentHospitalDisplay) ?></strong>
            <small><i></i><?= e($tr('Available', 'متاح')) ?></small>
            <button type="button" data-branch-open><?= e($tr('Change branch', 'تغيير الفرع')) ?></button>
        </section>

        <section class="elite-sidebar-card source-card">
            <span><?= e($tr('System Status', 'حالة النظام')) ?></span>
            <strong>Hospital Information System</strong>
            <small><i></i><?= e($tr('Available', 'متاح')) ?></small>
        </section>

        <div class="elite-sidebar-footer">
            <img src="<?= e($corporateLogo) ?>" alt="HMH">
        </div>
    </aside>

    <main class="elite-main" data-native-main data-native-main-contract="R4">
        <header class="elite-topbar<?= in_array($activePage, ['operations', 'lab', 'beds', 'branch-comparison', 'specialty-finance', 'doctors'], true) ? ' elite-topbar--flow-safe' : '' ?><?= $isDiarPremiumPage ? ' elite-topbar--diar-premium' : '' ?>">
            <div class="elite-title-block">
                <h1><?= e($pageTitle) ?></h1>
                <?php if (isset($diarLayoutDescriptions[$activePage])): ?>
                    <p><?= e($diarLayoutDescriptions[$activePage]) ?></p>
                <?php else: ?>
                <p><?= e($activePage === 'dashboard' ? $tr('Hospital performance, risk and decision priorities at a glance.', 'أداء المستشفى والمخاطر وأولويات القرار بنظرة واحدة.') : ($activePage === 'action-center' ? $tr('Ownership, due dates, escalation and follow-up for executive actions.', 'المسؤوليات والمواعيد والتصعيد والمتابعة للإجراءات التنفيذية.') : ($activePage === 'leadership-huddle' ? $tr('Daily leadership agenda, commitments and decisions.', 'أجندة القيادة اليومية والالتزامات والقرارات.') : ($activePage === 'revenue' ? t('revenue.layout_description') : ($activePage === 'inpatient-daily-revenue-settings' ? $tr('Branch-specific payer values managed in one place.', 'إدارة قيم جهات الدفع الخاصة بكل فرع من مكان واحد.') : ($activePage === 'inpatient-daily-revenue' ? $tr('Current inpatient census, daily revenue and key revenue signals for leadership review.', 'التعداد الحالي للمرضى المنومين والإيراد اليومي وأهم مؤشرات الإيراد لمراجعة الإدارة العليا.') : ($activePage === 'visits' ? t('visits.layout_description') : ($activePage === 'operations' ? t('operations.layout_description') : ($activePage === 'lab' ? t('diagnostics.layout_description') : ($activePage === 'doctors' ? t('doctors.layout_description') : ($activePage === 'beds' ? $tr('Executive bed capacity, unit efficiency and availability at a glance.', 'السعة التنفيذية للأسرة وكفاءة الوحدات والتوافر بنظرة سريعة.') : ($activePage === 'branch-comparison' ? $tr('See which named services increased or decreased in each branch.', 'معرفة الخدمات التي ارتفعت أو انخفضت في كل فرع.') : ($activePage === 'specialty-finance' ? $tr('Revenue, admissions and outpatient activity by specialty.', 'الإيرادات والدخول وزيارات العيادات الخارجية حسب التخصص في عرض تنفيذي.') : ($activePage === 'diar-rules' ? $tr('Governed thresholds, signal weights and approval history for medication inventory risk review.', 'الحدود المحكومة وأوزان مؤشرات المراجعة وسجل الاعتماد لمراجعة مخاطر مخزون الأدوية.') : t('layout.description'))))))))))))))) ?></p>
                <?php endif; ?>
            </div>

            <button type="button" class="elite-branch-select" data-branch-open>
                <span>⌖</span>
                <b><?= e($currentHospitalDisplay) ?></b>
                <small><?= e($tr('Current Branch', 'الفرع الحالي')) ?></small>
            </button>

            <form class="elite-search" action="index.php" method="get">
                <input type="hidden" name="page" value="<?= e((string)$activePage ?: 'dashboard') ?>">
                <input type="hidden" name="lang" value="<?= e($lang) ?>">
                <input name="q" placeholder="<?= e($isDiarPremiumPage ? $tr('Search dashboards, reports, cases, stores...', 'ابحث في اللوحات والتقارير والحالات والمخازن...') : $tr('Search dashboards, reports, patients...', 'ابحث في اللوحات والتقارير...')) ?>">
                <button type="submit">⌕</button>
            </form>

            <div class="elite-meta">
                <span><?= e($tr('Last updated', 'آخر تحديث')) ?></span>
                <strong><?= e($layoutLastUpdatedDisplay) ?></strong>
            </div>

            <a class="elite-lang" href="<?= e(lang_url(opposite_lang())) ?>"><?= e($isAr ? 'English' : 'العربية') ?></a>

            <div class="elite-user">
                <span><?= e(strtoupper((string)$userInitial)) ?></span>
                <div>
                    <strong><?= e($userName) ?></strong>
                    <small><?= e(AccessControl::roleLabel()) ?></small>
                    <a href="<?= e(url_to('logout')) ?>"><?= e($tr('Logout', 'خروج')) ?></a>
                </div>
            </div>
        </header>
        <?php if ($diarContextTabs !== []): ?>
            <nav class="diar-context-nav" aria-label="<?= e($tr('DIAR section pages', 'صفحات قسم DIAR')) ?>" data-diar-context-nav> <!-- DIAR_6B_3_R3_CONTEXT_NAV -->
                <div class="diar-context-breadcrumb">
                    <a class="diar-context-home" href="<?= e(url_to('diar-portal')) ?>"><?= e($tr('Medication Risk Intelligence', 'منظومة ذكاء مخاطر الأدوية')) ?></a>
                    <span aria-hidden="true">›</span>
                </div>
                <div class="diar-context-tabs">
                    <?php foreach ($diarContextTabs as $diarContextTab): ?>
                        <a class="<?= !empty($diarContextTab['active']) ? 'active' : '' ?>" href="<?= e(url_to((string)$diarContextTab['page'], (array)($diarContextTab['params'] ?? []))) ?>" <?= !empty($diarContextTab['active']) ? 'aria-current="page"' : '' ?>><?= e((string)$diarContextTab['label']) ?></a>
                    <?php endforeach; ?>
                </div>
            </nav>
        <?php endif; ?>

        <?= $content ?>
    </main>
</div>

<div class="sidebar-scrim" data-sidebar-close></div>

<div class="branch-modal" data-branch-modal aria-hidden="true">
    <div class="branch-backdrop" data-branch-close></div>
    <section class="branch-dialog aluminum-dialog" role="dialog" aria-modal="true">
        <button type="button" class="modal-close" data-branch-close aria-label="Close">×</button>
        <span class="overline"><?= e($tr('Branch Context', 'سياق الفرع')) ?></span>
        <h2><?= e($tr('Change active branch', 'تغيير الفرع النشط')) ?></h2>
        <p><?= e($tr('Choose from branches approved for live dashboard use.', 'اختر من الفروع المعتمدة للاستخدام الحي في لوحات المعلومات.')) ?></p>

        <form method="post" action="<?= e(url_to('switch-hospital')) ?>" class="branch-form aluminum-form">
            <?= Csrf::field() ?>
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <input type="hidden" name="redirect_to" value="<?= e($currentRelativeUrl) ?>">
            <div class="branch-options">
                <?php foreach ($liveHospitals as $code => $hospital): ?>
                    <?php $isActiveBranch = ((string)$code === $currentHospitalCode); ?>
                    <?php $optionLogo = $branchLogoMap[strtolower((string)$code)] ?? $corporateLogo; ?>
                    <label class="branch-option <?= $isActiveBranch ? 'selected' : '' ?>">
                        <input type="radio" name="hospital" value="<?= e((string)$code) ?>" <?= $isActiveBranch ? 'checked' : '' ?>>
                        <span class="branch-icon branch-logo-token"><img src="<?= e($optionLogo) ?>" alt="<?= e($hospital['name'] ?? (string)$code) ?>"></span>
                        <span class="branch-option-copy">
                            <strong><?= e($hospital['name'] ?? (string)$code) ?></strong>
                            <small><?= e(strtoupper((string)$code)) ?></small>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>
            <button class="btn primary full" type="submit"><?= e($tr('Apply branch', 'تطبيق الفرع')) ?></button>
        </form>
    </section>
</div>

<script>
(function () {
  const body = document.body;
  document.querySelectorAll('[data-sidebar-toggle]').forEach(btn => btn.addEventListener('click', () => body.classList.toggle('sidebar-open')));
  document.querySelectorAll('[data-sidebar-close]').forEach(btn => btn.addEventListener('click', () => body.classList.remove('sidebar-open')));
  const modal = document.querySelector('[data-branch-modal]');
  const open = () => { if (modal) { modal.classList.add('open'); modal.setAttribute('aria-hidden', 'false'); } };
  const close = () => { if (modal) { modal.classList.remove('open'); modal.setAttribute('aria-hidden', 'true'); } };
  document.querySelectorAll('[data-branch-open]').forEach(btn => btn.addEventListener('click', open));
  document.querySelectorAll('[data-branch-close]').forEach(btn => btn.addEventListener('click', close));
})();
</script>
    <?php if ($isDiarPremiumPage): ?>
        <script src="assets/js/native-executive-sidebar-r5-stable.js?v=diar-sidebar-r5-stable" defer></script>
    <?php else: ?>
    <script src="assets/js/native-executive-sidebar.js?v=native-sidebar-r4" defer></script> <!-- NATIVE_EXECUTIVE_SIDEBAR_R4_JS -->
    <?php endif; ?> <!-- DIAR_6B_2_R3_1_2_ROOT_STABILITY_JS -->
    <?php if ($isDiarPremiumPage): ?>
        <script src="assets/js/diar-premium-stabilization.js?v=diar-6b-2-r3-1-1" defer></script>
        <script src="assets/js/diar-evidence-rtl-closure.js?v=diar-6b3-r3" defer></script>
        <script src="assets/js/diar-rtl-geometry-audit-r3-1.js?v=diar-6b3-r3-1" defer></script>
        <script src="assets/js/diar-ltr-top-gap-audit-r1-2.js?v=diar-6b4-r1-2" defer></script> <!-- DIAR_6B_4_R1_2_LTR_TOP_GAP_AUDIT -->
        <script src="assets/js/diar-initial-render-evidence-r1-3.js?v=diar-6b4-r1-3" defer></script> <!-- DIAR_6B_4_R1_3_INITIAL_RENDER_GATE -->
    <?php endif; ?> <!-- DIAR_6B_3_R3_RTL_BROWSER_JS -->
    <?php if ($isDiarPremiumPage): ?>
    <script src="assets/js/diar-user-language-r26.js?v=diar-6b5-r2-6" defer></script> <!-- DIAR_6B_5_R2_6_EXECUTIVE_LANGUAGE_JS -->
    <?php endif; ?>
</body>
</html>
