<?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/htmlOpen.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">Vacaciones</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 Empleados</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-2-tab" data-toggle="pill" href="#pills-2" role="tab" aria-controls="pills-2" aria-selected="true">Buscar Vacaciones</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="numCod">Código</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCod" placeholder="">
                          </div>
                          <div class="col-sm-10">
                            <label for="txtNom">Nombre del Empleado</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNom" placeholder="" maxlength="100" disabled>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label for="numCiclo">Periodo:</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCiclo">
                          </div>
                          <div class="col-4">
                            <label for="dtDel">Inicio del Descanso</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtDel">
                          </div>
                          <div class="col-4">
                            <label for="dtAl">Fin del Descanso</label>
                            <input type="date" class="form-control form-control-sm form-control-as limpiar" id="dtAl">
                          </div>
                        </div>
                        <div class="form-row  align-items-end">
                          <div class="col-md-7">
                            <label for="txtObs">Observaciones:</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtObs" placeholder="" maxlength="100">
                          </div>
                          <div class="col-md-4">
                            <label for="txtSoli">Solicitud:</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtSoli" placeholder="" maxlength="30">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-3">
                            <label for="numDiasv">Dias Vacaciones:</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numDiasv">
                          </div>
                          <div class="col-6">
                            <label class="pr-1">Vacaciones Trabajadas</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTrabaja1" name="crTrabaja" class="custom-control-input" value=1>
                              <label class="custom-control-label" for="crTrabaja1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTrabaja2" name="crTrabaja" class="custom-control-input" value=0>
                              <label class="custom-control-label" for="crTrabaja2">No</label>
                            </div>
                          </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>
                        <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('../busEmpleado/index.html');
                ?>
              </div>
              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busVaca/index.html');
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputEmple = "numCod";
  var inputCiclo = "numCiclo";
  var inputDel = "dtDel";
  var inputAl = "dtAl";

  const numCod = document.thisform.numCod;
  const txtNom = document.thisform.txtNom;
  const dtDel = document.thisform.dtDel;
  const dtAl = document.thisform.dtAl;
  const numCiclo = document.thisform.numCiclo;
  const crTrabaja = document.thisform.crTrabaja;
  const txtObs = document.thisform.txtObs;
  const txtSoli = document.thisform.txtSoli;


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

  function limpiar(){
    $('.limpiar').val('');
//    txtNom.value = "";
    dtAl.value= '<?php echo $dtFec; ?>';
    crTrabaja.value=0;
    txtObs.value = "";
    txtSoli.value = "";
    numDiasv.value = "";
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    limpiar();
    numCiclo.value= '<?php echo $anoTrab; ?>';
    dtDel.value= '<?php echo $dtFec; ?>';
    numCod.disabled = true;
    txtNom.disabled = true;
    numCiclo.disabled = true;
    dtDel.disabled = true;
    dtAl.disabled = true;
    crTrabaja1.disabled = true;
    crTrabaja2.disabled = true;
    txtSoli.disabled = true;
    txtObs.disabled = true;
    numDiasv.disabled = true;


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


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

      const parametros = new FormData();
      parametros.append("action", "consultar");
      parametros.append("numCod", numCod.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.maestro === null) {
              numCod.focus();
              alWarning({"msg":{"title":"NO EXISTE","text":"Este codigo no ha sido registrado"}});
              return true;
            } else {
              txtNom.value = jsonJS.maestro.mae_nom+' '+jsonJS.maestro.mae_ape;
              //$("#selDepto").trigger("change");
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // VALID CODIGO
    $("form[name='thisform'] #numCiclo")
    .focus(function() {
      limpiar();
    });

    // VALID FECHA AL
    $("form[name='thisform'] #dtDel")
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .focus(function() {
      inputEmple = $('#numCod').attr('id');
      //$(this).attr('id');
      crTrabaja.value=0;
      txtObs.value = "";
      txtSoli.value = "";
      numDiasv.value = "";

      const parametros = new FormData();
      parametros.append("action", "consultarCiclo");
      parametros.append("numCiclo", numCiclo.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) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
          //  limpiar();
          //  (pressEnter) ? alClose() : alCloseFocus(txtNext);
          //  pressEnter = false;
          }
        }
      });
    })
    .blur(function() {
      inputEmple = $('#numCod').attr('id');
      //$(this).attr('id');
      if (restriccion(true)) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarVaca");
      parametros.append("numCod", numCod.value);
      parametros.append("numCiclo", numCiclo.value);
      parametros.append("dtDel", dtDel.value);

      dtAl.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);
            diasvant=0;
          } else {
            if (jsonJS.regvacd === null) {
              diasvant=0;
              nuevo=true;
            } else {
              //dtDel.value=jsonJS.regvacd.rvd_fdesi;
              dtAl.value=jsonJS.regvacd.rvd_fdesf;
              crTrabaja.value=jsonJS.regvacd.rvd_trabaja;
              txtObs.value=jsonJS.regvacd.rvd_obs;
              txtSoli.value=jsonJS.regvacd.rvd_soli;
              numDiasv.value=jsonJS.regvacd.rvd_diasv;
              diasvant=jsonJS.regvacd.rvd_diasv;
              nuevo=false;
            }
          }
        }
      });
    });
 /*   .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })  */


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

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

      parametros.append("nuevo", nuevo);
      parametros.append("numCod", numCod.value);
      parametros.append("numCiclo", numCiclo.value);
      parametros.append("txtNom", txtNom.value);
      parametros.append("dtDel", dtDel.value);
      parametros.append("dtAl", dtAl.value);
      parametros.append("crTrabaja", crTrabaja.value);
      parametros.append("txtObs", txtObs.value);
      parametros.append("txtSoli", txtSoli.value);
      parametros.append("numDiasv", numDiasv.value);
      parametros.append("diasvant", diasvant);

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

    // CLICK CLAVE
    $("#btnClave").click(function (){
      const fnT = function(){
        numCod.disabled = false;
        numCiclo.disabled = false;
        dtDel.disabled = false;
        dtAl.disabled = false;
        crTrabaja1.disabled = false;
        crTrabaja2.disabled = false;
        txtObs.disabled = false;
        txtSoli.disabled = false;
        numDiasv.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("numCod", numCod.value);
        parametros.append("numCiclo", numCiclo.value);
        parametros.append("dtDel", dtDel.value);
        parametros.append("diasvant", diasvant);
        
        numCod.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();
              numCod="";
            }
          }
        });
      }

      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(numCod.value))  || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? $('#numCiclo').focus() : 0;
        (relatedTarget == "#pills-2") ? $('#dtDel').focus() : 0;
      }
    //}
  });

</script>