<?php

if($_SESSION["tipo_usuario"] == "Inventario "){

  echo '<script>

    window.location = "inicio";

  </script>';

  return;

}

// 1. Traer todos los módulos
$item = null;
$valor = null;
$modulos  = ControladorModulo::ctrMostrarModulo($item,$valor);

// 2. Traer todas las acciones
$acciones = ControladorAccion::ctrMostrarAccion($item,$valor);

// 3. Traer todos los permisos guardados
$permisos = ControladorPermiso::ctrMostrarPermiso($item,$valor);

// 4. Armar array de combinaciones módulo-acción
$setPermisos = [];
foreach ($permisos as $p) {
    $setPermisos[$p['modulo_id'].'-'.$p['accion_id']] = true;
}


?>
<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1 class="font-weight-bold"><i class="fas fa-shield-alt mr-2"></i>Configuración de Permisos</h1>
        </div>
        <div class="col-sm-6 text-right">
            <button class="btn btn-primary rounded-pill shadow-sm" data-toggle="modal" data-target="#modalAgregarModulo">
              <i class="fas fa-plus mr-2"></i> Nuevo Módulo
            </button>
        </div>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="card shadow-sm border-0">
      <div class="card-body">
        <form role="form" method="post" enctype="multipart/form-data">
          
          <table class="table table-hover dt-responsive tablas border-0" width="100%">
            <thead class="bg-dark text-white">
              <tr>
                <th style="width: 50px">ID</th>
                <th>Nombre del Módulo</th>
                <th>Acciones Disponibles (Permisos)</th>
                <th style="width: 120px">Opciones</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($modulos as $m): ?>
                <tr>
                  <td class="align-middle text-muted"><?= $m['id']; ?></td>
                  <td class="align-middle">
                    <span class="badge badge-light p-2 text-uppercase" style="font-size: 0.9rem">
                      <i class="fas fa-folder mr-2 text-primary"></i> <?= htmlspecialchars($m['nombre']); ?>
                    </span>
                  </td>
                  <td class="align-middle">
                    <div class="d-flex flex-wrap">
                      <?php foreach($acciones as $a): 
                        $key = $m['id'].'-'.$a['id'];
                        $checked = isset($setPermisos[$key]) ? 'checked' : '';
                      ?>
                        <div class="custom-control custom-checkbox mr-4 py-1">
                          <input type="checkbox" 
                                 class="custom-control-input" 
                                 id="check-<?= $key ?>"
                                 name="acciones_modulo[<?= $m['id']; ?>][]" 
                                 value="<?= $a['id']; ?>" <?= $checked; ?>>
                          <label class="custom-control-label font-weight-normal" for="check-<?= $key ?>">
                            <?= htmlspecialchars($a['nombre']); ?>
                          </label>
                        </div>
                      <?php endforeach; ?>
                    </div>
                  </td>
                  <td class="align-middle text-center">
                    <div class="btn-group">
                      <button type="button" class="btn btn-sm btn-outline-warning btnEditarModulo" data-toggle="modal" idModulo="<?=$m['id']; ?>" data-target="#modalEditarModulo">
                        <i class="fas fa-edit"></i>
                      </button>
                      <button type="button" class="btn btn-sm btn-outline-danger btnEliminarModulo" idModulo="<?=$m['id']; ?>">
                        <i class="fas fa-trash"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>

          <div class="card-footer bg-white border-0 text-right mt-3">
            <hr>
            <button type="submit" class="btn btn-success btn-lg px-5 shadow rounded-pill">
              <i class="fas fa-save mr-2"></i> Guardar Cambios de Matriz
            </button>
          </div>

          <?php 
            $crearModulosyAcciones = new ControladorPermiso();
            $crearModulosyAcciones -> ctrGuardarPermisos();
          ?>
        </form>
      </div>
    </div>
  </section>
</div>

<!-- Modal agregar módulo -->
<div class="modal fade" id="modalAgregarModulo">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow-lg border-0">
      <form method="post" role="form">
        <div class="modal-header bg-primary text-white border-0">
          <h5 class="modal-title font-weight-bold"><i class="fas fa-cubes mr-2"></i> Nuevo Módulo de Sistema</h5>
          <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body p-4">
          <div class="form-group">
            <label class="text-muted font-weight-bold small">NOMBRE DEL MÓDULO</label>
            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text bg-light text-primary"><i class="fas fa-tag"></i></span>
              </div>
              <input type="text" name="nuevoNombre" class="form-control" placeholder="Ej: Facturación, Reportes..." pattern="[a-zA-Z ]+" required>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light border-0">
          <button type="button" class="btn btn-link text-muted" data-dismiss="modal">Cerrar</button>
          <button type="submit" class="btn btn-primary px-4 shadow-sm rounded-pill">Crear Módulo</button>
        </div>
        <?php 
          $crearModulo = new ControladorModulo();
          $crearModulo -> ctrCrearModulo();
        ?>
      </form>
    </div>
  </div>
</div>


<div class="modal fade" id="modalEditarModulo">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow-lg border-0">
      
      <form method="post" role="form">

        <div class="modal-header bg-warning text-white border-0">
          <h5 class="modal-title font-weight-bold">
            <i class="fas fa-edit mr-2"></i> Editar Nombre del Módulo
          </h5>
          <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>

        <div class="modal-body p-4">
          <div class="container-fluid">
            
            <input type="hidden" name="idModulo" id="idModulo">

            <div class="form-group">
              <label class="text-muted font-weight-bold small">NOMBRE ACTUALIZADO DEL MÓDULO</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text bg-light text-warning">
                    <i class="fas fa-folder-open"></i>
                  </span>
                </div>
                <input type="text" name="editarNombre" id="editarNombre" class="form-control" placeholder="Ingrese el nuevo nombre" required>
              </div>
              <small class="form-text text-muted">
                Este cambio se reflejará en la matriz de permisos y en el menú lateral.
              </small>
            </div>

          </div>
        </div>

        <div class="modal-footer bg-light border-0">
          <button type="button" class="btn btn-link text-muted font-weight-bold" data-dismiss="modal">CANCELAR</button>
          <button type="submit" class="btn btn-warning px-4 shadow-sm rounded-pill text-white">
            <i class="fas fa-sync-alt mr-2"></i> GUARDAR CAMBIOS
          </button>
        </div>

        <?php 
          $editarModulo = new ControladorModulo();
          $editarModulo->ctrEditarModulo();
        ?>

      </form>
    </div>
  </div>
</div>

  <?php 

$borrarModulo= new ControladorModulo();
$borrarModulo-> ctrBorrarModulo();

?>

  <script src="./vistas/js/plantilla.js"></script>
<script src="./vistas/js/modulo.js"></script>

 
  <script>

      
      var elemento = document.getElementById("mantenimiento");
      elemento.className += " active";

      var elemento = document.getElementById("mante");
      elemento.className += " menu-open";

      var elemento = document.getElementById("permisos");
      elemento.className += " active";
</script>
