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

$dtFec=date("Y-m-d");
$anoTrab=date("Y");
//, strtotime($_SESSION['empFtrab'])
?>
<?php include_once('../includes/htmlOpenPov.php'); ?>
    <style type="text/css">
      .
    </style>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-file-invoice"></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">ASIGNAR RESOLUCION</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="true">Buscar Resolucion</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-row">
                    <div class="col-12 col-sm-9">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-sm-4">
                            <label for="txtNumr">Resolucion Asignada</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNumr"  placeholder="" maxlength="30">
                          </div>
                        </div>
                        <h3 class="text-light"></h3>
                      </div>

                    </div>
                    <div class="col-12 col-lg-3">
                      <div class="form-group position-fixed-sm">
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-warning btn-lg btn-block" id="btnClave" type="button">CLAVE PARA ACCESAR</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                        </div>
                        <div class="form-row">
                        </div>
                      </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('../busResolu/index.html');
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputResolu = "txtNumr";
  var stat = 'A';
  var tipo = '';
  var serie = '';

  const txtNumr = document.thisform.txtNumr;

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtNumr.value)) {
        txtNomt.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de Resolucion"}});
        return true;
      }
    } else {
      if (isNullPer(txtNumr.value)) {
        return true;
      }
    } 
    return false;  
  }

  function limpiar(){
    $('.limpiar').val('');
  }


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

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

    // VALID CODIGO
    $("form[name='thisform'] #txtNumr")
    .focus(function() {
      inputResolu = $(this).attr('id');
    })
    .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 = btnGuardar;

      const parametros = new FormData();
      parametros.append("action", "consultarResolu");
      parametros.append("txtNumr", txtNumr.value);

      txtNext.focus()

      $.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) {
          console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            limpiar();
            
            if (jsonJS.resolu === null) {
              nuevo = true;
              stat='N';
              alWarning({"msg":{"title":"RESOLUCION NO REGISTRADA","text":"Esta resolucion no ha sido registrada."}});
              return true;
            } else {
              tipo = jsonJS.resolu.res_tipo;
              serie = jsonJS.resolu.res_serie;
              stat = jsonJS.resolu.res_stat;
              nuevo = false;
              if (stat == 'B') {
                alWarning({"msg":{"title":"RESOLUCION YA CADUCO","text":"No se grabara ningun cambio que haga"}});
                return true;
              }
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    })
    .init(function() {
      const parametros = new FormData();
      parametros.append("action", "consultar");

      $.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) {
          console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.caja === null) {
              alWarning({"msg":{"title":"NO EXISTE","text":"Este codigo no ha sido registrado"}});
              return true;
            } else {
              tipo = jsonJS.caja.caj_tipofac;
              serie = jsonJS.caja.caj_seriefac;
              txtNumr.value = jsonJS.caja.caj_resolu;
            }
          }
        }
      });
    });



    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};
      if (stat == 'B') {
        txtNumr.focus();
        alWarning({"msg":{"title":"RESOLUCION YA CADUCO","text":"No se grabara ningun cambio que haga"}});
        return true;
      }
      if (stat == 'N') {
        txtNumr.focus();
        alWarning({"msg":{"title":"RESOLUCION NO EXISTE","text":"Esta resolucion no ha sido registrada."}});
        return true;
      }

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

      parametros.append("nuevo", nuevo);
      parametros.append("txtNumr", txtNumr.value);
      parametros.append("tipo", tipo);
      parametros.append("serie", serie);

      txtNumr.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);
            txtNumr.disabled = true;
          }
        }
      });
    });

    // CLICK CLAVE
    $("#btnClave").click(function (){
      const fnT = function(){
        txtNumr.disabled = false;
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

  });

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

      if ((target == "#pills-0" && isNullPer(txtNumr.value))  || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? $('#btnGuardar').focus() : 0;
      }
    //}
  });

</script>