<?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: -31.5rem;
    height: 3px;
    width: 31rem;
    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-import">Importar Excel</button>
                      <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 Artigo</button>
                    </div>
                    <!-- /.col -->
                  </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">Artigos</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="tabelaDocumento" class="table table-bordered table-striped" style="line-height: 0.8;">
                    <thead>
                      <tr style="text-align: center;">
                        <th title="Código do Artigo">Artigo</th>
                        <th title="Descrição">Descrição</th>
                        <th title="Família">Família</th>
                        <th title="Preço Custo (Sem Imposto)">Preço (S/Imp)</th>
                        <th title="Preco Custo (Com Imposto)">Preço (C/Imp)</th>
                        <th title="Quatidade em Stock">Qtd. Stock</th>
                        <th title="Estado do Artigo">Estado</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 Artigos.
                </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">
                <button type="button" class="close" data-dismiss="modal" aria-label="close">
                  <small aria-hidden="true">
                    <small class="fas fa-close"></small>
                  </small>
                </button>
                <div class="progress-barra">
                  <div class="step">
                    <p style="margin: 0;">Geral</p>
                    <div class="bullet">
                      <span style="color: #666;">1</span>
                      <div class="check fas fa-check"></div>
                    </div>
                  </div>
                  <div class="step">
                    <p style="margin: 0;">Preços</p>
                    <div class="bullet">
                      <span style="color: #666;">2</span>
                      <div class="check fas fa-check"></div>
                    </div>
                  </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-4">
                              <div class="form-group margem">
                                <div class="wrapper-image">
                                  <div class="image-container">
                                    <i class="fas fa-image"></i>
                                  </div>
                                  <label for="file" class="camera-icon">
                                    <i class="fas fa-camera"></i>
                                  </label>
                                  <input type="file" id="file" name="file" accept="image/*" hidden>
                                </div>
                              </div>
                            </div>
                            <div class="col-md-4" style="display: flex; align-items: center;">
                              <div class="form-group" style="margin-top: .4rem;">
                                <small>Mensagem de erro</small>
                                <div class="custom-control custom-switch">
                                  <input type="checkbox" class="custom-control-input" id="controlaStock" value="0">
                                  <label class="custom-control-label" for="controlaStock">Controla Stock - Activo</label>
                                </div>
                              </div>
                            </div>
                            <div class="col-md-4" style="display: flex; align-items: center;">
                              <div class="form-group" style="margin-top: .4rem;">
                                <small>Mensagem de erro</small>
                                <div class="custom-control custom-switch">
                                  <input type="checkbox" class="custom-control-input" id="descontinuado" value="0">
                                  <label class="custom-control-label" for="descontinuado">Descontinuado - Activo</label>
                                </div>
                              </div>
                            </div>
                            <div class="col-md-4">
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="required">Nome</small>
                                <input type="text" class="form-control" id="nome" name="nome" placeholder="Nome do Artigo" title="Nome do Artigo" required>
                                <small>Mensagem de erro</small>
                              </div>
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="not-required">Código de Barras</small>
                                <input type="text" class="form-control" id="codigoBarra" name="codigoBarra" placeholder="Código de Barras" title="Código de Barras" required>
                                <small>Mensagem de erro</small>
                              </div>
                            </div>
                            <div class="col-md-4">
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="required">Família</small>
                                <select class="form-control select2" style="width: 100%;" id="idFamilia" name="idFamilia">
                                  <option value="0">Selecione a Família</option>
                                </select>
                                <small>Mensagem de erro</small>
                              </div>
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="not-required">Taxa</small>
                                <select class="form-control select2" style="width: 100%;" id="imposto" name="imposto">
                                  <option value="0">Não Sujeito</option>
                                </select>
                                <small>Mensagem de erro</small>
                              </div>
                            </div>
                            <div class="col-md-4">
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="not-required">Nome Curto</small>
                                <input type="text" class="form-control" id="nomeCurto" name="nomeCurto" placeholder="Nome Curto" title="Nome Curto" required>
                                <small>Mensagem de erro</small>
                              </div>
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="not-required">Tipo</small>
                                <select class="form-control select2" style="width: 100%;" id="tipoArtigo" name="tipoArtigo">
                                  <option value="P">Normal</option>
                                  <option value="S">Serviço</option>
                                  <option value="C">Comentário</option>
                                </select>
                                <small>Mensagem de erro</small>
                              </div>
                            </div>
                            <div class="col-md-4">
                              <div class="form-group" style="margin-bottom: 0;">
                                <small class="not-required">Unidades</small>
                                <select class="form-control unity" style="width: 100%;" id="unidademedida" name="unidademedida">
                                </select>
                                <small>Mensagem de erro</small>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-12">
                          <div class="form-group margem">
                            <small>Mensagem de erro</small>
                            <div class="form-group field btns">
                              <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary nextBtn" style="margin-top: 0;">
                                Seguinte
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="page" style="position: relative;">
                      <div class="row">
                        <div class="col-md-12">
                          <div class="form-group" style="height: 19rem; overflow-y: auto;">
                            <table name="tabelaLinhaPreco" id="tabelaLinhaPreco" class="table-sm" style="min-width: 100%; max-width: 100%;">
                              <thead>
                                <tr style="text-align: center;">
                                  <th scope="col"></th>
                                  <th scope="col">S/Imp.</th>
                                  <th scope="col">C/Imp.</th>
                                  <th scope="col">Margem</th>
                                </tr>
                              </thead>
                              <tbody id="corpoTabelaPreco">
                                <tr style="text-align: left;">
                                  <td>Preço de Custo:</td>
                                  <td>
                                    <div class="">
                                      <div class="form-group" style="margin-bottom: 0;">
                                        <input type="text" class="form-control" id="precoCustoSemImp" name="precoCustoSemImp" placeholder="0,00 Kzs" title="Data">
                                      </div>
                                    </div>
                                  </td>
                                  <td>
                                    <div class="">
                                      <div class="form-group" style="margin-bottom: 0;">
                                        <input type="text" class="form-control" id="precoCustoComImp" name="precoCustoComImp" placeholder="0,00 Kzs" title="Data">
                                      </div>
                                    </div>
                                  </td>
                                  <td></td>
                                  <td></td>
                                </tr>
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </div>
                      <div class="col-md-12" style="padding: 14px 0 0 0; bottom: 0; position: absolute;">
                        <div class="form-group field btns">
                          <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary prev-1 prev" style="margin-top: 0;">
                            Anterior
                          </button>
                          <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary submit next" style="margin-top: 0; margin-left: 3px !important;">
                            Gravar Artigo
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="col-md-12" style="opacity: 0;" id="footerPagamento">
                <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 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-import">
      <div class="modal-dialog modal-default">
        <div class="modal-content">
          <div class="modal-header" style="padding: 0.5rem;">
            <h3 class="card-title p-3">Importação Excel</h3>
          </div>
          <div class="modal-body" style="padding-bottom: 0px;">
            <div class="row">
              <div class="col-md-12">
                <div class="form-group" style="margin-bottom: 0;">
                  <label for="exampleInputFile">Pesquisar Ficheiro</label>
                  <div class="input-group">
                    <div class="custom-file">
                      <input type="file" class="custom-file-input" id="exampleInputFile">
                      <label class="custom-file-label" for="exampleInputFile">Procurar</label>
                    </div>
                    <div class="input-group-append">
                      <span class="input-group-text" id="btnImportExcel">Carregar</span>
                    </div>
                  </div>
                  <small>Mensagem de erro</small>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer" style="display: flex; flex-direction: row; align-items: center; justify-content: space-between;">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
            <button type="button" class="btn btn-primary" disabled>Importar</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <div class="modal fade" id="modal-artigoOpcoes">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header" style="padding: 0.5rem;">
            <h3 class="card-title p-3">Artigo - <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="width: 400px;">
                        <div class="form-group margem wrapper-info" style="margin-top: 1rem;">
                          <div class="caixa image-info" id="imagemInfo">
                            <i class="fas fa-image"></i>
                          </div>
                        </div>
                      </td>
                      <td style="padding: 20px 0px 0px 10px;">
                        <p>Id Artigo: <span id="codigoInfo"></span></p>
                        <p>Nome: <span id="nomeInfo"></span></p>
                        <p>Nome Curto: <span id="nomeCurtoInfo"></span></p>
                        <p>Família: <span id="familiaInfo"></span></p>
                        <p>Código de Barras: <span id="codigoBarraInfo"></span></p>
                        <p>Controlar Stock: <span id="controlaStockInfo"></span></p>
                        <p>Descontinuado: <span id="descontinuadoInfo"></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-detalhes">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">Detalhes do Documento</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="invoice p-3 mb-3" style="height: 30rem; overflow-y: scroll;">
              <!-- title row -->
              <div class="row">
                <div class="col-12">
                  <h4>
                    <span id="detalheCabecalho"></span>
                    <small class="float-right" id="detalheDataActual"></small>
                  </h4>
                </div>
                <!-- /.col -->
              </div>
              <!-- info row -->
              <div class="row invoice-info">
                <div class="col-sm-6 invoice-col">
                  <strong>Código Documento - <span id="detalheCodigo"></span></strong><br>
                  <span>Documento - </span><strong><span id="detalheDocumento"></span></strong><br>
                  <span>Série - </span><strong><span id="detalheSerie"></span></strong><br>
                  <span>Prazo de Pagamento - </span><strong><span id="detalhePrazoPagamento"></span></strong><br>
                  <span>Vendedor - </span><strong><span id="detalheVendedor"></span></strong>
                </div>
                <!-- /.col -->
                <div class="col-sm-6 invoice-col">
                  <strong><span>Entidade</span></strong><br>
                  <span>Identificador Cliente - </span><strong><span id="detalheIdCliente"></span></strong><br>
                  <span>Nome - </span><strong><span id="detalheNome"></span></strong><br>
                  <span>Morada - </span><strong><span id="detalheMorada"></span></strong><br>
                  <span>NIF - </span><strong><span id="detalheNif"></span></strong><br>
                </div>
              </div>
              <!-- /.row -->

              <!-- Table row -->
              <div class="row" style="margin-top: 1.5rem;">
                <div class="col-12 table-responsive">
                  <table class="table table-striped" style="text-align: center;">
                    <thead>
                      <tr>
                        <th title="Referência do Artigo">Referência</th>
                        <th title="Descrição">Descrição</th>
                        <th title="Quantidade">Qtd.</th>
                        <th title="Preço do Artigo">Preço</th>
                        <th title="Desconto">Desc.</th>
                        <th title="Imposto">Imposto</th>
                        <th title="Total">Total</th>
                      </tr>
                    </thead>
                    <tbody id="corpoTabelaDetalhes">
                    </tbody>
                  </table>
                </div>
                <!-- /.col -->
              </div>
              <!-- /.row -->

              <div class="row">
                <div class="col-6">
                  <p class="lead">Montante</p>

                  <div class="table-responsive">
                    <table class="table" id="detalheTabelaMontante">
                    </table>
                  </div>
                </div>
                <!-- /.col -->
              </div>
            </div>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.content-wrapper -->
    <?php include('footer.php'); ?>
