<?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 POLIZA -->
      <div class="modal fade" id="modalPol" tabindex="-1" role="dialog" aria-labelledby="modalPolTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" 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 Cuentas</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-4">
                          <label for="txtCta">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtaNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebe">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebe" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHaber">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHaber" placeholder="0.00">
                        </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('../busCuentasMov/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">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 for="selGrupo">Grupo a Generar</label>
                            <select class="form-control form-control-sm 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-4">
                            <label for="dtDel">Periodo del: </label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtDel">
                          </div>
                          <div class="col-4">
                            <label for="dtAl">Al: </label>
                            <input type="date" class="form-control form-control-sm form-control-as limpiar" id="dtAl">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                              <label class="font-size-sm" for="dtFec">Fecha de La Poliza:</label>
                              <input type="date" class="form-control form-control-sm form-control-as" id="dtFec">
                          </div>
                          <div class="col-3">
                              <label class="font-size-sm" for="numPol">Numero de Poliza:</label>
                              <input type="number" class="form-control form-control-sm form-control-as" id="numPol">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> </label>
                          </div>
                        </div>


                        <h3 class="text-light"></h3>

                        <div class="form-group">
                          <div class="form-row">
                            <div class="col-5">
                              <button type="button" class="btn btn-outline-success" id="btnAdd">
                                <i class="fas fa-plus-circle"></i> Agregar
                              </button>
                            </div>
                            <div class="col-7 text-right">
                              <button class="btn btn-outline-primary" id="btnPartida" type="button"><i class="fas fa-poll-h"></i> Generar Partida</button>
                            </div>
                          </div>
                          <div class="form-row">
                            <div class="col-2">
                              <label> </label>
                            </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="tblPol">
                                  <thead>
                                    <tr>
                                      <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                      <th scope="col" class="text-center">CUENTA</th>
                                      <th scope="col" class="text-center">DESCRIPCIÓN</th>
                                      <th scope="col" class="text-center">DEBE</th>
                                      <th scope="col" class="text-center">HABER</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                  </tbody>
                                  <tfoot>
                                    <th scope="col" class="ignore"></th>
                                    <th scope="col"></th>
                                    <th scope="col" class="text-right">Totales</th>
                                    <th scope="col" id="dataTotDebe" class="text-right">0.00</th>
                                    <th scope="col" id="dataTotHaber" class="text-right">0.00</th>
                                  </tfoot>
                                </table>
                              </div>
                            </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>
                    </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-outline-warning btn-lg btn-block" id="btnClave" type="button">CLAVE PARA ACCESAR</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 mt-3">
                            <button class="btn btn-outline-success btn-lg btn-block" id="btnTraslada" type="button">Trasladar a Contabilidad</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 mt-3">
                            <button class="btn btn-outline-info btn-lg btn-block" id="btnImprimir" type="button">Vista Previa Poliza</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";
  var btnAddEdit = "00";
  var nohaypol;

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

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

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

  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 restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionCtaCod() {
    if (isNullPer($("#"+inputCtaMov).val())) {
      $("#"+inputCtaMov+"Nom").val("");
      return true;
    }
    return false;
  }

  function restriccionModal() {
    if (restriccionCta()) {
      txtCta.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la CUENTA","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalPol').modal('toggle');
    return false;
  }

  function addRowPol(cta, ctaNom, debe, haber){
    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='#modalPol'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCta'>"+cta+"</td>"
                +"<td id='dataCtaNom'>"+ctaNom+"</td>"
                +"<td id='dataDebe' class='text-right' contenteditable='true'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right' contenteditable='true'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }

  function sumPol(){
    $("#tblPol #dataTotDebe").text(tblSumCol("tblPol", "dataDebe").toFixed(2));
    $("#tblPol #dataTotHaber").text(tblSumCol("tblPol", "dataHaber").toFixed(2));
  }

  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    dtDel.value= '<?php echo $dtFec; ?>';
    dtAl.value= '<?php echo $dtFec; ?>';
    dtFec.value= '<?php echo $dtFec; ?>';
    numPol.value = "";
    selGrupo.disabled = true;
    dtDel.disabled = true;
    dtAl.disabled = true;
    dtFec.disabled = true;
    numPol.disabled = true;
    btnAdd.disabled = true;
    btnPartida.disabled = true;
    btnTraslada.disabled = true;
    btnImprimir.disabled = true;

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

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

    // VALID GRUPO
    $("#selGrupo")
    .focus(function (){
      numPol.value="";
      tblClear("tblPol");
      sumPol();
    })  
    .blur(function (){
      if (restriccionCamposVacios()) {return};
 
      const parametros = new FormData();
      parametros.append("action", "corrPoliza");

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

    // VALID FECHAS
    $("#dtFec")
    .blur(function (){
      if (restriccionCamposVacios()) {return};
        txtThis = dtFec;

        const parametros = new FormData();
        parametros.append("action", "mCerrado");
        parametros.append("dtFec", txtThis.value);

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

            if(jsonJS.error == true){
              alError(jsonJS);
            } else {
              if (jsonJS.ciemes === null) {
                mesCerrado = false;
              } else {
                if (jsonJS.ciemes.ciem_stat == "C") {
                  mesCerrado = true;
                  setTimeout(function(){
                    if (!$('#numNum').is(':focus') && !$('#selBan').is(':focus')) {
                      if ($('input, textarea').is(':focus')) {
                        restriccionMesCerrado();
                      }
                    }
                  },0);
                } else {
                  mesCerrado = false;
                }
              }
            }
          }
        });
      }); 

    // CLICK CLAVE
    $("#btnClave").click(function (){
      const fnT = function(){
        //selGrupo.disabled = false;
        dtDel.disabled = false;
        dtAl.disabled = false;
        dtFec.disabled = false;
        numPol.disabled = false;
        btnAdd.disabled = false;
        btnPartida.disabled = false;
        btnTraslada.disabled = false;
        btnImprimir.disabled = false;
        const parametros = new FormData();
        parametros.append("action", "corrPoliza");

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

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK IMPRIMIR
    $("#btnImprimir").click(function (){
      if ($("#tblPol tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA GENERADO PARTIDA","text":"Primero debe usar el boton para generar partida"}});
        return;
      }

      const parametros = new FormData();
      parametros.append("action", "consultarPoliza");
      parametros.append("numPol", numPol.value);

      $.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.polizas)) {
              colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

              const getdtDel = "?dtDel="+dtDel.value;
              const getdtAl = "&dtAl="+dtAl.value;      
              const getdtFec = "&dtFec="+dtFec.value;      
              const getnumPol = "&numPol="+numPol.value;      
              const getselGrupo = "&selGrupo="+selGrupo.value;      
              const getGrupoNom = "&selGrupoNom="+$("#selGrupo option:selected").text();
              const getTblpol = "&tblPol="+tblToJson(colPol, "tblPol", 0);

              var url = window.location.origin+window.location.pathname+"print.php"+getdtDel+getdtAl+getdtFec+getnumPol+getselGrupo+getGrupoNom+getTblpol;

              window.open(url, '_blank');
            } else {
              numPol.focus();
              alWarning({"msg":{"title":"DOCUMENTO YA REGISTRADO","text":"Este Numero de Poliza ya fue registrado para sueldos, revise."}});
              return true;
            }
          }
        }
      }); 
    });

    // CLICK IMPRIMIR
    $("#btnTraslada").click(function (){
      if ($("#tblPol tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA GENERADO PARTIDA","text":"Primero debe usar el boton para generar partida"}});
        return;
      }

      const parametros = new FormData();
      parametros.append("action", "consultarPoliza");
      parametros.append("numPol", numPol.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        //async: false,
        beforeSend: function () {
          alLoad("Revisando ...")
        },
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);
          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            const parametros = new FormData();
            parametros.append("action", "consultarPoliza");
            parametros.append("numPol", numPol.value);

            $.ajax({
              data:  parametros,
              url:   window.location.origin+window.location.pathname+"actions.php",
              type:  "post",
              contentType: false,
              processData: false,
              beforeSend: function () {
                alLoad("Procesando ...")
              },
              success: function (jsonPhp) {
                //console.log(jsonPhp);
                const jsonJS = JSON.parse(jsonPhp);
                if(jsonJS.error == true){
                  alError(jsonJS);
                } else {
                  if (isNullPer(jsonJS.polizas)) {
                    nuevo=true;

                    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

                    parametros.append("action", "guardar");
                    parametros.append("nuevo", nuevo);
                    parametros.append("numPol", numPol.value);
                    parametros.append("dtDel", dtDel.value);
                    parametros.append("dtAl", dtAl.value);
                    parametros.append("dtFec", dtFec.value);
                    parametros.append("selGrupo", selGrupo.value);
                    parametros.append("selGrupoNom", $("#selGrupo option:selected").text());
                    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));

                    selGrupo.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 (jsonJS.probpol1 != "X") {
                            alError({"msg":{"type":"error","title":"PROBLEMA EN CUENTAS","text":"Alguna de las cuentas no esta asignada correctamente, verifique.", "ok":"Aceptar"}});
                                     return true;
                          }
                          alWarning({"msg":{"title":"POLIZA REGISTRADA","text":"Se registro la poliza de sueldos en contabilidad."}});
                          return true;
                          tblClear("tblPol");
                          sumPol();
                          alSuccess(jsonJS);
                        }
                      }
                    }); 

                  } else {
                    nuevo=false;
                    numPol.focus();
                    alWarning({"msg":{"title":"DOCUMENTO YA REGISTRADO","text":"Este Numero de Poliza ya fue registrado para sueldos, revise."}});
                    return true;
                  }
                }
              }
            }); 
          }
        }
      }); 
    });


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

    // CLICK AGREGAR
    $("#btnAgregar").click(function () {
      if (restriccionModal()) {return};
      addRowPol(txtCta.value, txtCtaNom.value, isNullNumber(numDebe.value).toFixed(2), isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
      $("#btnAdd").focus();
    });


  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionMesCerrado()) {return};
    $('#modalPol').modal('toggle');
    $("#pills-00-tab").text("Agregar");
    $("#btnAgregar").show();
    $("#btnModificar").hide();
    limpiarModalPol();
  });

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

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

    const dataCta = $(this).parents("tr").find("#dataCta");
    const dataCtaNom = $(this).parents("tr").find("#dataCtaNom");
    const dataDebe = $(this).parents("tr").find("#dataDebe");
    const dataHaber = $(this).parents("tr").find("#dataHaber");

    txtCta.value = dataCta.text();
    txtCtaNom.value = dataCtaNom.text();
    numDebe.value = dataDebe.text();
    numHaber.value = dataHaber.text();

    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataCta.text(txtCta.value);
      dataCtaNom.text(txtCtaNom.value);
      dataDebe.text(isNullNumber(numDebe.value).toFixed(2));
      dataHaber.text(isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
    });
  });

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


    // CLICK btnPartida
    $("#btnPartida").click(function (){
      if (restriccionCamposVacios()) {return};
      if (restriccionMesCerrado()) {return};
      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"Ya tiene partida generada"}});
        return;
      }

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("dtDel", dtDel.value);
      parametros.append("dtAl", dtAl.value);

      $('#btnAddEdit').focus();

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.hayFac=="S") {
              // Cuentas de gastos
              jsonJS.ctaGasto.forEach(function(i){
                addRowPol(i.cta, i.cta_nom, Number(i.cta_valor).toFixed(2), Number(i.cta_valorh).toFixed(2));
              });
            } else {
            }
            sumPol();
            alClose();
          }
        }
      });
    });


  // 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>