<?php
use App\Core\Auth;
use App\Core\Permission;
use App\Core\SpaceAccess;
use App\Core\PortalSimulation;

$pageTitle = $pageTitle ?? 'CDA';
$hideNavigation = $hideNavigation ?? false;
$currentPath =
    parse_url(
        $_SERVER['REQUEST_URI'] ?? '/',
        PHP_URL_PATH
    ) ?: '/';

$user = Auth::check()
    ? Auth::user()
    : null;
$directionPlanningMenu = false;
$directionTaskCount = 0;
if ($user && Permission::canViewFullProfessorRh() && Permission::can('professeurs.disciplines.manage')) {
    $directionPlanningMenu = true;
    try {
        $directionTaskCount = \App\Models\DirectionTask::count((int)($user['organisation_id'] ?? 1));
    } catch (\Throwable) {
        $directionTaskCount = 0;
    }
}

function cda_nav_active(
    string $path,
    string $currentPath
): string {
    return str_contains(
        $currentPath,
        $path
    ) ? ' is-active' : '';
}
?>
<!doctype html>
<html lang="fr">
<head>
    <meta charset="utf-8">

    <meta
        name="viewport"
        content="width=device-width,initial-scale=1"
    >

    <title>
        <?= htmlspecialchars((string)$pageTitle) ?>
        — Carrefour des Arts
    </title>

    <link
        rel="stylesheet"
        href="/public/assets/css/cda-v4.css"
    >

    <link
        rel="stylesheet"
        href="/public/assets/css/cda-v4-1-professors.css"
    >

    <link
        rel="stylesheet"
        href="/public/assets/css/cda-v4-3.css"
    >
<link rel="stylesheet" href="/public/assets/css/cda-global-search.css">
<link rel="stylesheet" href="/public/assets/css/axiom-foundation.css">
<link rel="stylesheet" href="/public/assets/css/axiom-studio.css">
<link rel="stylesheet" href="/public/assets/css/axiom-studio-ux.css?v=9.5.2">
<link rel="stylesheet" href="/public/assets/css/axiom-framework.css">
<link rel="stylesheet" href="/public/assets/css/cda-pilotage.css">
<link rel="stylesheet" href="/public/assets/css/cda-space-switcher-971.css?v=9.7.1">
<link rel="stylesheet" href="/public/assets/css/cda-direction-meetings-9694.css?v=9.6.94">
</head>
<body>

