<?= $this->extend('layouts/master') ?>

<?= $this->section('title') ?>
Permisos del perfil <?= $perfil['nombre'] ?>
<?= $this->endSection() ?>

<?= $this->section('pageContent') ?>

<div class="card">
    <div class="card-body">
        <h5 class="card-title fw-semibold mb-4">
            Permisos del perfil: <?= esc($perfil['nombre']) ?>
        </h5>

        <form method="post" action="<?= site_url('permisos/guardar/'.$perfil['id']) ?>">
           <div class="row">

            <?php
            // Agrupar permisos por módulo
            $modulos = [];
            foreach ($permisos as $p) {
                $modulos[$p['modulo']][] = $p;
            }
            ?>

            <?php foreach ($modulos as $modulo => $acciones): ?>
                <div class="col-md-12">
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-light">
                            <h6 class="mb-0 fw-bold text-primary text-uppercase"><?= esc($modulo) ?></h6>
                        </div>
                        <div class="card-body">

                            <?php foreach ($acciones as $a): ?>
                                <?php 
                                    $key = $a['modulo'].'_'.$a['accion'];
                                    $checked = isset($permisosMarcados[$key]) ? 'checked' : '';
                                ?>
                                <div class="form-check mb-2">
                                    <input 
                                        type="checkbox"
                                        class="form-check-input"
                                        id="perm_<?= $a['id'] ?>"
                                        name="permiso[]"
                                        value="<?= $a['id'] ?>"
                                        <?= $checked ?>
                                    >
                                    <label class="form-check-label" for="perm_<?= $a['id'] ?>">
                                        <?= ucfirst(esc($a['accion'])) ?>
                                    </label>
                                </div>
                            <?php endforeach ?>

                        </div>
                    </div>
                </div>
            <?php endforeach ?>

            </div>

            <button class="btn btn-primary mt-3">Guardar</button>
        </form>
    </div>
</div>

<?= $this->endSection() ?>
