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

$user = Auth::user();
$canAccessRevenue = (int)($user['dashboard_role_revenue'] ?? 0) === 1;
$appName = config('app.name', 'HMH Dashboard');
$activePage = $activePage ?? '';
$hospitals = config('hospitals', []);
$currentHospitalCode = Auth::hospital();
$currentHospital = $hospitals[$currentHospitalCode] ?? config('hospitals.' . $currentHospitalCode, []);
$lang = current_lang();
$dir = current_dir();
$isAr = $lang === 'ar';
$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'),
    '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'),
    'action-center' => $tr('Executive Action Center', 'مركز الإجراءات التنفيذي'),
    'leadership-huddle' => $tr('Leadership Huddle', 'اجتماع القيادة'),
];
$pageTitle = $pageTitleMap[$activePage] ?? ($title ?? $appName);
$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],
    ['page' => 'revenue', 'label' => $tr('Revenue', 'الإيرادات'), 'icon' => '◈', 'live' => true, 'visible' => $canAccessRevenue],
    ['page' => 'specialty-finance', 'label' => $tr('Specialty Finance', 'المالية حسب التخصص'), 'icon' => '◆', 'live' => true, 'visible' => $canAccessRevenue],
    ['page' => 'visits', 'label' => $tr('Visits', 'الزيارات'), 'icon' => '♧', 'live' => true],
    ['page' => 'doctors', 'label' => $tr('Doctors', 'الأطباء'), 'icon' => '♙', 'live' => true],
    ['page' => 'beds', 'label' => $tr('Beds & Capacity', 'الأسرة والسعة'), 'icon' => '▱', 'live' => true],
    ['page' => 'operations', 'label' => $tr('Operations', 'العمليات'), 'icon' => '✦', 'live' => true],
    ['page' => 'lab', 'label' => $tr('Lab & Radiology', 'المختبر والأشعة'), 'icon' => '⌬', 'live' => true],
    ['page' => 'quality', 'label' => $tr('Quality & Safety', 'الجودة والسلامة'), 'icon' => '◇', 'live' => false],
    ['page' => 'branch-comparison', 'label' => $tr('Branch Comparison', 'مقارنة الفروع'), 'icon' => '▥', 'live' => false],
    ['page' => 'leadership-huddle', 'label' => $tr('Daily Huddle', 'الاجتماع اليومي'), 'icon' => '☷', 'live' => true],
    ['page' => 'action-center', 'label' => $tr('Action Center', 'مركز الإجراءات'), 'icon' => '⚠', 'live' => true],
];

$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];
    }
}
?>
<!doctype html>
<html lang="<?= e($lang) ?>" dir="<?= e($dir) ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($pageTitle) ?> - <?= e($appName) ?></title>
    <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=phase10-10-patient-activity-parity">
    <link rel="stylesheet" href="assets/css/operations-executive-parity.css?v=phase10-11-operations-recovery">
    <link rel="stylesheet" href="assets/css/diagnostics-executive-parity.css?v=phase10-12-lab-radiology-recovery">
    <link rel="stylesheet" href="assets/css/doctors-executive-parity.css?v=phase10-13-doctors-legacy-parity">
    <link rel="stylesheet" href="assets/css/beds-executive-parity.css?v=phase10-14-beds-units-legacy-parity">
    <link rel="stylesheet" href="assets/css/specialty-finance-executive-parity.css?v=phase10-15-specialty-finance-recovery">
    <link rel="stylesheet" href="assets/css/executive-ui-core.css?v=h11-0-p5-1-global-executive-ui-contract-v2">
    <script src="assets/js/charts.js?v=phase10-15-specialty-finance-recovery" defer></script>
    <script src="assets/js/executive-ui.js?v=phase10-15-2-executive-ui-foundation" defer></script>
</head>
<body class="app-body elite-body exec-shell-v2 page-<?= e((string)$activePage) ?>" data-exec-ui-contract="v2">
<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">
    <aside class="elite-sidebar" data-sidebar>
        <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('Madina National Hospital', 'مستشفيات المدينة الوطني')) ?></small>
            </span>
        </a>

        <nav class="elite-nav" aria-label="Main navigation">
            <?php foreach ($navItems as $item): ?>
                <?php if (isset($item['visible']) && !$item['visible']) continue; ?>
                <?php if ($item['live']): ?>
                    <a class="<?= $activePage === $item['page'] ? 'active' : '' ?>" href="<?= e(url_to($item['page'])) ?>">
                        <span><?= e($item['icon']) ?></span><b><?= e($item['label']) ?></b>
                    </a>
                <?php else: ?>
                    <a class="disabled" href="#" aria-disabled="true">
                        <span><?= e($item['icon']) ?></span><b><?= e($item['label']) ?></b><em><?= e($tr('Soon', 'قريبًا')) ?></em>
                    </a>
                <?php endif; ?>
            <?php endforeach; ?>
        </nav>

        <section class="elite-sidebar-card">
            <span><?= e($tr('Active Branch', 'الفرع النشط')) ?></span>
            <strong><?= e($currentHospital['name'] ?? strtoupper($currentHospitalCode)) ?></strong>
            <small><i></i><?= e($tr('Connected', 'متصل')) ?></small>
            <button type="button" data-branch-open><?= e($tr('Change branch', 'تغيير الفرع')) ?></button>
        </section>

        <section class="elite-sidebar-card source-card">
            <span><?= e($tr('Data Source', 'مصدر البيانات')) ?></span>
            <strong>Oracle HIS</strong>
            <small><i></i><?= e($tr('Live connection', 'اتصال مباشر')) ?></small>
        </section>

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

    <main class="elite-main">
        <header class="elite-topbar">
            <div class="elite-title-block">
                <h1><?= e($pageTitle) ?></h1>
                <p><?= e($activePage === 'dashboard' ? $tr('Phase 10.4 — Executive Action Center Enabled', 'المرحلة 10.4 — تفعيل مركز الإجراءات التنفيذي') : ($activePage === 'action-center' ? $tr('Phase 10.6.6 — Governance, Ownership & Follow-up Management', 'المرحلة 10.6.6 — الحوكمة والمسؤولية وإدارة المتابعة') : ($activePage === 'leadership-huddle' ? $tr('Phase 10.7.2 — Executive Leadership Readability', 'المرحلة 10.7.2 — وضوح القراءة للإدارة العليا') : ($activePage === 'revenue' ? t('revenue.layout_description') : ($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 === 'specialty-finance' ? $tr('Executive MOH, drug and net revenue contribution by specialty.', 'مساهمة وزارة الصحة والأدوية وصافي الإيراد حسب التخصص في عرض تنفيذي.') : t('layout.description'))))))))))) ?></p>
            </div>

            <button type="button" class="elite-branch-select" data-branch-open>
                <span>⌖</span>
                <b><?= e($currentHospital['name'] ?? strtoupper($currentHospitalCode)) ?></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($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>
                    <a href="<?= e(url_to('logout')) ?>"><?= e($tr('Logout', 'خروج')) ?></a>
                </div>
            </div>
        </header>

        <?= $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 the operational branch. All dashboards will use this context after login.', 'اختر الفرع التشغيلي، وستعمل جميع اللوحات وفق هذا السياق بعد تسجيل الدخول.')) ?></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 ($hospitals 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>
</body>
</html>