<?php if (
    !$hideNavigation &&
    Auth::check()
): ?>
<div class="app-shell">
    <aside
        class="sidebar"
        id="sidebar"
    >
        <div class="brand">
            <div class="brand-logo">
                <img
                    src="/public/assets/images/logo-carrefour-des-arts.jpg"
                    alt="Carrefour des Arts"
                >
            </div>

            <div class="brand-text">
                <strong>
                    Carrefour des Arts
                </strong>

                <span>
                    Bray-Dunes · CDA V4
                </span>
            </div>
        </div>

        <?php
        $spaceLabels = ['famille'=>'Famille','professeur'=>'Prof','direction'=>'Direction','facturation'=>'Compte','axiom'=>'Admin'];
        $spaces = [];
        foreach (SpaceAccess::available() as $code) {
            $spaces[$code] = [$spaceLabels[$code], '/public/espaces?espace=' . $code];
        }
        $activeSpace = SpaceAccess::active();
        $spaceHomeUrl = '/public/espaces?espace=' . rawurlencode($activeSpace ?: 'direction');
        $simulationContext = Permission::isSuperAdmin() ? PortalSimulation::context() : null;
        $simulatedProfessorId = $simulationContext && $simulationContext['type'] === 'professeur' ? $simulationContext['id'] : null;
        $simulatedClientId = $simulationContext && $simulationContext['type'] === 'famille' ? $simulationContext['id'] : null;
        ?>
        <?php if ($spaces): ?>
        <nav class="space-switcher" aria-label="Modules AXIOM">
            <?php foreach ($spaces as $spaceCode => [$spaceLabel, $spaceUrl]): ?>
            <a
                href="<?= htmlspecialchars($spaceUrl, ENT_QUOTES, 'UTF-8') ?>"
                class="<?= $activeSpace === $spaceCode ? 'is-active' : '' ?>"
            ><?= htmlspecialchars($spaceLabel, ENT_QUOTES, 'UTF-8') ?></a>
            <?php endforeach; ?>
        </nav>
        <?php endif; ?>
        <?php if (Permission::isSuperAdmin() && $simulationContext): ?>
        <form method="post" action="/public/espaces/simulation/quitter" class="simulation-banner" aria-label="Simulation Super-admin active">
            <input type="hidden" name="_csrf" value="<?= htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8') ?>">
            <strong>Simulation <?= $simulationContext['type'] === 'professeur' ? 'Professeur' : 'Famille' ?> :</strong>
            <span><?= htmlspecialchars($simulationContext['label'] ?: ('#' . $simulationContext['id']), ENT_QUOTES, 'UTF-8') ?></span>
            <span>— droits réels Super-admin conservés</span>
            <a href="/public/espaces?espace=<?= $simulationContext['type'] === 'professeur' ? 'professeur' : 'famille' ?>">Changer</a>
            <button type="submit">Quitter la simulation</button>
        </form>
        <?php endif; ?>

        <nav class="main-nav" data-active-space="<?= htmlspecialchars($activeSpace, ENT_QUOTES, 'UTF-8') ?>">
            <div class="nav-label">
                Pilotage
            </div>

            <a
                class="nav-link<?= str_contains($currentPath, '/espaces') ? ' is-active' : '' ?>"
                href="<?= htmlspecialchars($spaceHomeUrl, ENT_QUOTES, 'UTF-8') ?>"
            >
                <span class="nav-symbol">⌂</span>
                <span>Accueil</span>
            </a>

            <?php if (in_array($activeSpace, ['famille', 'direction'], true) &&
                Permission::canAny('clients.view', 'family.profile.view')
            ): ?>
            <a
                class="nav-link<?= cda_nav_active('/clients', $currentPath) ?>"
                href="/public/clients"
            >
                <span class="nav-symbol">◉</span>
                <span><?= Permission::isFamilyPortalIdentity() ? 'Mon dossier familial' : 'Adhérents & familles' ?></span>
            </a>
            <?php endif; ?>

            <?php if ($activeSpace === 'famille'): ?>
            <a class="nav-link<?= cda_nav_active('/mon-espace/demandes', $currentPath) ?>" href="/public/mon-espace/demandes">
                <span class="nav-symbol">✉</span><span>Mes demandes</span>
            </a>
            <a class="nav-link<?= cda_nav_active('/mon-espace/factures', $currentPath) ?>" href="/public/mon-espace/factures">
                <span class="nav-symbol">€</span><span>Ma facturation</span>
            </a>
            <?php endif; ?>

            <?php if ($activeSpace === 'direction' &&
                Permission::can('professeurs.view')
            ): ?>
            <a
                class="nav-link<?= cda_nav_active('/professeurs', $currentPath) ?>"
                href="/public/professeurs"
            >
                <span class="nav-symbol">♬</span>
                <span>Professeurs</span>
            </a>
            <?php endif; ?>

            <?php if ($activeSpace === 'direction' &&
                Permission::can('ateliers.view')
            ): ?>
            <a
                class="nav-link<?= cda_nav_active('/ateliers', $currentPath) ?>"
                href="/public/ateliers"
            >
                <span class="nav-symbol">✦</span>
                <span>Cours & ateliers</span>
            </a>
            <?php endif; ?>

            <?php if ($activeSpace === 'direction' && $directionPlanningMenu): ?>
            <a
                class="nav-link<?= cda_nav_active('/mon-espace/demandes', $currentPath) ?>"
                href="/public/mon-espace/demandes"
            >
                <span class="nav-symbol">✉</span>
                <span>Demandes des adhérents</span>
            </a>
            <a
                class="nav-link<?= cda_nav_active('/direction/taches', $currentPath) ?>"
                href="/public/direction/taches"
            >
                <span class="nav-symbol">✓</span>
                <span>Tâches à valider</span>
                <?php if ($directionTaskCount > 0): ?><span class="nav-pill"><?= $directionTaskCount ?></span><?php endif; ?>
            </a>
            <a
                class="nav-link<?= cda_nav_active('/direction/reunions', $currentPath) ?>"
                href="/public/direction/reunions"
            >
                <span class="nav-symbol">▣</span>
                <span>Réunions</span>
            </a>
            <?php endif; ?>

            <?php if ($activeSpace === 'direction' &&
                Permission::can('tarifs.view')
            ): ?>
            <a
                class="nav-link<?= cda_nav_active('/tarifs', $currentPath) ?>"
                href="/public/tarifs"
            >
                <span class="nav-symbol">€</span>
                <span>Tarifs & réductions</span>
            </a>
            <?php endif; ?>

            <?php if (in_array($activeSpace, ['direction','professeur'], true) &&
                Permission::can('planning.view')
            ): ?>
            <a
                class="nav-link"
                href="/public/presences"
            >
                <span class="nav-symbol">▦</span>
                <span>Agenda</span>
                <span class="nav-pill">Bientôt</span>
            </a>
            <?php endif; ?>

            <?php if (in_array($activeSpace, ['direction','professeur'], true) &&
                Permission::can('presences.view')
            ): ?>
            <a
                class="nav-link"
                href="#"
            >
                <span class="nav-symbol">✓</span>
                <span>Présences</span>
            </a>
            <?php endif; ?>

            <?php if ($activeSpace === 'axiom'): ?>
            <div class="nav-label nav-label-space">
                Administration
            </div>

            <details class="nav-module-group" open>
                <summary><span class="nav-symbol">▦</span><span>Espaces de test</span></summary>
                <div class="nav-module-group-links">
                    <a class="nav-link" href="/public/espaces?espace=famille"><span>Portail Adhérent</span></a>
                    <a class="nav-link" href="/public/espaces?espace=professeur"><span>Espace Prof</span></a>
                    <a class="nav-link" href="/public/espaces?espace=direction"><span>Espace Direction</span></a>
                    <a class="nav-link" href="/public/espaces?espace=facturation"><span>Espace Compta</span></a>
                </div>
            </details>

            <details class="nav-module-group">
                <summary><span class="nav-symbol">⚙</span><span>Comptes et réglages</span></summary>
                <div class="nav-module-group-links">
            <?php if (
                Permission::can('utilisateurs.view')
            ): ?>
            <a
                class="nav-link"
                href="/public/utilisateurs"
            >
                <span class="nav-symbol">⚙</span>
                <span>Utilisateurs</span>
            </a>
            <?php endif; ?>

            <a
                class="nav-link<?= cda_nav_active('/parametres', $currentPath) ?>"
                href="/public/parametres"
            >
                <span class="nav-symbol">▤</span>
                <span>Paramètres</span>
            </a>
                </div>
            </details>
            <details class="nav-module-group">
                <summary><span class="nav-symbol">◉</span><span>Adhérents et inscriptions</span></summary>
                <div class="nav-module-group-links">
                    <a class="nav-link" href="/public/clients"><span>Adhérents & familles</span></a>
                    <a class="nav-link" href="/public/pilotage-disciplines"><span>Inscriptions & disciplines</span></a>
                </div>
            </details>
            <details class="nav-module-group">
                <summary><span class="nav-symbol">♬</span><span>Pédagogie et professeurs</span></summary>
                <div class="nav-module-group-links">
                    <a class="nav-link" href="/public/professeurs"><span>Dossiers professeurs</span></a>
                    <a class="nav-link" href="/public/ateliers"><span>Cours & ateliers</span></a>
                    <a class="nav-link" href="/public/presences"><span>Agenda & présences</span></a>
                </div>
            </details>
            <details class="nav-module-group">
                <summary><span class="nav-symbol">€</span><span>Facturation et comptabilité</span></summary>
                <div class="nav-module-group-links">
                    <a class="nav-link" href="/public/facturation/a-preparer"><span>À facturer</span></a>
                    <a class="nav-link" href="/public/facturation"><span>Factures & règlements</span></a>
                    <a class="nav-link" href="/public/comptabilite/tresorerie"><span>Trésorerie</span></a>
                </div>
            </details>
            <?php endif; ?>
        <?php
