<?php include('./header.php'); ?>
<style type="text/css">
  .logo img {
    width: 150px;
  }

  .container .form-outer {
    width: 100%;
    overflow: hidden;
  }

  .form-outer .formulario {
    display: flex;
    width: 400%;
  }

  .form-outer .formulario .page {
    width: 25%;
    transition: margin-left 0.3s ease-in-out;
  }

  .form-outer .formulario .page .field {
    display: flex;
  }

  .form-outer .formulario .page .field button:hover {
    background-color: #66009f;
    border-color: #66009f;
  }

  .form-outer .formulario .page .field button {
    background-color: #560085;
    border-color: #560085;
  }

  .formulario .page .btns button.prev {
    margin-right: 3px !important;
    font-size: 17px;
  }

  .formulario .page .btns button.next {
    margin-left: 3px !important;
  }

  .container .progress-barra {
    display: flex;
    justify-content: space-between;
  }

  .container .progress-barra .step {
    position: relative;
    text-align: center;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }

  .progress-barra .step p {
    font-size: 14px;
    font-weight: 500;
    color: #666;
    margin-bottom: 8px;
    transition: 0.2s;
  }

  .progress-barra .step p.active {
    color: #560085;
  }

  .progress-barra .step .bullet {
    position: relative;
    height: 35px;
    width: 35px;
    border: 2px solid #666;
    display: inline-block;
    border-radius: 50%;
    transition: 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .progress-barra .step .bullet.active {
    border-color: #560085;
    background: #560085;
  }

  .progress-barra .step .bullet span {
    font-weight: 500;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .progress-barra .step .bullet.active span {
    display: none;
  }

  .progress-barra .step:last-child .bullet:before,
  .progress-barra .step:last-child .bullet:after {
    display: none;
  }

  .progress-barra .step .bullet:before,
  .progress-barra .step .bullet:after {
    position: absolute;
    content: '';
    right: -14.35rem;
    height: 3px;
    width: 14rem;
    background: #666;
  }

  .progress-barra .step .bullet.active:after {
    background: #560085;
    transform: scaleX(0);
    transform-origin: left;
    animation: animate 0.3s linear forwards;
  }

  @keyframes animate {
    100% {
      transform: scaleX(1);
    }
  }

  .progress-barra .step .check {
    position: absolute;
    font-size: 15px;
    color: #666;
    display: none;
  }

  .progress-barra .step .check.active {
    display: block;
    color: #fff;
  }
</style>

<body class="hold-transition layout-top-nav">
  <div class="wrapper">
    <div class="preloader flex-column justify-content-center align-items-center">
    </div>
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <div class="content-header">
        <div class="container-fluid">
        </div><!-- /.container-fluid -->
      </div>
      <!-- /.content-header -->

      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-md-12">
              <div class="card card-default">
                <div class="card-body">
                  <div class="row">
                    <div class="col-md-2">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Totais</small>
                        <select class="form-control select2 campoRelatorio" style="width: 100%;" id="totais" name="totais">
                          <option value="mensais">Mensais</option>
                          <option value="anuais">Anuais</option>
                          <option value="entreDatas">Entre Datas</option>
                        </select>
                      </div>
                    </div>
                    <div id="div-mes" style="display: inline-flex;">
                      <div class="col-md-6">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Ano</small>
                          <input type="text" class="form-control campoRelatorio" id="anoMes" name="anoMes" placeholder="Ano" title="Ano" required>
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Mês</small>
                          <select class="form-control select2 campoRelatorio" style="width: 100%;" id="mes" name="mes">
                            <option value="1">Janeiro</option>
                            <option value="2">Fevereiro</option>
                            <option value="3">Março</option>
                            <option value="4">Abril</option>
                            <option value="5">Maio</option>
                            <option value="6">Junho</option>
                            <option value="7">Julho</option>
                            <option value="8">Agosto</option>
                            <option value="9">Setembro</option>
                            <option value="10">Outubro</option>
                            <option value="11">Novembro</option>
                            <option value="12">Dezembro</option>
                          </select>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-2" id="div-ano">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Ano</small>
                        <input type="text" class="form-control campoRelatorio" id="ano" name="ano" placeholder="Ano" title="Ano" required>
                      </div>
                    </div>
                    <div id="div-datas" style="display: inline-flex;">
                      <div class="col-md-6">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Data Inicial</small>
                          <input type="date" class="form-control campoRelatorio" id="dataInicial" name="dataInicial" placeholder="Data Inicial" title="Data Inicial" required>
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Data Final</small>
                          <input type="date" class="form-control campoRelatorio" id="dataFinal" name="dataFinal" placeholder="Data Final" title="Data Final" required>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Terminais</small>
                        <select class="form-control select2 campoRelatorio" style="width: 100%;" id="terminais" name="terminais">
                          <option value="geral">Geral</option>
                          <option value="porTerminal">Por Terminal</option>
                        </select>
                      </div>
                    </div>
                    <div class="col-md-2" id="div-terminal">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Terminal</small>
                        <select class="form-control select2 campoRelatorio" style="width: 100%;" id="idTerminal" name="idTerminal">
                        </select>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small>Botao</small>
                        <button type="button" class="btn btn-primary" style="width: 100%; padding: .3rem;" id="queryBtn">Executar</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-12">
              <div class="card card-default">
                <div class="card-header">
                  <h3 class="card-title">Relatório - Total de Vendas Por Tipo de Pagamento</h3>
                  <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                      <i class="fas fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-tool" data-card-widget="remove">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                  <table id="tabelaRelatorio" class="table table-bordered table-striped" style="line-height: 0.8;">
                    <thead>
                      <tr style="text-align: center;">
                        <th title="Referência Tipo de Pagamento" style="width: 15%;">Ref. Tipo Pagamento</th>
                        <th title="Descrição">Descrição</th>
                        <th title="Total">Total</th>
                      </tr>
                    </thead>
                    <tbody id="corpoTabela" style="text-align: center;">

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          <!-- /.card -->
        </div>
        <!-- /.container-fluid -->
      </section>
      <div class="modal fade" id="modal-documento">
        <div class="modal-dialog modal-xl">
          <div class="modal-content">
            <div class="modal-header">
              <div class="container">
                <div class="progress-barra">
                  <div class="step">
                    <p style="margin: 0;">Formulário de Família</p>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-body">
              <div class="container">
                <div class="card-body form-outer" style="padding: 0;">
                  <div class="formulario">
                    <div class="page slidePage">
                      <div class="row">
                        <div class="col-md-12">
                          <h5 style="margin-bottom: 1rem; justify-content: center;"><span id="doOpcao"></span> - <span id="codigo"></span></h5>
                          <div class="row">
                            <div class="col-md-10"></div>
                            <div class="col-md-6">
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="required">Descrição</small>
                                <input type="text" class="form-control" id="nome" name="nome" placeholder="Descrição" title="Descrição" required>
                                <small>Mensagem de erro</small>
                              </div>
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="not-required">Observações</small>
                                <textarea rows="4" type="text" class="form-control" id="nota" name="nota" placeholder="Observações" title="Observações" required></textarea>
                                <small>Mensagem de erro</small>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-12" style=" bottom: 0; padding-top: 14px;">
                          <div class="form-group margem">
                            <small>Mensagem de erro</small>
                            <div class="form-group field btns">
                              <button class="btn btn-block btn-primary submit next" style="margin-top: 0;">
                                Gravar Família
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>

                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="col-md-12" id="footerPagamento" style="opacity: 0;">
                <h4 style="display: flex; align-items: center; justify-content: space-between;"><span id="totalEntregue">ENTREGUE</span><span id="entregueSpan">0,00 Kzs</span></h4>
                <h4 style="display: flex; align-items: center; justify-content: space-between;"><span class="text-danger" id="totalText">TOTAL</span><span class="text-danger" id="totalSpan">0,00 Kzs</span></h4>
              </div>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <div class="modal fade" id="modal-cliente">
        <div class="modal-dialog modal-xl">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">Entidades</h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <table id="tabelaCliente" class="table table-hover table-bordered table-striped" style="line-height: 0.8;">
                <thead>
                  <tr style="text-align: center;">
                    <th title="Identificador da Entidade">Ref. Entidade</th>
                    <th title="Nome">Nome</th>
                    <th title="Nome Comercial">Nome Comercial</th>
                    <th title="Bilhete de Identidade do Cliente">B.I</th>
                    <th title="NIF do Cliente">NIF</th>
                    <th title="Localidade do Cliente">Localidade</th>
                    <th title="Data de Nascimento do Cliente">Data Nasc.</th>
                    <th title="Morada do Cliente">Morada</th>
                    <th title="Tipo">Tipo</th>
                    <th title="Estado do Cliente">Estado</th>
                  </tr>
                </thead>
                <tbody style="text-align: center;">
                </tbody>
              </table>
            </div>
            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
              <button type="button" class="btn btn-primary">Confirmar</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <div class="modal fade" id="modal-artigo">
        <div class="modal-dialog modal-xl">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">Artigos</h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <table id="tabelaArtigoListagem" class="table table-hover table-bordered table-striped" style="line-height: 0.8;">
                <thead>
                  <tr style="text-align: center;">
                    <th title="Referência">Referência</th>
                    <th title="Descrição do Artigo">Descrição</th>
                    <th title="Família">Família</th>
                    <th title="Preço do Artigo (S/Imp)">Preço (S/Imp)</th>
                    <th title="Preço do Artigo (C/Imp)">Preço (C/Imp)</th>
                    <th title="Qtd. Stock">Qtd. Stock</th>
                  </tr>
                </thead>
                <tbody style="text-align: center;">
                </tbody>
              </table>
            </div>
            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
              <button type="button" class="btn btn-primary">Confirmar</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
    </div>
    <div class="modal fade" id="modal-updateUsuario">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header" style="padding: 0.5rem;">
            <h3 class="card-title p-3">Família: <span id="nomeModal"></span></h3>
          </div>
          <div class="modal-body" style="padding-bottom: 0px;">
            <div class="row">
              <div class="col-md-12">
                <form name="tabelaInfo">
                  <table name="tabelaInfo" class="table table-sm table-bordered" style="min-width: 100%;
                      max-width: 100%;">
                    <tr name="linhaItem">
                      <td style="padding: 20px 0px 0px 10px;">
                        <p>Ref. da Família: <span id="codigoInfo"></span></p>
                        <p>Descrição: <span id="nomeInfo"></span></p>
                        <p>Observações: <span id="notaInfo"></span></p>
                      </td>
                    </tr>
                  </table>
                </form>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <div class="modal fade" id="modal-entidade">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">Entidades</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <table id="tabelaEntidade" class="table table-hover table-bordered table-striped" style="line-height: 0.8;">
              <thead>
                <tr style="text-align: center;">
                  <th title="Identificador da Entidade">Ref. Entidade</th>
                  <th title="Nome">Nome</th>
                  <th title="Nome Comercial">Nome Comercial</th>
                  <th title="Bilhete de Identidade do Entidade">B.I</th>
                  <th title="NIF do Entidade">NIF</th>
                  <th title="Localidade do Entidade">Localidade</th>
                  <th title="Data de Nascimento do Entidade">Data Nasc.</th>
                  <th title="Morada do Entidade">Morada</th>
                  <th title="Tipo">Tipo</th>
                  <th title="Estado do Entidade">Estado</th>
                </tr>
              </thead>
              <tbody style="text-align: center;">
              </tbody>
            </table>
          </div>
          <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
            <button type="button" class="btn btn-primary">Confirmar</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <div class="modal fade" id="modal-usuario">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">Usuários</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <table id="tabelaUsuario" class="table table-bordered table-striped" style="line-height: 0.8;">
              <thead>
                <tr style="text-align: center;">
                  <th title="Identificador do Usuário">Ref. Usuário</th>
                  <th title="Nome">Nome</th>
                  <th title="Género (Masculino, Feminino)">Género</th>
                  <th title="Bilhete de Identidade">B.I</th>
                  <th title="E-mail">E-mail</th>
                  <th title="Nome de Usuário">Nome de Usuário</th>
                </tr>
              </thead>
              <tbody id="corpoTabela" style="text-align: center;">

              </tbody>
            </table>
          </div>
          <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
            <button type="button" class="btn btn-primary">Confirmar</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.content-wrapper -->
    <?php include('footer.php'); ?>
</body>

</html>
<script>
  let idCliente;
  let valorLinha;
  let totalDoc;
  let pendenteVerify;
  let totalImposto = [];
  let dataHoraFormatada;
  let resizedImage;

  $(document).ready(function() {
    $.ajax({
      url: "includes/read/terminal.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        for (var key in data) {
          select += "<option value=" + data[key]['idTerminal'] + ">" + data[key]['nome'] + "</option>";
        }
        $("#idTerminal").html(select);
      }
    });
    $.ajax({
      url: "includes/read/tipoDoc.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        select += "<option value='0'>(Todos)</option>";
        for (var key in data) {
          select += "<option value=" + data[key]['idTipoDoc'] + ">" + data[key]['nome'] + "</option>";
        }
        $("#idTipoDocumento").html(select);
      }
    });
    $(function() {
      //Initialize Select2 Elements
      $('.select2').select2()

      //Initialize Select2 Elements
      $('.select2bs4').select2({
        theme: 'bootstrap4'
      })
    });
  });

  let urlToFile = (url) => {
    let arr = url.split(",");
    let mime = arr[0].match(/:(.*?);/)[1];
    let data = arr[1];

    let dataString = atob(data);
    let n = dataString.length;
    let dataArr = new Uint8Array(n);
    while (n--) {
      dataArr[n] = dataString.charCodeAt(n);
    }
    let file = new File([dataArr], 'File.jpg', {
      type: mime
    });
    return file;
  }

  /*$(document).ready(function() {
    const img_input = document.querySelector("#file");
    img_input.addEventListener("change", function() {
      const reader = new FileReader();
      reader.addEventListener("load", () => {
        const imgElement = document.createElement("img");
        imgElement.src = reader.result;
        imgElement.onload = function(e) {
          const canvas = document.createElement("canvas");
          const MAX_WIDTH = 400;
          const scaleSize = MAX_WIDTH / e.target.width;
          canvas.width = MAX_WIDTH;
          canvas.height = e.target.height * scaleSize;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);

          const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
          resizedImage = urlToFile(srcEncoded);
        }

        const uploaded_image = reader.result;
        document.querySelector(".image-container").style.backgroundImage = `url(${uploaded_image})`;
      });
      reader.readAsDataURL(this.files[0]);
      document.querySelector(".image-container").querySelector("i").style.display = "none";
    });
  });*/

  /*$(document).ready(function() {
    $.ajax({
      url: "includes/read/codigoDocumento.inc.php",
      type: "post",
      dataType: "json",
      data: {
        codigo: 2
      },
      success: function(data) {
        codigo.innerText = "<?php echo date("Y"); ?>" + "/" + data[0]["contador"];
      }
    });
  });*/


  function actualizarDataHora() {
    const dataActual = new Date();

    // Obtenha o ano, mês, dia, hora e minutos
    const ano = dataActual.getFullYear();
    const mes = formatoDoisDigitos(dataActual.getMonth() + 1);
    const dia = formatoDoisDigitos(dataActual.getDate());
    const hora = formatoDoisDigitos(dataActual.getHours());
    const minutos = formatoDoisDigitos(dataActual.getMinutes());
    dataHoraFormatada = `${ano}-${mes}-${dia}T${hora}:${minutos}`;

    function formatoDoisDigitos(valor) {
      return valor < 10 ? `0${valor}` : valor;
    }
  }

  setInterval(actualizarDataHora, 1000);
  // Função para formatar valores com dois dígitos
  actualizarDataHora();


  $(document).on('click', '#tabelaRelatorio tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    $('#tabelaRelatorio tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
    }
  });
