<?php
use App\Core\Permission;
$canManage = Permission::can('administration.permissions.manage');
?>
<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">Rôle</span>
        <h2><?= htmlspecialchars($role['libelle']) ?></h2>
        <p>Les utilisateurs rattachés à ce rôle héritent de toutes les permissions cochées.</p>
    </div>
    <span class="security-code"><?= htmlspecialchars($role['code']) ?></span>
</section>

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

    <div class="security-form-toolbar">
        <label>
            <span>⌕</span>
            <input type="search" placeholder="Filtrer les permissions…" data-permission-search>
        </label>

        <?php if ($canManage): ?>
        <div>
            <button type="button" class="security-btn security-btn-light" data-check-all>Tout autoriser</button>
            <button type="button" class="security-btn security-btn-light" data-uncheck-all>Tout retirer</button>
        </div>
        <?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>
                    <?php if ($canManage): ?>
                    <button type="button" data-module-toggle>Tout sélectionner</button>
                    <?php endif; ?>
                </header>

                <div class="security-permission-grid">
                    <?php foreach ($modulePermissions as $permission): ?>
                    <label
                        class="security-permission-row"
                        data-permission-row
                        data-search="<?= htmlspecialchars(mb_strtolower(
                            $permission['libelle'] . ' ' . $permission['code']
                        )) ?>"
                    >
                        <input
                            type="checkbox"
                            name="permissions[]"
                            value="<?= (int)$permission['id'] ?>"
                            <?= in_array((int)$permission['id'], $selected, true) ? 'checked' : '' ?>
                            <?= $canManage ? '' : 'disabled' ?>
                        >
                        <span>
                            <strong><?= htmlspecialchars($permission['libelle']) ?></strong>
                            <small><?= htmlspecialchars($permission['code']) ?></small>
                        </span>
                    </label>
                    <?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 le rôle</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-check-all]')?.addEventListener('click', () => {
        rows.forEach(row => row.querySelector('input').checked = true);
    });

    document.querySelector('[data-uncheck-all]')?.addEventListener('click', () => {
        rows.forEach(row => row.querySelector('input').checked = false);
    });

    document.querySelectorAll('[data-module-toggle]').forEach(button => {
        button.addEventListener('click', () => {
            const inputs = [...button.closest('[data-permission-module]').querySelectorAll('input[type="checkbox"]')];
            const shouldCheck = inputs.some(input => !input.checked);
            inputs.forEach(input => input.checked = shouldCheck);
            button.textContent = shouldCheck ? 'Tout retirer' : 'Tout sélectionner';
        });
    });
})();
</script>
