<?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">Series</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 Series</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 align-items-end">
                          <div class="col-sm-2">
                            <label for="txtCod">Codigo/Serie</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCod"  placeholder="" maxlength="20">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-5">
                            <label for="txtNom">Nombre:</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNom" placeholder="" maxlength="20">
                          </div>
                        </div>
                        <div class="form-row  align-items-end">
                          <div class="col-md-2">
                            <label for="numCorr">Correlativo:</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCorr" placeholder="0">
                          </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('../busTipov/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

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

  const txtCod = document.thisform.txtCod;
  const txtNom = document.thisform.txtNom;
  const numCorr = document.thisform.numCorr;


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

  function limpiar(){
    $('.limpiar').val('');
    txtNom.value="";
    numCorr.value = "";
  }


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

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


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

      const parametros = new FormData();
      parametros.append("action", "consultar");
      parametros.append("txtCod", txtCod.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.tipov === null) {
              nuevo = true;
              alWarning({"msg":{"title":"SERIE NO REGISTRADA","text":"Esta serie no ha sido registrada"}});
              return true;
            } else {
              txtCod.value = jsonJS.tipov.tv_cod;
              txtNom.value = jsonJS.tipov.tv_nom;
              numCorr.value = jsonJS.tipov.ctv_num;
              nuevo = false;
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });


    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};
      if (nuevo) {
        txtCod.focus();
        alWarning({"msg":{"title":"SERIE NO REGISTRADA","text":"Esta serie no ha sido registrada"}});
        return true;
      }
      if (isNullPer(numCorr.value)) {
        numCorr.focus();
        alWarning({"msg":{"title":"CORRELATIVO NO VALIDO","text":"Debe ingresar algun numero para el correlativo."}});
        return true;
      }

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

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

      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 = "";
          }
        }
      });
    });

    // CLICK CLAVE
    $("#btnClave").click(function (){
      const fnT = function(){
        txtCod.disabled = false;
        numCorr.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(txtCod.value))  || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? $('#numCorr').focus() : 0;
      }
    //}
  });

</script>