if ($activeSpace === 'axiom' && is_file(__DIR__ . '/studio_menu_addon.php')) {
    include __DIR__ . '/studio_menu_addon.php';
}
?>

<?php if ($activeSpace === 'direction' && \App\Core\Permission::can('communications.view')): ?>
<a href="/public/communications" class="nav-link">
<span>✉️</span>
Communications
</a>
<?php endif; ?>

<?php if ($activeSpace === 'direction' && \App\Core\Permission::can('communications.recipients.search')): ?>
<a href="/public/communications/intelligente" class="nav-link">
<span>🧠</span>
Communication intelligente
</a>
<?php endif; ?>

            <?php if ($activeSpace === 'axiom'): ?>
            <div class="nav-label">Plateforme AXIOM</div>
            <a class="nav-link<?= cda_nav_active('/administration/axiom', $currentPath) ?>" href="/public/administration/axiom">
                <span class="nav-symbol">◇</span>
                <span>AXIOM Studio</span>
            </a>
            <a class="nav-link<?= cda_nav_active('/administration/fondation', $currentPath) ?>" href="/public/administration/fondation">
                <span class="nav-symbol">◆</span>
                <span>Foundation</span>
            </a>
            <?php endif; ?>

</nav>

        <div class="sidebar-bottom">
            <div class="year-card">
                <span>Année scolaire</span>
                <strong>2026–2027</strong>
                <small>Inscriptions ouvertes</small>
            </div>
        </div>
    </aside>

    <section class="workspace">
        <header class="topbar">
            <div class="topbar-title">
                <button
                    type="button"
                    class="mobile-menu"
                    id="mobileMenuButton"
                >
                    ☰
                </button>

                <div>
                    <span>
                        Carrefour des Arts
                        de Bray-Dunes
                    </span>

                    <h1>
                        <?= htmlspecialchars(
                            (string)$pageTitle
                        ) ?>
                    </h1>
                </div>
            </div>

            <?php if ($activeSpace !== 'famille' && Permission::can('recherche.globale.use')): ?>
            <form
                class="global-search"
                action="/public/recherche-globale"
                method="get"
                role="search"
                data-global-search-form
            >
                <span>⌕</span>

                <input
                    type="search"
                    name="q"
                    placeholder="Rechercher un adhérent, un membre, un cours…"
                >

                <kbd>Ctrl K</kbd>
            </form>
            <?php endif; ?>

            <div class="topbar-user">
                <button
                    type="button"
                    class="notification"
                >
                    🔔<i></i>
                </button>

                <div class="avatar">
                    <?= htmlspecialchars(
                        mb_strtoupper(
                            mb_substr(
                                (string)(
                                    $user['prenom']
                                    ?? 'C'
                                ),
                                0,
                                1
                            )
                            .
                            mb_substr(
                                (string)(
                                    $user['nom']
                                    ?? 'A'
                                ),
                                0,
                                1
                            )
                        )
                    ) ?>
                </div>

                <div class="user-text">
                    <strong>
                        <?= htmlspecialchars(
                            trim(
                                (string)(
                                    $user['prenom']
                                    ?? ''
                                )
                                .
                                ' '
                                .
                                (string)(
                                    $user['nom']
                                    ?? ''
                                )
                            )
                        ) ?>
                    </strong>

                    <span><?= htmlspecialchars($spaceLabels[$activeSpace] ?? 'Utilisateur', ENT_QUOTES, 'UTF-8') ?></span>
                </div>

                <form
                    method="post"
                    action="/public/logout"
                >
                    <?= \App\Core\Csrf::field() ?>
                    <button
                        class="logout-button"
                    >
                        Déconnexion
                    </button>
                </form>
            </div>
        </header>

