<?php
include_once('../../../php/sessionStart.php');
include_once('../includes/htmlOpen.php');

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

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

$func = new functions();
$selectArray["modulos"] = $func->jsonEncodeArray($selectArray, "modulos");
?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-cog"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.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 form-row">
                    <div class="col-md-6">
                      <div class="form-row">
                        <div class="col-md-12">
                          <label for="txtCod">Usuario</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" placeholder="0" required>
                        </div>
                        <div class="col-md-12 mt-1">
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtUsuNom" placeholder="" disabled>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-6">
                      <label for="selMod">Módulo</label>
                      <select class="form-control form-control-sm form-control-as" name="selMod" id="selMod">
                        <option value="0">Seleccionar...</option>
                      </select>
                    </div>
                  </div>

                  <h3 class="text-light">Opciones</h3>
                  
                  <div class="form-group form-row">
                    <div class="col-md-12">
                      <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="cbTodos" name="cb" checked>
                        <label class="custom-control-label mt-0" for="cbTodos">Seleccionar Todos</label>
                      </div>
                    </div>
                    <div class="col-md-12">
                      <div class="table-responsive">
                        <table class="table table-hover table-borderless table-dark" id="tblOpc">
                          <thead>
                            <tr>
                              <th scope="col">Asignar</th>
                              <th scope="col">Opciones</th>
                            </tr>
                          </thead>
                          <tbody>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>

                  <div class="form-group form-row">
                    <div class="col">
                      <button class="btn btn-success btn-lg btn-block" id="btnGuardar" type="button">Guardar</button>
                    </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_once('../busUsuarios/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

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

  function checkboxStat(tf, form) {
    if (tf) {
      return '<div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" name="cb" id="cb'+form+'" checked><label class="custom-control-label" for="cb'+form+'"></label></div>';
    }
    return '<div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" name="cb" id="cb'+form+'"><label class="custom-control-label" for="cb'+form+'"></label></div>';
  }

  function restriccion(consultar = false){
    const usuCod = document.thisform.txtCod;
    if (isNullPer(usuCod.value)) {
      if (!consultar) {
        usuCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el usuario"}});
      } else {
        document.thisform.txtUsuNom.value = "";
      }
      return true;
    }
    return false;
  }

  function addRowOpc(usuo_stat, opcForm, opcNom) {
    const row = "<tr>"
                +"<td>"+checkboxStat(usuo_stat, opcForm)+"</td>"
                +"<td class='d-none'>"+opcForm+"</td>"
                +"<td>"+opcNom+"</td>"
                +"</tr>";
    $("#tblOpc tbody").append(row);
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    document.thisform.selMod.disabled = true;

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

    // VALID MODULO
    $("#selMod").change(function (){
      tblClear("tblOpc");
      modCod = document.thisform.selMod.value;

      if (modCod==0) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarOpc");
      parametros.append("txtCod", document.thisform.txtCod.value);
      parametros.append("selModCod", modCod);

      $.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 {
            if (jsonJS.maestro === null) {
              alError({"msg":{"type":"error","title":"No existe","text":"El módulo "+modCod+" no existe", "ok":"Aceptar"}});
            } else {
              jsonJS.opc.forEach(function(i){
                addRowOpc(i.usuo_stat, i.opcForm, i.opcNom);
              });
              tblAllChecked("tblOpc", "cb", "cbTodos");
              alClose();
            }
          }
        }
      });
    });

    // VALID USUARIO
    $("#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 (){
      txtThis = this;
      txtGetValue = document.thisform.txtUsuNom;
      txtNext = document.thisform.selMod;

      $(txtThis).off("blur");
      if (restriccion(true)) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarUsuCod");
      parametros.append("txtCod", txtThis.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 {
            if (jsonJS.usuarios === null) {
              txtGetValue.value = "";
              txtNext.disabled = true;
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"El usuario "+txtThis.value+" no ha sido registrado", "ok":"Aceptar"}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.usuarios.usu_nom;
              txtNext.disabled = false;

              // PARA MOSTRAR LOS MODULOS QUE TIENE PERMITIDOS
              const jsonMod = <?php echo ($selectArray["modulos"]); ?>;

              $("#selMod option").remove();
              $("#selMod").append($("<option>", { value: "0", text: "Seleccionar..." }));
              jsonMod.modulos.forEach(function(i, sb){
                if (parseInt(jsonJS.usuarios[i.modCampo])) {
                  $("#selMod").append($("<option>", { value: i.modCod, text: i.modNom }));
                }
              });
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
            tblClear("tblOpc");
            document.thisform.selMod.value = 0;
          }
        }
      });
    });

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

      colOpc = ["stat", "opcForm", "opcNom"];

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

      parametros.append("txtCod", document.thisform.txtCod.value);
      parametros.append("selModCod", document.thisform.selMod.value);
      parametros.append("tblOpc", tblToJsonCbSkip(colOpc, "tblOpc", 5, 0));

      document.thisform.selMod.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) {
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            tblClear("tblOpc");
            document.thisform.selMod.value = 0;
          }
        }
      });
    });

    // CLICK TODOS
    $('#cbTodos').click(function () {
      cbAllChecked("tblOpc", "cb", "cbTodos");
    });

    // FOCUS PILL
    $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
      $(e.target.attributes.href.value+' input').focus();
    });
  });
</script>