<?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">
            <!-- SELECT2 EXAMPLE -->
            <div class="col-md-12">
              <div class="card card-default">
                <div class="card-body button-nav">
                  <div class="row float-right">
                    <div class="col-md-12">
                      <button class="btn btn-opcao" id="btn-preview" disabled>Pré-visualizar</button>
                      <button class="btn btn-opcao">Importar</button>
                      <button class="btn btn-opcao botao-activo" id="btn">Novo Tipo de Usuário</button>
                    </div>
                  </div>
                  <!-- /.row -->
                </div>
                <!-- /.card-body -->
              </div>
            </div>
            <div class="col-md-12">
              <div class="card card-default">
                <div class="card-header">
                  <h3 class="card-title">Listagem dos Tipos de Usuário</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="tabelaTipoUsuario" class="table table-bordered table-striped" style="line-height: 0.8;">
                    <thead>
                      <tr style="text-align: center;">
                        <th title="Identificador do Tipo de Usuário">Ref. Tipo de Usuário</th>
                        <th title="Descrição da Tipo de Usuário">Descrição</th>
                        <th title="Observações Tipo de Usuário">Observação</th>
                        <th title="Opções"><i class="fa-solid fa-screwdriver-wrench"></i></th>
                      </tr>
                    </thead>
                    <tbody id="corpoTabela" style="text-align: center;">

                    </tbody>
                  </table>
                </div>
                <!-- /.card-body -->
                <div class="card-footer">
                  Listagem dos Tipo de Usuários.
                </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 Tipo de Usuário</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 Tipo de Usuário
                              </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="Tipo de Usuário">Tipo de Usuário</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-updateTipoEntidade">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header" style="padding: 0.5rem;">
            <h3 class="card-title p-3">Tipo de Usuário: <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 Tipo de Usuário: <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>
    <!-- /.content-wrapper -->
    <?php include('footer.php'); ?>
