<?php

use App\Core\Auth;
use App\Core\Config;
use App\Core\Session;
use App\Core\Version;

$uiVersion = '202615';

$appName = Config::get('APP_NAME', 'Darlink ERP');
$currentPage = $_GET['page'] ?? 'dashboard';

$currentUser = Auth::user();
$currentUserId = (int)($currentUser['id'] ?? 0);

$flashSuccess = Session::flash('success');
$flashInfo = Session::flash('info');
$flashWarning = Session::flash('warning');
$flashError = Session::flash('error');

function nav_active(array $pages, string $currentPage): string {
    foreach ($pages as $page) {
        if (nav_page_matches($page, $currentPage)) {
            return 'active';
        }
    }
    return '';
}

function group_show(array $pages, string $currentPage): string {
    foreach ($pages as $page) {
        if (nav_page_matches($page, $currentPage)) {
            return 'show';
        }
    }
    return '';
}

function nav_page_matches(string $page, string $currentPage): bool {
    return nav_resolve_page($currentPage) === $page;
}

function nav_resolve_page(string $currentPage): string {
    static $registeredPages = [
        'dashboard',
        'dashboard_commercial',
        'devis_analysis',
        'factures_clients_suivi',
        'articles_sales_analysis',
        'clients_analysis',
        'clients',
        'commercial_actions',
        'documents',
        'devis',
        'bons_livraison',
        'factures',
        'encaissements',
        'avoirs',
        'fournisseurs',
        'commandes_fournisseurs_dashboard',
        'commandes_fournisseurs',
        'receptions_fournisseurs',
        'factures_fournisseurs_dashboard',
        'factures_fournisseurs_finalisation',
        'factures_fournisseurs',
        'factures_fournisseurs_echeancier',
        'reglements_fournisseurs',
        'commandes_fournisseurs_analyse',
        'commandes_fournisseurs_finalisation',
        'articles',
        'stock_dashboard',
        'stock_finalisation',
        'stock',
        'utilisateurs',
        'maintenance',
        'parametres',
    ];

    if (in_array($currentPage, $registeredPages, true)) {
        return $currentPage;
    }

    $bestMatch = '';
    foreach ($registeredPages as $registeredPage) {
        if (
            str_starts_with($currentPage, $registeredPage . '_')
            && strlen($registeredPage) > strlen($bestMatch)
        ) {
            $bestMatch = $registeredPage;
        }
    }

    return $bestMatch;
}
?>
<!doctype html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <title><?= htmlspecialchars($title ?? $appName) ?></title>
<link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
    rel="stylesheet"
>

<link
    href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"
    rel="stylesheet"
>

<link
    href="assets/css/variables.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/darlink.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/sidebar.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/tables.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/buttons.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/cards.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/toolbar.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/badges.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

<link
    href="assets/css/components/forms.css?v=<?= $uiVersion ?>"
    rel="stylesheet"
>

	
<script>
    try {
        if (localStorage.getItem('darlink-sidebar-hidden') === '1') {
            document.documentElement.classList.add('darlink-sidebar-hidden');
        }
    } catch (error) {
        // Le menu reste visible si le stockage local n'est pas disponible.
    }
</script>
</head>
<body>
<header class="darlink-topbar d-flex align-items-center justify-content-between px-4">

    <div class="d-flex align-items-center gap-3">
        <button
            type="button"
            class="darlink-sidebar-toggle"
            id="darlinkSidebarToggle"
            title="Masquer le menu"
            aria-label="Masquer le menu latéral"
            aria-controls="darlinkSidebar"
            aria-expanded="true"
        >
            <i class="bi bi-layout-sidebar-inset" aria-hidden="true"></i>
        </button>

        <div>
        <strong><?= htmlspecialchars($appName) ?></strong>

        <span class="ms-2 text-white-50">
            <?= htmlspecialchars(Version::label()) ?>
        </span>
        </div>
    </div>

    <div class="dropdown">

        <button
            class="btn btn-link text-white text-decoration-none dropdown-toggle d-flex align-items-center gap-2"
            data-bs-toggle="dropdown"
        >

            <i class="bi bi-person-circle fs-4"></i>

            <div class="text-start">

                <div class="fw-semibold">

                    <?= htmlspecialchars(
                        trim(
                            ($currentUser['prenom'] ?? '')
                            . ' '
                            . ($currentUser['nom'] ?? '')
                        )
                        ?: ($currentUser['login'] ?? 'Utilisateur')
                    ) ?>

                </div>

                <small class="text-white-50">

                    <?= htmlspecialchars(
                        $currentUser['role'] ?? ''
                    ) ?>

                </small>

            </div>

        </button>

        <ul class="dropdown-menu dropdown-menu-end shadow">

            <li>

				<a
					class="dropdown-item"
					href="index.php?page=utilisateurs_show&id=<?= $currentUserId ?>"
				>
					<i class="bi bi-person me-2"></i>
					Mon profil
				</a>

            </li>

            <li>

				<a
					class="dropdown-item"
					href="index.php?page=utilisateurs_password&id=<?= $currentUserId ?>"
				>
					<i class="bi bi-key me-2"></i>
					Changer le mot de passe
				</a>

            </li>

            <li><hr class="dropdown-divider"></li>

            <li>

                <form method="post" action="index.php?page=logout" class="m-0">
                    <button type="submit" class="dropdown-item text-danger">
                        <i class="bi bi-box-arrow-right me-2"></i>
                        Déconnexion
                    </button>
                </form>

            </li>

        </ul>

    </div>

