<?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
$sGruposi = "SELECT * FROM gruposi where gru_emp='$empCod'";
$sMeses = "SELECT * FROM meses";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["meses"] = $db->query($sMeses);
$select["gruposi"] = $db->query($sGruposi);
$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));
$db->close();
?>
<?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 DETALLE DOCUMENTO -->
      <div class="modal fade" id="modalDetao" tabindex="-1" role="dialog" aria-labelledby="modalDetaoTitle" 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-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="false">Buscar Articulos</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" 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-00" role="tabpanel" aria-labelledby="pills-00-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">

                      <div class="form-row">
                        <div class="col-md-3">
                          <label class="font-size-sm text-success" for="txtCoddm">Código</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCoddm" maxlength="30">
                        </div>
                        <div class="col-sm-9 col-md-7">
                          <label class="font-size-sm text-success" for="txtDescdm">Descripción</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDescdm" maxlength="120" disabled>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnAgregar">Agregar</button>

                    <button type="button" class="btn btn-success btn-block" id="btnModificar">Modificar</button>
                  </form>

                </div>
                <div class="tab-pane fade" id="pills-01" role="tabpanel" aria-labelledby="pills-01-tab">
                  <?php
                    $a='00';
                    $b='01';
                    include('../busArtic2/index.html');
                  ?>
                </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">Mantenimiento</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 Articulo</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 align-items-center">
                          <div class="col-md-12">
                            <div class="form-row align-items-end">
                              <div class="col-lg-6 col-md-5">
                                <label class="font-size-lg" for="selGrupo">Grupo</label>
                                <select class="form-control form-control-lg form-control-as" name="selGrupo" id="selGrupo">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['gruposi'])) {
                                      echo  "<option value={$rec['gru_cod']}>".utf8_encode($rec['gru_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                            </div>
                          </div>
                        </div>

                        <div class="form-row">
                        </div>
                      </div>

                      <h3 class="text-light"></h3>
                      <div class="form-group">
                        <h4 class="text-success">DETALLE BOLSA:</h4>
                        <div class="form-row">
                          <div class="col-2">
                            <label class="font-size-md text-success" for="txtCodd">Código Articulo</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtCodd" maxlength="20">
                          </div>
                          <div class="col-6">
                            <label class="font-size-md text-success" for="txtDescd">Descripción</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtDescd" maxlength="120" disabled>
                          </div>
                          <div class="col-3 text-left">
                            <button type="button" class="btn btn-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar a tabla
                            </button>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblDetao">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="90">CODIGO</th>
                                    <th scope="col" class="text-center" width="300">DESCRIPCIÓN</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <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-info btn-block" id="btnGuardarImprimir" type="button">Imprimir / Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-3 col-md-12"></div>
                        </div>

                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busArtic/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 nuevoBolsa = true;
  var mesCerrado = false;
  var inputCtaMov = "txtCta";
  var totant = 0;
  var inputDocp = "numNum";
  var tblDetaoAnt;
  var tblPolAnt;
  var btnAddEdit = "00";
  var inputArtic = "txtCodd";
  var unimed = "XXX";
  var ctaInc = false;

  const selGrupo = document.thisform.selGrupo;

  const txtCodd = document.thisform.txtCodd;
  const txtDescd = document.thisform.txtDescd;

  const txtCoddm = document.getElementById("txtCoddm");
  const txtDescdm = document.getElementById("txtDescdm");

  function restriccion(consultar = false){
    if (!consultar) {
    /*  if (isNullPer(txtCod.value)) {
        txtCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Codigo de Producto terminado"}});
        return true;
      } */
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para la bolsa"}});
        return true;
      }
    } else {
      if (isNullPer(txtCod.value)) {
        return true;
      }
    }
    return false;
  }
  function condicionesobligatorias(){

  }

  function restriccionMesCerrado() {
    if (mesCerrado) {
      alError({"msg":{"type":"error","title":"Mes Cerrado","text":"No puede trabajar con este mes porque ya fue cerrado", "ok":"Aceptar"}});
      return true;
    }
    return false;
  }


  function restriccionCamposVacios() {
   /* if (isNullPer(txtCod.value)) {
      txtCod.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Codigo de producto terminado"}});
      return true;
    }
    return false; */
  }



  function restriccionCoddm() {
    if (isNullPer(txtCoddm.value)) {
      txtDescdm.value = "";
      return true;
    }
    return false;
  }

/*  function restriccionCoddm() {
    if (isNullPer($("#"+inputArtic).val())) {
      $("#txtDescdm").val("");
      return true;
    }
    return false;
  }  */

  function restriccionModal() {
    if (restriccionCoddm()) {
      txtCoddm.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Codigo de Articulo","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalDetao').modal('toggle');
   return false;
  }


  function addRowDetao(codd, descd){
    const row = "<tr>"
                +"<td scope='col' class='ignore'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalDetao'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodd'>"+codd+"</td>"
                +"<td id='dataDescd'>"+descd+"</td>"
                +"</tr>";
    $("#tblDetao tbody").append(row);
  }


  function consultarDoc(){
    if (restriccion(true)) {return};
    
    const parametros = new FormData();
    parametros.append("action", "consultardoc");

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

    //txtNext.focus()

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

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          if (isNullPer(jsonJS.bolsas)) {
            nuevo=true;
          } else {
            jsonJS.bolsas.forEach(function(i){
               addRowDetao(i.bol_cod, i.bol_desc);
            });  
            nuevo = false;
          }
        }
      }
    });
  }


  function guardarDoc(imprimir = false){
    if (restriccion()) {return};

    //console.log($('#selTdoci').find('option:selected').data('afecos'));

    numgru=selGrupo.value;

    const pIva = <?php echo $_SESSION["pIva"]; ?>;

    colDetao = ["acciones","codd", "descd"];

    const parametros = new FormData();

    parametros.append("action", "guardar");

    parametros.append("nuevo", nuevo);
    parametros.append("selGrupo", selGrupo.value);
    parametros.append("tblDetao", tblToJson(colDetao, "tblDetao", 0));

    selGrupo.focus();
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      async: true,
      beforeSend: function () {
        alLoad("Cargando...")
      },
      success: function (jsonPhp) {
        console.log(jsonPhp);
        setTimeout(function () {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          var snhacer = true;
          if (imprimir) {
            imprimirDoc(numgru);
          }
          limpiar();
          tblClear("tblDetao");
          alSuccess(jsonJS);
          //location.reload();
        }

        }), 0;
      }
    });
  }

  function imprimirDoc(numgru){

    const getnumgru = "?numgru="+numgru;

    var url = window.location.origin+window.location.pathname+"print.php"+getnumgru;

    window.open(url, '_blank');
  }



  function limpiarModalDetao(){
    txtCoddm.value = "";
    txtDescdm.value = "";
  }

  function limpiar(todo = false){
  }

  function limpiarDetao(){
    txtDescd.value = "";
  }


  function sumDetao(){
  }


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    //document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    //document.thisform.dtFvalida.value = '<?php echo $dtFec; ?>';

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


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

    // VALID BOLSAS
    $("#selGrupo")
    .focus(function() {
      inputArtic = $(this).attr('id');
      tblClear("tblDetao");
      limpiar();
      limpiarDetao();

    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .click(function() {
      inputArtic = $(this).attr('id');
      tblClear("tblDetao");
      limpiar();
      limpiarDetao();
    })
    .blur(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarBolsa");
      parametros.append("selGrupo", selGrupo.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);
            nuevoGrupo = true;
          } else {
            if (jsonJS.bolsas === null) {
              nuevoBolsa = true;
              selGrupo.focus();
            } else {
              nuevoBolsa = false;
              jsonJS.bolsas.forEach(function(i){
                 addRowDetao(i.bol_cod, i.bol_desc);
              });  
            }
          }
        }
      });
    });


    // VALID CODIGO
    $("#txtCodd")
    .focus(function() {
      inputArtic = $(this).attr('id');
      txtCodd.value="";
      limpiarDetao();
      if (restriccionCamposVacios()) {return};
      if (condicionesobligatorias()) {return};

    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-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;
            unimed="";
            ctacos="XXX";            
            ctainv="XXX";            
          } else {
            if (jsonJS.artic === null) {
              nuevoArtic = true;
              txtCodd.focus();
              txtDescd.value = "";
              alWarning({"msg":{"title":"No Existe","text":"Este Articulo no existe, debe revisar"}});
               return true;
            } else {
              txtCodd.value = jsonJS.artic.art_cod;
              txtDescd.value = jsonJS.artic.art_desc;

              if (jsonJS.artic.art_serv == 1) {
                txtDescd.disabled = false;
              } else {
                txtDescd.disabled = true;
              }
              nuevoArtic = false;
            }
          }
        }
      });
    });



    // FOCUS FECHA
    $("#txtDescd").focus(function (){
      if (restriccionCamposVacios()) {return};
      if (condicionesobligatorias()) {return};
      if (isNullPer(txtCodd.value)) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Codigo del Articulo o Si es Servicio ingrese SERV en mayuscula"}});
        return true;
        return true;
      }
    });

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

    // FOCUS DESCRIPCION MODAL
    $("#txtDescdm").focus(function (){
      if (isNullPer(txtCoddm.value)) {
        txtCoddm.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Codigo del Articulo o Si es Servicio ingrese SERV en mayuscula"}});
        return true;
      }
    });