</body>

<script src="../pos/javascript/function.js"></script>

</html>
<script>
  let idCliente;
  let valorLinha;
  let totalDoc;
  let pendenteVerify;
  let totalImposto = [];
  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() {
    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";
    });
  });

  function createDocumento() {
    Swal.fire({
      icon: 'info',
      title: 'Emitir Documento?',
      text: 'Tem a certeza que quer emitir esse Documento?',
      allowOutsideClick: false,
      showCancelButton: true,
      confirmButtonText: 'Confirmar',
      confirmButtonColor: '#560085',
      cancelButtonText: 'Cancelar',
      cancelButtonColor: '#560085',
    }).then((result) => {
      if (result.isConfirmed) {
        console.log("Esse é o código metade: ", codigo.innerText.split("/")[1]);
        console.log("Esse é o código todo: ", codigo.innerText);
        $.ajax({
          url: "includes/create/doc.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
            idTipoDoc: tipoDocumento.value,
            idEntidade: cliente.value,
            idPrazoPagamento: prazoPagamento.value,
            entregue: parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')),
            total: totalDoc,
            troco: 0
          },
          success: function(data) {
            let tabela = document.getElementById("tabelaArtigo");
            for (i = 1; i < tabela.rows.length; i++) {
              if (tabela.rows[i].querySelector('.inputSearchArtigo').value != "" && tabela.rows[i].querySelector('.qtd').value != "" && tabela.rows[i].querySelector('.preco').value != "" && tabela.rows[i].querySelector('.desconto').value != "" && tabela.rows[i].querySelector('.imposto').value != "" && tabela.rows[i].querySelector('.total').value != "") {
                $.ajax({
                  url: "includes/create/artigoDocumento.inc.php",
                  type: "post",
                  dataType: "json",
                  data: {
                    idDocumento: data,
                    idArtigo: parseInt(tabela.rows[i].querySelector('.inputSearchArtigo').value),
                    descricao: tabela.rows[i].querySelector('.descricao').value,
                    qtd: parseInt(tabela.rows[i].querySelector('.qtd').value.replace(/\ /g, '').replace(/\,/g, '.')),
                    preco: parseFloat(tabela.rows[i].querySelector('.preco').value.replace(/\ /g, '').replace(/\,/g, '.')),
                    desconto: parseFloat(tabela.rows[i].querySelector('.desconto').value.replace(/\ /g, '').replace(/\,/g, '.')),
                    idImposto: $(tabela.rows[i].querySelector('.imposto')).select2('data')[0].element.dataset.taxa,
                    total: parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')),
                  }
                });
              }
            }
          },
          error: function(data) {
            swal.fire({
              title: "Erro ao Emitir Documento!",
              text: "Erro ao Facturar!",
              confirmButtonText: 'Confirmar',
              icon: "error",
            });
          }
        }).done(function() {
          location.reload();
        });
      } else {
        location.reload();
      }
    });
  }

  function linhaPreco() {
    $.ajax({
      url: "includes/read/definicao.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        for (var key in data) {
          if (data[key]["idDefinicao"] == 1) {
            for (let i = 0; i < data[key]["valor"]; i++) {
              let select = `
          <tr style="text-align: left;" class="trPreco">
            <td>P.Venda (${i + 1}):</td>
            <td>
              <div class="">
                <div class="form-group" style="margin-bottom: 0;">
                  <input type="text" class="form-control sImp" placeholder="0,00 Kzs" title="Sem Imposto">
                </div>
              </div>
            </td>
            <td>
              <div class="">
                <div class="form-group" style="margin-bottom: 0;">
                  <input type="text" class="form-control cImp" placeholder="0,00 Kzs" title="Com Imposto">
                </div>
              </div>
            </td>
            <td>
              <div class="">
                <div class="form-group" style="margin-bottom: 0;">
                  <input type="text" class="form-control margem" placeholder="0,00%" title="Margem de Lucro">
                </div>
              </div>
            </td>
          </tr>
        `;
              $("#corpoTabelaPreco").append(select);
            }
          }
        }
      }
    }).done(function(data) {
      totalPreco();
      let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
      for (let i = 0; i < tr.length; i++) {
        let input = tr[i].getElementsByTagName("input");
        console.log("tr: ", tr[i], " ", i);

        for (let j = 0; j < input.length; j++) {
          console.log("Esses são os tds: ", j, "-", input[j]);

        }
      }
    });
  }

  $(document).ready(function() {
    linhaPreco();
    loadNovoId();
  });

  function loadNovoId() {
    funcaoAutoIncrement("../pos/includes/autoIncrement.inc.php", "post", "json", "test1234", "artigo", "a", function success(data) {
      codigo.innerText = data[0]["a"];
    }, function error(data) {

    }, function done(data) {

    });
  }

  $.ajax({
    url: "includes/read/familia.inc.php",
    type: "post",
    dataType: "json",
    success: function(data) {
      let select = "";
      select += "<option value='0'>Selecione a Família</option>";
      for (var key in data) {
        select += "<option value=" + data[key]['idFamilia'] + ">" + data[key]['nome'] + "</option>";
      }
      $("#idFamilia").html(select);
    }
  });

  $.ajax({
    url: "includes/read/taxa.inc.php",
    type: "post",
    dataType: "json",
    success: function(data) {
      let select = "";
      select += "<option value='0'>Não Sujeito</option>";
      for (var key in data) {
        select += "<option value=" + data[key]['taxaImposto'] + ">" + data[key]['nomeCodigoTaxa'] + "</option>";
      }
      $("#imposto").html(select);
    }
  });

  function sumMp() {
    let all = 0;
    let modoPagamento = document.querySelectorAll(".mp");
    for (let i = 0; i < modoPagamento.length; i++) {
      if (modoPagamento[i].value != "") {
        all += parseFloat(modoPagamento[i].value.replace(/\ /g, '').replace(/\,/g, '.'));
      }
    }
    entregueSpan.innerText = parseFloat(all);
    entregueSpan.innerText = entregueSpan.innerText.replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) < totalDoc) {
      totalText.innerText = "VALOR PENDENTE";
      totalText.className = "text-danger";
      totalSpan.className = "text-danger";
      totalSpan.innerText = totalDoc - parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
      totalSpan.innerText = totalSpan.innerText.replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
      recalcular();
    } else if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) == totalDoc && parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) != 0) {
      entregueSpan.className = "";
      totalEntregue.className = "";
      totalEntregue.innerText = "ENTREGUE";
      totalText.innerText = "SEM TROCO";
      totalText.className = "text-success";
      totalSpan.className = "text-success";
      totalSpan.innerText = totalDoc - parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
      totalSpan.innerText = totalSpan.innerText.replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
      recalcular();
    } else if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) > totalDoc) {
      entregueSpan.className = "";
      totalEntregue.className = "";
      totalEntregue.innerText = "ENTREGUE";
      totalText.innerText = "TROCO";
      totalText.className = "text-success";
      totalSpan.className = "text-success";
      totalSpan.innerText = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) - totalDoc;
      totalSpan.innerText = totalSpan.innerText.replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
      recalcular();
    }
  }

  function recalcular() {
    let total = 0;
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector('.total').value != "") {
        total += parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.'));
      }
    }
    console.log("Esse é o meu total: ", total);
  }

  function modoPagamentoFormatedNumber() {
    let modoPagamento = document.getElementsByClassName("mp");
    for (let i = 0; i < modoPagamento.length; i++) {
      modoPagamento[i].addEventListener("keyup", function() {
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;

        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        sumMp();
      });
    }
  };

  $(document).on("keypress", "#cliente", function(e) {
    if (event.which === 13) {
      event.preventDefault();
      searchCliente(cliente.value);
    }
  });

  $(document).on("focusout", "#cliente", function(e) {
    event.preventDefault();
    searchCliente(cliente.value);
  });

  $(document).on("click", "#btn-search-cliente", function(e) {
    e.preventDefault();
    $('#modal-cliente').modal('show');
  });

  function totalDocumento() {
    let all = 0;
    let total = document.querySelectorAll(".total");
    for (let i = 0; i < total.length; i++) {
      if (total[i].value != "") {

        all += (((parseFloat(total[i].closest('tr').querySelector('.imposto').value) / 100) * parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.'))) + parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')));

        //(parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) + 
      }
    }
    totalSpan.innerText = all;
    totalDoc = all;
    console.log("Total Documento all: ", all);
    totalSpan.innerText = totalSpan.innerText.replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    sumMp();
    viewConfirmacao();
    //reCalcularTotal();
  }

  $(document).on("click", ".next-1", function(e) {
    e.preventDefault();
    viewConfirmacao();
  });

  function viewConfirmacao() {
    descCodigo.innerText = codigo.innerText;
    descDocumento.innerText = $("#tipoDocumento option:selected").text();
    descSerie.innerText = serie.value;
    descPrazoPagamento.innerText = $("#prazoPagamento option:selected").text();
    descVendedor.innerText = vendedorFactura.value;
    descIdCliente.innerText = cliente.value;
    descNome.innerText = nomeCliente.value;
    descMorada.innerText = moradaCliente.value;
    descNif.innerText = nifCliente.value;
    descDataActual.innerText = "<?php echo "Data Actual: " . date("d-m-Y"); ?>";
    descCabecalho.innerText = "<?php echo $rows[1]['valor']; ?>";
    let tabela = document.getElementById("tabelaArtigo");
    let rows = "";
    for (i = 1; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector(".inputSearchArtigo").value != "" && tabela.rows[i].querySelector(".descricao").value != "" && tabela.rows[i].querySelector(".qtd").value != "" && tabela.rows[i].querySelector(".preco").value != "" && tabela.rows[i].querySelector(".desconto").value != "" && tabela.rows[i].querySelector(".total").value != "") {
        console.log("Linhas:", tabela.rows[i].querySelector(".inputSearchArtigo"));
        rows += `
        <tr>
          <td>${tabela.rows[i].querySelector(".inputSearchArtigo").value}</td>
          <td>${tabela.rows[i].querySelector(".descricao").value}</td>
          <td>${tabela.rows[i].querySelector(".qtd").value}</td>
          <td>${tabela.rows[i].querySelector(".preco").value}</td>
          <td>${tabela.rows[i].querySelector(".desconto").value}</td>
          <td>${tabela.rows[i].querySelector(".imposto").value + "%"}</td>
          <td>${tabela.rows[i].querySelector(".total").value}</td>
        </tr>`;
      }
    }
    $("#tabelaConfirmacaoBody").html(rows);
  }

  function searchCliente(id) {
    $.ajax({
      url: "includes/read/queryEntidadeCliente.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idEntidade: id,
        idTipoEntidade: 2
      },
      success: function(data) {
        const firstNextBtn = document.querySelector(".nextBtn");
        let small = cliente.parentElement.parentElement.querySelectorAll("small")[1];
        if (data == null) {
          if (cliente.value == "") {
            idCliente = undefined;
            cliente.className = "form-control is-invalid";
            small.style.visibility = "visible";
            small.style.color = "#dc3545";
            small.innerText = "Campo cliente não pode estar vazio!";
            nomeCliente.value = "";
            moradaCliente.value = "";
            nifCliente.value = "";
            firstNextBtn.setAttribute('disabled', 'disabled');
          } else {
            idCliente = undefined;
            cliente.className = "form-control is-invalid";
            small.style.visibility = "visible";
            small.style.color = "#dc3545";
            small.innerText = "Código digitado não corresponde a nenhum dos clientes!";
            nomeCliente.value = "";
            moradaCliente.value = "";
            nifCliente.value = "";
            firstNextBtn.setAttribute('disabled', 'disabled');
          }
        } else {
          for (var key in data) {
            cliente.className = "form-control";
            small.style.visibility = "hidden";
            idCliente = data[key]['idEntidade'];
            cliente.value = data[key]['idEntidade'];
            nomeCliente.value = data[key]['nome'];
            moradaCliente.value = data[key]['morada'];
            nifCliente.value = data[key]['nif'];
            firstNextBtn.removeAttribute('disabled');
          }
        }
      }
    });
  }

  function funcaoQueryArtigo(id, parametro) {
    $.ajax({
      url: "includes/read/queryArtigo.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id,
      },
      success: function(data) {
        if (data != null) {
          for (var key in data) {
            parametro.val(data[key]["idArtigo"]);
            parametro.closest('tr').find('.descricao').val(data[key]["nome"]);
            parametro.closest('tr').find('.preco').val(data[key]["preco"].replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
            parametro.closest('tr').find('.total').val(((parseFloat(data[key]["preco"])) * parametro.closest('tr').find('.qtd').val()) - (((parseFloat(data[key]["preco"])) * parametro.closest('tr').find('.qtd').val()) * parametro.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
            parametro.closest('tr').find('.total').val(parametro.closest('tr').find('.total').val().replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));

            if (!parametro.closest('tr').find('.total').val().includes(",")) {
              parametro.closest('tr').find('.total').val(parametro.closest('tr').find('.total').val().replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + ",00");
            }
            if (parametro.closest('tr').find('.total').val().split(",")[1].length == 1) {
              parametro.closest('tr').find('.total').val(parametro.closest('tr').find('.total').val().replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "0");
            }
          }
        } else {
          parametro.val("");
          parametro.closest('tr').find('.descricao').val("");
          parametro.closest('tr').find('.preco').val("");
          parametro.closest('tr').find('.total').val("");
        }
      }
    }).done(function() {
      totalDocumento();
      let referencia = document.querySelectorAll(".inputSearchArtigo");
      let resultado = mesmoArtigoVerify(referencia);
      if (resultado != undefined) {
        console.log("Resultados: ", parseFloat(resultado[0].replace(/\ /g, '').replace(/\,/g, '.')), ", ", parseFloat(resultado[1].replace(/\ /g, '').replace(/\,/g, '.')));
        console.log("Vamos lá ver: ", parametro);
        let result = funcaoLinha(resultado);
        if (result != null) {
          return result.querySelector(".qtd").value = parseInt(result.querySelector(".qtd").value) + 1;
        }
        console.log("Resultado: ", result);
      }
    });
  }

  function funcaoLinha(resultado) {
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
      let linha = tabela.rows[i].cells[0].querySelector("keyup").value;
      if (linha.includes(resultado[0].replace(/\ /g, '').replace(/\,/g, '.'))) {
        return tabela.rows[i];
      }
    }
    return null;
  }

  function mesmoArtigoVerify(referencia) {
    let valores = [];
    for (let i = 0; i < referencia.length; i++) {
      if (referencia[i].value !== "") {
        valores.push(referencia[i].value);
      }
    }
    let valoresDuplicados = [];
    for (let i = 0; i < valores.length; i++) {
      for (let j = i + 1; j < valores.length; j++) {
        if (valores[i] === valores[j] && !valoresDuplicados.includes(valores[i])) {
          valoresDuplicados.push(valores[i]);
        }
      }
    }
    if (valoresDuplicados != "") {
      console.log("Valores: ", valoresDuplicados);
      var elemento = $(".inputSearchArtigo").filter(function() {
        return $(this).val().indexOf(valoresDuplicados) !== -1;
      });
      let valor = elemento.first().closest('tr').find('.qtd').val();
      valor = parseInt(valor) + 1;
      elemento.first().closest('tr').find('.qtd').val(valor);
      totalLinhaArtigo(elemento.closest('tr').find('.qtd')[0]);
      elemento.first().closest('tr').addClass('blink');
      setTimeout(function() {
        elemento.first().closest('tr').removeClass('blink');
      }, 200);
      var table = $('#tabelaArtigo').DataTable();
      var row = elemento.last().closest('tr');
      if ($('#tabelaArtigo tbody tr').length > 1) {
        table.row(row).remove().draw();
      }
    }
  }

  $(document).ready(function() {
    $.ajax({
      url: "includes/read/queryUser.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idUsuario: <?php echo $_SESSION["usuarioId"]; ?>
      },
      success: function(data) {
        for (var key in data) {
          //vendedorFactura.value = data[key]["nome"];
        }
      }
    });
    //serie.value = "<?php //echo date("Y"); 
                      ?>";
    //dataActual.value = "<?php //echo date("Y-m-d"); 
                          ?>";
  });

  /*$(document).ready(function() {
    //readTipoDocumento();
    $.ajax({
      url: "includes/read/tipoDoc.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        select += "<option value='0'>Selecione o Tipo de Documento</option>";
        for (var key in data) {
          select += "<option value=" + data[key]['idTipoDoc'] + ">" + data[key]['nome'] + "</option>";
        }
        console.log(select);
        $("#tipoDocumento").html(select);
      }
    }).done(function() {
      tipoDocumento.setAttribute("disabled", "disabled");
      let promessa = new Promise(function(resolve, reject) {
        $('#tipoDocumento').val(1);
        $('#tipoDocumento').select2().trigger('change');
      });
      promessa.then(function() {
        $.ajax({
          url: "includes/read/prazoPagamento.inc.php",
          type: "post",
          dataType: "json",
          success: function(data) {
            let select = "";
            select += "<option value='0'>Selecione um Prazo de Pagamento</option>";
            for (var key in data) {
              if (data[key]['idPrazoPagamento'] == 1) {
                select += "<option value=" + data[key]['idPrazoPagamento'] + " disabled='disabled'>" + data[key]['nome'] + "</option>";
              } else {
                select += "<option value=" + data[key]['idPrazoPagamento'] + ">" + data[key]['nome'] + "</option>";
              }
            }
            $("#prazoPagamento").html(select);
          }
        });
      });
    });
  });*/

  /*$(document).ready(function() {
    let tabela = document.getElementById("tabelaLinhaPreco");
    for (i = 1; i < tabela.rows.length; i++) {
      tabela.rows[i].querySelector('.inputSearchArtigo').value = tabela.rows[i].querySelector('.inputSearchArtigo').value.replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      //parseFloat(tabela.rows[i].querySelector('.inputSearchArtigo').value.replace(/\ /g, '').replace(/\,/g, '.'));
    }
  });*/

  $(document).ready(function() {
    //readPrazoPagamento();
    $.ajax({
      url: "includes/read/prazoPagamento.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        select += "<option value='0'>Selecione um Prazo de Pagamento</option>";
        for (var key in data) {
          if (data[key]['idPrazoPagamento'] == 1) {
            select += "<option value=" + data[key]['idPrazoPagamento'] + " disabled='disabled'>" + data[key]['nome'] + "</option>";
          } else {
            select += "<option value=" + data[key]['idPrazoPagamento'] + ">" + data[key]['nome'] + "</option>";
          }
        }
        $("#prazoPagamento").html(select);
      }
    });
  });

  $(document).on('click', '#btnImportExcel', function(e) {
    e.preventDefault();

  });

  $(document).on('click', '#tabelaDocumento tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    let btn = document.querySelector("#btn-preview");
    $('#tabelaDocumento tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
      btn.removeAttribute("disabled");
    } else {
      btn.setAttribute("disabled", "disabled");
      btn.classList.remove("botao-activo");
    }
  });

  $(document).ready(function() {
    $.ajax({
      url: "includes/read/artigo.inc.php",
      type: "post",
      dataType: "json",
      data: {
        linhaPreco: 0
      }
    }).done(function(data) {
      $("#tabelaArtigoListagem").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "idArtigo"
        }, {
          data: "nome"
        }, {
          data: "familiaNome"
        }, {
          data: "precoSemImposto",
          render: function(data, type, row) {
            if (data == null) {
              return `0,00`;
            } else {
              return data;
            }
          }
        }, {
          data: "precoComImposto",
          render: function(data, type, row) {
            if (data == null) {
              return `0,00`;
            } else {
              return data;
            }
          }
        }, {
          data: "stock"
        }],
        "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('#tabelaArtigoListagem_wrapper .col-md-6:eq(0)');
    });
  });

  $(document).ready(function() {
    $.ajax({
      url: "includes/read/cliente.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTipoEntidade: 2
      }
    }).done(function(data) {
      $("#tabelaCliente").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('#tabelaCliente_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"
    }
  }

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

    for (i = 1; i < tabela.rows.length; i++) {
      tabela.rows[i].ondblclick = function() {
        searchCliente(this.cells[0].innerText);
        $('#modal-cliente').modal('hide');
      }
    }
  });
