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

$empCod = $_SESSION['empCod'];

$dtFec=date("Y-m-d");

# QUERYS
$sGrupo = "SELECT * FROM grupo WHERE gru_emp='".$_SESSION['empCod']."'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["grupo"] = $db->query($sGrupo);

?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-file-invoice"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
      ?>

      <!-- MODAL LISTA DE EMPLEADOS -->
      <div class="modal fade" id="modalListaEmp" tabindex="-1" role="dialog" aria-labelledby="modalListaEmpTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-007-tab" data-toggle="pill" href="#pills-007" role="tab" aria-controls="pills-007" aria-selected="true">Lista de Empleados a incluir</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-007" role="tabpanel" aria-labelledby="pills-007-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                          <label> </label>
                      </div>
                      <div class="form-row">
                        <div class="col-12 text-right mb-2">
                          <div class="custom-control custom-checkbox">
                            <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-bordered table-dark table-xs" id="tblListaEmp">
                              <thead>
                                <tr>
                                  <th scope="col" class="text-center" width="80">CODIGO</th>
                                  <th scope="col" class="text-center" width="360">NOMBRE</th>
                                  <th scope="col" class="text-center" width="150">PUESTO</th>
                                  <th scope="col" class="text-center" width="50">STATUS</th>
                                  <th scope="col" class="text-center" width="100">INCLUIR</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col"></th>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnContiLisDocp">Regresar</button>
                  </form>

                </div>
              </div>
           </div>
          </div>
        </div>
      </div>

      <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">Generacion de Planillas</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 class="font-size-lg" for="selGrupo">Grupo a Generar</label>
                            <select class="form-control form-control-lg form-control-as" name="selGrupo" id="selGrupo">