</header>

<div class="darlink-shell">
    <aside class="darlink-sidebar" id="darlinkSidebar">
        <nav class="darlink-nav">

            <button class="darlink-nav-section" data-bs-toggle="collapse" data-bs-target="#navPilotage" type="button">
                <span><i class="bi bi-speedometer2"></i> Pilotage</span>
                <i class="bi bi-chevron-down"></i>
            </button>
            <div id="navPilotage" class="collapse <?= group_show(['dashboard','dashboard_commercial','devis_analysis','factures_clients_suivi','articles_sales_analysis','clients_analysis'], $currentPage) ?>" data-bs-parent=".darlink-nav">
                <a class="darlink-menu-link <?= nav_active(['dashboard'], $currentPage) ?>" href="index.php?page=dashboard"><i class="bi bi-house"></i><span>Tableau de bord</span></a>
                <a class="darlink-menu-link <?= nav_active(['dashboard_commercial'], $currentPage) ?>" href="index.php?page=dashboard_commercial"><i class="bi bi-graph-up"></i><span>Commercial</span></a>
                <a class="darlink-menu-link <?= nav_active(['devis_analysis'], $currentPage) ?>" href="index.php?page=devis_analysis"><i class="bi bi-bar-chart"></i><span>Analyse devis</span></a>
                <a class="darlink-menu-link <?= nav_active(['factures_clients_suivi'], $currentPage) ?>" href="index.php?page=factures_clients_suivi"><i class="bi bi-cash-coin"></i><span>Suivi factures</span></a>
                <a class="darlink-menu-link <?= nav_active(['articles_sales_analysis'], $currentPage) ?>" href="index.php?page=articles_sales_analysis"><i class="bi bi-box-seam"></i><span>Articles vendus</span></a>
                <a class="darlink-menu-link <?= nav_active(['clients_analysis'], $currentPage) ?>" href="index.php?page=clients_analysis"><i class="bi bi-people"></i><span>Analyse clients</span></a>
            </div>

            <button class="darlink-nav-section" data-bs-toggle="collapse" data-bs-target="#navCommerce" type="button">
                <span><i class="bi bi-briefcase"></i> Commerce</span>
                <i class="bi bi-chevron-down"></i>
            </button>
            <div id="navCommerce" class="collapse <?= group_show(['clients','commercial_actions','documents','devis','bons_livraison','factures','encaissements','avoirs'], $currentPage) ?>" data-bs-parent=".darlink-nav">
				<a class="darlink-menu-link <?= nav_active(['clients'], $currentPage) ?>" href="index.php?page=clients"><i class="bi bi-people"></i><span>Clients</span></a>
                <a class="darlink-menu-link <?= nav_active(['commercial_actions'], $currentPage) ?>" href="index.php?page=commercial_actions"><i class="bi bi-megaphone"></i><span>Actions</span></a>
                <a class="darlink-menu-link <?= nav_active(['documents'], $currentPage) ?>" href="index.php?page=documents"><i class="bi bi-folder"></i><span>Documents</span></a>
                <a class="darlink-menu-link <?= nav_active(['devis'], $currentPage) ?>" href="index.php?page=devis"><i class="bi bi-file-earmark-text"></i><span>Devis</span></a>
                <a class="darlink-menu-link <?= nav_active(['bons_livraison'], $currentPage) ?>" href="index.php?page=bons_livraison"><i class="bi bi-truck"></i><span>BL</span></a>
                <a class="darlink-menu-link <?= nav_active(['factures'], $currentPage) ?>" href="index.php?page=factures"><i class="bi bi-receipt"></i><span>Factures</span></a>
                <a class="darlink-menu-link <?= nav_active(['encaissements'], $currentPage) ?>" href="index.php?page=encaissements"><i class="bi bi-wallet2"></i><span>Encaissements</span></a>
                <a class="darlink-menu-link <?= nav_active(['avoirs'], $currentPage) ?>" href="index.php?page=avoirs"><i class="bi bi-arrow-counterclockwise"></i><span>Avoirs</span></a>
            </div>

            <button class="darlink-nav-section" data-bs-toggle="collapse" data-bs-target="#navAchats" type="button">
                <span><i class="bi bi-building"></i> Achats</span>
                <i class="bi bi-chevron-down"></i>
            </button>
            <div id="navAchats" class="collapse <?= group_show(['fournisseurs','commandes_fournisseurs_dashboard','commandes_fournisseurs','receptions_fournisseurs','factures_fournisseurs_dashboard','factures_fournisseurs_finalisation','factures_fournisseurs','factures_fournisseurs_echeancier','reglements_fournisseurs','commandes_fournisseurs_analyse','commandes_fournisseurs_finalisation'], $currentPage)?>" data-bs-parent=".darlink-nav">
                <a class="darlink-menu-link <?= nav_active(['fournisseurs'], $currentPage) ?>" href="index.php?page=fournisseurs"><i class="bi bi-building"></i><span>Fournisseurs</span></a>
                <a class="darlink-menu-link <?= nav_active(['commandes_fournisseurs_dashboard'], $currentPage) ?>" href="index.php?page=commandes_fournisseurs_dashboard"><i class="bi bi-speedometer"></i><span>Dashboard achats</span></a>
                <a class="darlink-menu-link <?= nav_active(['commandes_fournisseurs'], $currentPage) ?>" href="index.php?page=commandes_fournisseurs"><i class="bi bi-cart-check"></i><span>Commandes</span></a>
                <a class="darlink-menu-link <?= nav_active(['receptions_fournisseurs'], $currentPage) ?>" href="index.php?page=receptions_fournisseurs"><i class="bi bi-box-seam"></i><span>Réceptions</span></a>
                <a class="darlink-menu-link <?= nav_active(['factures_fournisseurs_dashboard'], $currentPage) ?>" href="index.php?page=factures_fournisseurs_dashboard"><i class="bi bi-speedometer2"></i><span>Dashboard fourn.</span></a>
                <a class="darlink-menu-link <?= nav_active(['factures_fournisseurs'], $currentPage) ?>" href="index.php?page=factures_fournisseurs"><i class="bi bi-receipt-cutoff"></i><span>Factures</span></a>
                <a class="darlink-menu-link <?= nav_active(['factures_fournisseurs_echeancier'], $currentPage) ?>" href="index.php?page=factures_fournisseurs_echeancier"><i class="bi bi-calendar-event"></i><span>Échéancier</span></a>
                <a class="darlink-menu-link <?= nav_active(['reglements_fournisseurs'], $currentPage) ?>" href="index.php?page=reglements_fournisseurs"><i class="bi bi-cash-stack"></i><span>Règlements</span></a>
                <a class="darlink-menu-link <?= nav_active(['commandes_fournisseurs_analyse'], $currentPage) ?>" href="index.php?page=commandes_fournisseurs_analyse"><i class="bi bi-pie-chart"></i><span>Analyse marge</span></a>
                <a class="darlink-menu-link <?= nav_active(['commandes_fournisseurs_finalisation'], $currentPage) ?>" href="index.php?page=commandes_fournisseurs_finalisation"><i class="bi bi-check-circle"></i><span>Finalisation achats</span></a>
            </div>

            <button class="darlink-nav-section" data-bs-toggle="collapse" data-bs-target="#navStock" type="button">
                <span><i class="bi bi-boxes"></i> Stock</span>
                <i class="bi bi-chevron-down"></i>
            </button>
            <div id="navStock" class="collapse <?= group_show(['articles','stock_dashboard','stock_finalisation','stock'], $currentPage) ?>" data-bs-parent=".darlink-nav">
                <a class="darlink-menu-link <?= nav_active(['articles'], $currentPage) ?>" href="index.php?page=articles"><i class="bi bi-tags"></i><span>Articles</span></a>
                <a class="darlink-menu-link <?= nav_active(['stock_dashboard'], $currentPage) ?>" href="index.php?page=stock_dashboard"><i class="bi bi-speedometer"></i><span>Dashboard stock</span></a>
                <a class="darlink-menu-link <?= nav_active(['stock_finalisation'], $currentPage) ?>" href="index.php?page=stock_finalisation"><i class="bi bi-lock"></i><span>Cycle stock</span></a>
                <a class="darlink-menu-link <?= nav_active(['stock'], $currentPage) ?>" href="index.php?page=stock"><i class="bi bi-box-seam"></i><span>Stock</span></a>
            </div>

            <?php if (Auth::hasRole('ADMINISTRATEUR')): ?>
            <button class="darlink-nav-section" data-bs-toggle="collapse" data-bs-target="#navAdmin" type="button">
                <span><i class="bi bi-gear"></i> Administration</span>
                <i class="bi bi-chevron-down"></i>
            </button>
            <div id="navAdmin" class="collapse <?= group_show(['utilisateurs','maintenance','parametres'], $currentPage) ?>" data-bs-parent=".darlink-nav">
                <a class="darlink-menu-link <?= nav_active(['utilisateurs'], $currentPage) ?>" href="index.php?page=utilisateurs"><i class="bi bi-people"></i><span>Utilisateurs</span></a>
                <a class="darlink-menu-link <?= nav_active(['maintenance'], $currentPage) ?>" href="index.php?page=maintenance"><i class="bi bi-tools"></i><span>Maintenance</span></a>
                <a class="darlink-menu-link <?= nav_active(['parametres'], $currentPage) ?>" href="index.php?page=parametres"><i class="bi bi-gear"></i><span>Paramètres</span></a>
            </div>
            <?php endif; ?>

        </nav>
    </aside>

    <main class="darlink-main">
        <?php if ($flashSuccess): ?>
            <div class="alert alert-success darlink-notification" role="status" data-darlink-notification data-notification-type="success">
                <span><?= htmlspecialchars($flashSuccess) ?></span>
                <button type="button" class="btn-close" aria-label="Fermer" data-notification-close></button>
                <span class="darlink-notification-progress" aria-hidden="true"></span>
            </div>
        <?php endif; ?>
        <?php if ($flashInfo): ?>
            <div class="alert alert-info darlink-notification" role="status" data-darlink-notification data-notification-type="info">
                <span><?= htmlspecialchars($flashInfo) ?></span>
                <button type="button" class="btn-close" aria-label="Fermer" data-notification-close></button>
                <span class="darlink-notification-progress" aria-hidden="true"></span>
            </div>
        <?php endif; ?>
        <?php if ($flashWarning): ?>
            <div class="alert alert-warning darlink-notification" role="alert" data-darlink-notification data-notification-type="warning">
                <span><?= htmlspecialchars($flashWarning) ?></span>
                <button type="button" class="btn-close" aria-label="Fermer" data-notification-close></button>
                <span class="darlink-notification-progress" aria-hidden="true"></span>
            </div>
        <?php endif; ?>
        <?php if ($flashError): ?>
            <div class="alert alert-danger darlink-notification" role="alert" data-darlink-notification data-notification-type="error">
                <span><?= htmlspecialchars($flashError) ?></span>
                <button type="button" class="btn-close" aria-label="Fermer" data-notification-close></button>
            </div>
        <?php endif; ?>
        <?php require $viewFile; ?>
    </main>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/darlink.js"></script>
<script src="assets/js/notifications.js"></script>
<script>
    (function () {
        const root = document.documentElement;
        const toggle = document.getElementById('darlinkSidebarToggle');

        if (!toggle) {
            return;
        }

        function refreshToggle() {
            const hidden = root.classList.contains('darlink-sidebar-hidden');
            const label = hidden ? 'Afficher le menu' : 'Masquer le menu';

            toggle.title = label;
            toggle.setAttribute('aria-label', label + ' latéral');
            toggle.setAttribute('aria-expanded', hidden ? 'false' : 'true');
            toggle.innerHTML = hidden
                ? '<i class="bi bi-layout-sidebar-inset-reverse" aria-hidden="true"></i>'
                : '<i class="bi bi-layout-sidebar-inset" aria-hidden="true"></i>';
        }

        toggle.addEventListener('click', function () {
            root.classList.toggle('darlink-sidebar-hidden');

            try {
                localStorage.setItem(
                    'darlink-sidebar-hidden',
                    root.classList.contains('darlink-sidebar-hidden') ? '1' : '0'
                );
            } catch (error) {
                // Le repli fonctionne même si le stockage local est indisponible.
            }

            refreshToggle();
        });

        refreshToggle();
    }());
</script>
</body>
</html>
