<?php
// ============================================================
// includes/layout.php — وظائف التخطيط المشترك
// ============================================================

// ── Language helper ──────────────────────────────────────────
function getLang(): string {
    return $_COOKIE['kadiyati_lang'] ?? 'ar';
}

$LAYOUT_LABELS = [
    'ar' => [
        'brand'      => 'قضيتي',
        'brand_sub'  => 'نظام القضايا',
        'dashboard'  => 'لوحة التحكم',
        'users'      => 'إدارة المستخدمين',
        'lawyers'    => 'مراجعة المحامين',
        'create_clerk' => 'إنشاء حساب كاتب',
        'reports'    => 'التقارير',
        'audit'      => 'سجل التدقيق',
        'cases'      => 'القضايا',
        'sessions'   => 'الجلسات',
        'minutes'    => 'المحاضر',
        'judgments'  => 'الأحكام',
        'appeals'    => 'الاستئناف',
        'documents'  => 'الوثائق',
        'my_cases'   => 'قضاياي',
        'profile'    => 'ملفي الشخصي',
        'role_admin'  => 'مدير النظام',
        'role_clerk'  => 'أمين الضبط',
        'role_lawyer' => 'محامي',
        'notifs'     => 'الإشعارات',
        'mark_read'  => 'تحديد الكل كمقروء',
        'loading'    => 'جاري التحميل...',
        'dir'        => 'rtl',
        'lang'       => 'ar',
    ],
    'fr' => [
        'brand'      => 'Kadiyati',
        'brand_sub'  => 'Gestion Judiciaire',
        'dashboard'  => 'Tableau de bord',
        'users'      => 'Utilisateurs',
        'lawyers'    => 'Avocats',
        'create_clerk' => 'Créer un greffier',
        'reports'    => 'Rapports',
        'audit'      => 'Journal d\'audit',
        'cases'      => 'Dossiers',
        'sessions'   => 'Audiences',
        'minutes'    => 'Procès-verbaux',
        'judgments'  => 'Jugements',
        'appeals'    => 'Appels',
        'documents'  => 'Documents',
        'my_cases'   => 'Mes dossiers',
        'profile'    => 'Mon profil',
        'role_admin'  => 'Administrateur',
        'role_clerk'  => 'Greffier',
        'role_lawyer' => 'Avocat',
        'notifs'     => 'Notifications',
        'mark_read'  => 'Tout marquer lu',
        'loading'    => 'Chargement...',
        'dir'        => 'rtl',
        'lang'       => 'fr',
    ],
    'en' => [
        'brand'      => 'Kadiyati',
        'brand_sub'  => 'Case Management',
        'dashboard'  => 'Dashboard',
        'users'      => 'Users',
        'lawyers'    => 'Lawyers',
        'create_clerk' => 'Create Clerk',
        'reports'    => 'Reports',
        'audit'      => 'Audit Log',
        'cases'      => 'Cases',
        'sessions'   => 'Sessions',
        'minutes'    => 'Minutes',
        'judgments'  => 'Judgments',
        'appeals'    => 'Appeals',
        'documents'  => 'Documents',
        'my_cases'   => 'My Cases',
        'profile'    => 'My Profile',
        'role_admin'  => 'Administrator',
        'role_clerk'  => 'Court Clerk',
        'role_lawyer' => 'Lawyer',
        'notifs'     => 'Notifications',
        'mark_read'  => 'Mark all as read',
        'loading'    => 'Loading...',
        'dir'        => 'ltr',
        'lang'       => 'en',
    ],
];

function renderHead(string $pageTitle = ''): void {
    global $LAYOUT_LABELS;
    $lang = getLang();
    $lbl  = $LAYOUT_LABELS[$lang] ?? $LAYOUT_LABELS['ar'];
    $dir  = $lbl['dir'];
    $langAttr = $lbl['lang'];
    $baseUrl = BASE_URL;
    $title = $pageTitle ? $pageTitle . ' — ' . APP_NAME : APP_NAME;
    echo <<<HTML
<!DOCTYPE html>
<html lang="{$langAttr}" dir="{$dir}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{$title}</title>
<script>window.APP_BASE='{$baseUrl}';</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=Amiri:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="{$GLOBALS['BASE_URL_CSS']}">
</head>
<body>
HTML;
}