<!--                              <option value=99999>Todos los Grupos</option>    -->
                              <?php
                                while ($rec = $db->fetchAssoc($select['grupo'])) {
                                  echo  "<option value={$rec['gru_cod']}>".utf8_encode($rec['gru_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>

                          <div class="col-3">
                            <label class="font-size-lg" for="dtDel">Periodo del: </label>
                            <input type="date" class="form-control form-control-lg form-control-as" id="dtDel">
                          </div>
                          <div class="col-3">
                            <label class="font-size-lg" for="dtAl">Al: </label>
                            <input type="date" class="form-control form-control-lg form-control-as" id="dtAl">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label class="font-size-lg text-success" for="numDtra">Dias Trajados</label>
                            <input type="number" class="form-control form-control-lg form-control-as dec-1" id="numDtra" placeholder="0.0">
                          </div>
                          <div class="col-2">
                            <label class="font-size-lg text-success" for="numDsept">Dias Septimos</label>
                            <input type="number" class="form-control form-control-lg form-control-as dec-1" id="numDsept" placeholder="0.0">
                          </div>
                          <div class="col-3">
                            <label class="font-size-lg text-success" for="numDferi">Feriados/Asuetos/Bono Incentivo</label>
                            <input type="number" class="form-control form-control-lg form-control-as dec-1" id="numDferi" placeholder="0.0">
                          </div>
                        </div>

<!--                        <div class="form-row">
                          <div class="col-4">
                            <label class="pr-1">El pago de la primera quincena es solo anticipo, sin descuentos ?</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crAnti1" name="crAnti" class="custom-control-input calcular" value="S">
                              <label class="custom-control-label" for="crAnti1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crAnti2" name="crAnti" class="custom-control-input calcular" value="N">
                              <label class="custom-control-label" for="crAnti2">No</label>
                            </div>
                          </div>
                        </div>     -->
                      </div>
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-4">
                            <button class="btn btn-warning btn-lg btn-block" id="btnSelemple" type="button">Seleccionar Empleados</button>
                          </div>
                          <div class="col-4">
                            <button class="btn btn-success btn-lg btn-block" id="btnGenerar" type="button">Generar Planilla</button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputNumb = "numNumb";
  var inputCtaMov = "txtCtaord";
  var inputClien = "txtCli"
  var inputProypla = "txtCodp";

  const dtDel = document.thisform.dtDel;
  const dtAl = document.thisform.dtAl;

  function restriccion(consultar = false){
  }
  
  function restriccionCamposVacios() {
  }

  function limpiar(){
    dtDel.value= '<?php echo $dtFec; ?>';
    dtAl.value= '<?php echo $dtFec; ?>';
  }

  function addRowListaEmp(cod, nom, puesto, stat, l){
    const row = "<tr>"
                  +"<td id='datacod' class='text-left'>"+cod+"</td>"
                  +"<td id='datanom' class='text-left'>"+nom+"</td>"
                  +"<td id='datapuesto' class='text-left'>"+puesto+"</td>"
                  +"<td id='datastat' class='text-center'>"+stat+"</td>"
                  +"<td class='text-center'>"
                    +"<div class='custom-control custom-checkbox'>"
                    +"<input type='checkbox' class='custom-control-input' id='dataCheck"+l+"' name='cb' checked>"
                    +"<label class='custom-control-label mt-0' for='dataCheck"+l+"'></label>"
                    +"</div>"
                  +"</td>"
                +"</tr>";
    $("#tblListaEmp tbody").append(row);
  }

  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    dtDel.value= '<?php echo $dtFec; ?>';
    dtAl.value= '<?php echo $dtFec; ?>';
    numDtra.value = (13).toFixed(1);
    numDsept.value = (2).toFixed(1);
    numDferi.value= "";
    // SHOW MODAL
    $('#modalListaEmp').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      }
    });

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

    // VALID CODIGO
    $("#dtAl")
    .blur(function (){
      var da = new Date(dtAl.value).getTime();
      var dd = new Date(dtDel.value).getTime();
      var diff = da - dd;
      diff = Number(diff/(1000*60*60*24)+1);
      console.log(diff);
      if (diff<16) {
         numDtra.value = (diff-2);
      } else {
         (13).toFixed(1);
      }
      console.log((Number(numDtra.value)+Number(numDsept.value)));

      if ((Number(numDtra.value)+Number(numDsept.value))<15) {
         numDferi.value = (15-(Number(numDtra.value)+Number(numDsept.value)));
      } else {
         numDferi.value = (0).toFixed(1);
      }

    });


    // FOCUS INPUT
    $("form[name='thisform'] input, select").focus(function (){
      if (!($("input:visible:first").is(":focus"))) {
        if (restriccionCamposVacios()) {return};
      }
    });

    $("#btnSelemple").click(function (){
      if (restriccion()) {return};
      if (dtDel.value==dtAl.value || dtDel.value>dtAl.value) {
        dtDel.focus();
        alWarning({"msg":{"title":"PERIODO INVALIDO","text":"Revise su rango de fechas, para el periodo"}});
        return true;
      }
      const parametros = new FormData();
      parametros.append("action", "consultarProypla");
      parametros.append("selGrupo", selGrupo.value);
      parametros.append("dtDel", dtDel.value);
      parametros.append("dtAl", dtAl.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            tblClear("tblListaEmp");
            if (isNullPer(jsonJS.maestro)) {
              alWarning({"msg":{"title":"NO HAY EMPLEADOS REGISTRADOS","text":"No hay empleados registrados para generar, revise."}});
              return true;
            } else {
              jsonJS.maestro.forEach(function(i,index){
                addRowListaEmp(i.mae_cod, i.mae_nom+" "+i.mae_ape, i.tpu_nom, i.mae_stat, index);
              });  
              $('#modalListaEmp').modal('toggle');
            }
          }
        }
      });
    });

    $("#btnContiLisDocp").click(function (){
      $('#modalListaEmp').modal('toggle');
    });

  $('#cbTodos').click(function () {
    cbAllChecked("tblListaEmp", "cb", "cbTodos");
  });

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

      // PARA VER SI LA LISTA DE EMPLEADOS ESTA VACIA, PARA LLENARLA
      if ($("#tblListaEmp tbody").children().length == 0) {
        alWarning({"msg":{"title":"SELECCIONAR EMPLEADOS","text":"Por favor antes utilice el bonton para seleccionar empleados"}});
        return true;
      }

      colListaEmp = ["cod", "nom", "pue", "stat", "check"];

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

      parametros.append("nuevo", nuevo);
      parametros.append("dtDel", dtDel.value);
      parametros.append("dtAl", dtAl.value);
      parametros.append("crAnti", "N");
      parametros.append("selGrupo", selGrupo.value);
      parametros.append("numDtra", numDtra.value);
      parametros.append("numDsept", numDsept.value);
      parametros.append("numDferi", numDferi.value);
      parametros.append("tblListaEmp", tblToJsonCbSkip(colListaEmp, "tblListaEmp", 10, 4));
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        async: true,
        beforeSend: function () {
          alLoad("Generando Planilla, puede tardar un momento, espere ...")
        },
        success: function (jsonPhp) {
          console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            tblClear("tblListaEmp");
            limpiar();
            alWarning({"msg":{"title":"PLANILLA GENERADA","text":"Se genero la planilla No. "+jsonJS.numpla}});
          }
        }
      });
    });
  });

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

</script>