<?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">Resoluciones</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 align-items-end">
                          <div class="col-sm-4">
                            <label for="txtNumr">Numero Resolucion</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNumr"  placeholder="" maxlength="30">
                          </div>
                          <div class="col-4">
                            <label for="dtFec">Fecha Resolucion</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label for="txtSerie">Serie:</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtSerie" placeholder="" maxlength="20">
                          </div>
                        </div>
                        <div class="form-row  align-items-end">
                          <div class="col-md-4">
                            <label for="numCorri">Correlativo Inicial:</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCorri" placeholder="0">
                          </div>
                          <div class="col-md-4">
                            <label for="numCorrf">Correlativo Final:</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCorrf" placeholder="0">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-4">
                            <label for="dtFecven">Fecha Vencimiento</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFecven">
                          </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 class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-lg btn-block" id="btnLista" type="button">Listado de Resoluciones</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 nuevoserie = true;
  var inputResolu = "txtNumr";
  var fecg = '<?php echo $dtFec; ?>';
  var stat = 'A';

  const txtNumr = document.thisform.txtNumr;
  const dtFec = document.thisform.dtFec;
  const txtSerie = document.thisform.txtSerie;
  const numCorri = document.thisform.numCorri;
  const numCorrf = document.thisform.numCorrf;
  const dtFecven = document.thisform.dtFecven;


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtNumr.value)) {
        txtNumr.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('');
    dtFec.value= '<?php echo $dtFec; ?>';
    txtSerie.value="";
    numCorri.value = 0;
    numCorrf.value = 0;
    dtFecven.value= '<?php echo $dtFec; ?>';
  }


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

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


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

      const parametros = new FormData();
      parametros.append("action", "consultar");
      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='A';
            } else {
              dtFec.value = jsonJS.resolu.res_fec;
              txtSerie.value = jsonJS.resolu.res_serie;
              numCorri.value = jsonJS.resolu.res_ini;
              numCorrf.value = jsonJS.resolu.res_fin;
              dtFecven.value = jsonJS.resolu.res_fecven;
              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;
          }
        }
      });
    });

    // VALID Serie
    $("form[name='thisform'] #txtSerie")
    .blur(function (){
      if (restriccion(true)) {return};

      txtNext = numCorrf;

      const parametros = new FormData();
      parametros.append("action", "consultarSerie");
      parametros.append("txtSerie", txtSerie.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 {
            if (jsonJS.corrtipov === null) {
              nuevoserie = true;
              numCorri.value=1;
              numCorrf.value=2;
            } else {
              if (nuevo) {
                numCorri.value = jsonJS.corrtipov.ctv_num;
              }
              nuevoserie = false;
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // VALID Numero Final
    $("form[name='thisform'] #numCorrf")
    .blur(function (){
      if (restriccion(true)) {return};
      if (Number(numCorrf.value) <= Number(numCorri.value)) {
        numCorrf.focus();
        alWarning({"msg":{"title":"Numero Final Erroneo","text":"El Numero Final, no puede ser ni menor, ni igual al numero Inicial"}});
        return true;
      }
    });

    // VALID Fechas
    $("form[name='thisform'] #dtFec")
    .blur(function (){
      if (restriccion(true)) {return};
      if (dtFec.value > fecg && nuevo) {
        dtFec.focus();
        alWarning({"msg":{"title":"Fecha Invalida","text":"La fecha de la resolucion no puede ser mayor que la fecha actual"}});
        return true;
      }
      if (dtFec.value < sumYMD(fecg,Number(-10)) && nuevo) {
        dtFec.focus();
        alWarning({"msg":{"title":"Fecha Invalida","text":"Se paso de los diez dias permitidos para registrar la resolucion."}});
        return true;
      }
    });

    // VALID Fechas
    $("form[name='thisform'] #dtFecven")
    .blur(function (){
      if (restriccion(true)) {return};
      if (dtFecven.value < dtFec.value) {
        dtFecven.focus();
        alWarning({"msg":{"title":"Fecha de Vencimiento Invalida","text":"La fecha de Vencimiento, no puede ser menor a la fecha de la resolucion."}});
        return true;
      }
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};
      if (stat == 'B') {
        alWarning({"msg":{"title":"RESOLUCION YA CADUCO","text":"No se grabara ningun cambio que haga"}});
        return true;
      }
      if (dtFecven.value < dtFec.value) {
        dtFecven.focus();
        alWarning({"msg":{"title":"Fecha de Vencimiento Invalida","text":"La fecha de Vencimiento, no puede ser menor a la fecha de la resolucion."}});
        return true;
      }
      if (dtFec.value > fecg && nuevo) {
        dtFec.focus();
        alWarning({"msg":{"title":"Fecha Invalida","text":"La fecha de la resolucion no puede ser mayor que la fecha actual"}});
        return true;
      }
      if (dtFec.value < sumYMD(fecg,Number(-10)) && nuevo) {
        dtFec.focus();
        alWarning({"msg":{"title":"Fecha Invalida","text":"Se paso de los diez dias permitidos para registrar la resolucion."}});
        return true;
      }
      if (Number(numCorrf.value) <= Number(numCorri.value)) {
        numCorrf.focus();
        alWarning({"msg":{"title":"Numero Final Erroneo","text":"El Numero Final, no puede ser ni menor, ni igual al numero Inicial"}});
        return true;
      }

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

      parametros.append("nuevo", nuevo);
      parametros.append("nuevoserie", nuevoserie);
      parametros.append("txtNumr", txtNumr.value);
      parametros.append("dtFec", dtFec.value);
      parametros.append("txtSerie", txtSerie.value);
      parametros.append("numCorri", numCorri.value);
      parametros.append("numCorrf", numCorrf.value);
      parametros.append("dtFecven", dtFecven.value);
      parametros.append("stat", stat);
      parametros.append("fecg", fecg);

      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);
            limpiar();
            txtNumr.value = "";
          }
        }
      });
    });

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

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      const fnT = function(){

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

        parametros.append("txtNumr", txtNumr.value);
        
        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);
              //numNum.value = "";
              limpiar();
              txtNumr="";
            }
          }
        });
      }

      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") ? $('#dtFec').focus() : 0;
      }
    //}
  });

</script>