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

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

$cajBodega = $_SESSION['cajBodega'];

# QUERYS
$sBodegas = "SELECT * FROM bodegas where bod_emp='$empCod' AND bod_cod='$cajBodega' ORDER BY bod_cod";
$sTipodoci = "SELECT *, TRIM(td_nom) as td_nom FROM tipodoci WHERE td_eos='E'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["bodegas"] = $db->query($sBodegas);
$select["tipodoci"] = $db->query($sTipodoci);

$db->close();

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

        $modalImp = "modalImp";
        include_once('../../../php/includes/modalImp.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">Listado de Ingresos</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 Articulos</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 Proveedores</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="form-group col-12">
                      <div class="form-row">
                        <div class="col-md-3">
                          <label class="font-size-md" for="selTipo">Tipo de Documentos</label>
                          <select class="form-control form-control-md form-control-as font-size-m" name="selTipo" id="selTipo">
                            <option value="0000">Todos los Tipos</option>
                            <?php
                              while ($rec = $db->fetchAssoc($select['tipodoci'])) {
                                echo  '<option value="'.$rec['td_cod'].'">'.utf8_encode($rec['td_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>
                        <div class="col-2">
                          <label class="font-size-md" for="dtFecI">Desde  que fecha</label>
                          <input type="date" class="form-control form-control-md form-control-as" id="dtFecI" placeholder="">
                        </div>
                        <div class="col-2">
                          <label class="font-size-md" for="dtFecF">Hasta que fecha</label>
                          <input type="date" class="form-control form-control-md form-control-as" id="dtFecF" placeholder="">
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-2">
                          <label class="font-size-md" for="txtCodp">Código Proveedor</label>
                          <input type="text" class="form-control form-control-md form-control-as" id="txtCodp" maxlength="20">
                        </div>
                        <div class="col-5">
                          <label class="font-size-md" for="txtNomp">Nombre Proveedor</label>
                          <input type="text" class="form-control form-control-md form-control-as" id="txtNomp" maxlength="100" disabled>
                        </div>
                      </div>

                      <div class="form-row">
                        <div class="col-2">
                          <label class="font-size-md" for="txtCodd">Código</label>
                          <input type="text" class="form-control form-control-md form-control-as" id="txtCodd" maxlength="20">
                        </div>
                        <div class="col-5">
                          <label class="font-size-md" for="txtDescd">Descripción del Articulo</label>
                          <input type="text" class="form-control form-control-md form-control-as" id="txtDescd" maxlength="120" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-3">
                          <label class="font-size-md" for="selBodega">De que Bodega</label>
                          <select class="form-control form-control-md form-control-as" name="selBodega" id="selBodega">
                            <?php
                              while ($rec = $db->fetchAssoc($select['bodegas'])) {
                                echo  '<option value="'.$rec['bod_cod'].'">'.utf8_encode($rec['bod_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>
                        <div class="col-4">
                          <label class="font-size-lg" > </label>
                          <button class="btn btn-primary btn-md btn-block" id="btnMostrar" type="button">Mostrar</button>
                        </div>
                      </div>
  <!---                    
                      <div class="form-row align-items-end mt-3">
                      </div>
  --->                    
                    </div>
                    <div class="col-12 col-sm-10">
                      <div class="form-group">
                        <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">
                              <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-md" id="tblLista">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center" width="200">BODEGA</th>
                                    <th scope="col" class="text-center" width="200">TIPO</th>
                                    <th scope="col" class="text-center">NUMERO</th>
                                    <th scope="col" class="text-center" width="35">FEC/DOCTO.</th>
                                    <th scope="col" class="text-center" width="600">PROVEEDOR</th>
                                    <th scope="col" class="text-center" style="min-width:75px">VALOR</th>
                                    <th scope="col" class="text-center" width="35">SELECCIONAR</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-2">
                      <div class="form-group position-fixed-sm">
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnPdfdoc" type="button">Genera PDF Documento</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-md btn-block" id="btnExcelLista" type="button">Genera Excel Listado</button>
                          </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('../busArtic/index.html');
                ?>
              </div>
              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busProvcp/index.html');
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputNext = "selBodega";
  var inputArtic = "txtCodd";
  var inputProvcp = "txtCodp"

  const dtFecI = document.thisform.dtFecI;
  const dtFecF = document.thisform.dtFecF;
  const txtCodd = document.thisform.txtCodd;
  const txtDescd = document.thisform.txtDescd;
  const selBodega = document.thisform.selBodega;
  const txtCodp = document.thisform.txtCodp;
  const txtNomp = document.thisform.txtNomp;

  const colLista = ["bodegacod", "bodeganom", "tipo", "tiponom", "numero", "fecha", "codp", "nomp", "valor", "stat"];

    
  function addRowDet(bodegacod, bodeganom,tipo, tiponom, numero, fecha, codp, nomp, valor, i){
    const row = "<tr>"
                +"<td id='dataBodegacod' class='d-none'>"+bodegacod+"</td>"
                +"<td id='dataBodeganom'>"+bodeganom+"</td>"
                +"<td id='dataTipo' class='d-none'>"+tipo+"</td>"
                +"<td id='dataTiponom'>"+tiponom+"</td>"
                +"<td id='dataNumero'>"+numero+"</td>"
                +"<td id='dataFecha' class='text-center'>"+YMDToDMY(fecha)+"</td>"
                +"<td id='dataCodp' class='d-none'>"+codp+"</td>"
                +"<td id='dataNomp'>"+nomp+"</td>"
                +"<td id='dataValor' class='text-right'>"+valor+"</td>"
                +'<td class="text-center">'
                  +'<div class="btn-group btn-checkbox" data-toggle="buttons">'
                    +'<label class="btn btn-secondary cbFac" style="font-size:16px;">'
                      +'<input type="checkbox" id="dataCheck'+i+'" name="cb">'
                      +'<span class="fas fa-check fa-sm"></span>'
                    +'</label>'
                  +'</div>'
                +'</td>'
                +"</tr>";
    $("#tblLista tbody").append(row);
  }

  function limpiar(){
  }

  function restriccionCamposVacios() {
  }


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();

    dtFecI.value = dateToday();
    dtFecF.value = dateToday();
    txtCodd.value = "";
    txtDescd.value = "";
    selTipo.value="0010";

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


    // VALID CODIGO
    $("#txtCodd")
    .focus(function() {
      inputArtic = $(this).attr('id');
      txtCodd.value="";
      txtDescd.value = "";
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarArtic");
      parametros.append("txtCodd", txtCodd.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);
            nuevoArtic = true;
          } else {
            if (jsonJS.artic === null) {
              nuevoArtic = true;
              txtCodd.focus();
              txtDescd.value = "";
              alWarning({"msg":{"title":"No Existe","text":"Este Articulo no existe, debe registrarlo"}});
               return true;
            } else {
              txtCodd.value = jsonJS.artic.art_cod;
              txtDescd.value = jsonJS.artic.art_desc;
              nuevoArtic = false;
            }
          }
        }
      });
    });

    // VALID CODIGO PROVEEDOR
    $("#txtCodp")
    .focus(function() {
      inputProvcp = $(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarProvcp");
      parametros.append("txtCod", txtCodp.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);
            nuevoProvee = true;
          } else {
            if (jsonJS.provcp === null) {
              nuevoProvee = true;
              txtCodp.focus();
              txtNomp.value = "";
              alWarning({"msg":{"title":"No Existe","text":"Este proveedor no existe, debe registrarlo"}});
               return true;
            } else {
              txtNomp.value = jsonJS.provcp.pro_nom;
              nuevoProvee = false;
            }
          }
        }
      });
    });

    // VALID CODIGO
    $("#dtFecI")
    .focus(function() {
      restriccionCamposVacios();
    });

    $("#dtFecF")
    .focus(function() {
      restriccionCamposVacios();
    });

    // CLICK BOTON MOSTRAR
    $("#btnMostrar").click(function (){

      const parametros = new FormData();
      parametros.append("action", "consultarDoc");
      parametros.append("txtCodp", txtCodp.value);
      parametros.append("dtFecI", dtFecI.value);
      parametros.append("dtFecF", dtFecF.value);
      parametros.append("txtCodd", txtCodd.value);
      parametros.append("selBodega", selBodega.value);
      parametros.append("selTipo", selTipo.value);
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
        },
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.doctose === null) {
            } else {
              tblClear("tblLista");
              jsonJS.doctose.forEach(function(i, index){
                addRowDet(i.de_bodent,i.bod_nom,i.de_tipo, i.td_nom, i.de_num, i.de_fec, i.de_codp, i.pro_nom, i.de_total, index);
              });
              //tblAllChecked("tblFac", "cb", "cbTodos");
              //alClose();
            }
          }
        }
      });
    });

    // CLICK IMPRIMIR
    $("#btnPdfdoc").click(function (){

      const jsonLista = JSON.parse(tblToJsonCbSkip(colLista, "tblLista", 11, 9));

      console.log(tblToJsonCbSkip(colLista, "tblLista", 11, 9))
      jsonLista.forEach(function(i) {
        console.log(JSON.stringify(new Array(i)))
        var getTblLista = JSON.stringify(new Array(i));

        var url = window.location.origin+window.location.pathname+"print.php?tblLista="+getTblLista;
        window.open(url, '_blank');
      });
    });

    // CLICK EXCEL
    $("#btnPdfLista").click(function (){
      const parametros = new FormData();
      parametros.append("action", "imprimir");
      parametros.append("txtCodp", txtCodp.value);
      parametros.append("dtFecI", dtFecI.value);
      parametros.append("dtFecF", dtFecF.value);
      parametros.append("txtCodd", txtCodd.value);
      parametros.append("selBodega", selBodega.value);
      parametros.append("selTipo", selTipo.value);
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
        },
        success: function (jsonPhp) {
          var url = window.location.origin+window.location.pathname+"printlista.php";
          window.open(url, '_blank');
        }
      });
    });
    // CLICK EXCEL
    $("#btnExcelLista").click(function (){

      const getselTipo = "?selTipo="+selTipo.value;      
      const getTiponom = "&Tiponom="+$("#selTipo option:selected").text();      
      const getdtFecI = "&dtFecI="+dtFecI.value;      
      const getdtFecF = "&dtFecF="+dtFecF.value;      
      const gettxtCodp = "&txtCodp="+txtCodp.value;      
      const gettxtNomp = "&txtNomp="+txtNomp.value;      
      const gettxtCodd = "&txtCodd="+txtCodd.value;      
      const gettxtDescd = "&txtDescd="+txtDescd.value;      
      const getselBodega = "&selBodega="+selBodega.value;      
      const getBodeganom = "&Bodeganom="+$("#selBodega option:selected").text();      

      var url = window.location.origin+window.location.pathname+"excel.php"+getselTipo+getTiponom+getdtFecI+getdtFecF+gettxtCodp+gettxtNomp+gettxtCodd+gettxtDescd+getselBodega+getBodeganom;

      window.location.href = url;
    });

  });

  // 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") ? $('#'+inputNext).focus() : 0;
        (relatedTarget == "#pills-2") ? txtCodd.focus() : 0;

      }
    }
  });

</script>