<?php
/**
 * Fichier  : views/layout.php
 * Auteur   : KREMER Régis
 * Version  : 2.3.0
 * Date     : 2026-02-26
 * Description : Vue — Layout principal (header, nav, scripts globaux)
 *
 * Changelog :
 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée
 *   v2.1.1 (2026-02-21) — Corrections sécurité (CSRF, MIME, session, migrateSuppliers)
 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,
 *   v2.3.0 (2026-02-26) — Lot 1: menu conditionné par permissions + page Emplacements.
 *                      import CSV, historique prix, bon de livraison multi-lignes
 */
// ================================================================
// STOCKMASTER PRO v4.0 — LAYOUT AVEC SIDEBAR
// Desktop: Sidebar drawer à gauche
// Mobile: Bottom nav + slide menu
// ================================================================
$settings   = getSettings();
$company    = $settings['companyName'] ?? 'StockMaster Pro';
$user       = currentUser();
$role       = $user['role'] ?? 'user';
// ────────────────────────────────────────────────────────────────
// Langue UI (cookie > user > fr) — nécessaire car i18n.js prend
// _SM_LANG_PHP comme source de vérité.
// ────────────────────────────────────────────────────────────────
$supportedLangs = ['fr','en','de','es','it','nl','pt','pl','ru','tr','ar','ja','ko','zh','hi','id','uk'];

$lang = 'fr';

// 1) Cookie (priorité)
if (!empty($_COOKIE['sm_lang'])) {
    $c = strtolower(trim((string)$_COOKIE['sm_lang']));
    if (in_array($c, $supportedLangs, true)) {
        $lang = $c;
    }
}

// 2) Préférence user (si existante) — uniquement si cookie absent ou invalide
if ($lang === 'fr' && !empty($user['lang'])) {
    $u = strtolower(trim((string)$user['lang']));
    if (in_array($u, $supportedLangs, true)) {
        $lang = $u;
    }
}

$isAdminArea = ($role==='admin') || hasPerm('admin.access');
$userName   = $user['name'] ?? 'Utilisateur';
$userInitials = strtoupper(substr($userName, 0, 2));

