<?php 
include_once('../../../php/sessionStart.php'); 
include_once('../../../php/db/dbExec.php');
include_once('../../../php/functions.php');

# QUERYS
$sModulos = "SELECT * FROM modulos";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["modulos"] = $db->query($sModulos);
$selectArray["modulos"] = $db->sFetchAll($sModulos);
$db->close();

$func = new functions();
$selectArray["modulos"] = $func->jsonEncodeArray($selectArray, "modulos");
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-cog"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');

        $modalImp = "modalImp";
        include_once('../../../php/includes/modalImp.php');
      ?>

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="false">Buscar Usuarios</a>
              </li>
            </ul>
            <div class="tab-content bg-transparent border-0" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-0" role="tabpanel" aria-labelledby="pills-0-tab">
                
                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-group">
                    <div class="form-row">
                      <div class="col-md-2">
                        <label for="txtCod">Código</label>
                        <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" placeholder="">
                      </div>
                      <div class="col-md-5">
                        <label for="txtNom">Nombre</label>
                        <input type="text" class="form-control form-control-sm form-control-as limpiar form-info" id="txtNom" placeholder="">
                      </div>
                      <div class="col-md-5">
                        <label for="txtPue">Puesto</label>
                        <input type="text" class="form-control form-control-sm form-control-as limpiar form-info" id="txtPue" placeholder="">
                      </div>
                    </div>

                    <div class="form-row mt-2">
                      <div class="col-md-3">
                        <div class="custom-control custom-switch" id="cambiarClave">
                          <input type="checkbox" class="custom-control-input" name="cbCambiarClave" id="cbCambiarClave">
                          <label class="custom-control-label" for="cbCambiarClave">Cambiar Contraseña</label>
                        </div>
                      </div>
                    </div>

                    <div id="ingresarClaves" class="d-print-none">
                      <div class="form-row">
                        <div class="col-md-4" id="claveActual">
                          <label for="txtClaveActual">Contraseña Actual</label>
                          <input type="password" class="form-control form-control-sm form-control-as limpiar" id="txtClaveActual" placeholder="">
                        </div>
                        <div class="col-md-4">
                          <label for="txtClaveNueva">Nueva Contraseña</label>
                          <input type="password" class="form-control form-control-sm form-control-as limpiar form-info" id="txtClaveNueva" placeholder="">
                        </div>
                        <div class="col-md-4">
                          <label for="txtClaveNuevaC">Confirmar Contraseña</label>
                          <input type="password" class="form-control form-control-sm form-control-as limpiar form-info" id="txtClaveNuevaC" placeholder="">
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="form-group">
                    <h3 class="text-light">Privilegios</h3>

                    <div class="form-row">
                      <div class="col-md-3">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbEliminarUsu" id="cbEliminarUsu">
                          <label class="custom-control-label" for="cbEliminarUsu">Eliminación de Usuarios</label>
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbModificarUsu" id="cbModificarUsu">
                          <label class="custom-control-label" for="cbModificarUsu">Modificación de Usuarios</label>
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbEliminar" id="cbEliminar">
                          <label class="custom-control-label" for="cbEliminar">Eliminación de Datos</label>
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbModificar" id="cbModificar">
                          <label class="custom-control-label" for="cbModificar">Modificación de Datos</label>
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="custom-control custom-switch">
                          <input type="checkbox" class="custom-control-input" name="cbConsultar" id="cbConsultar">
                          <label class="custom-control-label" for="cbConsultar">Consultar Datos</label>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="form-group">
                    <h3 class="text-light">Módulos</h3>

                    <div class="form-row">
                      <?php
                        while ($rec = $db->fetchAssoc($select['modulos'])) {
                          echo  '
                          <div class="col-md-3">
                            <div class="custom-control custom-switch">
                              <input type="checkbox" class="custom-control-input" name='.$rec["modCod"].' id='.$rec["modCod"].'>
                              <label class="custom-control-label" for='.$rec["modCod"].'>'.utf8_encode($rec["modNom"]).'</label>
                            </div>
                          </div>';
                        }
                      ?>
                    </div>
                  </div>

                  <div class="form-group">
                    <div class="form-row">
                      <div class="form-group col">
                        <button class="btn btn-success btn-lg btn-block" id="btnGuardar" type="button">Guardar</button>
                      </div>
                      <div class="form-group col">
                        <button class="btn btn-danger btn-lg btn-block" id="btnBorrar" type="button">Borrar</button>
                      </div>
                      <div class="form-group col">
                        <button class="btn btn-primary btn-lg btn-block" id="btnImprimir" type="button">Imprimir Listado</button>
                      </div>
                    </div>
                  </div>
                </form>

              </div>

              <div class="tab-pane fade" id="pills-1" role="tabpanel" aria-labelledby="pills-1-tab">
                <?php
                  $a='0';
                  $b='1';
                  include('../busUsuarios/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var inputUsu = "txtCod";
  var pressEnter = false;
  var nuevo = true;

  const txtCod = document.thisform.txtCod;
  const txtNom = document.thisform.txtNom;
  const txtPue = document.thisform.txtPue;
  const txtClaveActual = document.thisform.txtClaveActual;
  const txtClaveNueva = document.thisform.txtClaveNueva;

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtCod.value)) {
        txtCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO"}});
        return true;
      }
    } else {
      if (isNullPer(txtCod.value)) {
        limpiar();
        return true;
      }
    }
    return false;
  }
  
  function restriccionACtaCod() {
    if (isNullPer(txtACtaCod.value)) {
      txtACtaNom.value = "";
      return true;
    }
    return false;
  }

  function limpiar(){
    $(".limpiar").val("");
    $("input:checkbox").prop("checked", false);
  }

  $(document).ready(function() {
    $("#badgeUlcam").text(textUlcam);
    $('#ingresarClaves').hide();
    $(this).find('input:visible:first').focus();

    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });

    // VALID CODIGO
    $("#txtCod")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      if (restriccion(true)) {return};

      txtNext = txtNom;

      const parametros = new FormData();
      parametros.append("action", "consultar");

      parametros.append("txtCod", txtCod.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
          alLoad("Consultando...")
        },
        success: function (jsonPhp) {
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            limpiar();
            
            if (isNullPer(jsonJS.usuarios)) {
              nuevo = true;
              txtClaveActual.value = "";
              $('#claveActual').addClass('d-none');
              $('#cambiarClave').addClass('d-none');
              cbCambiarClave.checked = 0;
              cbCambiarClave.click();
              cbCambiarClave.checked = 1;
            } else {
              cbCambiarClave.checked = 1;
              cbCambiarClave.click();
              cbCambiarClave.checked = 0;
              $('#claveActual').removeClass('d-none');
              $('#cambiarClave').removeClass('d-none');

              txtNom.value = jsonJS.usuarios.usu_nom;
              txtPue.value = jsonJS.usuarios.usu_pue;
              cbEliminarUsu.checked = (jsonJS.usuarios.usu_priv & 16) ? 1 : 0;
              cbModificarUsu.checked = (jsonJS.usuarios.usu_priv & 8) ? 1 : 0;
              cbEliminar.checked = (jsonJS.usuarios.usu_priv & 4) ? 1 : 0;
              cbModificar.checked = (jsonJS.usuarios.usu_priv & 2) ? 1 : 0;
              cbConsultar.checked = (jsonJS.usuarios.usu_priv & 1) ? 1 : 0;

              jsonJS.modulos.forEach(function(i, sb){
                document.getElementById(i.modCod).checked = parseInt(jsonJS.usuarios[i.modCampo]);
              });
              nuevo = false;
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // VALID CAMBIAR CLAVE
    $("#cbCambiarClave").change(function (){
      if (this.checked) {
        $('#ingresarClaves').show(500);
        if (!isMobile()) {
          txtClaveActual.focus();
        }
      } else {
        $('#ingresarClaves').hide(500);
      }
    });

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      txtCod.focus();
      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "borrar");

        parametros.append("txtCod", txtCod.value);
        
        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Cargando...")
          },
          success: function (jsonPhp) {
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alErrorFocus(jsonJS);
            } else {
              alSuccess(jsonJS);
              limpiar();
              txtCod.value = "";
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};

      var cbPriv = 0;
      cbPriv += (cbEliminarUsu.checked) ? 16 : 0;
      cbPriv += (cbModificarUsu.checked) ? 8 : 0;
      cbPriv += (cbEliminar.checked) ? 4 : 0;
      cbPriv += (cbModificar.checked) ? 2 : 0;
      cbPriv += (cbConsultar.checked) ? 1 : 0;

      const parametros = new FormData();
      parametros.append("action", "guardar");

      if (cbCambiarClave.checked) {
        if (isNullPer(txtClaveNueva.value) && isNullPer(txtClaveNuevaC.value)) {
          txtClaveNueva.focus();
          alError({"msg":{"type":"error","title":"Contraseñas Vacías","text":"La Nueva Contraseña y Contraseña de Confirmación están vacías, es necesario ingresar una contraseña, ","ok":"Aceptar"}});
          return;
        }
        if (txtClaveNueva.value != txtClaveNuevaC.value) {
          txtClaveNuevaC.focus();
          alError({"msg":{"type":"error","title":"Contraseñas no Coinciden","text":"La Contraseña de Confirmación no coincide con la Nueva Contraseña","ok":"Aceptar"}});
          return;
        }
      }

      parametros.append("nuevo", nuevo);
      parametros.append("txtCod", txtCod.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("txtPue", txtPue.value);
      parametros.append("cbCambiarClave", cbCambiarClave.checked);
      parametros.append("txtClaveActual", txtClaveActual.value);
      parametros.append("txtClaveNueva", txtClaveNueva.value);
      parametros.append("cbPriv", cbPriv);

      const jsonJS = <?php echo ($selectArray["modulos"]); ?>;

      jsonJS.modulos.forEach(function(i, sb){
        parametros.append(i.modCod, document.getElementById(i.modCod).checked);
      });
      parametros.append("jsonMod", JSON.stringify(jsonJS.modulos));

      txtCod.focus();
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
          alLoad("Cargando...")
        },
        success: function (jsonPhp) {
          console.log(jsonPhp)
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            limpiar();
            txtCod.value = "";
            txtCod.focus();
          }
        }
      });
    });

    // CLICK IMPRIMIR
    $("#btnImprimir").click(function (){
      window.open(window.location.origin+window.location.pathname+"print.php", '_blank');
    });
  });

  // FOCUS PILL
  $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
    if (!isMobile()) {
      const target = e.target.attributes.href.value;
      $(target+' input:visible:first').focus();
    }
  });

</script>