<?php
use App\Core\Permission;
$canManage = Permission::isSuperAdmin()
    && (int)$account['id'] !== (int)(\App\Core\Auth::id() ?? 0);

$scopeLabels = [
    'global' => 'Global',
    'organisation' => 'Organisation',
    'ses_ateliers' => 'Ses ateliers',
    'ses_groupes' => 'Ses groupes',
    'ses_seances' => 'Ses séances',
    'dossiers_affectes' => 'Dossiers affectés',
];
?>
<link rel="stylesheet" href="/public/assets/css/cda-security.css?v=7220">

<section class="security-page-head">
    <div>
        <a href="/public/administration/securite" class="security-back">← Sécurité & autorisations</a>
        <span class="security-kicker">Exceptions utilisateur</span>
        <h2><?= htmlspecialchars($account['prenom'] . ' ' . $account['nom']) ?></h2>
        <p><?= htmlspecialchars($account['email']) ?></p>
    </div>
    <div class="security-legend">
        <span class="is-inherited">Hérité du rôle</span>
        <span class="is-allowed">Autorisation spécifique</span>
        <span class="is-denied">Interdiction spécifique</span>
    </div>
</section>

<div class="security-priority-note">
    <strong>Règle de calcul</strong>
    <span>Une exception utilisateur remplace toujours le droit hérité du rôle.</span>
</div>

<section class="security-effective-summary">
    <header>
        <div>
            <span class="security-kicker">Contrôle effectif</span>
            <h3>Espaces réellement accessibles</h3>
        </div>
        <small>Calculés à partir des permissions AXIOM et des rattachements réels</small>
    </header>
    <div class="security-space-grid">
        <?php
        $spaceLabels = [
            'famille' => ['Famille', 'Adhérents, familles et inscriptions'],
            'professeur' => ['Prof', 'Profil pédagogique rattaché'],
            'direction' => ['Direction', 'Pilotage pédagogique et RH'],
            'facturation' => ['Compte', 'Facturation, paiements et comptabilité'],
            'axiom' => ['Admin', 'Utilisateurs, paramètres et AXIOM'],
        ];
        foreach ($spaceLabels as $code => [$label, $description]):
            $allowed = !empty($spaces[$code]);
        ?>
        <article class="<?= $allowed ? 'is-allowed' : 'is-denied' ?>">
            <span><?= $allowed ? '✓' : '×' ?></span>
            <div><strong><?= htmlspecialchars($label) ?></strong><small><?= htmlspecialchars($description) ?></small></div>
            <b><?= $allowed ? 'Accessible' : 'Verrouillé' ?></b>
        </article>
        <?php endforeach; ?>
    </div>
</section>

<?php if (Permission::isSuperAdmin() && !$canManage): ?>
<div class="security-lock-note">
    🔒 Vos propres permissions sont en lecture seule. Un autre super-administrateur doit les modifier.
</div>
<?php endif; ?>