// ── Traductions PHP pour les éléments rendus côté serveur ──────
// Le sidebar et les titres sont générés par PHP — on les traduit ici
$navLabels = [
    'fr' => ['Accueil','Scanner','Mouvements','Produits','Kits','Réservations','Magasins','Emplacements','Fournisseurs','Marques','Commandes','Inventaires','Alertes','Codes barres','Utilisateurs','Rapports','Pilotage','Paramètres'],
    'en' => ['Home','Scanner','Movements','Products','Kits','Reservations','Warehouses','Locations','Suppliers','Brands','Orders','Inventories','Alerts','Barcodes','Users','Reports','Analytics','Settings'],
    'de' => ['Startseite','Scanner','Bewegungen','Produkte','Kits','Reservierungen','Lager','Standorte','Lieferanten','Marken','Bestellungen','Inventuren','Warnungen','Barcodes','Benutzer','Berichte','Steuerung','Einstellungen'],
    'es' => ['Inicio','Escáner','Movimientos','Productos','Kits','Reservas','Almacenes','Ubicaciones','Proveedores','Marcas','Pedidos','Inventarios','Alertas','Códigos de barras','Usuarios','Informes','Control','Configuración'],
    'it' => ['Home','Scanner','Movimenti','Prodotti','Kit','Prenotazioni','Magazzini','Posizioni','Fornitori','Marche','Ordini','Inventari','Avvisi','Codici a barre','Utenti','Rapporti','Controllo','Impostazioni'],
    'nl' => ['Home','Scanner','Bewegingen','Producten','Kits','Reserveringen','Magazijnen','Locaties','Leveranciers','Merken','Bestellingen','Inventarissen','Waarschuwingen','Barcodes','Gebruikers','Rapporten','Sturing','Instellingen'],
    'pt' => ['Início','Scanner','Movimentos','Produtos','Kits','Reservas','Armazéns','Localizações','Fornecedores','Marcas','Pedidos','Inventários','Alertas','Códigos de barras','Usuários','Relatórios','Controle','Configurações'],
    'pl' => ['Strona główna','Skaner','Ruchy','Produkty','Zestawy','Rezerwacje','Magazyny','Lokalizacje','Dostawcy','Marki','Zamówienia','Inwentarze','Alerty','Kody kreskowe','Użytkownicy','Raporty','Sterowanie','Ustawienia'],
    'ru' => ['Главная','Сканер','Движения','Товары','Комплекты','Резервации','Склады','Местоположения','Поставщики','Марки','Заказы','Инвентари','Оповещения','Штрих-коды','Пользователи','Отчёты','Управление','Настройки'],
    'tr' => ['Ana Sayfa','Tarayıcı','Hareketler','Ürünler','Kitler','Rezervasyonlar','Depolar','Konumlar','Tedarikçiler','Markalar','Siparişler','Envanterler','Uyarılar','Barkodlar','Kullanıcılar','Raporlar','Kontrol','Ayarlar'],
    'ar' => ['الرئيسية','الماسح','الحركات','المنتجات','الأطقم','الحجوزات','المستودعات','المواقع','الموردون','العلامات','الطلبات','المخزون','التنبيهات','الباركود','المستخدمون','التقارير','التحكم','الإعدادات'],
    'ja' => ['ホーム','スキャナ','動き','製品','キット','予約','倉庫','場所','サプライヤー','ブランド','注文','在庫','アラート','バーコード','ユーザー','レポート','制御','設定'],
    'ko' => ['홈','스캐너','이동','제품','키트','예약','창고','위치','공급업체','브랜드','주문','재고','알림','바코드','사용자','보고서','제어','설정'],
    'zh' => ['主页','扫描仪','移动','产品','套件','预订','仓库','位置','供应商','品牌','订单','库存','警报','条形码','用户','报告','控制','设置'],
    'hi' => ['होम','स्कैनर','आवाजाही','उत्पाद','किट','आरक्षण','गोदाम','स्थान','आपूर्तिकर्ता','ब्रांड','ऑर्डर','सूची','अलर्ट','बारकोड','उपयोगकर्ता','रिपोर्ट','नियंत्रण','सेटिंग्स'],
    'id' => ['Beranda','Pemindai','Gerakan','Produk','Kit','Reservasi','Gudang','Lokasi','Pemasok','Merek','Pesanan','Inventaris','Peringatan','Barcode','Pengguna','Laporan','Kontrol','Pengaturan'],
    'uk' => ['Головна','Сканер','Рухи','Товари','Комплекти','Резервації','Склади','Місця','Постачальники','Марки','Замовлення','Інвентарі','Сповіщення','Штрих-коди','Користувачі','Звіти','Керування','Налаштування'],
];
$nl = $navLabels[$lang] ?? $navLabels['fr'];
$navTitles = [
    'fr' => ['Tableau de bord','Produits','Magasins','Mouvements','Inventaires','Scanner','Codes à barres','Rapports','Paramètres','Utilisateurs','Alertes','Fournisseurs','Marques','Bons de commande','Emplacements','Lots','Kits','Réservations','Pilotage','Gestion magasins'],
    'en' => ['Dashboard','Products','Warehouses','Movements','Inventories','Scanner','Barcodes','Reports','Settings','Users','Alerts','Suppliers','Brands','Purchase orders','Locations','Lots','Kits','Reservations','Analytics','Warehouse management'],
    'de' => ['Dashboard','Produkte','Lager','Bewegungen','Inventuren','Scanner','Barcodes','Berichte','Einstellungen','Benutzer','Warnungen','Lieferanten','Marken','Bestellungen','Standorte','Lose','Kits','Reservierungen','Steuerung','Lagerverwaltung'],
    'es' => ['Panel','Productos','Almacenes','Movimientos','Inventarios','Escáner','Códigos de barras','Informes','Configuración','Usuarios','Alertas','Proveedores','Marcas','Pedidos','Ubicaciones','Lotes','Kits','Reservas','Control','Gestión almacenes'],
    'it' => ['Pannello','Prodotti','Magazzini','Movimenti','Inventari','Scanner','Codici a barre','Rapporti','Impostazioni','Utenti','Avvisi','Fornitori','Marche','Ordini','Posizioni','Lotti','Kit','Prenotazioni','Controllo','Gestione magazzini'],
    'nl' => ['Dashboard','Producten','Magazijnen','Bewegingen','Inventarissen','Scanner','Barcodes','Rapporten','Instellingen','Gebruikers','Waarschuwingen','Leveranciers','Merken','Bestellingen','Locaties','Loten','Kits','Reserveringen','Sturing','Magazijnbeheer'],
    'pt' => ['Painel','Produtos','Armazéns','Movimentos','Inventários','Scanner','Códigos de barras','Relatórios','Configurações','Usuários','Alertas','Fornecedores','Marcas','Pedidos','Localizações','Lotes','Kits','Reservas','Controle','Gestão de armazéns'],
    'pl' => ['Panel','Produkty','Magazyny','Ruchy','Inwentarze','Skaner','Kody kreskowe','Raporty','Ustawienia','Użytkownicy','Alerty','Dostawcy','Marki','Zamówienia','Lokalizacje','Partie','Zestawy','Rezerwacje','Sterowanie','Zarządzanie magazynem'],
    'ru' => ['Панель','Товары','Склады','Движения','Инвентари','Сканер','Штрих-коды','Отчёты','Настройки','Пользователи','Оповещения','Поставщики','Марки','Заказы','Местоположения','Партии','Комплекты','Резервации','Управление','Управление складом'],
];
$nt = $navTitles[$lang] ?? $navTitles['fr'];
$titlesKeys = ['dashboard','products','warehouses','movements','inventory','scanner','barcodes','reports','settings','users','alerts','suppliers','brands','orders','locations','lots','kits','reservations','analytics','warehouse-manager','help'];