</script>
<script type="module">
  /*import {
    initializeApp
  } from 'https://www.gstatic.com/firebasejs/10.1.0/firebase-app.js'
  import {
    getAnalytics
  } from 'https://www.gstatic.com/firebasejs/10.1.0/firebase-analytics.js'
  import {
    getAuth
  } from 'https://www.gstatic.com/firebasejs/10.1.0/firebase-auth.js'
  import {
    getFirestore,
    collection,
    addDoc,
    getDocs
  } from 'https://www.gstatic.com/firebasejs/10.1.0/firebase-firestore.js'

  const firebaseConfig = {
    apiKey: "AIzaSyAYl5f_OOc_aosK9sURTixa1tCckK6lpMY",
    authDomain: "serra-trucks-d2fe5.firebaseapp.com",
    projectId: "serra-trucks-d2fe5",
    storageBucket: "serra-trucks-d2fe5.appspot.com",
    messagingSenderId: "698670207304",
    appId: "1:698670207304:web:c117cd4d8d8f1816c0e37d",
    measurementId: "G-W6ZYHPBKPF"
  };

  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);*/


  function loadEntidade(tipoEntidade) {
    $.ajax({
      url: "includes/read/entidade.inc.php",
      type: "post",
      dataType: "json",
      data: {
        tipoEntidade: tipoEntidade
      }
    }).done(function(data) {
      $("#tabelaEntidade").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "idEntidade"
        }, {
          data: "nome"
        }, {
          data: "nomeComercial"
        }, {
          data: "bi",
          visible: false
        }, {
          data: "nif",
          visible: false,
        }, {
          data: "localidade",
          visible: false
        }, {
          data: "dataNasc",
          visible: false
        }, {
          data: "morada",
          visible: false
        }, {
          data: "tipoEntidadeNome"
        }, {
          data: "estado",
          visible: false,
          render: function(data) {
            if (data == 0) {
              return "<small class='badge badge-success'>Activo</small>";
            } else if (data == 1) {
              return "<small class='badge badge-danger'>Inactivo</small>";
            }
          }
        }],
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "language": idiomaPortugues,
        lengthMenu: [
          [7, 25, 50, -1],
          [10, 25, 50, 'All']
        ],
        "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
      }).buttons().container().appendTo('#tabelaEntidade_wrapper .col-md-6:eq(0)');
    });
  }

  function loadUsuario() {
    $.ajax({
      url: "includes/read/usuario.inc.php",
      type: "post",
      dataType: "json"
    }).done(function(data) {
      console.log(data);
      $("#tabelaUsuario").DataTable({
        "aaData": data,
        "columns": [{
          data: "idUsuario"
        }, {
          data: "nome"
        }, {
          data: "genero"
        }, {
          data: "bi"
        }, {
          data: "email"
        }, {
          data: "nomeUsuario"
        }],
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "language": idiomaPortugues,
        lengthMenu: [
          [7, 25, 50, -1],
          [10, 25, 50, 'All']
        ],
        "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
      }).buttons().container().appendTo('#tabelaUsuario_wrapper .col-md-6:eq(0)');
    });
  }

  $('#totais').on('change', function() {
    event.preventDefault();
    if (this.value == 'anuais') {
      $("#div-datas").hide(500);
      $("#div-mes").hide(500);
      $("#div-ano").show(500);
    } else if (this.value == 'entreDatas') {
      $("#div-ano").hide();
      $("#div-mes").hide();
      $("#div-datas").show(500);
    } else if (this.value == 'mensais') {
      $("#div-ano").hide();
      $("#div-datas").hide();
      $("#div-mes").show(500);
    }
  });

  $('#terminais').on('change', function() {
    event.preventDefault();
    if (this.value == 'geral') {
      $("#div-terminal").hide(500);
    } else if (this.value == 'porTerminal') {
      $("#div-terminal").show(500);
    }
  });

  let linha;
  $(document).ready(function() {
    $("#div-datas").hide();
    $("#div-ano").hide();
    $("#div-terminal").hide();
    loadEntidade(2);
    loadUsuario();
    $.ajax({
      url: "includes/read/tipoUsuario.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        select += "<option value='0'>Selecione um Tipo de Usuario</option>";
        for (var key in data) {
          select += "<option value=" + data[key]['idTipoUsuario'] + ">" + data[key]['nome'] + "</option>";
        }
        $("#idTipoUsuario").html(select);
      }
    });
  });

  function updateLinha(linha) {
    $.ajax({
      url: "includes/read/queryFamilia.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idFamilia: linha[0].innerText,
      },
      success: function(data) {
        for (var key in data) {
          linha[1].innerText = data[key]["nome"];
          linha[2].innerText = data[key]["nota"];
        }
      }
    });
  }

  function insertLinha(id) {
    $.ajax({
      url: "includes/read/queryFamilia.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idFamilia: id,
      },
      success: function(data) {
        console.log("Família: ", data);
        for (var key in data) {
          var novaLinha = {
            idFamilia: data[key]["idFamilia"],
            nome: data[key]["nome"],
            nota: data[key]["nota"],
          };
          $('#tabelaRelatorio').DataTable().row.add(novaLinha).draw(false);
        }
      }
    });
  }

  $('#queryBtn').on('click', function(e) {
    e.preventDefault();
    $.ajax({
      url: "includes/report/vendaTotalTipoPagamento.inc.php",
      type: "post",
      dataType: "json",
      data: {
        totais: totais.value,
        anoMes: anoMes.value,
        mes: mes.value,
        ano: ano.value,
        dataInicial: dataInicial.value,
        dataFinal: dataFinal.value,
        terminais: terminais.value,
        idTerminal: idTerminal.value,
      }
    }).done(function(data) {
      console.log("Resultado: ", data);
      $("#tabelaRelatorio").DataTable().clear().draw();
      $("#tabelaRelatorio").DataTable().rows.add(data).draw();
    });
  });

  $(document).ready(function() {
    $.ajax({
      url: "includes/report/vendaTotalTipoPagamento.inc.php",
      type: "post",
      dataType: "json",
      data: {
        totais: totais.value,
        anoMes: anoMes.value,
        mes: mes.value,
        ano: ano.value,
        dataInicial: dataInicial.value,
        dataFinal: dataFinal.value,
        terminais: terminais.value,
        idTerminal: idTerminal.value,
      }
    }).done(function(data) {
      console.log(data);
      $("#tabelaRelatorio").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "refModoPagamento"
        }, {
          data: "modoPagamento"
        }, {
          data: "total",
          render: function(data, type, row) {
            if (data == null) {
              return `0,00`;
            } else {
              return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
            }
          }
        }],
        columnDefs: [{
          targets: -1,
          orderable: false
        }],
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "language": idiomaPortugues,
        lengthMenu: [
          [8, 25, 50, -1],
          [10, 25, 50, 'All']
        ],
        "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
      }).buttons().container().appendTo('#tabelaRelatorio_wrapper .col-md-6:eq(0)');
    });
  });

  var idiomaPortugues = {
    buttons: {
      copy: "Copiar",
      print: "Imprimir",
      colvis: "Visibilidade"
    },
    "sProcessing": "A processar...",
    "sLengthMenu": "Mostrar _MENU_ dos registros",
    "sZeroRecords": "Sem resultados!",
    "sEmptyTable": "Tabela sem dados disponíveis",
    "sInfo": "De _START_ à _END_ de um total de _TOTAL_ registros",
    "sInfoEmpty": "De 0 à 0 de um total de 0 registros",
    "sInfoFiltered": "(filtrado de um total de _MAX_ registros)",
    "sInfoPostFix": "",
    "sSearch": "Pesquisar:",
    "sUrl": "",
    "sInfoThousands": ",",
    "sLoadingRecords": "A carregar...",
    "oPaginate": {
      "sFirst": "Primeira",
      "sLast": "Última",
      "sNext": "Seguinte",
      "sPrevious": "Anterior"
    },
    "oAria": {
      "sSortAscending": ": Activar para ordenar a coluna de forma ascendente",
      "sSortDescending": ": Activar para ordenar a coluna de forma descendente"
    }
  }

  $('#tabelaRelatorio tbody').on('click', 'td', function() {
    let tabela = document.getElementById("tabelaRelatorio");

    for (let i = 1; i < tabela.rows.length; i++) {
      tabela.rows[i].ondblclick = function() {
        linha = this.cells[0].parentElement;
        idUsuario = this.cells[0].innerHTML;
        nomeEdit = this.cells[1];
        generoEdit = this.cells[2];
        biEdit = this.cells[3];
        emailEdit = this.cells[4];
        nomeUsuarioEdit = this.cells[5];

        console.log(idUsuario);
        ajax();
        //$('#modal-lg').modal('show');
        //this.classList.remove("selected");
      }
    }
  });

  function reload() {
    $('#modal-documento').modal('hide');
    resetForm();
    loadNovoId();
    nome.value = "";
    nome.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    nome.className = "form-control";
    nota.value = "";
    nota.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    nota.className = "form-control";
    document.querySelector(".submit").removeAttribute('disabled');
  }

  $(document).on("click", "#btn", function(e) {
    e.preventDefault();
    doOpcao.innerText = "Nova Família";
    reload();

    $('#modal-documento').modal('show');
    $(function() {
      //Initialize Select2 Elements
      $('.select2').select2()

      //Initialize Select2 Elements
      $('.select2bs4').select2({
        theme: 'bootstrap4'
      })
    })
    /*$('#modal-documento').modal({
      backdrop: 'static'
    }, 'show');*/
  });

  function ajax(idUsuario) {
    $.ajax({
      url: "includes/read/queryFamilia.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idUsuario: idUsuario
      },
      success: function(data) {
        console.log("Resultados: ", data);
        imagemInfo = document.getElementById("imagemInfo");
        img = document.querySelector(".image-info");

        imgUpdate = document.querySelector(".image-container");

        for (var key in data) {
          if (data[key]['imagem'] != null) {
            img.querySelector("i").style.display = "none";
            imagemInfo.style.backgroundImage = "url('images/usuario/" + data[key]['imagem'] + "')";
            console.log("Tem imagem!");
          } else {
            console.log("Não tem imagem!");
            img.querySelector("i").style.display = "block";
            imagemInfo.style.backgroundImage = "url('images/usuario/" + data[key]['imagem'] + "')";
          }

          nomeModal.innerText = data[key]['nome'];
          codigoInfo.innerText = data[key]['idUsuario'];
          nomeInfo.innerText = data[key]['nome'];
          nomeUsuarioInfo.innerText = data[key]['nomeUsuario'];
          generoInfo.innerText = data[key]['genero'];
          biInfo.innerText = data[key]['bi'];
          emailInfo.innerText = data[key]['email'];
          enderecoInfo.innerText = data[key]['endereco'];
          telefoneInfo.innerText = data[key]['telefone'];
          dataNascInfo.innerText = data[key]['dataNasc'];
          dataAdesaoInfo.innerText = data[key]['dataAdesao'];
          estadoInfo.innerText = data[key]['estado'];
          tipoUsuarioInfo.innerText = data[key]['tipoUsuario'];

          imgUpdate.style.backgroundImage = "url('images/usuario/" + data[key]['imagem'] + "')";
          imgUpdate.querySelector("i").style.display = "none";

          nome.value = data[key]['nome'];
          nomeUsuario.value = data[key]['nomeUsuario'];

          $('#genero').val(data[key]['genero']);
          $('#genero').select2().trigger('change');

          email.value = data[key]['email'];
          bi.value = data[key]['bi'];

          $('#idTipoUsuario').val(data[key]['idTipoUsuario']);
          $('#idTipoUsuario').select2().trigger('change');
        }
      }
    }).done(function(data) {
      $('#modal-updateUsuario').modal('show');
    });
  }

  function detalhes(id) {
    $.ajax({
      url: "includes/read/queryFamilia.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idFamilia: id
      },
      success: function(data) {
        console.log("Essas são as famílias", data);
        for (var key in data) {
          nomeModal.innerText = data[key]["nome"];
          codigoInfo.innerText = data[key]["idFamilia"];
          nomeInfo.innerText = data[key]["nome"];
          notaInfo.innerText = data[key]["nota"];
        }
      }
    });
  }

  $('#tabelaRelatorio').on('click', '.btn-more', function(e) {
    e.preventDefault();
    $('#modal-updateUsuario').modal('show');
    linha = $(this).closest('tr').find('td');
    detalhes($(this).closest('tr').find('td')[0].textContent);
  });

  $('#tabelaRelatorio').on('click', '.btn-update', function(e) {
    e.preventDefault();
    linha = $(this).closest('tr').find('td');
    doOpcao.innerText = "Editar Família";
    resetForm();
    $('#modal-documento').modal('show');
    let id = $(this).closest('tr').find('td')[0].textContent;
    $.ajax({
      url: "includes/read/queryFamilia.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idFamilia: id
      },
      success: function(data) {
        for (var key in data) {
          codigo.innerText = data[key]["idFamilia"];

          if (data[key]["nome"] != "") {
            nome.value = data[key]["nome"];
          } else {
            nome.value = "";
          }

          if (data[key]["nota"] != "") {
            nota.value = data[key]["nota"];
          } else {
            nota.value = "";
          }
        }
        console.log(data)
      }
    });
  });

  $('#tabelaRelatorio').on('click', '.btn-delete', function(e) {
    e.preventDefault();
    linha = $(this).closest('tr').find('td');
    let id = $(this).closest('tr').find('td')[0].textContent;
    let nome = $(this).closest('tr').find('td')[1].textContent;
    swal.fire({
        title: "Tem a certeza que pretende eliminar Família?",
        text: "Família: " + nome,
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: 'Confirmar',
        confirmButtonColor: '#560085',
        cancelButtonText: 'Cancelar',
        cancelButtonColor: '#560085',
      })
      .then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: "includes/delete/familia.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idFamilia: id
            },
            success: function(data) {
              console.log(data);
              swal.fire({
                title: "Família " + nome + " eliminado com sucesso!",
                icon: "success",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
              });
              $('#tabelaRelatorio').DataTable().row(linha).remove().draw(false);
            },
            error: function(data) {
              swal.fire({
                title: "Erro ao eliminar Família!",
                text: "Família associada a um ou mais artigos.",
                icon: "error",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
              });
            }
          });
        }
      });
  });

  function loadNovoId() {
    $.ajax({
      url: "includes/read/codigoFamilia.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        codigo.innerText = data;
      }
    });
  }

  $('#tabelaArtigo').on('click', '.remove_row', function(e) {
    e.preventDefault();
    var table = $('#tabelaArtigo').DataTable();
    var row = $(this).closest('tr');
    if ($('#tabelaArtigo tbody tr').length > 1) {
      table.row(row).remove().draw();
    } else {
      row.find('.inputSearchArtigo').val("");
      row.find('.descricao').val("");
      row.find('.qtd').val(1);
      row.find('.preco').val("");
      row.find('.desconto').val("0,00%");
      row.find('.imposto').val(0);
      row.find('.imposto').select2().trigger('change');
      row.find('.total').val("");
    }
    totalDocumento();
  });

  $('#tabelaArtigo').on('keypress', '.inputSearchArtigo', function() {
    if (event.which === 13) {
      event.preventDefault();
      funcaoQueryArtigo($(this).val(), $(this));
      totalDocumento();
    }
  });

  $('#tabelaArtigo').on('focusout', '.inputSearchArtigo', function() {
    event.preventDefault();
    if (this.value == "") {
      $(this).closest('tr').find('.inputSearchArtigo').val("");
      $(this).closest('tr').find('.descricao').val("");
      $(this).closest('tr').find('.qtd').val(1);
      $(this).closest('tr').find('.preco').val("");
      $(this).closest('tr').find('.desconto').val("0,00%");
      $(this).closest('tr').find('.imposto').val(0);
      $(this).closest('tr').find('.imposto').select2().trigger('change');
      $(this).closest('tr').find('.total').val("");
    } else {
      funcaoQueryArtigo($(this).val(), $(this));
    }
    totalDocumento();
  });

  $(document).on("click", ".submit", function(e) {
    e.preventDefault();
    if (nome.value != '') {
      familia();
    }
  });

  /*async function createUsuario(img) {
    try {
      const docRef = await addDoc(collection(db, "user"), {
        isVerified: false,
        username: nomeUsuario.value,
        password: "admin"
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
    $.ajax({
      url: "includes/create/usuario.inc.php",
      type: "post",
      data: {
        nome: nome.value,
        nomeUsuario: nomeUsuario.value,
        genero: genero.value,
        email: email.value,
        bi: bi.value,
        idTipoUsuario: idTipoUsuario.value
      },
      success: function(data) {
        swal.fire({
          title: "Cadastro efectuado com sucesso!",
          text: "Família " + nome.value + " cadastrado!",
          confirmButtonText: 'Confirmar',
          confirmButtonColor: '#560085',
          icon: "success",
        }).then(() => {
          if (img[0] != null) {
            foto(data, img);
          }
        });
        nome.value = "";
        nome.className = "form-control";
        nomeUsuario.value = "";
        nomeUsuario.className = "form-control";
        $('#genero').val(0);
        $('#genero').select2().trigger('change');
        email.value = "";
        email.className = "form-control";
        bi.value = "";
        bi.className = "form-control";
        $('#idTipoUsuario').val(0);
        $('#idTipoUsuario').select2().trigger('change');
        let smallIdTipoUsuario = idTipoUsuario.parentElement.querySelectorAll("small")[1];
        smallIdTipoUsuario.style.visibility = "hidden";
        let smallGenero = genero.parentElement.querySelectorAll("small")[1];
        smallGenero.style.visibility = "hidden";
      },
      error: function(data) {
        swal.fire({
          title: "Erro ao cadastrar Família!",
          text: "Erro ao cadastrar Família: " + nome.value + " !",
          confirmButtonText: 'Confirmar',
          confirmButtonColor: '#560085',
          icon: "error",
        });
      }
    }).done(function(data) {
      console.log(data);
    });
  }*/

  function familia() {
    if (doOpcao.innerText == "Nova Família") {
      $.ajax({
        url: "includes/create/familia.inc.php",
        type: "post",
        data: {
          idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
          nome: nome.value,
          nota: nota.value,
        },
        success: function(data) {
          swal.fire({
            title: "Cadastro efectuado com sucesso!",
            text: "Família " + nome.value + " cadastrado!",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "success",
          });
          insertLinha(data);
          reload();
        },
        error: function(data) {
          swal.fire({
            title: "Erro ao cadastrar Família!",
            text: "Erro ao cadastrar Família: " + nome.value + " !",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "error",
          });
        }
      }).done(function(data) {
        console.log(data);
      });
    } else {
      $.ajax({
        url: "includes/update/familia.inc.php",
        type: "post",
        data: {
          idFamilia: codigo.innerText,
          idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
          nome: nome.value,
          nota: nota.value,
        },
        success: function(data) {
          swal.fire({
            title: "Informações Actualizadas com sucesso!",
            text: "Família " + nome.value + ".",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "success",
          });
          updateLinha(linha);
          reload();
        },
        error: function(data) {
          swal.fire({
            title: "Erro ao cadastrar Família!",
            text: "Erro ao cadastrar Família: " + nome.value + " !",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "error",
          });
        }
      }).done(function(data) {
        console.log(data);
      });
    }
  }

  function foto(identificador, img) {
    let form_data = new FormData();
    form_data.append('id', identificador);
    form_data.append('imagem', resizedImage);

    $.ajax({
      url: "includes/create/fotoUsuario.inc.php",
      type: "post",
      data: form_data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(data) {
        console.log(data);
      }
    });
  }

  $(document).on("click", "#btn-delete", function(e) {
    e.preventDefault();
    console.log(idUsuario);
    swal.fire({
        title: "Tem a certeza que pretende eliminar usuario?",
        text: "usuario: " + nome.value,
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: 'Confirmar',
        confirmButtonColor: '#560085',
        cancelButtonText: 'Cancelar',
        cancelButtonColor: '#560085',
      })
      .then((result) => {
        if (result.isConfirmed) {
          if (idUsuario != 1) {
            $.ajax({
              url: "php/delete/usuario.php",
              type: "post",
              dataType: "json",
              data: {
                idUsuario: idUsuario
              },
              success: function(data) {
                console.log(data);
                swal.fire({
                  title: "usuario " + nome.value + " eliminado com sucesso!",
                  icon: "success",
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: '#560085',
                });
                $('#tabelaRelatorio').DataTable().row(linha).remove().draw(false);
              },
              error: function(data) {
                swal.fire({
                  title: "Erro ao eliminar usuario!",
                  text: "Erro ao apagar usuario: " + nome.value + " !",
                  icon: "error",
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: '#560085',
                });
              }
            });
          } else {
            swal.fire({
              title: "Erro ao eliminar Família!",
              text: "Família: " + nome.value + " não pode ser eliminado!",
              confirmButtonText: 'Confirmar',
              confirmButtonColor: '#560085',
              icon: "error",
            });
          }
        }
      });
  });
</script>
<script src="./validation/parametroFamilia.js"></script>