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

# QUERYS
$sTipov = "SELECT * FROM tipov tv
           LEFT JOIN tipoaboc ta ON tv.tv_tipoabo=ta.ta_cod
           WHERE tv_fel='S' AND tv_abrev LIKE 'NC%'";
$sTipovFac = "SELECT * FROM tipov WHERE tv_fel='S' AND tv_cod LIKE 'F%'";
$sVendedor = "SELECT * FROM vendedor";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$select["tipovFac"] = $db->query($sTipovFac);
$select["vendedor"] = $db->query($sVendedor);
$db->close();

$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));

$wsBANGUAT = new wsBANGUATExec();
$tcam = 0;
foreach ($wsBANGUAT->sEx() as $Body) {
  $tcam = $Body->TipoCambioDiaResponse->TipoCambioDiaResult->CambioDolar->VarDolar->referencia;
}
?>
<?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-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-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>

      <!-- MODAL DETALLE -->
      <div class="modal fade" id="modalDet" tabindex="-1" role="dialog" aria-labelledby="modalDetTitle" 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-10-tab" data-toggle="pill" href="#pills-10" role="tab" aria-controls="pills-10" aria-selected="true"></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-10" role="tabpanel" aria-labelledby="pills-10-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="txtDetCod">Código</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDetCod" placeholder="">
                        </div>
                        <div class="col-12">
                          <label for="txtDesc">Descripción</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDesc" placeholder="">
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numCant">Cantidad</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numCant" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numUnit">Unitario</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numUnit" placeholder="0.00">
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnAgregarDet">Agregar</button>
                    <button type="button" class="btn btn-success btn-block" id="btnModificarDet">Modificar</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">Mantenimiento</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 align-items-end">
                          <div class="col-6 col-md-3">
                            <label for="selTipo">Tipo</label>
                            <select class="form-control form-control-sm form-control-as" name="selTipo" id="selTipo">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipov'])) {
                                  echo  "<option value={$rec['tv_cod']} data-impues={$rec['tv_impues']} data-pone={$rec['tv_pone']} data-tipoabo={$rec['tv_tipoabo']} data-trela={$rec['ta_trela']}>".utf8_encode($rec['tv_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-6 col-md-4">
                            <label for="txtSerie">Serie Factura</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtSerie">
                          </div>
                          <div class="col-6 col-md-5">
                            <label for="numNum">Número Factura</label>
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar" id="numNum">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-12">
                            <label for="txtMot">Motivo de Ajuste</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtMot">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-md-3">
                            <label for="selTipoFac">Tipo Factura</label>
                            <select class="form-control form-control-sm form-control-as" name="selTipoFac" id="selTipoFac" disabled>
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipovFac'])) {
                                  echo  "<option value={$rec['tv_cod']} data-impues={$rec['tv_impues']} data-pone={$rec['tv_pone']}>".utf8_encode($rec['tv_abrev']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="txtCliCod">Código Cliente</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtCliCod" disabled>
                          </div>
                          <div class="col-md-6">
                            <label for="txtCliNom"></label>
                            <input type="text" class="form-control form-control-sm form-control-as form-info limpiar" id="txtCliNom" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-9">
                            <label for="txtNomFac">A nombre de</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtNomFac" disabled>
                          </div>
                          <div class="col-md-3">
                            <label for="txtNit">NIT</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtNit" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-12">
                            <label for="txtDir">Dirección</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtDir" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-center">
                          <div class="col-md-4">
                            <label for="selVend">Vendedor</label>
                            <select class="form-control form-control-sm form-control-as" name="selVend" id="selVend" disabled>
                              <?php
                                while ($rec = $db->fetchAssoc($select['vendedor'])) {
                                  echo  '<option value="'.TRIM($rec['vend_cod']).'">'.utf8_encode($rec['vend_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-4 text-center">
                            <label class="pr-1">Tipo de Cambio</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTcam1" name="crTcam" class="custom-control-input" value="L" disabled>
                              <label class="custom-control-label" for="crTcam1">Q</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTcam2" name="crTcam" class="custom-control-input" value="E" disabled>
                              <label class="custom-control-label" for="crTcam2">$</label>
                            </div>
                          </div>
                          <div class="col-md-4">
                            <label for="numSaldo">Saldo Factura</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numSaldo" disabled>
                          </div>
                        </div>

                      </div>

                      <div class="form-group">
                        <h4 class="text-light">Detalle</h4>
                        <div class="form-row">
                          <div class="col-5">
                            <button type="button" class="btn btn-success" id="btnAddDet">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                        </div>
                        <h3 class="text-light"></h3>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" style="font-size: 12px;" id="tblDet">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="40">CÓDIGO</th>
                                    <th scope="col" class="text-center" width="400">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" width="10">CANTIDAD</th>
                                    <th scope="col" class="text-center" width="10">UNITARIO</th>
                                    <th scope="col" class="text-center" width="10">SUBTOTAL</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" class="text-right">TOTAL</th>
                                  <th scope="col" id="dataTot" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <h4 class="text-light">Partida</h4>
                        <div class="form-row">
                          <div class="col-5">
                            <button type="button" class="btn btn-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                          <div class="col-7 text-right">
                            <button class="btn btn-primary" id="btnPartida" type="button"><i class="fas fa-poll-h"></i> Generar Partida</button>
                          </div>
                        </div>
                        <h3 class="text-light"></h3>
                        <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" 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"></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="col-12 col-sm-3">
                      <div class="form-group position-fixed-md m-md-10">

                        <div class="form-row align-items-end">
                          <div class="col-6 col-sm-12">
                            <label for="dtFec">Fecha del Documento</label>
                            <input type="date" class="form-control form-control-sm form-control-as form-info" id="dtFec" placeholder="" disabled>
                          </div>
                          <div class="col-6 col-sm-12">
                            <label for="numTcam">Tipo de Cambio <span style="font-size: 12px">(Banco de Guatemala)</span></label>
                            <input type="number" class="form-control form-control-sm form-control-as form-info dec-5 pl-3" id="numTcam" placeholder="0.00000" disabled>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" id="btnVistaPrevia" type="button">Vista Previa</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 fecAnt = "0000-00-00";
  var mesCerrado = false;
  var inputCtaMov = "txtCta";
  var inputClienccCod = "txtCliCod";
  var cliCta = "";
  var DocumentGUIDF = "";
  var totFac = 0;
  var fecFac = "0000-00-00";
  var bodega = "";
    
  const colDet = ["acciones", "cod", "descrip", "cant", "preu", "sub", "cosu"];

  // Valores
  var tot = 0;
  var ret = 0;
  var reti = 0;
  var iva = 0;
  var sub = 0;

  //const crFpag = document.thisform.crFpag;
  const crTcam = document.thisform.crTcam;

  function restriccion(consultar = false, mes = true){
    if (!consultar) {
      if (isNullPer(txtCliCod.value)) {
        txtCliCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO CLIENTE"}});
        return true;
      }
      if ($("#tblDet #dataTot").text() == "0.00") {
        alWarning({"msg":{"title":"Total en Cero","text":"No se puede guardar porque el total documento es cero"}});
        return true;
      }
      if (($('#selTipo').find('option:selected').data('pone')=='N')) {
        if (Number($("#tblDet #dataTot").text()) > numSaldo.value) {
          alWarning({"msg":{"title":"Total Incorrecto","text":"No se puede guardar porque el total del documento es mayor al saldo de la factura"}});
          return true;
        }
      }
      if ($("#dataTotDebe").text() != $("#dataTotHaber").text()) {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
        return true;
      }
      // PARA VER SI LA PARTIDA ESTÁ VACÍA
/*      if ($("#tblPol tbody").children().length == 0) {
        alWarning({"msg":{"title":"Partida Vacía","text":"Es necesario Generar Partida"}});
        return true;
      }   */
      // RECORRER PARTIDA PARA BUSCAR UNA CUENTA NO DEFINIDA
      var ctaInc = false;
      $("#tblPol tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes("XXXX")) {
          ctaInc = true;
          return false;
        }
      });
    } else {
      if (isNullPer(txtSerie.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(txtCliCod.value)) {
      txtCliCod.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO CLIENTE"}});
      return true;
    }
    return false;
  }

  function restriccionModalDet() {
    if (isNullPer(txtDesc.value)) {
      txtDesc.value = "";
      txtDesc.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la DESCRIPCIÓN","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalDet').modal('toggle');
    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 restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function addRowDet(cod, desc, cant, unit, sub, cosu){
    const row = "<tr>"
                +"<td scope='col'>"
                  +"<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='btnDelDet'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditDet' data-toggle='modal' data-target='#modalDet'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCod'>"+cod+"</td>"
                +"<td id='dataDesc'>"+desc+"</td>"
                +"<td id='dataCant' class='text-right'>"+cant+"</td>"
                +"<td id='dataUnit' class='text-right'>"+unit+"</td>"
                +"<td id='dataSub' class='text-right'>"+sub+"</td>"
                +"<td id='dataCosu' class='d-none'>"+cosu+"</td>"
              +"</tr>";
    $("#tblDet tbody").append(row);
  }

  function addRowPol(cta, ctaNom, debe, haber){
    const row = "<tr>"
                +"<td scope='col'>"
                  +"<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'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }

  function limpiarModalDet(){
    txtDetCod.value = "";
    txtDesc.value = "";
    numCant.value = "";
    numUnit.value = "";
  }

  function limpiarModalPol(){
    txtCta.value = "";
    txtCtaNom.value = "";
    numDebe.value = "";
    numHaber.value = "";
  }

  function limpiar() {
    cliCta = "";
    DocumentGUIDF = "";
    totFac = 0;
    fecFac = "0000-00-00";
    
    $(".limpiar").val("");
    tblClear("tblDet");
    tblClear("tblPol");
    sumDet();
    sumPol();
  }

  function sumDet(){
    $("#tblDet #dataTot").text(tblSumCol("tblDet", "dataSub").toFixed(2));
  }

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

  function getElements(locationPHP) {
    return window.location.origin+window.location.pathname+locationPHP+".php";
  }

  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    selTipo.value = "NCRE";
    date = new Date();
    dtFec.value = dateToday();
    numTcam.value = <?php echo $tcam; ?>.toFixed(5);
    crTcam.value = "L";

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

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

    // VALID CUENTA
    $("#txtCta")
    .focus(function() {
      inputCtaMov = $(this).attr('id');
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-01-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtaNom");
      txtNext = document.getElementById("numDebe");

      $(txtThis).off("blur");
      if (restriccionCta()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCta");
      parametros.append("txtDetCod", txtThis.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.cuentas.cta_con != "N") {
                txtGetValue.value = "";
                alErrorFocusTimer({"msg":{"type":"error","title":"No puede usar esta cuenta","text":"La cuenta "+txtThis.value+" no es de movimiento, no la puede usar", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cuentas.cta_nom;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // VALID CLICOD
    $("#txtCliCod")
    .focus(function() {
      inputClienccCod = $(this).attr('id');
    })
    .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 (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCliNom");
      txtNext = document.getElementById("txtNomFac");

      $(txtThis).off("blur");

      const parametros = new FormData();
      parametros.append("action", "consultarCliencc");
      parametros.append("txtCliCod", txtThis.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cliencc === null) {
              $(".limpiar").val("");
              crTcam.value = "Q";
              //crFpag.value = 2;
              cliCta = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"El cliente "+txtThis.value+" no ha sido registrado", "ok":"Aceptar"}}, txtThis);
            } else {
              if (jsonJS.cliencc.cli_stat != 'A') {
                $(".limpiar").val("");
                crTcam.value = "Q";
                //crFpag.value = 2;
                cliCta = "";
                alWarningFocus({"msg":{"type":"error","title":"Inactivo","text":"No puede utilizar al cliente "+txtThis.value+" porque está de inactivo", "ok":"Aceptar"}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cliencc.cli_nom;
                txtNomFac.value = jsonJS.cliencc.cli_nomfac;
                txtNit.value = jsonJS.cliencc.cli_nit;
                txtDir.value = jsonJS.cliencc.cli_dir;
                selVend.value = jsonJS.cliencc.cli_ven;
                crTcam.value = jsonJS.cliencc.cli_tipo;
                //crFpag.value = (jsonJS.cliencc.cli_dcre == 0) ? 1 : 2;
                cliCta = jsonJS.cliencc.cli_cta;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // VALID TIPO
    $("#selTipo")
    .change(function (){
      limpiar();
    });

    // FOCUS SERIE
    $("#txtSerie")
    .focus(function (){
      limpiar();
    });

    // VALID SERIE, NUM
    $("#txtSerie, #numNum")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .change(function (){
      if (restriccion(true)) {return};
      txtThis = this;
      txtNext = txtMot;

      $(txtThis).off("blur");

      const parametros = new FormData();
      parametros.append("action", "consultar");
      parametros.append("txtSerie", txtSerie.value);
      parametros.append("numNum", numNum.value);

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

          tblClear("tblDet");
          tblClear("tblPol");

          mesCerrado = false;
          partidaMayorizada = false;
          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.facturas === null) {
              limpiar();
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"Esta factura no ha sido registrada", "ok":"Aceptar"}}, txtThis);
            } else {
              if (jsonJS.facturas.dc_tot == 0) {
                limpiar()
                alErrorFocus({"msg":{"type":"warning","title":"Factura Anulada","text":"No puede usar esta factura porque está anulada", "ok":"Aceptar"}}, txtThis);
              } else {
                var dcAbo = jsonJS.facturas.dc_abo;
                var dcTot = jsonJS.facturas.dc_tot;
                const comparacion = ($('#selTipo').find('option:selected').data('pone')!='N') ? dcAbo > 0 : dcAbo < dcTot;

                if (comparacion) {
                  cliCta = jsonJS.facturas.cli_cta;
                  mesCerrado = (jsonJS.facturas.ciem_stat === "C") ? true : false;
                  partidaMayorizada = (jsonJS.polizas.pol_stat === "A") ? true : false;
                  DocumentGUIDF = jsonJS.facturas.fact_documentguid;
                  totFac = (dcTot-dcAbo).toFixed(2);
                  fecFac = jsonJS.facturas.fact_fec;
                  bodega = jsonJS.facturas.fact_fec;
                  selTipoFac.value = jsonJS.facturas.fact_tipo;
                  txtCliCod.value = jsonJS.facturas.fact_codp;
                  txtCliNom.value = jsonJS.facturas.cli_nom;
                  txtNomFac.value = jsonJS.facturas.fact_nom;
                  txtNit.value = jsonJS.facturas.fact_nit;
                  txtDir.value = jsonJS.facturas.fact_dir;
                  selVend.value = jsonJS.facturas.fact_vend;
                  crTcam.value = (jsonJS.facturas.fact_tcam > 1) ? "E" : "L";
                  numTcam.value = jsonJS.facturas.fact_tcam;
                  txtMot.value = jsonJS.facturas.fact_motanu;
                  numSaldo.value = (dcTot-dcAbo).toFixed(2);

                  jsonJS.fact_det.forEach(function(i){
                    addRowDet(i.factd_cod, i.factd_desc, i.factd_cant, (Number(i.factd_preu)).toFixed(2), i.factd_tot, i.factd_cosu)
                  });
                  sumDet();
                  sumPol();

                  (pressEnter) ? alClose() : alCloseFocus(txtNext);
                } else {
                  limpiar();
                  if (($('#selTipo').find('option:selected').data('pone')!='N')) {
                    alErrorFocus({"msg":{"type":"warning","title":"Factura sin Abonos","text":"No puede usar esta factura porque no tiene abonos", "ok":"Aceptar"}}, txtThis);
                  } else {
                    alErrorFocus({"msg":{"type":"warning","title":"Factura Abonada","text":"No puede usar esta factura porque ya tiene abonos", "ok":"Aceptar"}}, txtThis);
                  }
                }
              }

            }
            pressEnter = false;
          }
        }
      });
    });

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

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

      const parametros = new FormData();
      parametros.append("action", "guardar");
      parametros.append("selTipoCod", selTipo.value);
      parametros.append("txtCliCod", txtCliCod.value);
      parametros.append("txtNomFac", txtNomFac.value);
      parametros.append("txtNit", txtNit.value);
      parametros.append("txtDir", txtDir.value);
      parametros.append("selVendCod", selVend.value);
      parametros.append("crTcam", crTcam.value);
      //parametros.append("crFpag", crFpag.value);
      parametros.append("numTcam", numTcam.value);
      parametros.append("dtFec", dtFec.value);
      parametros.append("tot", $("#tblDet #dataTot").text());
      parametros.append("tblDet", tblToJson(colDet, "tblDet", 0));
      parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));

      parametros.append("txtSerie", txtSerie.value);
      parametros.append("numNum", numNum.value);
      parametros.append("txtMot", txtMot.value);
      parametros.append("DocumentGUIDF", DocumentGUIDF);
      parametros.append("totFac", totFac);
      parametros.append("fecFac", fecFac);
      parametros.append("bodega", bodega);
      parametros.append("selTipoPone", $('#selTipo').find('option:selected').data('pone'));
      parametros.append("selTipoTipoabo", $('#selTipo').find('option:selected').data('tipoabo'));
      parametros.append("selTipoTrela", $('#selTipo').find('option:selected').data('trela'));

      txtCliCod.focus();
      
      $.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){
          } else {
            $(".limpiar").val("");
            tblClear("tblDet");
            tblClear("tblPol");
            sumDet();
            sumPol();
            alSuccessStop(jsonJS);
          }
          alError(jsonJS);
        }
      });
    });

    // CLICK VISTA PREVIA
    $("#btnVistaPrevia").click(function (){
      const tcam = (crTcam.value!='L') ? '$' : 'Q';
      var totLetras = "";
      if (tcam == 'Q') {
        totLetras = numeroALetras($("#tblDet #dataTot").text(), 2, {
                      plural: 'quetzales',
                      singular: 'quetzal',
                      centPlural: 'centavos',
                      centSingular: 'centavo'
                    }).toUpperCase()
      } else {
        totLetras = numeroALetras($("#tblDet #dataTot").text(), 2, {
                      plural: 'dólares',
                      singular: 'dólar',
                      centPlural: 'centavos',
                      centSingular: 'centavo'
                    }).toUpperCase()
      }

      const parametros = new FormData();
      parametros.append("action", "imprimir");
      parametros.append("selTipoCod", selTipo.value);
      parametros.append("txtNomFac", txtNomFac.value);
      parametros.append("txtNit", txtNit.value);
      parametros.append("txtDir", txtDir.value);
      parametros.append("dtFec", dtFec.value);
      parametros.append("tcam", tcam);
      parametros.append("dataTot", $("#tblDet #dataTot").text());
      parametros.append("totLetras", totLetras);
      parametros.append("tblDet", tblToJson(colDet, "tblDet", 0));
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
        },
        success: function (jsonPhp) {
          window.open(getElements("preview"), '_blank');
        }
      });
    });

    // CLICK PARTIDA
    $("#btnPartida").click(function (){
      if (restriccionCamposVacios()) {return};
      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }
      if ($("#tblDet #dataTot").text() == 0) {
        alWarning({"msg":{"title":"Total en Cero","text":"No se puede realizar acciones en la partida porque el total de la factura es cero"}});
        return;
      }

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("cliCta", cliCta);
      parametros.append("numTcam", numTcam.value);
      parametros.append("crTcam", crTcam.value);
      parametros.append("selTipoCod", selTipo.value);
      parametros.append("tot", $("#tblDet #dataTot").text());

      $('#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 {
            tblClear("tblPol");
            sumPol();

            tot = Number(jsonJS.tot);
            iva = Number(jsonJS.iva);
            sub = Number(jsonJS.sub);
            
            if ($('#selTipo').find('option:selected').data('pone')!="N") {
              // Cuenta Clientes
              if (!isNullPer(jsonJS.ctaCli)) {
                addRowPol(jsonJS.ctaCli.cta, jsonJS.ctaCli.cta_nom, tot.toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Cuenta no definida", tot.toFixed(2), "0.00");
              }

              // Cuenta IVA
              if (iva != 0) {
                if (!isNullPer(jsonJS.ctaIva)) {
                  addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, "0.00", iva.toFixed(2));
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de IVA", "0.00", iva.toFixed(2));
                }
              }

              // Cuenta Servicios
              if (sub != 0) {
                if (!isNullPer(jsonJS.ctaServ)) {
                  addRowPol(jsonJS.ctaServ.cta, jsonJS.ctaServ.cta_nom, "0.00", sub.toFixed(2));
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Servicios", "0.00", sub.toFixed(2));
                }
              }
            } else {
              // Cuenta Clientes
              if (!isNullPer(jsonJS.ctaCli)) {
                addRowPol(jsonJS.ctaCli.cta, jsonJS.ctaCli.cta_nom, "0.00", tot.toFixed(2));
              } else {
                addRowPol("XXXXXXX", "Cuenta no definida", "0.00", tot.toFixed(2));
              }

              // Cuenta IVA
              if (iva != 0) {
                if (!isNullPer(jsonJS.ctaIva)) {
                  addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, iva.toFixed(2), "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de IVA", iva.toFixed(2), "0.00");
                }
              }

              // Cuenta Servicios
              if (sub != 0) {
                if (!isNullPer(jsonJS.ctaServ)) {
                  addRowPol(jsonJS.ctaServ.cta, jsonJS.ctaServ.cta_nom, sub.toFixed(2), "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Servicios", sub.toFixed(2), "0.00");
                }
              }
            }
            sumPol();
            alClose();
          }
        }
      });
    });

    // CLICK AGREGAR
    $("#btnAgregarDet").click(function () {
      if (restriccionModalDet()) {return};
      addRowDet(txtDetCod.value, txtDesc.value, isNullNumber(numCant.value).toFixed(2), isNullNumber(numUnit.value).toFixed(2), isNullNumber(numCant.value*numUnit.value).toFixed(2));
      limpiarModalDet();
      sumDet();
      $("#btnAddDet").focus();
    });

    // 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", "#btnAddDet", function () {
    if (restriccionCamposVacios()) {return};
    $('#modalDet').modal('toggle');
    $("#pills-10-tab").text("Agregar");
    $("#btnAgregarDet").show();
    $("#btnModificarDet").hide();
    limpiarModalDet();
  });

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

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

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

  // CLICK EDIT
  $("body").on("click", "#btnEditDet", function() {
    $('#pills-10-tab').text("Modificar");
    $('#btnAgregarDet').hide();
    $('#btnModificarDet').show();

    const dataCod = $(this).parents("tr").find("#dataCod");
    const dataDesc = $(this).parents("tr").find("#dataDesc");
    const dataCant = $(this).parents("tr").find("#dataCant");
    const dataUnit = $(this).parents("tr").find("#dataUnit");
    const dataSub = $(this).parents("tr").find("#dataSub");

    txtDetCod.value = dataCod.text();
    txtDesc.value = dataDesc.text();
    numCant.value = dataCant.text();
    numUnit.value = dataUnit.text();

    $("body").on("click", "#btnModificarDet", function() {
      if (restriccionModalDet()) {return};
      dataCod.text(txtDetCod.value);
      dataDesc.text(txtDesc.value);
      dataCant.text(isNullNumber(numCant.value).toFixed(2));
      dataUnit.text(isNullNumber(numUnit.value).toFixed(2));
      dataSub.text(isNullNumber(numCant.value*numUnit.value).toFixed(2));
      limpiarModalDet();
      sumDet();
    });
  });

  // 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();
    });
  });

  // MODALDET HIDDEN
  $('#modalDet').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificarDet");
  });

  // MODALPOL HIDDEN
  $('#modalPol').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") ? txtCliCod.focus() : 0;
      }
    }
  });
</script>