// Construction sûre : évite array_combine() (warnings → 500 en prod si error_reporting strict)
$titlesTranslated = [];
$fallbackNt = $navTitles['fr'] ?? [];
foreach ($titlesKeys as $i => $k) {
    if (isset($nt[$i]) && $nt[$i] !== '') {
        $titlesTranslated[$k] = $nt[$i];
    } elseif (isset($fallbackNt[$i]) && $fallbackNt[$i] !== '') {
        $titlesTranslated[$k] = $fallbackNt[$i];
    } else {
        // Fallback ultime lisible
        $titlesTranslated[$k] = ucfirst(str_replace(['-','_'],' ', $k));
    }
}
// Helper pour générer les URLs propres
function pageUrl($pageId) {
    // Utiliser les URLs propres si mod_rewrite est actif
    // Fallback vers les URLs classiques sinon
    return $pageId;  // URL propre: /sm/dashboard, /sm/products, etc.
}

// Libellé "Aides" (page help)
$helpLabels = [
    'fr'=>'Aides',
    'en'=>'Help',
    'de'=>'Hilfe',
    'es'=>'Ayuda',
    'it'=>'Aiuto',
    'nl'=>'Hulp',
    'pt'=>'Ajuda',
    'pl'=>'Pomoc',
    'ru'=>'Помощь',
];
$helpLabel = $helpLabels[$lang] ?? 'Aides';

// Navigation items — labels traduits selon $lang
$navAll = [

    ['id'=>'dashboard',    'label'=>$nl[0],  'icon'=>'home'],
    ['id'=>'scanner',      'label'=>$nl[1],  'icon'=>'scan'],
    ['id'=>'movements',    'label'=>$nl[2],  'icon'=>'move'],
    ['id'=>'products',     'label'=>$nl[3],  'icon'=>'box'],
    ['id'=>'kits',         'label'=>$nl[4],  'icon'=>'box'],
    ['id'=>'reservations', 'label'=>$nl[5],  'icon'=>'check'],
    ['id'=>'warehouses',   'label'=>$nl[6],  'icon'=>'warehouse'],
    ['id'=>'locations',    'label'=>$nl[7],  'icon'=>'pin'],
    ['id'=>'suppliers',    'label'=>$nl[8],  'icon'=>'users'],
    ['id'=>'brands',       'label'=>$nl[9],  'icon'=>'tag'],
    ['id'=>'orders',       'label'=>$nl[10], 'icon'=>'clipboard'],
    ['id'=>'inventory',    'label'=>$nl[11], 'icon'=>'check'],
    ['id'=>'alerts',       'label'=>$nl[12], 'icon'=>'bell'],
    ['id'=>'barcodes',     'label'=>$nl[13], 'icon'=>'barcode'],
    ['id'=>'users',        'label'=>$nl[14], 'icon'=>'users'],
    ['id'=>'reports',      'label'=>$nl[15], 'icon'=>'report'],
    ['id'=>'analytics',    'label'=>$nl[16], 'icon'=>'chart'],
    ['id'=>'settings',     'label'=>$nl[17], 'icon'=>'gear'],
    ['id'=>'help',         'label'=>$helpLabel,  'icon'=>'info'],
];