function renderSidebar(string $active = ''): void {
    global $LAYOUT_LABELS;
    $lang = getLang();
    $lbl  = $LAYOUT_LABELS[$lang] ?? $LAYOUT_LABELS['ar'];

    $user = currentUser();
    $role = $user['role'];

    $adminMenu = [
        ['icon' => 'bi-speedometer2',      'label' => $lbl['dashboard'],     'href' => 'dashboard.php',      'key' => 'dashboard'],
        ['icon' => 'bi-people',             'label' => $lbl['users'],         'href' => 'users.php',          'key' => 'users'],
        ['icon' => 'bi-person-check',       'label' => $lbl['lawyers'],       'href' => 'lawyers.php',        'key' => 'lawyers'],
        ['icon' => 'bi-person-plus',        'label' => $lbl['create_clerk'],  'href' => '../admin/create_clerk.php', 'key' => 'create_clerk'],
        ['icon' => 'bi-bar-chart-line',     'label' => $lbl['reports'],       'href' => 'reports.php',        'key' => 'reports'],
        ['icon' => 'bi-shield-check',       'label' => $lbl['audit'],         'href' => 'audit.php',          'key' => 'audit'],
    ];
    $clerkMenu = [
        ['icon' => 'bi-speedometer2',       'label' => $lbl['dashboard'],     'href' => 'dashboard.php',      'key' => 'dashboard'],
        ['icon' => 'bi-folder2-open',       'label' => $lbl['cases'],         'href' => 'cases.php',          'key' => 'cases'],
        ['icon' => 'bi-calendar3',          'label' => $lbl['sessions'],      'href' => 'sessions.php',       'key' => 'sessions'],
        ['icon' => 'bi-journal-text',       'label' => $lbl['minutes'],       'href' => 'minutes.php',        'key' => 'minutes'],
        ['icon' => 'bi-award',              'label' => $lbl['judgments'],     'href' => 'judgments.php',      'key' => 'judgments'],
        ['icon' => 'bi-arrow-repeat',       'label' => $lbl['appeals'],       'href' => 'appeals.php',        'key' => 'appeals'],
        ['icon' => 'bi-file-earmark-arrow-up','label' => $lbl['documents'],   'href' => 'documents.php',      'key' => 'documents'],
    ];
    $lawyerMenu = [
        ['icon' => 'bi-speedometer2',       'label' => $lbl['dashboard'],     'href' => 'dashboard.php',      'key' => 'dashboard'],
        ['icon' => 'bi-folder2-open',       'label' => $lbl['my_cases'],      'href' => 'my-cases.php',       'key' => 'my_cases'],
        ['icon' => 'bi-file-earmark-arrow-up','label' => $lbl['documents'],   'href' => 'documents.php',      'key' => 'documents'],
        ['icon' => 'bi-person-gear',        'label' => $lbl['profile'],       'href' => 'profile.php',        'key' => 'profile'],
    ];

    $menu = match($role) {
        'admin'  => $adminMenu,
        'clerk'  => $clerkMenu,
        'lawyer' => $lawyerMenu,
        default  => []
    };

    $roleLabel = match($role) {
        'admin'  => $lbl['role_admin'],
        'clerk'  => $lbl['role_clerk'],
        'lawyer' => $lbl['role_lawyer'],
        default  => ''
    };

    $brandName = $lbl['brand'];
    $brandSub  = $lbl['brand_sub'];

    $notifCount = getUnreadNotifCount($user['id']);
    $notifBadge = $notifCount > 0 ? "<span class='notif-badge'>{$notifCount}</span>" : '';
    $baseModule = BASE_URL . '/modules/' . $role . '/';

    $items = '';
    foreach ($menu as $item) {
        $isActive = ($active === $item['key']) ? 'active' : '';
        $items .= "<li><a href='{$baseModule}{$item['href']}' class='sidebar-link {$isActive}'><i class='{$item['icon']}'></i><span>{$item['label']}</span></a></li>";
    }

    $initials = mb_substr($user['name'], 0, 1, 'UTF-8');

    echo <<<HTML
<div class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">
      <svg width="24" height="24" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
        <line x1="16" y1="4" x2="16" y2="28" stroke="#0A1628" stroke-width="2.2" stroke-linecap="round"/>
        <line x1="7" y1="7" x2="25" y2="7" stroke="#0A1628" stroke-width="2.2" stroke-linecap="round"/>
        <line x1="7" y1="7" x2="3.5" y2="15" stroke="#0A1628" stroke-width="1.8" stroke-linecap="round"/>
        <line x1="7" y1="7" x2="10.5" y2="15" stroke="#0A1628" stroke-width="1.8" stroke-linecap="round"/>
        <path d="M3 15 Q7 18 11 15" stroke="#0A1628" stroke-width="1.8" fill="none" stroke-linecap="round"/>
        <line x1="25" y1="7" x2="21.5" y2="15" stroke="#0A1628" stroke-width="1.8" stroke-linecap="round"/>
        <line x1="25" y1="7" x2="28.5" y2="15" stroke="#0A1628" stroke-width="1.8" stroke-linecap="round"/>
        <path d="M21 15 Q25 18 29 15" stroke="#0A1628" stroke-width="1.8" fill="none" stroke-linecap="round"/>
        <line x1="11" y1="28" x2="21" y2="28" stroke="#0A1628" stroke-width="2.2" stroke-linecap="round"/>
      </svg>
    </div>
    <div class="brand-text"><span class="brand-name">{$brandName}</span><span class="brand-sub">{$brandSub}</span></div>
  </div>
  <nav class="sidebar-nav">
    <ul class="nav-list">{$items}</ul>
  </nav>
  <div class="sidebar-footer">
    <div class="user-info">
      <div class="user-avatar">{$initials}</div>
      <div class="user-meta">
        <div class="user-name">{$user['name']}</div>
        <div class="user-role">{$roleLabel}</div>
      </div>
    </div>
    <a href="../../includes/logout.php" class="logout-btn" title="تسجيل الخروج"><i class="bi bi-box-arrow-right"></i></a>
  </div>
</div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
HTML;
}