<form method="post" action="/public/administration/securite/utilisateur" class="security-permission-form">
    <input type="hidden" name="_csrf" value="<?= htmlspecialchars($_SESSION['_csrf'] ?? '') ?>">
    <input type="hidden" name="user_id" value="<?= (int)$account['id'] ?>">

    <div class="security-form-toolbar">
        <label>
            <span>⌕</span>
            <input type="search" placeholder="Filtrer les permissions…" data-permission-search>
        </label>
        <?php if ($canManage): ?>
        <button type="button" class="security-btn security-btn-light" data-reset-all>
            Réinitialiser toutes les exceptions
        </button>
        <?php endif; ?>
    </div>

    <div class="security-modules">
        <?php foreach ($permissions as $module => $modulePermissions): ?>
            <section class="security-module" data-permission-module>
                <header>
                    <div>
                        <strong><?= htmlspecialchars(ucfirst(str_replace('_', ' ', $module))) ?></strong>
                        <small><?= count($modulePermissions) ?> autorisation<?= count($modulePermissions) > 1 ? 's' : '' ?></small>
                    </div>
                </header>

                <div class="security-user-permissions">
                    <?php foreach ($modulePermissions as $permission):
                        $id = (int)$permission['id'];
                        $override = $overrides[$id] ?? null;
                        $state = $override
                            ? ((int)$override['accordee'] === 1 ? 'allow' : 'deny')
                            : 'inherit';
                        $scope = $override['perimetre'] ?? 'global';
                        $isInherited = in_array($id, $inherited, true);
                        $effectivePermission = $effective[$id] ?? null;
                        $isEffective = (int)($effectivePermission['accordee'] ?? 0) === 1;
                        $origin = (string)($effectivePermission['origine'] ?? 'aucun');
                    ?>
                    <div
                        class="security-user-permission"
                        data-permission-row
                        data-search="<?= htmlspecialchars(mb_strtolower(
                            $permission['libelle'] . ' ' . $permission['code']
                        )) ?>"
                    >
                        <div class="security-permission-name">
                            <strong><?= htmlspecialchars($permission['libelle']) ?></strong>
                            <small><?= htmlspecialchars($permission['code']) ?></small>
                            <span class="security-effective-badge <?= $isEffective ? 'is-on' : 'is-off' ?>">
                                <?= $isEffective ? 'Effectif' : 'Refusé' ?>
                                · <?= htmlspecialchars($origin) ?>
                            </span>
                        </div>

                        <div class="security-segmented">
                            <label>
                                <input
                                    type="radio"
                                    name="permission_state[<?= $id ?>]"
                                    value="inherit"
                                    <?= $state === 'inherit' ? 'checked' : '' ?>
                                    <?= $canManage ? '' : 'disabled' ?>
                                >
                                <span>Hériter<?= $isInherited ? ' ✓' : '' ?></span>
                            </label>
                            <label>
                                <input
                                    type="radio"
                                    name="permission_state[<?= $id ?>]"
                                    value="allow"
                                    <?= $state === 'allow' ? 'checked' : '' ?>
                                    <?= $canManage ? '' : 'disabled' ?>
                                >
                                <span>Autoriser</span>
                            </label>
                            <label>
                                <input
                                    type="radio"
                                    name="permission_state[<?= $id ?>]"
                                    value="deny"
                                    <?= $state === 'deny' ? 'checked' : '' ?>
                                    <?= $canManage ? '' : 'disabled' ?>
                                >
                                <span>Interdire</span>
                            </label>
                        </div>

                        <select
                            name="permission_scope[<?= $id ?>]"
                            <?= $canManage ? '' : 'disabled' ?>
                            aria-label="Périmètre"
                        >
                            <?php foreach ($scopeLabels as $scopeCode => $scopeLabel): ?>
                            <option
                                value="<?= htmlspecialchars($scopeCode) ?>"
                                <?= $scope === $scopeCode ? 'selected' : '' ?>
                            >
                                <?= htmlspecialchars($scopeLabel) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endforeach; ?>
    </div>

    <?php if ($canManage): ?>
    <footer class="security-sticky-actions">
        <a href="/public/administration/securite" class="security-btn security-btn-light">Annuler</a>
        <button type="submit" class="security-btn security-btn-primary">
            Enregistrer les exceptions
        </button>
    </footer>
    <?php endif; ?>
</form>

<script>
(() => {
    const rows = [...document.querySelectorAll('[data-permission-row]')];
    const modules = [...document.querySelectorAll('[data-permission-module]')];
    const search = document.querySelector('[data-permission-search]');

    search?.addEventListener('input', () => {
        const query = search.value.trim().toLocaleLowerCase('fr');
        rows.forEach(row => row.hidden = !row.dataset.search.includes(query));
        modules.forEach(module => {
            module.hidden = ![...module.querySelectorAll('[data-permission-row]')]
                .some(row => !row.hidden);
        });
    });

    document.querySelector('[data-reset-all]')?.addEventListener('click', () => {
        if (!confirm('Supprimer toutes les exceptions et revenir aux rôles ?')) return;
        rows.forEach(row => {
            const inherit = row.querySelector('input[value="inherit"]');
            if (inherit) inherit.checked = true;
        });
    });
})();
</script>