// Filter by permissions/role
if(!$isAdminArea){
    $navAll = array_filter($navAll, fn($n)=>in_array($n['id'],['dashboard','scanner','movements','products']));
}

// Mobile bottom nav: max 5 items
$moreLabel = ['fr'=>'Plus','en'=>'More','de'=>'Mehr','es'=>'Más','it'=>'Altro','nl'=>'Meer','pt'=>'Mais','pl'=>'Więcej','ru'=>'Ещё','tr'=>'Daha','ar'=>'المزيد','ja'=>'もっと','ko'=>'더보기','zh'=>'更多','hi'=>'अधिक','id'=>'Lainnya','uk'=>'Більше'];
$ml = $moreLabel[$lang] ?? 'Plus';
$bottomNav = ($role==='admin')
    ? [
        ['id'=>'dashboard','label'=>$nl[0],'icon'=>'home'],
        ['id'=>'scanner','label'=>$nl[1],'icon'=>'scan'],
        ['id'=>'products','label'=>$nl[3],'icon'=>'box'],
        ['id'=>'movements','label'=>$nl[2],'icon'=>'move'],
        ['id'=>'more','label'=>$ml,'icon'=>'dots'],
      ]
    : [
        ['id'=>'dashboard','label'=>$nl[0],'icon'=>'home'],
        ['id'=>'scanner','label'=>$nl[1],'icon'=>'scan'],
        ['id'=>'products','label'=>$nl[3],'icon'=>'box'],
        ['id'=>'movements','label'=>$nl[2],'icon'=>'move'],
      ];

$pageTitle = $titlesTranslated[$page] ?? ($nl[0] ?? 'Page');

