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

$empCod = $_SESSION['empCod'];
$usuNom = $_SESSION['usuNom'];

# QUERYS
$sBancos = "SELECT *, TRIM(ban_nom) as ban_nom FROM bancos WHERE ban_emp='$empCod'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["bancos"] = $db->query($sBancos);
$db->close();
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-print"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
      ?>
      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Impresion de Cheques por Rango</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-group">

                    <div class="form-row">
                      <div class="col-3"></div>
                      <div class="col-md-6">
                        <label for="selTipo" class="font-size-lg">Seleccione Cuenta Bancaria</label>
                          <select class="form-control form-control-sm form-control-as font-size-lg" name="selBan" id="selBan">
                            <?php
                              while ($rec = $db->fetchAssoc($select['bancos'])) {
                                echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                              }
                            ?>
                          </select>
                      </div>
                      <div class="col-3"></div>
                    </div>

                    <div class="form-row align-items-end mt-4">
                      <div class="col-6">
                        <label for="numChi" class="font-size-lg">Cheque Inicial:</label>
                        <input type="number" class="form-control form-control-as" id="numChi" value=1 placeholder="">
                      </div>
                      <div class="col-6">
                        <label for="numChf" class="font-size-lg">Cheque Final: </label>
                        <input type="number" class="form-control form-control-as" id="numChf" value=1 placeholder="">
                      </div>
                    </div>

                  </div>

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

                  <div class="form-group">
                    <div class="form-row">
                      <div class="form-group col-3">
                      </div>
                      <div class="form-group col-6">
                        <button class="btn btn-primary btn-lg btn-block" id="btnImprimir" type="button">Imprimir</button>
                      </div>
                      </div>
                  </div>
                </form>

              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var usuario = "<?php echo $usuNom ?>";
  const numChi = document.thisform.numChi;
  const numChf = document.thisform.numChf;
  const selBanCod = document.thisform.selBan;
  
  function restriccion() {
    if (isNullPer(selBan.value)) {
      selBan.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de Cuenta Bancaria"}});
      return true;
    }
    if (isNullPer(numChi.value)) {
      numChi.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de Cheque Inicial"}});
      var lerror=true;
      return true;
    }
    if (isNullPer(numChf.value)) {
      numChf.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Numero de Cheque Final"}});
      return true;
    }
    // FINAL NO PUEDE SER MENOR AL INICIAL
    if (numChf.value < numChi.value) {
      numChf.focus();
      alWarning({"msg":{"title":"Dato Erroneo","text":"El cheque final no puede ser menor al cheque inicial"}});
      return true;
    }
    return false;
  }

  /*function addPage(i){
    <?php $numPages = "+"; ?>
    switch ($('#selBan').find('option:selected').data('forma')){
      case 1:
        var p = 'ban1010';
        break;
      case 2:
        var p = 'ban1011';
        break;
      default:
        var p = 'ban1010';
        break;
    }
    //$(".print1").append(p);
  }   */

  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(index){
    $("#tblPol #dataTotDebe").text(tblSumCol("tblPol", "dataDebe").toFixed(2));
    $("#tblPol #dataTotHaber").text(tblSumCol("tblPol", "dataHaber").toFixed(2));

//    $(".print1 .pag-"+index+" #tblPolPrint #dataTotDebe").text(tblSumPol(".print1 .pag-"+index+" #tblPolPrint", "dataDebe").toFixed(2));
 //   $(".print1 .pag-"+index+" #tblPolPrint #dataTotHaber").text(tblSumPol(".print1 .pag-"+index+" #tblPolPrint", "dataHaber").toFixed(2));
  }

  function tblSumPol(tabla, id) {
    var acum = 0;
    $(tabla).find('tbody tr #'+id).each(function () {
      acum += parseFloat($(this).text());
    });
    return acum;
  }

  function consultarChequei(){
    r = false;

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

    parametros.append("numNum", numChi.value);
    parametros.append("selBanCod", selBan.value);
    
    //numChi.focus()

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

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          if (jsonJS.cheques === null) {
            alWarning({"msg":{"title":"CHEQUE NO EXISTE","text":"El número de Cheque inicial NO HA SIDO REGISTRADO, verifique."}});
            r = true;
          }
        }
      }
    });
    return r;
  }

  function consultarChequef(){
    r = false;

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

    parametros.append("numNum", numChf.value);
    parametros.append("selBanCod", selBan.value);

    //numChf.focus()

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

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          if (jsonJS.cheques === null) {
            alWarning({"msg":{"title":"CHEQUE NO EXISTE","text":"El número de Cheque final NO HA SIDO REGISTRADO, verifique."}});
            r = true
          }
        }
      }
    });
    return r;
  }


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    
    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });

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

      const parametros = new FormData();
      parametros.append("action", "imprimir");

      parametros.append("numChi", numChi.value);
      parametros.append("numChf", numChf.value);
      parametros.append("selBanCod", selBan.value);

      var pch = "";


      switch ($('#selBan').find('option:selected').data('forma')){
        case 1:
          pch = 'ban1010';
          break;
        case 2:
          pch = 'ban1011';
          break;
        default:
          pch = 'ban1010';
          break;
      }

      $.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) {
          const jsonJS = JSON.parse(jsonPhp);
          tblPolAnt = JSON.stringify(jsonJS.poli_det);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cheques === null) {
              alWarning({"msg":{"title":"No Existe","text":"No hay cheques registrados en este rango, cambie el rango de cheques a imprimir"}});
            } else {
              tblClear("tblPolPrint", true);
              //$(".print1").empty();
              jsonJS.cheques.forEach(function(i){
                //addPage(index);

                //tblClear("tblPolPrint", true);
                fecha = new Date(i.ch_fec);
                var options = { year: 'numeric', month: 'long', day: 'numeric' };
                $("."+pch+" #printBlanco").text('   ');

                $("."+pch+" #printFec").text(fecha.toLocaleDateString("es-ES", options));
                $("."+pch+" #printTot").text(i.ch_tot);
                $("."+pch+" #printBene").text(i.ch_bene);
                $("."+pch+" #printTotl").text(numeroALetras(i.ch_tot, 2).toUpperCase());
                $("."+pch+" #printNego").text(((i.ch_nego=="S") ? 'true' : 'false' == 'true') ? "NO NEGOCIABLE" : "");
                $("."+pch+" #printCon").text(i.ch_con);
                $("."+pch+" #printNumch").text(i.ch_num);
                $("."+pch+" #printBanNom").text(i.ban_nom);
                $("."+pch+" #printUsunom").text(usuario);
                $("."+pch+" #printBanCtab").text(i.ban_ctab);

                $('.'+pch).printThis({
                  importCSS: false,
                  loadCSS: bootstrapPrint,
                }); 

                var poli_det = jsonJS.poli_det.filter(function(p) {
                  return p.pold_num == i.ch_num;
                });

                poli_det.forEach(function(i){
                  addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
                });

                //sumPol(index);
                sumPol();
                $("."+pch+" #tblPolPrint tbody").append($('#tblPol tbody').clone().find(".ignore").remove().end().html());
                $("."+pch+" #tblPolPrint tfoot").append($('#tblPol tfoot').clone().find(".ignore").remove().end().html());



                tblClear("tblPol");
              });

              alClose();
            }
          }
        }
      });
    });
  });
</script>

<?php include('../banPrint/ban1010.php'); ?>
<?php include('../banPrint/ban1011.php'); ?>