</body>

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

  let btnOpcao = document.querySelectorAll(".btn-opcao");
  for (let i = 0; i < btnOpcao.length; i++) {
    btnOpcao[i].addEventListener("click", function() {
      for (let j = 0; j < btnOpcao.length; j++) {
        btnOpcao[j].classList.remove("botao-activo");
      }
      btnOpcao[i].classList.add("botao-activo");
    });
  }

  $(document).ready(function() {
    $(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', '#tabelaTipoUsuario tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    let btn = document.querySelector("#btn-preview");
    $('#tabelaTipoUsuario tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
      btn.removeAttribute("disabled");
    } else {
      btn.setAttribute("disabled", "disabled");
      btn.classList.remove("botao-activo");
    }
  });
</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);*/

  let linha;
  $(document).ready(function() {
    $.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/queryTipoUsuario.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTipoUsuario: 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/queryTipoUsuario.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTipoUsuario: id,
      },
      success: function(data) {
        console.log("Tipo de Usuário: ", data);
        for (var key in data) {
          var novaLinha = {
            idTipoUsuario: data[key]["idTipoUsuario"],
            nome: data[key]["nome"],
            nota: data[key]["nota"],
          };
          $('#tabelaTipoUsuario').DataTable().row.add(novaLinha).draw(false);
        }
      }
    });
  }

  $(document).ready(function() {
    $.ajax({
      url: "includes/read/tipoUsuario.inc.php",
      type: "post",
      dataType: "json"
    }).done(function(data) {
      console.log(data);
      $("#tabelaTipoUsuario").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "idTipoUsuario"
        }, {
          data: "nome"
        }, {
          data: "nota"
        }, {
          data: null,
          render: function(data, type, row) {
            return `
            <div id="dropdownOpcoes" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="display:flex; align-items: center; justify-content: space-around;"><button class="btn btn-outline-primary opcoes" style="padding: .2rem .7rem; line-height: 1; border: none;"><i class="fa-solid fa-ellipsis-vertical"></i></button></div>
            <ul aria-labelledby="dropdownOpcoes" class="dropdown-menu border-0 shadow">
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item btn-more" style="padding: .8rem; border-radius: 5px;">Informações</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item btn-update" style="padding: .8rem; border-radius: 5px;">Editar</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item btn-delete" style="padding: .8rem; border-radius: 5px;">Eliminar</a></li>
            </ul>`;
          }
        }],
        columnDefs: [{
          targets: -1,
          orderable: false
        }],
        "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('#tabelaTipoUsuario_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"
    }
  }

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

    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");
      }
    }
  });

  $('#tabelaTipoUsuario tbody').on('click', 'tr', function() {
    detalhes(this.cells[0].innerText);
  });

  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-preview", function(e) {
    e.preventDefault();
    $('#modal-updateTipoEntidade').modal('show');
  });

  $(document).on("click", "#btn", function(e) {
    e.preventDefault();
    doOpcao.innerText = "Novo Tipo de Usuário";
    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/queryTipoUsuario.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-updateTipoEntidade').modal('show');
    });
  }

  function detalhes(id) {
    $.ajax({
      url: "includes/read/queryTipoUsuario.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTipoUsuario: id
      },
      success: function(data) {
        console.log("Essas são as Tipo de Usuários", data);
        for (var key in data) {
          nomeModal.innerText = data[key]["nome"];
          codigoInfo.innerText = data[key]["idTipoUsuario"];
          nomeInfo.innerText = data[key]["nome"];
          notaInfo.innerText = data[key]["nota"];
        }
      }
    });
  }

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

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

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

  $('#tabelaTipoUsuario').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 Tipo de Usuário?",
        text: "Tipo de Usuário: " + nome,
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: 'Confirmar',
        confirmButtonColor: '#560085',
        cancelButtonText: 'Cancelar',
        cancelButtonColor: '#560085',
      })
      .then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: "includes/delete/tipoUsuario.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idTipoUsuario: id
            },
            success: function(data) {
              console.log(data);
              swal.fire({
                title: "Tipo de Usuário " + nome + " eliminado com sucesso!",
                icon: "success",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
              });
              $('#tabelaTipoUsuario').DataTable().row(linha).remove().draw(false);
            },
            error: function(data) {
              swal.fire({
                title: "Erro ao eliminar Tipo de Usuário!",
                text: "Tipo de Usuário associado a uma ou mais Documentos.",
                icon: "error",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
              });
            }
          });
        }
      });
  });

  function loadNovoId() {
    $.ajax({
      url: "includes/read/codigoTipoUsuario.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 != '') {
      tipoUsuario();
    }
  });

  /*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: "Tipo de Usuário " + 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 Tipo de Usuário!",
          text: "Erro ao cadastrar Tipo de Usuário: " + nome.value + " !",
          confirmButtonText: 'Confirmar',
          confirmButtonColor: '#560085',
          icon: "error",
        });
      }
    }).done(function(data) {
      console.log(data);
    });
  }*/

  function tipoUsuario() {
    if (doOpcao.innerText == "Novo Tipo de Usuário") {
      let id = {
        idCodigoTaxa: codigo.innerText
      }
      let dados = {
        nome: nome.value,
        nota: nota.value,
      };
      let tabela = "codigoTaxa";
      $.ajax({
        url: "includes/create/a.inc.php",
        type: "post",
        data: {
          id: id,
          tabela: tabela,
          dados: dados
        },
        success: function(data) {
          console.log("Informação: ", data);
          swal.fire({
            title: "Cadastro efectuado com sucesso!",
            text: "Tipo de Usuário " + nome.value + " cadastrado!",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "success",
          });
          //insertLinha(data);
          //reload();
        },
        error: function(data) {
          swal.fire({
            title: "Erro ao cadastrar Tipo de Usuário!",
            text: "Erro ao cadastrar Tipo de Usuário: " + nome.value + " !",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "error",
          });
        }
      }).done(function(data) {
        console.log(data);
      });
    } else {
      $.ajax({
        url: "includes/update/tipoUsuario.inc.php",
        type: "post",
        data: {
          idTipoUsuario: 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: "Tipo de Usuário " + nome.value + ".",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "success",
          });
          updateLinha(linha);
          reload();
        },
        error: function(data) {
          swal.fire({
            title: "Erro ao cadastrar Tipo de Usuário!",
            text: "Erro ao cadastrar Tipo de Usuário: " + 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',
                });
                $('#tabelaTipoUsuario').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 Tipo de Usuário!",
              text: "Tipo de Usuário: " + nome.value + " não pode ser eliminado!",
              confirmButtonText: 'Confirmar',
              confirmButtonColor: '#560085',
              icon: "error",
            });
          }
        }
      });
  });
</script>
<script src="./validation/parametroTipoUsuario.js"></script>