// Count active alerts for badge
$alertBadge = 0;
if($role==='admin'){
    $alerts   = loadData('alerts');
    $stock    = loadData('stock');
    foreach($alerts as $a){
        foreach($stock as $s){
            if((string)($s['productId']??'')===(string)($a['productId']??'')
            && (string)($s['warehouseId']??'')===(string)($a['warehouseId']??'')){
                $qty = (int)($s['quantity']??0);
                if(($a['type']??'')==='min' && $qty<=(int)($a['threshold']??0)) $alertBadge++;
                if(($a['type']??'')==='max' && $qty>=(int)($a['threshold']??0)) $alertBadge++;
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($lang ?? 'fr') ?>" data-theme="<?= htmlspecialchars($theme) ?>" dir="<?= in_array($lang??'fr', ['ar']) ? 'rtl' : 'ltr' ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
<meta name="theme-color" content="#0f172a" id="metaThemeColor">
<meta name="csrf-token" content="<?= csrfToken() ?>">
<title><?= htmlspecialchars($pageTitle) ?> — <?= htmlspecialchars($company) ?></title>
<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=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">

<link rel="stylesheet" href="assets/css/app.css">
<!-- IMPORTANT: styles utilitaires (ex: onglets Rapports, correctifs UI) -->
<link rel="stylesheet" href="assets/css/addons.css">

<!-- Scroll-to-top (isolé, sans dépendre de app.js / App) -->
<link rel="stylesheet" href="assets/css/scrolltop.css">
<!-- Harmonisation design v2.3.0 -->
<link rel="stylesheet" href="assets/css/enhancements.css">
<!-- Page d'aide -->
<link rel="stylesheet" href="assets/css/help.css">
<link rel="stylesheet" href="assets/css/slide-menu.css">
</head>
<body>

<div class="app-shell">
    <!-- ═══════════════════════════════════════════════════════════
         SIDEBAR (Desktop only)
         ═══════════════════════════════════════════════════════════ -->
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-logo">
                <div class="logo-icon" id="sidebarToggle" role="button" tabindex="0" title="Ouvrir/Fermer le menu"><img src="assets/img/sm.png" alt="SM" class="logo-img"></div>
                <span class="logo-text"><?= htmlspecialchars($company) ?></span>
            </div>
        </div>

        <nav class="sidebar-nav">
            <?php foreach($navAll as $n): ?>
            <a href="<?= pageUrl($n['id']) ?>" class="sidebar-link <?= $page===$n['id']?'active':'' ?>" title="<?= htmlspecialchars($n['label']) ?>" data-label="<?= htmlspecialchars($n['label']) ?>">
                <?php if($n['icon'] === 'clipboard'): ?>
                <span class="sidebar-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:100%;height:100%"><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="9" y1="16" x2="13" y2="16"/></svg></span>
                <?php else: ?>
                <span class="sidebar-icon" data-icon="<?= $n['icon'] ?>"></span>
                <?php endif; ?>
                <span class="sidebar-label"><?= htmlspecialchars($n['label']) ?></span>
                <?php if($n['id']==='alerts' && $alertBadge>0): ?>
                    <span class="sidebar-badge"><?= min($alertBadge,99) ?></span>
                <?php endif; ?>
            </a>
            <?php endforeach; ?>
        </nav>

	        <div class="sidebar-footer">
	            <img class="sidebar-footer-logo" src="assets/img/sm_logo.png" alt="MageStock">
	        </div>
    </aside>

    <!-- ═══════════════════════════════════════════════════════════
         MAIN AREA
         ═══════════════════════════════════════════════════════════ -->
    <div class="main-area">
        <!-- Top Header -->
        <header class="top-header" id="appHeader">
            <div class="header-left">
                <button class="header-btn mobile-menu-btn" id="btnHamburger">
                    <svg viewBox="0 0 24 24"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
                </button>
                <h1 class="header-title"><?= htmlspecialchars($pageTitle) ?></h1>
            </div>
            <div class="header-right">
                <!-- Sélecteur de langue -->
                <div class="lang-picker" id="langPicker">
                    <button class="header-btn lang-picker-btn" id="langPickerBtn" title="Langue / Language">
                        <span id="langFlag">🌐</span>
                    </button>
                    <div class="lang-picker-dropdown" id="langPickerDropdown"></div>
                </div>
                <button class="header-btn" id="btnTheme" title="Changer de thème">
                    <svg class="icon-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                    <svg class="icon-moon" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>
                </button>
                <?php if($role==='admin' && $alertBadge > 0): ?>
                <a href="<?= pageUrl('alerts') ?>" class="header-btn header-alerts">
                    <svg viewBox="0 0 24 24"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg>
                    <span class="header-badge"><?= min($alertBadge,99) ?></span>
                </a>
                <?php endif; ?>
                <!-- Utilisateur (en haut à droite, à côté de la déconnexion) -->
                <div class="header-user" title="<?= htmlspecialchars($userName) ?>">
<div class="header-user-meta">
                        <div class="header-user-name"><?= htmlspecialchars($userName) ?></div>
                        <div class="header-user-role"><?= $role==='admin' ? 'Administrateur' : 'Utilisateur' ?></div>
                    </div>
                </div>
            
                <a href="logout" class="header-btn" id="btnLogout" title="Déconnexion" aria-label="Déconnexion">
                    <svg viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
                </a>
</div>
        </header>

        <!-- Page Content -->
        <main class="main-content" id="appContent">
            <?php require_once APP_ROOT.'/views/'.$page.'.php'; ?>
        </main>

        <!-- Footer -->
        <footer class="main-footer">
            Développé par <strong>KREMER Régis</strong> &copy; <?= date('Y') ?> MageStock
            <span class="footer-sep">•</span>
            <a href="index.php?page=license" class="footer-license-link">Licence d’utilisation</a>
        </footer>
    </div>

    <!-- ═══════════════════════════════════════════════════════════
         BOTTOM NAV (Mobile)
         ═══════════════════════════════════════════════════════════ -->
    <nav class="bottom-nav" id="bottomNav">
    <?php foreach($bottomNav as $bn):
        $isMore = ($bn['id']==='more');
        $isActive = (!$isMore && $page===$bn['id']);
    ?>
        <button class="bnav-item <?= $isActive?'active':'' ?> <?= $isMore?'bnav-more':'' ?>"
                <?= !$isMore ? 'onclick="location.href=\''.pageUrl($bn['id']).'\'"' : 'id="btnBnavMore"' ?>>
            <?php if($bn['icon'] === 'clipboard'): ?>
        <span class="bnav-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:100%;height:100%"><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="9" y1="16" x2="13" y2="16"/></svg></span>
        <?php else: ?>
        <span class="bnav-icon" data-icon="<?= $bn['icon'] ?>"></span>
        <?php endif; ?>
            <span class="bnav-label"><?= htmlspecialchars($bn['label']) ?></span>
        </button>
    <?php endforeach; ?>
    </nav>

    <!-- ═══════════════════════════════════════════════════════════
         SLIDE MENU (Mobile)
         ═══════════════════════════════════════════════════════════ -->
    <div class="slide-menu-backdrop" id="slideBackdrop"></div>
    <nav class="slide-menu" id="slideMenu">
        <div class="slide-menu-head">
            <div class="slide-menu-brand">
                <?php if(file_exists(APP_ROOT.'/assets/img/sm.png')): ?>
                    <img src="assets/img/sm.png" alt="Logo" class="slide-menu-logo">
                <?php else: ?>
                    <div class="slide-menu-logo-ph">M</div>
                <?php endif; ?>
                <span class="slide-menu-title"><?= htmlspecialchars($company) ?></span>
            </div>
            <button class="slide-menu-close" id="btnSlideClose">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
        </div>
        <div class="slide-menu-body">
        <?php foreach($navAll as $n): ?>
            <a href="<?= pageUrl($n['id']) ?>" class="slide-item <?= $page===$n['id']?'active':'' ?>">
                <?php if($n['icon'] === 'clipboard'): ?>
                <span class="slide-item-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:100%;height:100%"><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="9" y1="16" x2="13" y2="16"/></svg></span>
                <?php else: ?>
                <span class="slide-item-icon" data-icon="<?= $n['icon'] ?>"></span>
                <?php endif; ?>
                <span><?= htmlspecialchars($n['label']) ?></span>
                <?php if($n['id']==='alerts' && $alertBadge>0): ?>
                    <span class="slide-badge"><?= min($alertBadge,99) ?></span>
                <?php endif; ?>
            </a>
        <?php endforeach; ?>
            <a href="logout" class="slide-item slide-logout">
                <span class="slide-item-icon" data-icon="logout"></span>
                <span>Déconnecter</span>
            </a>
        </div>
    </nav>
</div>

<!-- ═══════════════════════════════════════════════════════════
     MODAL
     ═══════════════════════════════════════════════════════════ -->
<div class="modal-overlay" id="modalOverlay">
    <div class="modal" id="modalBox">
        <div class="modal-hdr">
            <div class="modal-hdr-icon" id="modalIcon"></div>
            <div class="modal-hdr-text">
                <h3 id="modalTitle">Titre</h3>
                <p id="modalSub"></p>
            </div>
            <button class="modal-close" id="modalCloseBtn">
                <svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
        </div>
        <div class="modal-body" id="modalBody"></div>
        <div class="modal-footer" id="modalFooter"></div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════
     TOAST CONTAINER
     ═══════════════════════════════════════════════════════════ -->
<div class="toast-wrap" id="toastWrap"></div>

<!-- ═══════════════════════════════════════════════════════════
     PRINT OVERLAY
     ═══════════════════════════════════════════════════════════ -->
<div class="print-overlay" id="printOverlay" style="display:none">
    <div class="print-hdr">
        <h2 id="printTitle">Codes à barres</h2>
        <div class="print-hdr-btns">
            <button class="btn btn-primary" onclick="window.print()">Imprimer</button>
            <button class="btn btn-secondary" id="btnClosePrint">Fermer</button>
        </div>
    </div>
    <div class="print-grid" id="printGrid"></div>
</div>

<!-- ═══════════════════════════════════════════════════════════
     SCRIPTS
     ═══════════════════════════════════════════════════════════ -->
<script src="libs/jsbarcode.all.min.js"></script>
<script src="libs/qrcode.js"></script>
<script src="libs/quagga2.min.js"></script>
<script src="libs/html5-qrcode.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script src="assets/js/pagination.js"></script>
<script src="assets/js/validator.js"></script>
<!-- Langue PHP injectée AVANT i18n.js — priorité absolue sur localStorage -->
<script>window._SM_LANG_PHP='<?= htmlspecialchars($lang) ?>';window.SM_LANG=window._SM_LANG_PHP;</script>
<script src="assets/js/i18n.js?v=5"></script>
<script src="assets/js/i18n-pages.js?v=1"></script>

<script src="<?= 'assets/js/api.js?v=' . filemtime(__DIR__.'/../assets/js/api.js') ?>"></script>
<script src="<?= 'assets/js/utils.js?v=' . filemtime(__DIR__.'/../assets/js/utils.js') ?>"></script>
<script src="assets/js/table-sort.js?v=1.0.0"></script>
<script src="assets/js/scanner/ScannerService.js?v=20260217091258"></script>
<script src="assets/js/infinite-scroll.js"></script>
<script src="<?= 'assets/js/app.js?v=' . filemtime(__DIR__.'/../assets/js/app.js') ?>"></script>

<script src="<?= 'assets/js/pages/dashboard.js?v=' . filemtime(__DIR__.'/../assets/js/pages/dashboard.js') ?>"></script>
<script src="<?= 'assets/js/pages/products.js?v=' . filemtime(__DIR__.'/../assets/js/pages/products.js') ?>"></script>
<script src="<?= 'assets/js/pages/warehouses.js?v=' . filemtime(__DIR__.'/../assets/js/pages/warehouses.js') ?>"></script>
<script src="<?= 'assets/js/pages/movements.js?v=' . filemtime(__DIR__.'/../assets/js/pages/movements.js') ?>"></script>
<script src="<?= 'assets/js/pages/inventory.js?v=' . filemtime(__DIR__.'/../assets/js/pages/inventory.js') ?>"></script>
<script src="<?= 'assets/js/pages/scanner.js?v=' . filemtime(__DIR__.'/../assets/js/pages/scanner.js') ?>"></script>
<script src="<?= 'assets/js/pages/barcodes.js?v=' . filemtime(__DIR__.'/../assets/js/pages/barcodes.js') ?>"></script>
<script src="<?= 'assets/js/pages/reports.js?v=' . filemtime(__DIR__.'/../assets/js/pages/reports.js') ?>"></script>
<script src="<?= 'assets/js/pages/settings.js?v=' . filemtime(__DIR__.'/../assets/js/pages/settings.js') ?>"></script>
<script src="<?= 'assets/js/pages/users.js?v=' . filemtime(__DIR__.'/../assets/js/pages/users.js') ?>"></script>
<script src="<?= 'assets/js/pages/alerts.js?v=' . filemtime(__DIR__.'/../assets/js/pages/alerts.js') ?>"></script>
<script src="<?= 'assets/js/pages/suppliers.js?v=' . filemtime(__DIR__.'/../assets/js/pages/suppliers.js') ?>"></script>
<script src="<?= 'assets/js/pages/orders.js?v=' . filemtime(__DIR__.'/../assets/js/pages/orders.js') ?>"></script>
<script src="<?= 'assets/js/pages/brands.js?v=' . filemtime(__DIR__.'/../assets/js/pages/brands.js') ?>"></script>
<script src="<?= 'assets/js/pages/locations.js?v=' . filemtime(__DIR__.'/../assets/js/pages/locations.js') ?>"></script>
<script src="<?= 'assets/js/pages/lots.js?v=' . filemtime(__DIR__.'/../assets/js/pages/lots.js') ?>"></script>
<script src="<?= 'assets/js/pages/kits.js?v=' . filemtime(__DIR__.'/../assets/js/pages/kits.js') ?>"></script>
<script src="<?= 'assets/js/pages/reservations.js?v=' . filemtime(__DIR__.'/../assets/js/pages/reservations.js') ?>"></script>
<script src="<?= 'assets/js/pages/analytics.js?v=' . filemtime(__DIR__.'/../assets/js/pages/analytics.js') ?>"></script>
<script src="assets/js/push-notifications.js"></script>
<script src="assets/js/slide-menu.js"></script>

<script>
window.SM_PAGE = '<?= $page ?>';
window.SM_ROLE = '<?= $role ?>';
window.USER_ROLE = '<?= $role ?>';
window.CSRF_TOKEN = '<?= csrfToken() ?>';
window.__CSRF_TOKEN__ = window.CSRF_TOKEN;
document.addEventListener('DOMContentLoaded', () => (window._i18nReady ? window._i18nReady.finally(() => App.init()) : App.init()));
</script>

<!-- Scroll-to-top (global, isolé) -->
<div id="scrollTopProgress" aria-label="Retour en haut">
  <svg viewBox="0 0 60 60">
    <circle class="bg" cx="30" cy="30" r="24"></circle>
    <circle class="progress" cx="30" cy="30" r="24"></circle>
  </svg>
  <div class="arrow">↑</div>
</div>
<script src="assets/js/scrolltop.js"></script>
</body>
</html>