</script>
<script>
  let linha;
  $(document).ready(function() {
    addRow();
    $.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);
      }
    });
  });

  $(document).ready(function() {
    $.ajax({
      url: "includes/read/artigo.inc.php",
      type: "post",
      dataType: "json",
      data: {
        linhaPreco: 0
      }
    }).done(function(data) {
      $("#tabelaDocumento").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "idArtigo"
        }, {
          data: "nome"
        }, {
          data: "familiaNome"
        }, {
          data: "precoSemImposto",
          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, " ");
            }
          }
        }, {
          data: "precoComImposto",
          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, " ");
            }
          }
        }, {
          data: "stock"
        }, {
          data: "estado",
          render: function(data, type, row) {
            if (data == 0) {
              return `<small class='badge badge-danger'>Inactivo</small>`;
            } else if (data == 1) {
              return `<small class='badge badge-success'>Activo</small>`;
            }
          }
        }, {
          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('#tabelaDocumento_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"
    }
  }

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

    for (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 ajax() {
      $.ajax({
        url: "includes/read/queryUser.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'];
            idInfo.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-artigoOpcoes').modal('show');
      });
    }
  });

  function totalLinhaArtigo(parametro) {
    if (parametro.closest('tr').querySelector('.total').value != "") {
      parametro.closest('tr').querySelector('.total').value = (parseFloat(parametro.closest('tr').querySelector('.preco').value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.closest('tr').querySelector('.qtd').value.replace(/\ /g, '').replace(/\,/g, '.'))) - ((parseFloat(parametro.closest('tr').querySelector('.preco').value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.closest('tr').querySelector('.qtd').value.replace(/\ /g, '').replace(/\,/g, '.'))) * parseFloat(parametro.closest('tr').querySelector('.desconto').value.replace(/\,/g, '.').replace(/\%/g, '')) / 100);
      parametro.closest('tr').querySelector('.total').value = (parametro.closest('tr').querySelector('.total').value).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      if (!parametro.closest('tr').querySelector('.total').value.includes(",")) {
        parametro.closest('tr').querySelector('.total').value = (parametro.closest('tr').querySelector('.total').value).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + ",00";
      }
      if (parametro.closest('tr').querySelector('.total').value.split(",")[1].length == 1) {
        parametro.closest('tr').querySelector('.total').value = (parametro.closest('tr').querySelector('.total').value).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    }
    totalDocumento();
    viewConfirmacao();
  }

  function totalPreco() {
    let sImp = document.querySelectorAll(".sImp");
    for (let i = 0; i < sImp.length; i++) {
      sImp[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;

        var formatedNumber = this.value.replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        precoSemImp();
      });
    }

    let cImp = document.querySelectorAll(".cImp");
    for (let i = 0; i < cImp.length; i++) {
      cImp[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;

        var formatedNumber = this.value.replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        precoComImp();
      });
    }

    let precoCustoSemImp = document.querySelector("#precoCustoSemImp");
    precoCustoSemImp.addEventListener("keyup", function(e) {
      e.preventDefault();
      var removeChar = this.value.replace(/[^0-9\.]/g, '');
      var removeDot = removeChar.replace(/\./g, '');
      this.value = removeDot;

      var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      this.value = formatedNumber;
      totalPrecoCustoSemImp();
    });

    let precoCustoComImp = document.querySelector("#precoCustoComImp");
    precoCustoComImp.addEventListener("keyup", function(e) {
      e.preventDefault();
      var removeChar = this.value.replace(/[^0-9\.]/g, '');
      var removeDot = removeChar.replace(/\./g, '');
      this.value = removeDot;

      var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      this.value = formatedNumber;
      totalPrecoCustoComImp();
    });

    let margem = document.querySelectorAll(".margem");
    for (let i = 0; i < margem.length; i++) {
      margem[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        margemPorcentagem();
      });
    }
  }

  function precoSemImp() {
    let tabela = document.getElementById("tabelaLinhaPreco");
    for (i = 2; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector('.sImp').value != "") {
        tabela.rows[i].querySelector('.cImp').value = (((parseFloat($("#imposto").val().replace(/\ /g, '').replace(/\,/g, '.')) / 100) * (parseFloat(tabela.rows[i].querySelector('.sImp').value.replace(/\ /g, '').replace(/\,/g, '.')))) + (parseFloat(tabela.rows[i].querySelector('.sImp').value.replace(/\ /g, '').replace(/\,/g, '.'))));
        tabela.rows[i].querySelector('.cImp').value = parseFloat(tabela.rows[i].querySelector('.cImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

        /*if (tabela.rows[i].querySelector('#precoCustoComImp').value != "" && tabela.rows[i].querySelector('#precoCustoSemImp').value != "") {
        tabela.rows[i].querySelector('.margem').value = (parseFloat($(".cImp").val().replace(/\ /g, '').replace(/\,/g, '.')) - (parseFloat($("#precoCustoComImp").val().replace(/\ /g, '').replace(/\,/g, '.'))));
        }*/
      }
    }
  }

  function precoComImp() {
    let tabela = document.getElementById("tabelaLinhaPreco");
    for (i = 2; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector('.cImp').value != "") {
        tabela.rows[i].querySelector('.sImp').value = parseFloat(tabela.rows[i].querySelector('.cImp').value.replace(/\ /g, '').replace(/\,/g, '.')) / (1 + (parseFloat($("#imposto").val().replace(/\ /g, '').replace(/\,/g, '.'))) / 100);
        tabela.rows[i].querySelector('.sImp').value = parseFloat(tabela.rows[i].querySelector('.sImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    }
  }

  function totalPrecoCustoSemImp() {
    if (document.querySelector('#precoCustoSemImp').value != "") {
      document.querySelector('#precoCustoComImp').value = (((parseFloat($("#imposto").val().replace(/\ /g, '').replace(/\,/g, '.')) / 100) * (parseFloat(document.querySelector('#precoCustoSemImp').value.replace(/\ /g, '').replace(/\,/g, '.')))) + (parseFloat(document.querySelector('#precoCustoSemImp').value.replace(/\ /g, '').replace(/\,/g, '.'))));
      document.querySelector('#precoCustoComImp').value = parseFloat(document.querySelector('#precoCustoComImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    }
  }

  function totalPrecoCustoComImp() {
    if (document.querySelector('#precoCustoComImp').value != "") {
      document.querySelector('#precoCustoSemImp').value = parseFloat(document.querySelector('#precoCustoComImp').value.replace(/\ /g, '').replace(/\,/g, '.')) / (1 + (parseFloat($("#imposto").val().replace(/\ /g, '').replace(/\,/g, '.'))) / 100);
      document.querySelector('#precoCustoSemImp').value = parseFloat(document.querySelector('#precoCustoSemImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    }
  }

  function margemPorcentagem() {
    let tabela = document.getElementById("tabelaLinhaPreco");
    for (i = 2; i < tabela.rows.length; i++) {
      if (document.querySelector('#precoCustoSemImp').value != "" && document.querySelector('#precoCustoComImp').value != "") {
        if (tabela.rows[i].querySelector('.margem').value != "") {
          tabela.rows[i].querySelector('.sImp').value = (parseFloat(document.querySelector('#precoCustoSemImp').value.replace(/\ /g, '').replace(/\,/g, '.')) + (parseFloat(document.querySelector('#precoCustoSemImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2) * (parseFloat(tabela.rows[i].querySelector('.margem').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2)) / 100));
          tabela.rows[i].querySelector('.cImp').value = (parseFloat(document.querySelector('#precoCustoComImp').value.replace(/\ /g, '').replace(/\,/g, '.')) + (parseFloat(document.querySelector('#precoCustoComImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2) * (parseFloat(tabela.rows[i].querySelector('.margem').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2)) / 100));

          tabela.rows[i].querySelector('.sImp').value = parseFloat(tabela.rows[i].querySelector('.sImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          tabela.rows[i].querySelector('.cImp').value = parseFloat(tabela.rows[i].querySelector('.cImp').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        } else {
          tabela.rows[i].querySelector('.sImp').value = "";
          tabela.rows[i].querySelector('.cImp').value = "";
        }
      }
    }
  }

  function updateLinha(linha) {
    $.ajax({
      url: "includes/read/queryArtigoList.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: linha[0].innerText,
        linhaPreco: 0
      },
      success: function(data) {
        for (var key in data) {
          linha[1].innerText = data[key]["nome"];
          linha[2].innerText = data[key]["familiaNome"];
          if (data[key]["precoSemImposto"] == null) {
            linha[3].innerText = `0,00`;
          } else {
            linha[3].innerText = data[key]["precoSemImposto"];
          }

          if (data[key]["precoComImposto"] == null) {
            linha[4].innerText = `0,00`;
          } else {
            linha[4].innerText = data[key]["precoComImposto"];
          }
          linha[5].innerText = data[key]["stock"];
          if (data[key]["estado"] == 0) {
            linha[6].innerHTML = `<small class='badge badge-danger'>Inactivo</small>`;
          } else {
            linha[6].innerHTML = `<small class='badge badge-success'>Activo</small>`;
          }
        }
      }
    });
  }


  function insertLinha(id) {
    $.ajax({
      url: "includes/read/queryArtigoList.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id,
        linhaPreco: 0
      },
      success: function(data) {
        for (var key in data) {
          var novaLinha = {
            idArtigo: data[key]["idArtigo"],
            nome: data[key]["nome"],
            familiaNome: data[key]["familiaNome"],
            precoSemImposto: data[key]["precoSemImposto"] == null ? "0,00" : data[key]["precoSemImposto"],
            precoComImposto: data[key]["precoComImposto"] == null ? "0,00" : data[key]["precoComImposto"],
            stock: data[key]["stock"],
            estado: data[key]["estado"],
          };
          $('#tabelaDocumento').DataTable().row.add(novaLinha).draw(false);
        }
      }
    });
  }

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

  function reload() {
    $('#modal-documento').modal('hide');
    resetForm();
    loadNovoId();
    let imagem = document.querySelector('.image-container');
    let iconImage = imagem.querySelector('i');

    imagem.style.backgroundImage = ``;
    iconImage.style.display = "block";
    controlaStock.checked = false;
    controlaStock.value = 0;
    descontinuado.checked = false;
    descontinuado.value = 0;
    nome.value = "";
    nome.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    nome.className = "form-control";

    codigoBarra.value = "";
    codigoBarra.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    codigoBarra.className = "form-control";

    $('#idFamilia').val(0);
    $('#idFamilia').select2().trigger('change');
    document.querySelector("#idFamilia").parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    idFamilia.classList.remove("select2-danger");

    nomeCurto.value = "";
    nomeCurto.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    nomeCurto.className = "form-control";

    document.querySelector(".submit").removeAttribute('disabled');
  }

  $(document).on("change", "#imposto", function(e) {
    e.preventDefault();
    precoSemImp();
  });

  $(document).on("click", "#btn-import", function(e) {
    e.preventDefault();
    $('#modal-import').modal('show');
  });

  $(document).on("click", "#btn-preview", function(e) {
    e.preventDefault();
    $('#modal-artigoOpcoes').modal('show');
  });

  $(document).on("click", "#btn", function(e) {
    e.preventDefault();
    doOpcao.innerText = "Novo Artigo";
    reload();

    funcaoAutoIncrement('../pos/includes/autoIncrement.inc.php', 'post', 'json', 'dbbuesimples', 'artigo', 'lastId', function success(data) {
      console.log("Ver autoincrmeent: ", data[0].lastId);
      var v = $('#codigo').html().split('/')[0];
      // var year = new Date().getFullYea();
      $('#codigo').html(`${new Date().getFullYear()}/${data[0].lastId}`)

    }, function error(data) {}, function done(data) {});

    $('#modal-documento').modal('show');
    funcaoSelect("../pos/includes/select.inc.php", "post", "json", "unidademedida", function success(data) {
      let un = [];
      data.forEach(unidade => {
        var option = {
          id: unidade.idUnidadeMedida,
          text: `${unidade.nome} - (${unidade.sigla})`
        };
        un.push(option);
      });
      $('.unity').select2({
        placeholder: 'Selecione uma unidade',
        allowClear: true,
        data: un
      });

    }, function error(data) {}, function done(data) {});

    var table = $("#tabelaArtigo").DataTable();
    table.destroy();
    var tabela = $("#tabelaArtigo").DataTable({
      select: 'single',
      dom: 'Bfrtip',
      buttons: [{
        text: 'Adicionar Artigo',
        action: function(e, dt, node, config) {
          addRow();
        }
      }],
      "searching": false,
      "responsive": true,
      "lengthChange": false,
      "autoWidth": true,
      "language": idiomaPortugues,
      lengthMenu: [
        [7, 25, 50, -1],
        [10, 25, 50, 'All']
      ],
      columnDefs: [{
        targets: -1,
        orderable: false
      }],
      scrollResize: true,
      scrollCollapse: true,
      paging: false,
      scrollY: "28vh"
    });

    $('#modal-documento').on('shown.bs.modal', function() {
      tabela.columns.adjust().draw();
    });
    /*$('#modal-documento').modal({
      backdrop: 'static'
    }, 'show');*/
  });

  $('#tabelaArtigo').on('click', '.btnSearchArtigo', function() {
    let botao = $(this);
    $('#modal-artigo').modal('show');
    $('#tabelaArtigoListagem tbody').on('click', 'td', function() {
      let tabela = document.getElementById("tabelaArtigoListagem");

      for (i = 1; i < tabela.rows.length; i++) {
        tabela.rows[i].ondblclick = function() {
          $.ajax({
            url: "includes/read/queryArtigo.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idArtigo: this.cells[0].innerText,
            },
            success: function(data) {
              for (var key in data) {
                botao.closest('tr').find('.inputSearchArtigo').val(data[key]["idArtigo"]);
                botao.closest('tr').find('.descricao').val(data[key]["nome"]);
                botao.closest('tr').find('.preco').val(data[key]["preco"].replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                botao.closest('tr').find('.total').val(((data[key]["preco"]) * botao.closest('tr').find('.qtd').val()) - (((data[key]["preco"]) * botao.closest('tr').find('.qtd').val()) * botao.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
                botao.closest('tr').find('.total').val(botao.closest('tr').find('.total').val().replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));

                if (!botao.closest('tr').find('.total').val().includes(",")) {
                  botao.closest('tr').find('.total').val((botao.closest('tr').find('.total').val()).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + ",00");
                }
                if (botao.closest('tr').find('.total').val().split(",")[1].length == 1) {
                  botao.closest('tr').find('.total').val((botao.closest('tr').find('.total').val()).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "0");
                }
                $('#modal-artigo').modal('hide');
              }
            }
          }).done(function() {
            totalDocumento();
          });
        }
      }
    });
  });

  function addRow() {
    var table = $('#tabelaArtigo').DataTable();
    var linha = $(`<tr>
        <td style="padding: .2rem; vertical-align: inherit;">
          <div class="input-group input-group">
            <input type="text" class="form-control form-control inputSearchArtigo" placeholder="Procurar" title="Procurar Artigo" data-inputmask="'mask': ['AAA-99-99-AA', 'LD-99-99-AA']" data-mask>
            <div class="input-group-append">
              <button type="button" class="btn btn btn-default btnSearchArtigo"  style="line-height: 0 ;">
                  <i class="fa fa-search"></i>
              </button>
            </div>
          </div>
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control descricao" placeholder="Descrição" title="Descrição">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control qtd" placeholder="Quantidade" title="Quantidade" value="1">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control preco" placeholder="Preço" title="Preço">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control desconto" placeholder="Desconto" title="Desconto" value="0,00%">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <select class="form-control imposto select2" style="width: 100%;" placeholder="Imposto" title="Imposto">
            <option value="0">Não Sujeito</option>
          </select>
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control total" placeholder="Total" title="Total" disabled>
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <button class='btn btn-block btn-danger btn-delete remove_row' type='button'><i class="fa fa-xmark"></i></button>
        </td>
    </tr>`);
    const no = table.row.add(linha).draw().node();
    $(function() {
      //Initialize Select2 Elements
      $('.select2').select2()

      //Initialize Select2 Elements
      $('.select2bs4').select2({
        theme: 'bootstrap4'
      })
    });
    console.log("aqui: ", $(no).find('.imposto'));
    $.ajax({
      url: "includes/read/imposto.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        select += "<option value='0'>Não Sujeito</option>";
        for (var key in data) {
          select += "<option value=" + data[key]['taxa'] + ">" + data[key]['nome'] + "</option>";
        }
        $(no).find('.imposto').html(select);
      }
    });
    let preco = document.querySelectorAll(".preco");
    for (let i = 0; i < preco.length; i++) {
      preco[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;

        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
        }
        /*var commaIndex = this.value.indexOf(',');
        this.setSelectionRange(commaIndex, commaIndex);
        this.focus();*/
        if (this.value != "" && this.closest('tr').querySelector('.qtd').value != "" && this.closest('tr').querySelector('.desconto').value != "") {
          totalLinhaArtigo(preco[i]);
        }
        //reCalcularTotal();
      });

      /*preco[i].addEventListener("blur", function(e) {
        e.preventDefault();
        if (!this.value.includes(",")) {
          this.value = this.value.replace(/[^0-9\.]/g, '');
          this.value = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ") + ",00";
        }
      });*/
    }

    let qtd = document.querySelectorAll(".qtd");
    for (let i = 0; i < qtd.length; i++) {
      qtd[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
          totalSpan.className = "";
        }

        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        if (this.value != "" && this.closest('tr').querySelector('.preco').value != "" && this.closest('tr').querySelector('.desconto').value != "") {
          totalLinhaArtigo(qtd[i]);
        }
        //reCalcularTotal();
      });
    }

    let desconto = document.querySelectorAll(".desconto");

    for (let i = 0; i < desconto.length; i++) {
      desconto[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var cleanedInput = this.value.replace(/[^0-9,]/g, '');
        var replacedInput = cleanedInput.replace(/,+/g, ',');
        var formattedInput = replacedInput.replace(/(\,\d{2})[\d,]*/, '$1');

        var parts = formattedInput.split(',');
        var leftNumber = parseInt(parts[0]);
        if (isNaN(leftNumber) || leftNumber < 0 || leftNumber > 100) {
          leftNumber = Math.min(Math.max(leftNumber, 0), 100);
          if (!isNaN(leftNumber.toString())) {
            formattedInput = leftNumber.toString();
          }
        }

        if (this.value.includes("100")) {
          this.value = "100,00%";
        }

        this.value = formattedInput + "%";
        this.selectionStart = this.value.length - 1;
        this.selectionEnd = this.value.length - 1;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
        }

        if (this.value != "" && this.closest('tr').querySelector('.qtd').value != "" && this.closest('tr').querySelector('.preco').value != "") {
          totalLinhaArtigo(desconto[i]);
        }
        //reCalcularTotal();
      });

      desconto[i].addEventListener("click", function(e) {
        e.preventDefault();
        this.value = "";
      });

      desconto[i].addEventListener("blur", function(e) {
        e.preventDefault();
        if (this.value == "" || this.value == "%") {
          this.value = "0,00%";
        }
        if (this.value.includes(",%")) {
          var parts = this.value.split(",");
          this.value = parts[0] + ",00%";
        }
        if (!this.value.includes(',')) {
          var lastIndex = this.value.length - 1;
          this.value = this.value.slice(0, lastIndex) + ',00' + this.value.slice(lastIndex);
        }

        if (this.value.includes("100")) {
          this.value = "100,00%";
        }
        totalDocumento();
      });

      desconto[i].addEventListener("keyup", function(e) {
        if (e.keyCode === 8) {
          var indice = this.value.indexOf("%");
          if (indice !== -1 && this.selectionStart > indice) {
            var newValue = this.value.substring(0, indice);
            this.value = newValue;
            this.selectionStart = indice;
            this.selectionEnd = indice;
            this.focus();
          }
        }

        if (this.value.includes("100")) {
          this.value = "100,00%";
        }

        if (this.value == "%") {
          this.value = "0,00%";
          desconto[i].closest('tr').querySelector('.total').value = desconto[i].closest('tr').querySelector('.qtd').value.replace(/\ /g, '').replace(/\,/g, '.') * desconto[i].closest('tr').querySelector('.preco').value.replace(/\ /g, '').replace(/\,/g, '.');
          desconto[i].closest('tr').querySelector('.total').value = (desconto[i].closest('tr').querySelector('.total').value).replace(/\B(?=(\d{3})+(?!\d))/g, " ") + ",00";
        }
        totalDocumento();
      });

    }
  }

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

  $('#tabelaDocumento').on('click', '.btn-update', function(e) {
    e.preventDefault();
    linha = $(this).closest('tr').find('td');
    doOpcao.innerText = "Editar Artigo";
    resetForm();
    $('#modal-documento').modal('show');
    let id = $(this).closest('tr').find('td')[0].textContent;
    $.ajax({
      url: "includes/read/queryArtigoList.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id,
        linhaPreco: 0
      },
      success: function(data) {
        let imagem = document.querySelector('.image-container');
        let iconImage = imagem.querySelector('i');
        for (var key in data) {
          codigo.innerText = data[key]["idArtigo"];
          if (data[key]["imagem"] != null) {
            imagem.style.backgroundImage = `url('./images/artigo/${data[key]["imagem"]}')`;
            iconImage.style.display = "none";
          } else {
            imagem.style.backgroundImage = ``;
            iconImage.style.display = "block";
          }

          if (data[key]["controlaStock"] == 0) {
            controlaStock.checked = false;
            controlaStock.value = 0;
          } else {
            controlaStock.checked = true;
            controlaStock.value = 1;
          }

          if (data[key]["descontinuado"] == 0) {
            descontinuado.checked = false;
            descontinuado.value = 0;
          } else {
            descontinuado.checked = true;
            descontinuado.value = 1;
          }

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

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


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

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

          if (data[key]["precoCustoSemImp"] != "") {
            precoCustoSemImp.value = data[key]["precoCustoSemImp"];
            precoCustoSemImp.value = parseFloat(precoCustoSemImp.value).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          } else {
            precoCustoSemImp.value = "";
          }

          if (data[key]["precoCustoComImp"] != "") {
            precoCustoComImp.value = data[key]["precoCustoComImp"];
            precoCustoComImp.value = parseFloat(precoCustoComImp.value).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          } else {
            precoCustoComImp.value = "";
          }
        }
      }
    });

    $.ajax({
      url: "includes/read/queryPrecoArtigo.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id
      },
      success: function(data) {
        let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
        for (let i = 0; i < tr.length; i++) {
          tr[i].querySelector(".sImp").value = "";
          tr[i].querySelector(".cImp").value = "";
          tr[i].querySelector(".margem").value = "";
        }
        for (let i = 0; i < data.length; i++) {
          for (let j = 0; j < tr.length; j++) {
            if (data[i]['indice'] == j + 1) {
              tr[j].querySelector(".sImp").value = data[i]["semImposto"] ? parseFloat(data[i]["semImposto"]).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : "";
              tr[j].querySelector(".cImp").value = data[i]["comImposto"] ? parseFloat(data[i]["comImposto"]).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : "";
              tr[j].querySelector(".margem").value = data[i]["margem"] ? parseFloat(data[i]["margem"]).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : "";
            }
            /**/
          }
        }
      }
    });
  });

  $('#tabelaDocumento').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 artigo?",
        text: "Artigo: " + nome,
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: 'Confirmar',
        confirmButtonColor: '#560085',
        cancelButtonText: 'Cancelar',
        cancelButtonColor: '#560085',
      })
      .then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: "includes/delete/artigo.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idArtigo: id
            },
            success: function(data) {
              console.log(data);
              swal.fire({
                title: "Artigo " + nome + " eliminado com sucesso!",
                icon: "success",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
              });
              $('#tabelaDocumento').DataTable().row(linha).remove().draw(false);
            },
            error: function(data) {
              swal.fire({
                title: "Erro ao eliminar artigo!",
                text: "Erro ao apagar artigo '" + nome + "' porque já foi faturado!",
                icon: "error",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
              });
            }
          });
        }
      });
  });


  function detalhes(id) {
    detalheCabecalho.innerText = "<?php echo $rows[1]['valor']; ?>";
    $.ajax({
      url: "includes/read/queryArtigoList.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id,
        linhaPreco: 0
      },
      success: function(data) {
        for (var key in data) {
          nomeModal.innerText = data[key]["nome"];
          if (data[key]["imagem"] != null) {
            imagemInfo.querySelector('i').style.display = "none";
            imagemInfo.style.backgroundImage = `url('./images/artigo/${data[key]["imagem"]}')`;
          } else {
            imagemInfo.querySelector('i').style.display = "block";
            imagemInfo.style.backgroundImage = ``;
          }
          codigoInfo.innerText = data[key]["idArtigo"];
          nomeInfo.innerText = data[key]["nome"];
          nomeCurtoInfo.innerText = data[key]["nomeCurto"];
          familiaInfo.innerText = data[key]["familiaNome"];
          codigoBarraInfo.innerText = data[key]["codigoBarra"];
          if (data[key]["controlaStock"] == 0) {
            controlaStockInfo.innerText = "Não";
          } else {
            controlaStockInfo.innerText = "Sim";
          }

          if (data[key]["descontinuado"] == 0) {
            descontinuadoInfo.innerText = "Não";
          } else {
            descontinuadoInfo.innerText = "Sim";
          }
        }
      }
    });
  }

  $('#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();
  });

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

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

  function insertPreco(idArtigo) {
    let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
    for (let i = 0; i < tr.length; i++) {
      var indice = i + 1;
      if (tr[i].querySelector(".sImp").value != "" && tr[i].querySelector(".cImp").value != "") {

        funcaoInsert("../pos/includes/insert.inc.php", "post", "json", "precoArtigo", {
          idArtigo: idArtigo,
          semImposto: tr[i].querySelector(".sImp").value.replace(/\ /g, '').replace(/\,/g, '.'),
          comImposto: tr[i].querySelector(".cImp").value.replace(/\ /g, '').replace(/\,/g, '.'),
          margem: tr[i].querySelector(".margem").value.replace(/\ /g, '').replace(/\,/g, '.'),
          indice: indice
        }, function success(data) {
          document.querySelector('#precoCustoSemImp').value = "";
          document.querySelector('#precoCustoComImp').value = "";
          for (let i = 0; i < document.querySelectorAll('.sImp').length; i++) {
            document.querySelectorAll('.sImp')[i].value = "";
            document.querySelectorAll('.cImp')[i].value = "";
            document.querySelectorAll(".margem")[i].value = "";
          }
        }, function error(data) {

        }, function done(data) {

        });
      }
    }
  }

  function deletePreco(idArtigo) {
    funcaoDelete("../pos/includes/delete.inc.php", "post", "json", "precoArtigo", {
      idArtigo: idArtigo
    }, function success(data) {}, function error(data) {

    }, function done(data) {
      console.log(data);
    });
  }

  $(document).on("click", "#controlaStock", function(e) {
    let controlaStock = document.getElementById("controlaStock");
    $.ajax({
      url: "includes/read/verifyItem.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: codigo.innerText,
      },
      success: function(data) {
        if (data != null) {
          if (data[0]["controlaStock"] == 1) {
            swal.fire({
              title: "Erro ao retirar controla stock!",
              text: "O artigo: " + nome.value + ". Está incluso em um ou mais documentos.",
              confirmButtonColor: '#560085',
              confirmButtonText: 'Confirmar',
              icon: "error",
            });
            controlaStock.checked = true;
          } else {
            if (controlaStock.checked) {
              controlaStock.value = 1;
            } else {
              controlaStock.value = 0;
            }
          }
        }
      }
    });
  });

  $(document).on("click", "#controlaStock", function(e) {
    if (this.checked) {
      this.value = 1;
    } else {
      this.value = 0;
    }
  });

  $(document).on("click", "#descontinuado", function(e) {
    if (this.checked) {
      this.value = 1;
    } else {
      this.value = 0;
    }
  });

  function artigo(img) {
    if (doOpcao.innerText == "Novo Artigo") {

      $.ajax({
        url: "includes/create/artigo.inc.php",
        type: "post",
        data: {
          idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
          idFamilia: idFamilia.value,

          idUnidadeMedida: $('#unidademedida').val(), // scripttt

          tipoArtigo: tipoArtigo.value,
          nome: nome.value,
          nomeCurto: nomeCurto.value,
          codigoBarra: codigoBarra.value,
          unidadeVenda: 0,
          descontinuado: descontinuado.value,
          controlaStock: controlaStock.value,
          precoCustoSemImp: precoCustoSemImp.value.replace(/\ /g, '').replace(/\,/g, '.'),
          precoCustoComImp: precoCustoComImp.value.replace(/\ /g, '').replace(/\,/g, '.'),
        },
        success: function(data) {
          swal.fire({
            title: "Cadastro efectuado com sucesso!",
            text: "Artigo " + nome.value + " cadastrado!",
            confirmButtonColor: '#560085',
            confirmButtonText: 'Confirmar',
            icon: "success",
          }).then(() => {
            insertPreco(data);
            if (img[0] != null) {
              foto(data, img);
            }
            insertLinha(data);
            reload();
          });
        },
        error: function(data) {
          swal.fire({
            title: "Erro ao Cadastrar nome!",
            text: "Erro ao Cadastrar nome: " + nome.value + " !",
            confirmButtonText: 'Confirmar',
            icon: "error",
          });
        }
      }).done(function(data) {
        console.log(data);
      });
    } else {
      let dados = {
        idArtigo: codigo.innerText,
        idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
        idFamilia: idFamilia.value,
        tipoArtigo: tipoArtigo.value,
        nome: nome.value,
        nomeCurto: nomeCurto.value,
        codigoBarra: codigoBarra.value,
        unidadeVenda: 0,
        descontinuado: descontinuado.value,
        controlaStock: controlaStock.value,
        precoCustoSemImp: precoCustoSemImp.value.replace(/\ /g, '').replace(/\,/g, '.'),
        precoCustoComImp: precoCustoComImp.value.replace(/\ /g, '').replace(/\,/g, '.'),
      };
      let tabela = "artigo";
      funcaoUpdate("../pos/includes/update.inc.php", "post", "json", tabela, dados, {
        idArtigo: codigo.innerText
      }, function success(data) {
        swal.fire({
          title: "Informações Actualizadas com sucesso!",
          text: "Artigo " + nome.value + ".",
          confirmButtonColor: '#560085',
          confirmButtonText: 'Confirmar',
          icon: "success",
        }).then(() => {
          deletePreco(codigo.innerText);
          insertPreco(codigo.innerText);
          if (img[0] != null) {
            foto(codigo.innerText, img);
          }
          updateLinha(codigo.innerText);
          reload();
        });
      }, function error(data) {
        swal.fire({
          title: "Erro ao Cadastrar nome!",
          text: "Erro ao Cadastrar nome: " + nome.value + " !",
          confirmButtonText: 'Confirmar',
          icon: "error",
        });
      }, function done(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',
        cancelButtonText: 'Cancelar',
      })
      .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',
                });
                $('#tabelaDocumento').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',
                });
              }
            });
          } else {
            swal.fire({
              title: "Erro ao eliminar Usuário!",
              text: "Usuário: " + nome.value + " não pode ser eliminado!",
              confirmButtonText: 'Confirmar',
              icon: "error",
            });
          }
        }
      });
  });
</script>
<script src="./validation/parametroArtigo.js"></script>