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

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

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];
$empNit = $_SESSION['empNit'];

# QUERYS
$sBancos = "SELECT *, 
              TRIM(ban_nom) as ban_nom,
              TRIM(ban_ctab) as ban_ctab,
              TRIM(ban_ctac) as ban_ctac
            FROM bancos WHERE ban_emp='$empCod'";
$sTpuesto = "SELECT * FROM tpuesto ORDER BY tpu_nom";
$sGrupo = "SELECT * FROM grupo WHERE gru_emp='".$_SESSION['empCod']."'";
$sDep = "SELECT * FROM dep WHERE dep_emp='".$_SESSION['empCod']."'";
$sBodegapro = "SELECT * FROM bodegapro";
# EJECUCION DE QUERYS
$db = new dbExec();
$select["bancos"] = $db->query($sBancos);
$select["tpuesto"] = $db->query($sTpuesto);
$select["grupo"] = $db->query($sGrupo);
$select["dep"] = $db->query($sDep);
$select["bodegapro"] = $db->query($sBodegapro);
?>
<?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');
      ?>

      <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">Pago en Efectivo NPI</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 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-md-10">
                      <div class="form-group">

                        <div class="form-row">
                          <div class="col-2.5">
                              <label class="font-size-md" for="numNum">Número de Planilla</label>
                              <input type="number" class="form-control form-control-md form-control-as" id="numNum" placeholder="0">
                          </div>
                          <div class="col-3">
                              <label class="font-size-md" for="dtDel">Periodo del:</label>
                              <input type="date" class="form-control form-control-md form-control-as" id="dtDel" placeholder="" disabled>
                          </div>
                          <div class="col-3">
                              <label class="font-size-md" for="dtAl">Al</label>
                              <input type="date" class="form-control form-control-md form-control-as" id="dtAl" maxlength="20" disabled>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-sm-3">
                            <label class="font-size-md" for="selBodegapro">Bodega</label>
                            <select class="form-control form-control-md form-control-as" name="selBodegapro" id="selBodegapro">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bodegapro'])) {
                                  echo  "<option value={$rec['bp_cod']}>".utf8_encode($rec['bp_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-sm-3">
                            <label  class="font-size-md" for="selDep">Departamento dentro de la empresa</label>
                            <select class="form-control form-control-md form-control-as" name="selDep" id="selDep">
                              <option value="000">Todos los Departamentos</option>
                              <?php
                                while ($rec = $db->fetchAssoc($select['dep'])) {
                                  echo  "<option value={$rec['dep_cod']}>".utf8_encode($rec['dep_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-sm-3">
                            <label class="font-size-md" for="selPuesto">Puesto/Area</label>
                            <select class="form-control form-control-md form-control-as" name="selPuesto" id="selPuesto">
                              <option value="000">Todos los Puestos/Areas</option>
                              <?php
                                while ($rec = $db->fetchAssoc($select['tpuesto'])) {
                                  echo  "<option value={$rec['tpu_cod']}>".utf8_encode($rec['tpu_nom']).'</option>';
                                }
                              ?>
                            </select >
                          </div>
                        </div>
                      <div class="form-row">
<!---                          <div class="col-md-6">
                            <label class="font-size-md text-success" for="selBan">Cuenta para Generar Archivo</label>
                            <select class="form-control form-control-md form-control-as" name="selBan" id="selBan">
                              <?php
//                                while ($rec = $db->fetchAssoc($select['bancos'])) {
//                                  echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
//                                }
                              ?>
                            </select>
                          </div>   --->
                          <div class="col-3">
                              <label class="font-size-md" for="dtFec">Fecha del reporte:</label>
                              <input type="date" class="form-control form-control-md form-control-as" id="dtFec">
                          </div>
                        </div>
                        <div class="form-row">
                        </div>
                      </div>

                      <h3 class="text-light"></h3>
                      <h3 class="text-light"></h3>
                      <div class="form-group">
                        <div class="form-row">
                        </div>
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group position-fixed-md">
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-outline-success btn-block" id="btnImprimir" type="button">Imprimir Listado</button>
                          </div>
                          <div class="col-3 col-md-12"></div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-outline-info btn-block" id="btnExcel" type="button">Generar Excel</button>
                          </div>
                          <div class="col-3 col-md-12"></div>
                        </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('../busPlani/index.html');
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var nuevoArtic = true;
  var mesCerrado = false;
  var inputCtaMov = "txtCta";
  var totant = 0;
  var inputPlani = "numNum";
  var tblNomperAnt;
  var btnAddEdit = "00";
  var inputArtic = "txtCodd";
  var unimed = "XXX";
  var ctaInc = false;
  
  const numNum = document.thisform.numNum;
  const dtDel = document.thisform.dtDel;
  const dtAl = document.thisform.dtAl;
  const dtFec = document.thisform.dtFec;


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE PLANILLA"}});
        return true;
      }
    } else {
      if (isNullPer(numNum.value)) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE PLANILLA"}});
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(numNum.value)) {
      numNum.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE PLANILLA"}});
      return true;
    }
    return false;
  }


  function consultarPla(){
    if (restriccion(true)) {return};
    
    if (!isNullPer(numNum.value)) {
      const parametros = new FormData();
      parametros.append("action", "consultarPla");

      parametros.append("numNum", numNum.value);
      parametros.append("selBodegapro", selBodegapro.value);
      parametros.append("selDep", selDep.value);
      parametros.append("selPuesto", selPuesto.value);

      //txtNext.focus()

      $.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);
          tblNomperAnt = JSON.stringify(jsonJS.nomper);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (isNullPer(jsonJS.nomper)) {
              selPuesto.focus();
              alWarning({"msg":{"title":"PLANILLA NO REGISTRADA","text":"No hay planilla registrada con estos parametros, revise."}});
              return true;
            }
          }
        }
      });
    }      
  }

  function consultarPla1(){
    if (restriccion(true)) {return};
    
    if (!isNullPer(numNum.value)) {
      const parametros = new FormData();
      parametros.append("action", "consultarPla1");

      parametros.append("numNum", numNum.value);

      //txtNext.focus()

      $.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);
          tblNomperAnt = JSON.stringify(jsonJS.nomper);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (isNullPer(jsonJS.nomper)) {
              numNum.focus();
              alWarning({"msg":{"title":"PLANILLA NO REGISTRADA","text":"Esta Planilla no ha sido registrada, revise."}});
              return true;
            } else {
            //dtDel.value = jsonJS.nomper.np_fini;
            //dtAl.value = jsonJS.nomper.np_ffin;
            if (jsonJS.ctrpla.ctrp_sino=='S') {
              numNum.focus();
              alWarning({"msg":{"title":"PLANILLA NO ES DE ESTE TIPO","text":"Esta Planilla no fue registrada para este tipo de personal, debe usar la otra opcion, o ingresar el numero correcto de planilla"}});
            } 
            jsonJS.nomper.forEach(function(i){
               dtDel.value= i.np_fini;
               dtAl.value= i.np_ffin;
               //addRowNomper(i.np_cod, i.mae_nom+" "+i.mae_ape, i.tpu_nom, i.np_totdev, i.np_totdes, i.np_liqrec);
            });  
            //sumDetao();
            nuevo = false;
          }
        }
      }
    });
    }      
  }

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

  function getElements(locationPHP) {
    const getnumNum = "?numNum="+numNum.value;
    const getdtDel = "&dtDel="+dtDel.value;      
    const getdtAl = "&dtAl="+dtAl.value;      
    const getdtFec = "&dtFec="+dtFec.value;
    const getselBodegapro = "&selBodegapro="+selBodegapro.value;
    const getselDep = "&selDep="+selDep.value;
    const getselPuesto = "&selPuesto="+selPuesto.value;

    return window.location.origin+window.location.pathname+locationPHP+".php"+getnumNum+getdtDel+getdtAl+getdtFec+getselBodegapro+getselDep+getselPuesto;
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    //document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    //document.thisform.dtFvalida.value = '<?php echo $dtFec; ?>';
    numNum.value="";
    dtDel.value = dateToday();
    dtAl.value = dateToday();
    dtFec.value = dateToday();

    // SHOW MODAL
    $('#modalNomper').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      }
    });

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

    // FOCUS NUMERO DE PLANILLA
    $("#numNum")
    .focus(function() {
      numNum.value="";
      limpiar();
    })
    .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 (){
      consultarPla1();
    });
  });

    // FOCUS ORDEN DE COMPRA
  //  $("#numOrdenc").change(function (){
  //    consultarOrden();
  //  });


    // CLICK IMPRIMIR
    $("#btnImprimir").click(function (){
      if (restriccion(true)) {return};

      const getnumNum = "?numNum="+numNum.value;
      const getdtDel = "&dtDel="+dtDel.value;      
      const getdtAl = "&dtAl="+dtAl.value;      
      const getdtFec = "&dtFec="+dtFec.value;
      const getselBodegapro = "&selBodegapro="+selBodegapro.value;
      const getselDep = "&selDep="+selDep.value;
      const getselPuesto = "&selPuesto="+selPuesto.value;

      var url = window.location.origin+window.location.pathname+"print.php"+getnumNum+getdtDel+getdtAl+getdtFec+getselBodegapro+getselDep+getselPuesto;

      window.open(url, '_blank');
    });
    // CLICK IMPRIMIR
    $("#btnExcel").click(function (){
      if (restriccion(true)) {return};

      const getnumNum = "?numNum="+numNum.value;
      const getdtDel = "&dtDel="+dtDel.value;      
      const getdtAl = "&dtAl="+dtAl.value;      
      const getdtFec = "&dtFec="+dtFec.value;      
      const getselBodegapro = "&selBodegapro="+selBodegapro.value;
      const getselDep = "&selDep="+selDep.value;
      const getselPuesto = "&selPuesto="+selPuesto.value;

      var url = window.location.origin+window.location.pathname+"excel.php"+getnumNum+getdtDel+getdtAl+getdtFec+getselBodegapro+getselDep+getselPuesto;

      window.location.href = url;
    });

    // CLICK IMPRIMIR
    $("#btnArchivo").click(function (){
      if (restriccion()) {return};
      //window.location.href = getElements("archivo");
      window.open(getElements("archivo"), '_blank');
      alWarning({"msg":{"title":"Archivo Generado","text":"Se genero el archivo, lo puede ubicar en la carpeta /Acreditaciones"}});
      return true;
    });


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

</script>

