<?php

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

  echo '<script>

    window.location = "inicio";

  </script>';

  return;

}

?>

<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-users-cog mr-2"></i>Gestión de Usuarios</h1>
        </div>
        <div class="col-sm-6 text-right">
          <button class="btn btn-primary rounded-pill shadow-sm px-4" data-toggle="modal" data-target="#modalAgregarUsuario">
            <i class="fas fa-plus-circle mr-2"></i> Nuevo Usuario
          </button>
        </div>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="card shadow-sm border-0">
      <div class="card-body">
        <table class="table table-hover dt-responsive tablas border-0" width="100%">
          <thead class="bg-dark text-white">
            <tr>
              <th style="width: 10px">#</th>
              <th>Nombre Completo</th>
              <th>Usuario</th>
              <th>Perfil</th>
              <th>Cargo / Rol</th>
              <th>Estado</th>
              <th>Último Acceso</th>
              <th>Acciones</th>
            </tr>
          </thead>
          <tbody>
            <?php 
              $item = null; $valor = null;
              $usuarios = ControladorUsuarios::ctrMostrarUsuarios($item, $valor);

              foreach($usuarios as $key => $value){
                $empleado = ControladorEmpleado::ctrMostrarEmpleado("id_empleado", $value["id_empleado"]);
                $rol = ControladorRol::ctrMostrarRol1("usuario_id", $value["id_usuario"]);

                echo '<tr>
                        <td class="align-middle">'.($key+1).'</td>
                        <td class="align-middle font-weight-bold">'.$empleado["nombre"].'</td>
                        <td class="align-middle text-primary">@'.$value["usuario"].'</td>';
                
                // Foto con estilo Avatar
                $foto = (!empty($value["foto"])) ? $value["foto"] : "vistas/dist/img/usuarios/anonymous.jpg";
                echo '<td class="align-middle text-center">
                        <img src="'.$foto.'" class="img-circle shadow-sm border" width="40px" height="40px" style="object-fit: cover;">
                      </td>';
                
                echo '<td class="align-middle"><span class="badge badge-info px-3 py-2">'.$rol["nombre"].'</span></td>';

                // Estado con estilo Pill
                if($value["estado"] != "inactivo"){
                  echo '<td class="align-middle"><button class="btn btn-success btn-sm btnActivar1 rounded-pill px-3" idUsuario="'.$value["id_usuario"].'" estadoUsuario="inactivo">Activo</button></td>';
                }else {
                  echo '<td class="align-middle"><button class="btn btn-danger btn-sm btnActivar1 rounded-pill px-3" idUsuario="'.$value["id_usuario"].'" estadoUsuario="activo">Inactivo</button></td>';
                }

                echo '<td class="align-middle small text-muted">'.($value["ultimo_login"] ?: "Sin registros").'</td>
                        <td class="align-middle text-center">
                          <div class="btn-group">
                            <button class="btn btn-light btn-sm border shadow-sm btnEditarUsuario" idUsuario="'.$value["id_usuario"].'" data-toggle="modal" data-target="#modalEditarUsuario"><i class="fas fa-pencil-alt text-warning"></i></button>
                            <button class="btn btn-light btn-sm border shadow-sm btnEliminarUsuario" idUsuario="'.$value["id_usuario"].'" fotoUsuario="'.$value["foto"].'" usuario="'.$value["usuario"].'"><i class="fa fa-times text-danger"></i></button>
                          </div>
                        </td>
                      </tr>';
              }
            ?>
          </tbody>
        </table>
      </div>
    </div>
  </section>