/*
    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      const numDoc = numNum.value;
      const serieo = selSerieo.value;

      numNum.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "borrar");
        parametros.append("selSerieo", selSerieo.value);
        parametros.append("selSerieoNom", $('#selSerieo').find('option:selected').text());
        parametros.append("numNum", numDoc);

        $.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 {
              numNum.value = "";
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });


    // CLICK ANULAR
    $("#btnAnular").click(function (){
      const numDoc = numNum.value;
      const serieo = selSerieo.value;

      numNum.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "anular");
        parametros.append("selSerieo", serieo);
        parametros.append("selSerieoNom", $('#selSerieo').find('option:selected').text());
        parametros.append("numNum", numDoc);
        parametros.append("tblDetaoAnt", tblDetaoAnt);


        $.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 {
              numNum.value = "";
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    */


    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      restriccion();
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para la Bolsa"}});
        return;
      }
      guardarDoc();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para la Bolsa"}});
        return;
      }
      guardarDoc(true);
    });
  });  

  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    if (condicionesobligatorias()) {return};
    if (txtCodd.value == "") {
      alWarning({"msg":{"title":"CAMPO OBLIGATORIO EN DETALLE","text":"No ha ingresado codigo de la linea en el detalle"}});
      return;
    }
    if (txtDescd.value == "") {
      alWarning({"msg":{"title":"CAMPO OBLIGATORIO EN DETALLE","text":"No ha ingresado Descripcion de la linea en el detalle"}});
      return;
    }
    addRowDetao(txtCodd.value, txtDescd.value);
    txtCodd.value="";
    txtCodd.focus();
  });

  // CLICK DEL
  $("body").on("click", "#btnDel", function() {
    const row = $(this).parents("tr");
    alDelete(function fn(){
      row.remove();
      sumDetao();
    });
  });

  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-00-tab').text("Modificar");
    $('#btnAgregar').hide();
    $('#btnModificar').show();

    const dataCodd = $(this).parents("tr").find("#dataCodd");
    const dataDescd = $(this).parents("tr").find("#dataDescd");

    txtCoddm.value = dataCodd.text();
    txtDescdm.value = dataDescd.text();
    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataCodd.text(txtCoddm.value);
      dataDescd.text(txtDescdm.value);
      limpiarModalDetao();
    });
  });



  // MODALDetao HIDDEN
  $('#modalDetao').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificar");
  });


  // 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") ? txtCod.focus() : 0;
        (relatedTarget == "#pills-2") ? txtCodd.focus() : 0;
        (relatedTarget == "#pills-01") ? txtCoddm.focus() : 0;
      }
      //$(target+' input:visible:first').focus();
    }
  });

</script>
