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

$pCaja = $_SESSION['pCaja'];

# QUERYS
$sTipov = "SELECT * FROM tipov WHERE tv_fel='S'";
$sMeses = "SELECT * FROM meses";
$sBancos = "SELECT * FROM bancos WHERE ban_emp='".$_SESSION['empCod']."'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$select["meses"] = $db->query($sMeses);
$select["bancos"] = $db->query($sBancos);
$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/htmlOpenPov.php'); ?>
    <style type="text/css">
      /* TAMAÑO PERSONALIZADO PARA TABLA DE ESTE FORMULARIO */
      .table th,
      .table td {
        padding: 0 .3em 0 .3em;
        font-size: 12px;
      }
    </style>
    <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 CORREO ELECTRONICO -->
      <div class="modal fade" id="modalMail" tabindex="-1" role="dialog" aria-labelledby="modalMailTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg" role="document">
          <div class="modal-content bg-ligth">
            <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-12-tab" data-toggle="pill" href="#pills-12" role="tab" aria-controls="pills-12" aria-selected="true">CORREO ELECTRONICO</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-12" role="tabpanel" aria-labelledby="pills-12-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">

                    <div class="form-group">
                      <div class="form-row align-items-end">
                        <div class="col-12">
                          <label class="font-size-xl text-success" style="font-size:25px;" for="txtMail">Correo al que se enviara</label>
                          <input type="text" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtMail" placeholder="Correo">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-12">
                          <label class="font-size-xl text-success" style="font-size:25px;" for="txtMail1">Con Copia 1</label>
                          <input type="text" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtMail1" placeholder="Copia 1">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-12">
                          <label class="font-size-xl text-success" style="font-size:25px;" for="txtMail2">Con Copia 2</label>
                          <input type="text" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtMail2" placeholder="Copia 2">
                        </div>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-3">
                        <label></label>
                      </div>
                      <div class="col-6">
                        <button type="button" class="btn btn-success btn-block" id="btnEnviar">Continuar</button>
                      </div>
                    </div>
                  </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-md-2"></div>
                          <div class="col-6 col-md-4">
                            <label class="font-size-md" style="font-size:17px;" for="dtFecIni">Fecha Inicio</label>
                            <input type="date" class="form-control form-control-md form-control-as form-info" style="font-size:17px;" id="dtFecIni" placeholder="">
                          </div>
                          <div class="col-6 col-md-4">
                            <label class="font-size-md" style="font-size:17px;" for="dtFecFin">Fecha Fin</label>
                            <input type="date" class="form-control form-control-md form-control-as form-info" style="font-size:17px;" id="dtFecFin" placeholder="">
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row align-items-center">
                          <div class="col-6">
                            <button type="button" class="btn btn-secondary" style="font-size:21px;" id="btnConsultar">
                              <i class="fas fa-tasks"></i> Consultar Facturas
                            </button>
                          </div>
                          <div class="col-12 col-md-3"></div>
                          <div class="col-12 col-md-6">
                            <label for="txtFiltrar"></label>
                            <div class="input-group input-group-sm mb-3">
                              <div class="input-group-prepend">
                                <span class="input-group-text" id="inputGroup-sizing-sm"><i class="fas fa-search" aria-label="small"></i></span>
                              </div>
                              <input type="text" class="form-control" aria-label="small" aria-describedby="inputGroup-sizing-sm" placeholder="Filtrar.." style="font-size:18px;" id="txtFiltrar">
                            </div>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-11">
                            <div class="table-responsive"  style="height:600%;">
                              <table class="table table-dark table-hover table-bordered table-md table-striped" id="tblFac">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="70">ID Interno</th>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="70">Fecha</th>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="90">Nit</th>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="400">Nombre en la Factura</th>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="10"></th>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="50">Total</th>
                                    <th scope="col" class="text-center" style="font-size:21px;" width="30">Seleccionar</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="col-12 col-sm-3">
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" style='font-size:26px;' id="btnEmail" type="button">Enviar por Correo</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" style='font-size:26px;' id="btnImprimirIndividual" type="button" disabled>Imprimir Ticket</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" style='font-size:26px;' id="btnImprimirPdf" type="button">Generar PDF</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";

  const txtSerie = document.thisform.txtSerie;
  const dtFec = document.thisform.dtFec;
  const colFac = ["IDInterno", "fec", "correo", "cod", "nom", "tcam", "tot", "tdocnom", "totLetras", "stat"];

  function addRowFac(IDInterno, fec, correo, nit, nom, tcam, tot, tdocnom, totLetras, i){
    var totLetras = "";
    if (tcam == 'Q') {
      totLetras = numeroALetras(tot, 2, {
                    plural: 'quetzales',
                    singular: 'quetzal',
                    centPlural: 'centavos',
                    centSingular: 'centavo'
                  }).toUpperCase()
    } else {
      totLetras = numeroALetras(tot, 2, {
                    plural: 'dólares',
                    singular: 'dólar',
                    centPlural: 'centavos',
                    centSingular: 'centavo'
                  }).toUpperCase()
    }
    const row = "<tr>"
                  +"<td id='dataIDInterno' style='font-size:21px;'>"+IDInterno+"</td>"
                  +"<td id='dataFec' class='text-center' style='font-size:21px;'>"+YMDToDMY(fec)+"</td>"
                  +"<td id='dataCorreo' class='d-none'>"+correo+"</td>"
                  +"<td id='dataCod' style='font-size:21px;'>"+nit+"</td>"
                  +"<td id='dataNom' style='font-size:21px;'>"+nom+"</td>"
                  +"<td id='dataTcam' class='text-right' style='font-size:21px;'>"+tcam+"</td>"
                  +"<td id='dataTot' class='text-right' style='font-size:21px;'>"+tot+"</td>"
                  +"<td id='dataTdocnom' class='d-none'>"+tdocnom+"</td>"
                  +"<td id='dataTotLetras' class='d-none'>"+totLetras+"</td>"
                  +'<td class="text-center">'
                    +'<div class="btn-group btn-checkbox" data-toggle="buttons">'
                      +'<label class="btn btn-secondary cbFac" style="font-size:16px;">'
                        +'<input type="checkbox" id="dataCheck'+i+'" name="cb">'
                        +'<span class="fas fa-check fa-sm"></span>'
                      +'</label>'
                    +'</div>'
                  +'</td>'
                +"</tr>";
    $("#tblFac tbody").append(row);
  }

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

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    dtFecIni.value = dateToday();
    dtFecFin.value = dateToday();
    email = "";

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

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

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

    // VALID TASA DE CAMBIO
    $("#btnConsultar")
    .click(function (){
      const parametros = new FormData();
      parametros.append("action", "consultarFacturas");
      parametros.append("dtFecIni", dtFecIni.value);
      parametros.append("dtFecFin", dtFecFin.value);
      tblClear("tblFac");

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.facturas === null) {
            } else {
              jsonJS.facturas.forEach(function(i, index){
                addRowFac(i.fact_idinterno, i.fact_fec, i.cli_email, i.fact_nit, i.fact_nom, (i.fact_tcam > 1) ? "$" : "Q", i.fact_tot, i.tv_nom, index);
              });
              tblAllChecked("tblFac", "cb", "cbTodos");
              alClose()
            }
          }
        }
      });
    });

    // CLICK EMAIL
    $("#btnEmail").click(function (){
      //if (restriccion()) {return};
      $("#tblFac tbody tr").each(function(){
        if ($(this).find('td input[name="cb"]').is(":checked")) {
          //console.log($("#dataCorreo").text());
          txtMail.value = $("#dataCorreo").text();
        }
      });
      $('#modalMail').modal('toggle');
    });
    // BOTON PARA CONTINUAR Y DECIDIR SI IMPRIME O MANDA CORREO
    $("#btnEnviar").click(function (){
      $('#modalMail').modal('toggle');
      const parametros = new FormData();
      parametros.append("action", "email");
      parametros.append("correoe", txtMail.value);
      parametros.append("correoe1", txtMail1.value);
      parametros.append("correoe2", txtMail2.value);
      parametros.append("dtFecIni", dtFecIni.value);
      parametros.append("dtFecFin", dtFecFin.value);
      parametros.append("tblFac", tblToJsonCbSkip(colFac, "tblFac", 11, 9));
      //console.log(tblToJsonCbSkip(colFac, "tblFac", 10, 7))
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"email.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 {
            alSuccess(jsonJS);
          }
        }
      });
    });

    // CLICK IMPRIMIR INDIVIDUAL
    $("#btnImprimirIndividual").click(function (){
      const parametros = new FormData();
      parametros.append("action", "imprimir");
      parametros.append("tblFac", tblToJsonCbSkip(colFac, "tblFac", 11, 9));
      console.log(tblToJsonCbSkip(colFac, "tblFac", 10, 8))
      
      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"printticket.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
        },
        success: function (jsonPhp) {
          console.log(jsonPhp);

          if(isNullPer(jsonPhp)){
//            window.open(getElements("print"), '_blank');
          } else {
            const jsonJS = JSON.parse(jsonPhp);
            alError(jsonJS);
          }
        }
      }); 
    });

    // CLICK IMPRIMIR INDIVIDUAL
    $("#btnImprimirPdf").click(function (){
      const jsonFac = JSON.parse(tblToJsonCbSkip(colFac, "tblFac", 11, 9));

      console.log(tblToJsonCbSkip(colFac, "tblFac", 11, 9))
      jsonFac.forEach(function(i) {
        console.log(JSON.stringify(new Array(i)))
        var getTblFac = JSON.stringify(new Array(i));

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

    // CLICK TODOS
    $('#cbTodos').change(function () {
      (this.checked) ? $(".cbFac").addClass("active") : $(".cbFac").removeClass("active");
      cbAllChecked("tblFac", "cb", "cbTodos");
    });
  });

  $("#txtFiltrar").on("keyup", function() {
    var value = accent_fold($(this).val().toLowerCase());
    $("#tblFac tbody tr").filter(function() {
      $(this).toggle(accent_fold($(this).text()).toLowerCase().indexOf(value) > -1)
    });
  });
</script>