</div>

   <!-- MODAL AGREGAR USUARIO -->

  <div class="modal fade" id="modalAgregarUsuario">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow-lg border-0">
      <form role="form" method="post" enctype="multipart/form-data">
        <div class="modal-header bg-primary text-white border-0">
          <h5 class="modal-title font-weight-bold"><i class="fas fa-user-plus mr-2"></i> Registrar Usuario</h5>
          <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
        </div>

        <div class="modal-body p-4 text-center">
          <div class="mb-4">
            <div class="position-relative d-inline-block">
              <img src="vistas/dist/img/usuarios/anonymous.png" class="img-circle shadow border previsualizar" width="120px" height="120px" style="object-fit: cover;">
              <label for="nuevaFoto" class="btn btn-sm btn-primary rounded-circle position-absolute" style="bottom: 0; right: 0;">
                <i class="fas fa-camera"></i>
                <input type="file" id="nuevaFoto" name="nuevaFoto" class="nuevaFoto d-none">
              </label>
            </div>
            <p class="text-muted small mt-2">Formatos: JPG, PNG. Máx 2MB</p>
          </div>

          <div class="text-left">
            <div class="form-group">
              <label class="font-weight-bold small text-muted">TRABAJADOR ASOCIADO</label>
              <div class="input-group">
                <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-id-card"></i></span></div>
                <select class="form-control" name="nuevoEmpleado" required>
                  <option value="">Seleccionar un Trabajador</option>
                  <?php
                    $empleados = ControladorEmpleado::ctrMostrarEmpleadoU(null, null);
                    foreach($empleados as $v) {
                      if ($v["flag"] == 0) echo '<option value="'.$v["id_empleado"].'">'.$v["nombre"].'</option>';
                    }
                  ?>
                </select>
              </div>
            </div>

            <div class="row">
              <div class="col-md-6 form-group">
                <label class="font-weight-bold small text-muted">NOMBRE DE USUARIO</label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-at"></i></span></div>
                  <input type="text" class="form-control" name="nuevoUsuario" placeholder="User123" required>
                </div>
              </div>
              <div class="col-md-6 form-group">
                <label class="font-weight-bold small text-muted">CONTRASEÑA</label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-lock"></i></span></div>
                  <input type="password" class="form-control" name="nuevoPassword" placeholder="******" required>
                </div>
              </div>
            </div>

           <div class="form-group">
            <label class="font-weight-bold small text-muted">CARGO / ROL DEL SISTEMA</label>
            <div class="input-group">
              <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-user-shield"></i></span></div>
              <select class="form-control" name="nuevoPerfil" id="nuevoPerfil" required>
                <option value="">Seleccionar cargo</option>
                <?php
                  $roles = ControladorRol::ctrMostrarRol(null, null);
                  foreach($roles as $v) echo '<option value="'.$v["id"].'">'.$v["nombre"].'</option>';
                ?>
              </select>
            </div>
          </div>

          <div class="form-group" id="grupoArea" style="display:none;">
            <label class="font-weight-bold small text-muted">AREA</label>
            <div class="input-group">
              <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-hospital"></i></span></div>
              <select class="form-control" name="nuevaArea" id="nuevaArea">
                <option value="">Seleccionar Area</option>
                <?php
                  $area = ControladorArea::ctrMostrarArea(null, null);
                  foreach($area as $a) echo '<option value="'.$a["id"].'">'.$a["nombre_area"].'</option>';
                ?>
              </select>
            </div>
        </div>


          </div>
        </div>

        <div class="modal-footer bg-light border-0">
          <button type="button" class="btn btn-link text-muted" data-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary px-4 rounded-pill shadow-sm">Guardar Usuario</button>
        </div>
        <?php (new ControladorUsuarios())->ctrCrearUsuario(); ?>
      </form>
    </div>
  </div>
</div>

       <!-- MODAL EDITAR USUARIO -->