<?php
$axiomNavigation = \App\Core\AxiomNavigation::context($_SERVER['REQUEST_URI'] ?? '/');
if ($axiomNavigation !== null):
?>
<section class="axiom-framework-nav" aria-label="Navigation AXIOM">
    <a class="axiom-framework-back" href="<?= htmlspecialchars($axiomNavigation['back']) ?>">← Retour</a>
    <nav class="axiom-framework-breadcrumb" aria-label="Fil d’Ariane">
        <?php foreach ($axiomNavigation['breadcrumbs'] as $index => $item): ?>
            <?php if ($index > 0): ?><span aria-hidden="true">›</span><?php endif; ?>
            <?php if (!empty($item['url'])): ?>
                <a href="<?= htmlspecialchars($item['url']) ?>"><?= htmlspecialchars($item['label']) ?></a>
            <?php else: ?>
                <strong><?= htmlspecialchars($item['label']) ?></strong>
            <?php endif; ?>
        <?php endforeach; ?>
    </nav>
    <div class="axiom-framework-actions">
        <?php if (\App\Core\Permission::can('axiom.kernel.view')): ?><a href="/public/administration/axiom/kernel">Kernel</a><?php endif; ?>
        <?php if (\App\Core\Permission::can('updates.view')): ?><a href="/public/studio/mises-a-jour">Mises à jour</a><?php endif; ?>
        <?php if (\App\Core\Permission::can('backups.view')): ?><a href="/public/studio/sauvegardes">Sauvegardes</a><?php endif; ?>
        <?php if (\App\Core\Permission::can('administration.permissions.view')): ?><a href="/public/administration/securite">Permissions</a><?php endif; ?>
    </div>
</section>
<?php endif; ?>

        <main class="content">
<?php else: ?>
<main class="login-page">
<?php endif; ?>

<?php if (
    !empty($_SESSION['error'])
): ?>
<div class="alert alert-error">
    <?= htmlspecialchars(
        (string)$_SESSION['error']
    ) ?>
</div>
<?php unset($_SESSION['error']); endif; ?>