function renderTopbar(string $pageTitle, int $notifCount = 0): void {
    global $LAYOUT_LABELS;
    $lbl   = $LAYOUT_LABELS[getLang()] ?? $LAYOUT_LABELS['ar'];
    $badge = $notifCount > 0 ? "<span class='badge rounded-pill bg-danger'>{$notifCount}</span>" : '';
    $user  = currentUser();
    $notifTitle = $lbl['notifs'];
    $markRead   = $lbl['mark_read'];
    $loading    = $lbl['loading'];
    echo <<<HTML
<header class="topbar">
  <button class="topbar-toggle" id="sidebarToggle"><i class="bi bi-list"></i></button>
  <div class="topbar-title">{$pageTitle}</div>
  <div class="topbar-actions">
    <div style="display:flex;gap:4px;margin-left:8px;">
      <button class="lang-btn-top" onclick="applyLang('ar')" data-lang="ar" style="font-size:11px;padding:4px 9px;border-radius:6px;border:1px solid rgba(201,168,76,.3);background:transparent;color:#7A8A9C;cursor:pointer;font-family:'Cairo',sans-serif;font-weight:700;transition:.2s">ع</button>
      <button class="lang-btn-top" onclick="applyLang('fr')" data-lang="fr" style="font-size:11px;padding:4px 9px;border-radius:6px;border:1px solid rgba(201,168,76,.3);background:transparent;color:#7A8A9C;cursor:pointer;font-family:'Cairo',sans-serif;font-weight:700;transition:.2s">FR</button>
      <button class="lang-btn-top" onclick="applyLang('en')" data-lang="en" style="font-size:11px;padding:4px 9px;border-radius:6px;border:1px solid rgba(201,168,76,.3);background:transparent;color:#7A8A9C;cursor:pointer;font-family:'Cairo',sans-serif;font-weight:700;transition:.2s">EN</button>
    </div>
    <div class="notif-wrap">
      <button class="topbar-icon-btn" id="notifBtn" title="{$notifTitle}">
        <i class="bi bi-bell"></i>{$badge}
      </button>
      <div class="notif-dropdown" id="notifDropdown">
        <div class="notif-header"><span>{$notifTitle}</span><a href="#" id="markAllRead" class="mark-all">{$markRead}</a></div>
        <div id="notifList" class="notif-list"><div class="notif-loading"><i class="bi bi-hourglass-split"></i> {$loading}</div></div>
      </div>
    </div>
    <div class="topbar-user">{$user['name']}</div>
  </div>
</header>
HTML;
}

function renderFoot(): void {
    $jsUrl = BASE_URL . '/public/assets/js/main.js';
    $i18nUrl = BASE_URL . '/public/assets/js/i18n.js';
    echo <<<HTML
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="{$jsUrl}"></script>
<script src="{$i18nUrl}"></script>
<script>
if(typeof initI18n==='function') document.addEventListener('DOMContentLoaded', initI18n);
// Highlight active lang button in topbar
document.addEventListener('DOMContentLoaded', function(){
  var l = localStorage.getItem('kadiyati_lang')||'ar';
  document.querySelectorAll('.lang-btn-top').forEach(function(b){
    if(b.dataset.lang===l){ b.style.background='rgba(201,168,76,.2)'; b.style.color='#C9A84C'; }
  });
});
</script>
</body>
</html>
HTML;
}