<div class="modal fade" id="modalEditarUsuario">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow-lg border-0">
      
      <form role="form" method="post" enctype="multipart/form-data">

        <div class="modal-header bg-info text-white border-0">
          <h5 class="modal-title font-weight-bold">
            <i class="fas fa-user-edit mr-2"></i> Actualizar Datos de Usuario
          </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">
            
            <div class="text-center mb-4">
              <div class="position-relative d-inline-block">
                <img src="vistas/dist/img/usuarios/anonymous.png" class="img-circle shadow border previsualizar" width="100px" height="100px" style="object-fit: cover;">
                <label for="editarFoto" class="btn btn-xs btn-info rounded-circle position-absolute" style="bottom: 0; right: 0; padding: 5px 8px;">
                  <i class="fas fa-pencil-alt"></i>
                  <input type="file" id="editarFoto" name="editarFoto" class="nuevoFoto d-none">
                </label>
              </div>
              <input type="hidden" name="fotoActual" id="fotoActual">
            </div>

            <div class="form-group">
              <label class="text-muted font-weight-bold small">TRABAJADOR</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text bg-light"><i class="fas fa-user"></i></span>
                </div>
                <select class="form-control" name="editarNombre" readonly>
                    <option value="" id="editarNombre"></option>
                </select>
              </div>
            </div>

            <div class="form-group">
              <label class="text-muted font-weight-bold small">NOMBRE DE USUARIO</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text bg-light"><i class="fas fa-at"></i></span>
                </div>
                <input type="text" class="form-control font-weight-bold" id="editarUsuario" name="editarUsuario" readonly required>
                <input type="hidden" id="usuario_id" name="usuario_id">
              </div>
            </div>

            <div class="form-group">
              <label class="text-muted font-weight-bold small">CAMBIAR CONTRASEÑA</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text bg-light"><i class="fas fa-unlock-alt"></i></span>
                </div>
                <input type="password" class="form-control" name="editarPassword" placeholder="Dejar en blanco para mantener actual">
                <input type="hidden" id="passwordActual" name="passwordActual">
              </div>
            </div>

            <div class="form-group">
              <label class="text-muted font-weight-bold small">CARGO / ROL EN SISTEMA</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text bg-light"><i class="fas fa-user-shield"></i></span>
                </div>
                <select class="form-control select2" name="editarPerfil" id="selectorEditarPerfil">
                  <?php
                    $item1 = null; $valor1 = null;
                    $rol = ControladorRol::ctrMostrarRol($item1, $valor1);
                    foreach($rol as $key => $value){
                      echo '<option value="'.$value["id"].'">'.$value["nombre"].'</option>';
                    }
                  ?>
                </select>
              </div>
            </div>

            <div class="form-group" id="grupoEditarArea" style="display:none;">
              <label class="font-weight-bold small text-muted">AREA</label>
              <div class="input-group">
                <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-hospital"></i></span></div>
                <select class="form-control" name="editarArea" id="editarArea">
                  <option value="">Seleccionar Area</option>
                  <?php
                    $area = ControladorArea::ctrMostrarArea(null, null);
                    foreach($area as $a) echo '<option value="'.$a["id"].'">'.$a["nombre_area"].'</option>';
                  ?>
                </select>
              </div>
            </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-info px-4 shadow-sm rounded-pill font-weight-bold text-white">
            <i class="fas fa-save mr-2"></i> ACTUALIZAR USUARIO
          </button>
        </div>

        <?php 
          $editarUsuario = new ControladorUsuarios();
          $editarUsuario->ctrEditarUsuario();
        ?>

      </form>
    </div>
  </div>
</div>
<?php 

$borrarUsuario = new ControladorUsuarios();
$borrarUsuario -> ctrBorrarUsuario();

?>
<script>
        $(function () {
          $("#example1").DataTable();
          $('#example2').DataTable({
            "paging": true,
            "lengthChange": false,
            "searching": false,
            "ordering": true,
            "info": true,
            "autoWidth": false,
          });
        });
</script>
<script src="./vistas/js/plantilla.js"></script>
<script src="./vistas/js/usuarios.js"></script>
<script>
      
      var elemento = document.getElementById("mantenimiento");
      elemento.className += " active";

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

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

