<?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: #4a0073;
    border-color: #4a0073;
  }

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

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

  .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: 600;
    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: 600;
    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: -20.35rem;
    height: 3px;
    width: 20rem;
    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;
  }

  .tooltip-container {
    position: relative;
    float: right;
    margin-left: 10px;
  }

  .tooltip-content {
    margin-left: 1rem;
    margin-top: 2.5rem;
    display: none;
    position: fixed;
    padding: 10px;
    z-index: 9999;
  }


  .tooltip-content label {
    display: block;
    margin-bottom: 5px;
  }

  .tooltip-content input {
    width: 100%;
    box-sizing: border-box;
    margin-bottom: 10px;
  }

  .tooltip-show {
    display: block;
  }
</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">
                      <li class="nav-item dropdown btn">
                        <a id="btn-preview" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Pré-visualizar</a>
                        <ul aria-labelledby="btn-preview" class="dropdown-menu border-0 shadow">
                          <li><button id="./formLayoutA4Pl.php" class="dropdown-item btn-layout" disabled>Documento A4 Pro-Luzes</button></li>
                          <li><button id="./formLayoutA4.php" class="dropdown-item btn-layout" disabled>Documento A4</button></li>
                          <li><button id="./formLayoutTicket.php" class="dropdown-item btn-layout" disabled>Documento Ticket</button></li>
                        </ul>
                      </li>
                      <button class="btn btn-opcao">Importar</button>
                      <button class="btn btn-opcao botao-activo" id="btn">Nova Factura</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">Documentos</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 Documento">Documento</th>
                        <th title="Valor Entregue">Valor Entregue</th>
                        <th title="Troco">Troco</th>
                        <th title="Data Documento">Data Documento</th>
                        <th title="Usuário-Vendedor">Vendedor</th>
                        <th title="Total do Documento">Total</th>
                        <th title="Nome do Entidade">Entidade</th>
                        <th title="Estado do Documento">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 Facturas.
                </div>
              </div>
            </div>
          </div>
          <!-- /.card -->
        </div>
        <!-- /.container-fluid -->
      </section>

    </div>
    <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;">Artigos</p>
                  <div class="bullet">
                    <span style="color: #666;">2</span>
                    <div class="check fas fa-check"></div>
                  </div>
                </div>
                <div class="step">
                  <p style="margin: 0;">Confirmação</p>
                  <div class="bullet">
                    <span style="color: #666;">3</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" style="position: relative;">
                    <div class="row">
                      <div class="col-md-6">
                        <h5 style="margin-bottom: 1rem; justify-content: center;">Documento - <span id="codigo"></span></h5>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="required">Tipo de Documento</small>
                          <select class="form-control select2" style="width: 100%;" id="tipoDocumento" name="tipoDocumento">
                          </select>
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Série</small>
                          <input type="text" class="form-control" id="serie" name="serie" placeholder="Série" title="Série" disabled>
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="required">Prazo de Pagamento</small>
                          <select class="form-control select2" style="width: 100%;" id="prazoPagamento" name="prazoPagamento">
                          </select>
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Vendedor</small>
                          <input type="text" class="form-control" id="vendedorFactura" name="vendedorFactura" placeholder="Vendedor" title="Vendedor" disabled>
                        </div>
                      </div>
                      <div class="col-md-6">
                        <h5 style="margin-bottom: 1rem; justify-content: center;">Entidade</h5>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Entidade</small>
                          <div class="input-group input-group">
                            <input type="text" class="form-control form-control" id="entidade" name="entidade" placeholder="Pesquisar Entidade" title="Pesquisar Entidade">
                            <div class="input-group-append">
                              <button type="button" id="btn-search-entidade" class="btn btn btn-default" style="line-height: 0 ;">
                                <i class="fa fa-search"></i>
                              </button>
                            </div>
                          </div>
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Nome</small>
                          <input type="text" class="form-control" id="nomeEntidade" name="nomeEntidade" placeholder="Nome" title="Nome do Entidade" disabled>
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Morada</small>
                          <input type="text" class="form-control" id="moradaEntidade" name="moradaEntidade" placeholder="Morada do Entidade" title="Morada do Entidade" disabled>
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="required">NIF do Entidade</small>
                          <input type="text" class="form-control" id="nifEntidade" name="nifEntidade" placeholder="NIF do Entidade" title="NIF (Número de Identificação Fiscal) do Entidade" disabled>
                        </div>
                      </div>
                      <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; bottom: 0; position: relative;">
                        <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 nextButton" 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">
                        <h6>
                          <div class="tooltip-container">
                            <button class="float-right" id="outrasOpcoes" style="border: none; color: #560085; background: #5600851c;padding: .5rem;border-radius: 10px;font-weight: 600;margin-top: 0.5rem;text-align: center; cursor: pointer;padding: .375rem .75rem;font-size: .8rem;line-height: 1.5;border-radius: .5rem">Outras Opções</button>
                            <div class="col-12 col-sm-6 tooltip-content">
                              <div class="card card-primary card-outline card-outline-tabs" style="width: 45%;">
                                <div class="card-header p-0 border-bottom-0">
                                  <ul class="nav nav-tabs" id="custom-tabs-four-tab" role="tablist">
                                    <li class="nav-item">
                                      <a class="nav-link active" id="custom-tabs-four-total-tab" data-toggle="pill" href="#custom-tabs-four-total" role="tab" aria-controls="custom-tabs-four-total" aria-selected="true">Totais</a>
                                    </li>
                                    <li class="nav-item">
                                      <a class="nav-link" id="custom-tabs-four-imposto-tab" data-toggle="pill" href="#custom-tabs-four-imposto" role="tab" aria-controls="custom-tabs-four-imposto" aria-selected="false">Impostos</a>
                                    </li>
                                    <li class="nav-item">
                                      <a class="nav-link" id="custom-tabs-four-saldo-tab" data-toggle="pill" href="#custom-tabs-four-saldo" role="tab" aria-controls="custom-tabs-four-saldo" aria-selected="false">Saldo</a>
                                    </li>
                                    <li class="nav-item">
                                      <a class="nav-link" id="custom-tabs-four-observacao-tab" data-toggle="pill" href="#custom-tabs-four-observacao" role="tab" aria-controls="custom-tabs-four-observacao" aria-selected="false">Observações</a>
                                    </li>
                                  </ul>
                                </div>
                                <div class="card-body">
                                  <div class="tab-content" id="custom-tabs-four-tabContent">
                                    <div class="tab-pane fade show active" id="custom-tabs-four-total" role="tabpanel" aria-labelledby="custom-tabs-four-total-tab">
                                      <div class="row">
                                        <div class="col-md-6">
                                          <p>Total Bruto</p>
                                          <p>Desconto de Linha</p>
                                        </div>
                                        <div class="col-md-6">
                                          <p style="text-align: right;" id="opcaoTotalBruto">0,00</p>
                                          <p style="text-align: right;" id="opcaoDescontoLinha">0,00</p>
                                        </div>
                                        <div class="col-md-6">
                                          <div class="form-group" style="margin-bottom: 0;">
                                            <small class="not-required">Desconto Global %</small>
                                            <input type="text" class="form-control" id="descontoGlobalPorcentagem" placeholder="0,00%" title="Desconto Global Porcentagem">
                                          </div>
                                        </div>
                                        <div class="col-md-6">
                                          <div class="form-group" style="margin-bottom: 0;">
                                            <small class="not-required">Desconto Global</small>
                                            <input type="text" class="form-control" id="descontoGlobalValor" name="descontoGlobalValor" placeholder="0,00" title="Desconto Global Por Valor">
                                          </div>
                                        </div>
                                        <div class="col-md-6">
                                          <p>Total Líquido</p>
                                          <p>Total Impostos</p>
                                          <p>Total Documento</p>
                                          <p>Total Retenção</p>
                                        </div>
                                        <div class="col-md-6">
                                          <p style="text-align: right;" id="opcaoTotalLiquido">0,00</p>
                                          <p style="text-align: right;" id="opcaoTotalImposto" id="opcaoTotalImposto">0,00</p>
                                          <p style="text-align: right;" id="opcaoTotalDocumento">0,00</p>
                                          <p style="text-align: right;">0,00</p>
                                        </div>
                                        <div class="col-md-12">
                                          <div class="form-group" style="margin-bottom: 0;">
                                            <small class="not-required">Arredondamento</small>
                                            <input type="text" class="form-control" id="arredondamento" placeholder="0,00" title="Arredondamento">
                                          </div>
                                        </div>
                                        <div class="col-md-6">
                                          <p>Valor a Pagar</p>
                                        </div>
                                        <div class="col-md-6">
                                          <p style="text-align: right;" id="opcaoValorPagar">0,00</p>
                                        </div>
                                      </div>
                                    </div>
                                    <div class="tab-pane fade" id="custom-tabs-four-imposto" role="tabpanel" aria-labelledby="custom-tabs-four-imposto-tab">
                                      <div class="row">
                                        <div class="col-md-12">
                                          <table class="table table-sm" style="text-align: center;">
                                            <thead>
                                              <tr>
                                                <th title="Taxa %"><small>Taxa %</small></th>
                                                <th title="Incidência"><small>Incidência</small></th>
                                                <th title="Impostos"><small>Impostos</small></th>
                                                <th title="Valor"><small>Valor</small></th>
                                              </tr>
                                            </thead>
                                            <tbody id="impostoOpcao">
                                            </tbody>
                                          </table>
                                        </div>
                                      </div>
                                    </div>
                                    <div class="tab-pane fade" id="custom-tabs-four-saldo" role="tabpanel" aria-labelledby="custom-tabs-four-saldo-tab">
                                      <div class="row">
                                        <div class="col-md-12">
                                          <table class="table table-sm">
                                            <thead>
                                              <tr>
                                                <th title="Total"><small>Total</small></th>
                                                <th title="Não Vencido"><small>N.Vencido</small></th>
                                                <th title="Até 30 Dias"><small>30 Dias</small></th>
                                                <th title="De 31 até 60 Dias"><small>31-60 Dias</small></th>
                                                <th title="De 61 até 90 Dias"><small>61-90 Dias</small></th>
                                                <th title="Mais de 90 Dias"><small>+90 Dias</small></th>
                                              </tr>
                                            </thead>
                                            <tbody>
                                            </tbody>
                                          </table>
                                        </div>
                                      </div>
                                    </div>
                                    <div class="tab-pane fade" id="custom-tabs-four-observacao" role="tabpanel" aria-labelledby="custom-tabs-four-observacao-tab">
                                      <div class="row">
                                        <div class="col-md-12">
                                          <div class="form-group" style="margin-bottom: 0;">
                                            <small class="not-required">Observações</small>
                                            <textarea class="form-control" name="" id="" cols="30" rows="10"></textarea>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <!-- /.card -->
                              </div>
                            </div>
                          </div>

                        </h6>
                        <table id="tabelaArtigo" class="table table-hover table-bordered table-striped">
                          <thead style="border-bottom-left-radius: 0;">
                            <tr style="text-align: center;">
                              <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>
                              <th title="Opções"><i class="fa-solid fa-screwdriver-wrench"></i></th>
                            </tr>
                          </thead>
                          <tbody style="text-align: center;">
                          </tbody>
                        </table>
                      </div>
                      <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; 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 prevButton" style="margin-top: 0;">
                            Anterior
                          </button>
                          <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary next-1 next nextButton" style="margin-top: 0;">
                            Seguinte
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="page" style="position: relative;">
                    <h5 style="margin-bottom: 1rem; justify-content: center;">Confirmação</h5>
                    <div class="row">
                      <div class="col-12">
                        <div class="invoice p-3 mb-3" style="height: 21rem; overflow-y: scroll;">
                          <!-- title row -->
                          <div class="row">
                            <div class="col-12">
                              <h4>
                                <span id="descCabecalho"></span>
                                <small class="float-right" id="descDataActual"></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="descCodigo"></span></strong><br>
                              <span>Documento - </span><strong><span id="descDocumento"></span></strong><br>
                              <span>Série - </span><strong><span id="descSerie"></span></strong><br>
                              <span>Prazo de Pagamento - </span><strong><span id="descPrazoPagamento"></span></strong><br>
                              <span>Vendedor - </span><strong><span id="descVendedor"></span></strong>
                            </div>
                            <!-- /.col -->
                            <div class="col-sm-6 invoice-col">
                              <strong><span>Entidade</span></strong><br>
                              <span>Identificador Entidade - </span><strong><span id="descIdEntidade"></span></strong><br>
                              <span>Nome - </span><strong><span id="descNome"></span></strong><br>
                              <span>Morada - </span><strong><span id="descMorada"></span></strong><br>
                              <span>NIF - </span><strong><span id="descNif"></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-hover table-striped" style="text-align: center;" id="tabelaConfirmacao">
                                <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="tabelaConfirmacaoBody">
                                </tbody>
                              </table>
                            </div>
                            <!-- /.col -->
                          </div>
                        </div>
                        <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; bottom: 0; position: absolute;">
                          <div class="form-group field btns">
                            <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary prev-2 prev prevButton" style="margin-top: 0;">
                              Anterior
                            </button>
                            <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary submit nextButton" style="margin-top: 0; margin-left: 3px !important;">
                              Gravar Documento
                            </button>
                          </div>
                        </div>
                      </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-entidade">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">Entidades</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <table id="tabelaEntidade" class="table table-hover table-bordered table-striped" style="line-height: 0.8;">
              <thead>
                <tr style="text-align: center;">
                  <th title="Identificador da Entidade">Ref. Entidade</th>
                  <th title="Nome">Nome</th>
                  <th title="Nome Comercial">Nome Comercial</th>
                  <th title="Bilhete de Identidade do Entidade">B.I</th>
                  <th title="NIF do Entidade">NIF</th>
                  <th title="Localidade do Entidade">Localidade</th>
                  <th title="Data de Nascimento do Entidade">Data Nasc.</th>
                  <th title="Morada do Entidade">Morada</th>
                  <th title="Tipo">Tipo</th>
                  <th title="Estado do Entidade">Estado</th>
                </tr>
              </thead>
              <tbody style="text-align: center;">
              </tbody>
            </table>
          </div>
          <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
            <button type="button" class="btn btn-primary" id="getEntitySelected">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" id="confirmArticle">Confirmar</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 Entidade - </span><strong><span id="detalheIdEntidade"></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>
    <div class="modal fade" id="modal-layout">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">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="row">
              <div class="col-md-12">
                <iframe id="layoutDocumento" src="./formLayoutA4.php" frameborder="0" width="100%" style="height: 60vh;"></iframe>
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
            <button type="button" class="btn btn-primary" id="btn-print">Imprimir</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.content-wrapper -->
    <?php include('footer.php'); ?>
</body>

</html>
<script src="./validation/formFactura.js"></script>
<script>
  let idEntidade;
  let valorLinha;
  let totalDoc;
  let pendenteVerify;
  let totalImposto = [];
  let linhaPrecoEntidade;
  let codigoReport;
  let nomeReport;
  let tipoDoc;
  let tipoEntidade;
  let idDoc;

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

  function createDocumento() {
    Swal.fire({
      icon: 'info',
      title: 'Emitir Documento?',
      text: 'Tem a certeza que quer emitir essa Documento?',
      allowOutsideClick: false,
      showCancelButton: true,
      confirmButtonText: 'Confirmar',
      confirmButtonColor: '#560085',
      cancelButtonText: 'Cancelar',
      cancelButtonColor: '#560085',
    }).then((result) => {
      if (result.isConfirmed) {
        let idUsuario = <?php echo $_SESSION["usuarioId"]; ?>;
        let tipoDocumento = document.querySelector('#tipoDocumento').value;
        let entidade = document.querySelector('#entidade').value;
        let prazoPagamento = document.querySelector('#prazoPagamento').value;
        let entregueSpan = parseFloat(document.querySelector('#entregueSpan').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let totalDocumento = totalDoc;
        let totalSpan = parseFloat(document.querySelector('#totalSpan').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let opcaoTotalLiquido = parseFloat(document.querySelector('#opcaoTotalLiquido').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let opcaoTotalImposto = parseFloat(document.querySelector('#opcaoTotalImposto').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let descontoGlobalValor = document.querySelector('#descontoGlobalValor').value == "" ? 0 : parseFloat(document.querySelector('#descontoGlobalValor').value.replace(/\ /g, '').replace(/\,/g, '.'));

        $.ajax({
          url: "includes/create/doc.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idUsuario: idUsuario,
            idTipoDoc: tipoDocumento,
            idEntidade: entidade,
            idPrazoPagamento: prazoPagamento,
            entregue: entregueSpan,
            total: totalDocumento,
            troco: totalSpan,
            totalLiquido: opcaoTotalLiquido,
            totalImposto: opcaoTotalImposto,
            descontoGlobal: descontoGlobalValor
          },
          success: function(data) {
            let id = data;
            let tabela = document.getElementById("tabelaArtigo");
            for (i = 1; i < tabela.rows.length; i++) {
              let inputSearchArtigo = tabela.rows[i].querySelector('.inputSearchArtigo').value;
              let qtd = tabela.rows[i].querySelector('.qtd').value;
              let preco = tabela.rows[i].querySelector('.preco').value;
              let desconto = tabela.rows[i].querySelector('.desconto').value;
              let imposto = tabela.rows[i].querySelector('.imposto').value;
              let total = tabela.rows[i].querySelector('.total').value;
              let taxa = $(tabela.rows[i].querySelector('.imposto')).select2('data')[0].element.dataset.taxa;

              if (inputSearchArtigo != "" && qtd != "" && preco != "" && desconto != "" && imposto != "" && total != "") {
                $.ajax({
                  url: "includes/create/artigoDocumento.inc.php",
                  type: "post",
                  dataType: "json",
                  data: {
                    idDocumento: id,
                    idArtigo: parseInt(inputSearchArtigo),
                    descricao: tabela.rows[i].querySelector('.descricao').value,
                    qtd: parseInt(qtd),
                    preco: parseFloat(preco.replace(/\ /g, '').replace(/\,/g, '.')),
                    desconto: parseFloat(desconto.replace(/\ /g, '').replace(/\,/g, '.')),
                    idImposto: parseFloat($(tabela.rows[i].querySelector('.imposto')).select2('data')[0].element.dataset.taxa.replace(/\ /g, '').replace(/\,/g, '.')),
                    imposto: parseFloat(imposto.replace(/\ /g, '').replace(/\,/g, '.')),
                    total: parseFloat(total.replace(/\ /g, '').replace(/\,/g, '.')),
                  },
                  success: function(data) {
                    reload(1);
                    loadNovoId();
                  },
                  error: function(data) {
                    reload(0);
                    loadNovoId();
                  }
                }).done(function(data) {

                });
              }
            }
          },
          error: function(data) {
            swal.fire({
              title: "Erro ao Emitir Documento!",
              text: "Erro ao Facturar!",
              confirmButtonText: 'Confirmar',
              icon: "error",
            });
          }
        }).done(function(data) {
          $.ajax({
            url: "includes/read/queryDocumento.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idDocumento: data,
            },
            success: function(data) {
              for (let i = 0; i < data.length; i++) {
                var novaLinha = {
                  codigoDocumento: data[i]["codigoDocumento"],
                  entregue: data[i]["entregue"],
                  troco: data[i]["troco"],
                  dataDoc: data[i]["dataDoc"],
                  nomeU: data[i]["nomeU"],
                  total: data[i]["total"],
                  nomeE: data[i]["nomeE"],
                };
                $('#tabelaDocumento').DataTable().row.add(novaLinha).draw(false);
              }
            },
            error: function(data) {}
          }).done(function(data) {});
        });
      } else {
        reload(0);
        loadNovoId();
        totalDocumento();
        //location.reload();
      }
    });
  }

  $(document).ready(function() {
    funcaoSelect("../pos/includes/select.inc.php", "post", "json", "tipoDoc", function success(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>";
      }
      $("#tipoDocumento").html(select);
    }, function error(data) {

    }, function done(data) {
      tipoDocumento.setAttribute("disabled", "disabled");
      let promessa = new Promise(function(resolve, reject) {
        let tipoDocumento = "<?php echo $_GET['tipoDocumento']; ?>";
        let natureza = "<?php echo $_GET['natureza']; ?>";
        let id = {
          tipoDocumento: tipoDocumento,
          natureza: natureza
        }
        funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", id, "tipoDoc", function success(data) {
          $('#tipoDocumento').val(data[0]['tipoDoc']);
          $('#tipoDocumento').select2().trigger('change');
          loadEntidade(data[0]['tipoEnt']);
          tipoEntidade = data[0]['tipoEnt'];
          loadTabelaDocumento(data[0]['tipoDoc']);
          funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idTipoEntidade: data[0]['tipoEnt']
          }, "tipoEntidade", function success(data) {
            funcaoEntidade(data[0]['nome']);
          }, function error(data) {

          }, function done(data) {

          });
        }, function error(data) {

        }, function done(data) {

        });
      });
    });
  });

  $(document).ready(function() {
    let parametro = 1;
    funcaoSelect("../pos/includes/select.inc.php", "post", "json", "prazoPagamento", function success(data) {
      let select = "";
      select += "<option value='0'>Selecione um Prazo de Pagamento</option>";
      for (var key in data) {
        if (data[key]['idPrazoPagamento'] == parametro) {
          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);
    }, function error(data) {

    }, function done(data) {
      $('#prazoPagamento').val(parametro + 1);
      $('#prazoPagamento').select2().trigger('change');
    });

    funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
      idUsuario: 1
    }, "viewusuariotipo", function success(data) {
      vendedorFactura.value = data[0]['nome'];
    }, function error(data) {}, function done(data) {

    });
  });

  function insertLinha(id) {
    $.ajax({
      url: "includes/read/queryDocumento.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idDocumento: id,
      },
      success: function(data) {
        console.log("Usuário: ", data);
        for (var key in data) {
          var novaLinha = {
            codigoDocumento: data[key]["codigoDocumento"],
            entregue: data[key]["entregue"],
            troco: data[key]["troco"],
            dataDoc: data[key]["dataDoc"],
            nomeU: data[key]["nomeU"],
            total: data[key]["total"],
            nomeE: data[key]["nomeE"],
          };
          $('#tabelaDocumento').DataTable().row.add(novaLinha).draw(false);
        }
        createLayout(data[key]["idDocumento"], data[key]["codigoDocumento"], "documentoA4");
        createLayout(data[key]["idDocumento"], data[key]["codigoDocumento"], "documentoTicket");
      }
    });
  }

  function createLayout(idDocumento, nomeDocumento, tipoLayout) {
    $.ajax({
      url: "includes/create/layout.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idDocumento: idDocumento,
        nomeDocumento: nomeDocumento,
        tipoLayout: tipoLayout
      }
    });
  }

  function reload(parametro) {
    if (parametro == 1) {
      swal.fire({
        title: "Documento emitido com sucesso!",
        text: "Documento Documento",
        confirmButtonText: 'Confirmar',
        confirmButtonColor: '#560085',
        icon: "success",
      });
    }

    $('#modal-documento').modal('hide');
    resetForm();
    loadNovoId();
    $('#prazoPagamento').val(1);
    $('#prazoPagamento').select2().trigger('change');
    document.querySelector("#prazoPagamento").parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    prazoPagamento.classList.remove("select2-danger");
    entidade.value = "";
    entidade.parentElement.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    entidade.className = "form-control";
    nomeEntidade.value = "";
    nomeEntidade.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    nomeEntidade.className = "form-control";
    moradaEntidade.value = "";
    moradaEntidade.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    moradaEntidade.className = "form-control";
    nifEntidade.value = "";
    nifEntidade.className = "form-control";
    $('#tabelaArtigo').DataTable().clear().draw();
    footerPagamento.style.opacity = 0;
    document.querySelector(".nextBtn").removeAttribute('disabled');
    addRow();
  }

  function loadNovoId() {
    funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
      tipoDocumento: "<?php echo $_GET['tipoDocumento']; ?>",
      natureza: "<?php echo $_GET['natureza']; ?>"
    }, "tipoDoc", function success(data) {
      funcaoCount("../pos/includes/count.inc.php", "post", "json", "documento", {
        idTIpoDoc: data[0]['tipoDoc']
      }, function success(data) {
        codigo.innerText = parseInt(data[0]["COUNT(*)"]) + 1;
      }, function error(data) {

      }, function done(data) {

      });
    }, function error(data) {

    }, function done(data) {

    });
  }

  $(document).ready(function() {
    loadNovoId();
    $.ajax({
      url: "includes/read/modoPagamento.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        for (var key in data) {
          select += `
          <tr id="${data[key]['idModoPagamento']}">
            <td style="border: 0; width: 10%; vertical-align: middle;">${data[key]['idModoPagamento']}</td>
            <td style="border: 0; width: 70%; vertical-align: middle;">${data[key]['nome']}</td>
            <td style="border: 0; width: 20%;" vertical-align: middle;>
              <input type="text" class="form-control mp" placeholder="0,00">
            </td>
          </tr>`;
        }
        $("#modoPagamentoBody").html(select);
        modoPagamentoFormatedNumber();
      }
    });
  });

  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 = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).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 = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).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 = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).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 = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).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();
      });
    }
  };

  function searchEntidade(idEntidade, tipoEntidade) {
    if (idEntidade !== "0" && idEntidade !== "1") {
      funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
        idEntidade: idEntidade,
        idTipoEntidade: tipoEntidade
      }, "viewEntidade", function success(data) {
        entidade.parentElement.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
        nomeEntidade.setAttribute('disabled', 'disabled');
        nomeEntidade.className = "form-control";
        nomeEntidade.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
        const firstNextBtn = document.querySelector(".nextBtn");
        if (data == null) {
          idEntidade = undefined;
          entidade.value = "";
          nomeEntidade.value = "";
          moradaEntidade.value = "";
          nifEntidade.value = "";
          linhaPrecoEntidade = "";
          firstNextBtn.setAttribute('disabled', 'disabled');
        } else {
          for (let i = 0; i < data.length; i++) {
            idEntidade = data[i]['idEntidade'];
            entidade.value = data[i]['idEntidade'];
            nomeEntidade.value = data[i]['nome'];
            moradaEntidade.value = data[i]['morada'];
            nifEntidade.value = data[i]['nif'];
            linhaPrecoEntidade = data[i]["linhaPreco"];
            firstNextBtn.removeAttribute('disabled');
          }
        }
      }, function error(data) {

      }, function done(data) {
        let linhaPreco;
        if (data != null) {
          if (data[0]['linhaPreco'] == 0) {
            funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
              idDefinicao: 2
            }, "definicao", function success(data) {
              linhaPreco = data[0]['valor'];
            }, function error(data) {

            }, function done(data) {

            });
          } else {
            linhaPreco = data[0]['linhaPreco'];
          }
          loadTabelaArtigo(linhaPreco, function callback(data) {
            var tabelaArtigoListagem = $("#tabelaArtigoListagem").DataTable();
            tabelaArtigoListagem.clear();
            tabelaArtigoListagem.rows.add(data);
            tabelaArtigoListagem.draw();
          });
        }
      });
    } else {
      entidade.parentElement.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
      idEntidade = undefined;
      entidade.value = "";
      nomeEntidade.value = "";
      moradaEntidade.value = "";
      nifEntidade.value = "";
      linhaPrecoEntidade = "";
      firstNextBtn.setAttribute('disabled', 'disabled');
    }
  }

  function loadTabelaArtigo(linhaPreco, callback) {
    let tabela;
    let iteracao = 0;
    funcaoSelect("../pos/includes/select.inc.php", "post", "json", "viewartigousuariofamilia", function success(data) {
      console.log(data);
      tabela = data;
      for (let i = 0; i < data.length; i++) {
        tabela[i].precoComImposto = 0;
        tabela[i].precoSemImposto = 0;
        tabela[i].stock = 0;
        funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
          idArtigo: data[i]["idArtigo"],
          indice: linhaPreco
        }, "precoArtigo", function success(data) {
          if (data != null) {
            $("#tabelaArtigoListagem").DataTable().cell(i, 3).data(data[0]['semImposto']).draw();
            $("#tabelaArtigoListagem").DataTable().cell(i, 4).data(data[0]['comImposto']).draw();
          }
          funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
            idArtigo: tabela[i]["idArtigo"]
          }, "artigoStock", function success(data) {
            if (data != null) {
              $("#tabelaArtigoListagem").DataTable().cell(i, 5).data(data[0]['qtdDisponivel']).draw();
            }
          }, function error(data) {

          }, function done(data) {

          });
        }, function error(data) {

        }, function done(data) {

        });
        iteracao = iteracao + 1;
      }
      if (iteracao == data.length) {
        callback(tabela);
      }
    }, function error(data) {

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

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

  $(document).on("focusout", "#entidade", function(e) {
    event.preventDefault();
    searchEntidade(entidade.value, tipoEntidade);
  });

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

  $("#getEntitySelected").on('click', function() {
    var selectedData = $('#tabelaEntidade tbody').find('tr.selected td')[0].textContent;
    console.log(selectedData);
    searchEntidade(selectedData, tipoEntidade);
    $('#modal-entidade').modal('hide');
  });

  function outrasOpcoes() {
    let totalOpcao = 0;
    let descontoOpcao = 0;
    let totalLiquidoOpcao = 0;
    let totalImpostoOpcao = 0;
    let total = document.querySelectorAll(".total");
    let preco = document.querySelectorAll(".preco");
    let qtd = document.querySelectorAll(".qtd");
    let desconto = document.querySelectorAll(".desconto");
    let imposto = document.querySelectorAll(".imposto");
    for (let i = 0; i < total.length; i++) {
      if (total[i].value != "") {
        totalOpcao += (parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.')));

        totalLiquidoOpcao += parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.'));

        totalImpostoOpcao += (parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(imposto[i].value.replace(/\ /g, '').replace(/\,/g, '.')) / 100));
      }

      if (total[i].value != "" && preco[i].value != "") {
        descontoOpcao += ((parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.'))) - parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')));
      }
    }
    opcaoTotalBruto.innerText = parseFloat(totalOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoDescontoLinha.innerText = parseFloat(descontoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalLiquido.innerText = parseFloat(totalLiquidoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalImposto.innerText = parseFloat(totalImpostoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalDocumento.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    opcaoTotalDocumento.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    let dados = "";
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector('.inputSearchArtigo').value != "") {
        dados += `
      <tr>
        <td class="tdTaxa"><small>${parseFloat(tabela.rows[i].querySelector('.imposto').value).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</small></td>
        <td class="tdIncidencia"><small>${parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
        <td class="tdImposto"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
        <td class="tdValor"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) + (parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
      </tr>
    `;
      }
    }
    $('#impostoOpcao').html(dados);

    let taxaSet = new Set();

    for (let i = 0; i < $("#impostoOpcao tr").length; i++) {
      let td = $("#impostoOpcao tr")[i].querySelector('.tdTaxa');
      let tr = $("#impostoOpcao tr")[i];

      if (taxaSet.has(td.innerText)) {
        let incidenciaAtual = parseFloat(tr.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let novoValorIncidencia = incidenciaAtual + parseFloat(td.parentElement.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        tr.querySelector('.tdIncidencia').innerHTML = `<small>${novoValorIncidencia.toFixed(2)}</small>`;
        td.parentElement.remove();
      } else {
        taxaSet.add(td.innerText);
      }
    }

    /*let valoresImpostoOpcao = [];
    let tabelaImpostoOpcao = document.querySelectorAll("#impostoOpcao tr");
    for (let i = 0; i < tabelaImpostoOpcao.length; i++) {
      valoresImpostoOpcao.push(tabelaImpostoOpcao[i].querySelectorAll('td')[0].textContent);
    }

    let valoresDuplicadosImpostoOpcao = [];
    for (let i = 0; i < tabelaImpostoOpcao.length; i++) {
      for (let j = i + 1; j < tabelaImpostoOpcao.length; j++) {
        if (valoresImpostoOpcao[i] === valoresImpostoOpcao[j] && !valoresDuplicadosImpostoOpcao.includes(valoresImpostoOpcao[i])) {
          valoresDuplicadosImpostoOpcao.push(valoresImpostoOpcao[i]);
        }
      }
    }
    if (valoresDuplicadosImpostoOpcao.length > 0) {
      let somaIncidencia = 0;
      let somaImposto = 0;
      let somaValor = 0;
      var elemento = $("#impostoOpcao td").filter(function() {
        var texto = $(this).find('td').text().trim();
        return $(this).text().indexOf(valoresDuplicadosImpostoOpcao) !== -1;
      });

      console.log("VAMOS VER A INCIDÊNCIA: ", elemento.parent('tr').find('.tdIncidencia'));
      for(let i = 0; i < elemento.parent('tr').find('.tdIncidencia').length; i++){
        if(elemento.parent('tr').find('.tdIncidencia') != null){
          somaIncidencia += parseFloat(elemento.parent('tr').find('.tdIncidencia')[i].innerText.replace(/\ /g, '').replace(/\,/g, '.'));
          somaImposto += parseFloat(elemento.parent('tr').find('.tdImposto')[i].innerText.replace(/\ /g, '').replace(/\,/g, '.'));
          somaValor += parseFloat(elemento.parent('tr').find('.tdValor')[i].innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        }
      }
      elemento.first().parent('tr').find('td')[1].innerHTML = `<small>${parseFloat(somaIncidencia).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small>`;
      elemento.first().parent('tr').find('td')[2].innerHTML = `<small>${parseFloat(somaImposto).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small>`;
      elemento.first().parent('tr').find('td')[3].innerHTML = `<small>${parseFloat(somaValor).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small>`;
      elemento.parent('tr').not(':first').remove();
    }*/

    opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    $(document).on('keyup', '#arredondamento', function(e) {
      if (arredondamento.value != "") {
        opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao) + parseFloat(arredondamento.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      } else {
        opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    });

    $(document).on('keyup', '#descontoGlobalValor', function(e) {
      if (descontoGlobalValor.value != "") {
        opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

        descontoGlobalPorcentagem.value = ((parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.')) / parseFloat(totalOpcao)) * 100).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    });

    $(document).on('keyup', '#descontoGlobalPorcentagem', function(e) {
      if (descontoGlobalPorcentagem.value != "") {
        opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

        descontoGlobalValor.value = ((parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.')) / 100) * parseFloat(totalOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    });
  }

  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 = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    sumMp();
    viewConfirmacao();
    outrasOpcoes();
    //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;
    descIdEntidade.innerText = entidade.value;
    descNome.innerText = nomeEntidade.value;
    descMorada.innerText = moradaEntidade.value;
    descNif.innerText = nifEntidade.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>${parseFloat(tabela.rows[i].querySelector(".preco").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".desconto").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".imposto").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".total").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
        </tr>`;
      }
    }
    $("#tabelaConfirmacaoBody").html(rows);
  }

  function funcaoQueryEntidade(id) {
    $.ajax({
      url: "includes/read/searchEntidade.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idEntidade: id,
        idTipoEntidade: tipoEntidade
      },
      success: function(data) {
        const firstNextBtn = document.querySelector(".nextBtn");
        let small = entidade.parentElement.parentElement.querySelectorAll("small")[1];
        if (data == null) {
          if (entidade.value == "") {
            idEntidade = undefined;
            entidade.className = "form-control is-invalid";
            small.style.visibility = "visible";
            small.style.color = "#dc3545";
            small.innerText = "Campo cliente não pode estar vazio!";
            nomeEntidade.value = "";
            moradaEntidade.value = "";
            nifEntidade.value = "";
            firstNextBtn.setAttribute('disabled', 'disabled');
          } else {
            idEntidade = undefined;
            entidade.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!";
            nomeEntidade.value = "";
            moradaEntidade.value = "";
            nifEntidade.value = "";
            firstNextBtn.setAttribute('disabled', 'disabled');
          }
        } else {
          for (var key in data) {
            entidade.className = "form-control";
            small.style.visibility = "hidden";
            idEntidade = data[key]['idEntidade'];
            entidade.value = data[key]['idEntidade'];
            nomeEntidade.value = data[key]['nome'];
            moradaEntidade.value = data[key]['morada'];
            nifEntidade.value = data[key]['nif'];
            linhaPrecoEntidade = data[key]["linhaPreco"];
            firstNextBtn.removeAttribute('disabled');
          }
        }
      }
    }).done(function(data) {
      for (var key in data) {
        $.ajax({
          url: "includes/read/artigo.inc.php",
          type: "post",
          dataType: "json",
          data: {
            linhaPreco: data[key]["linhaPreco"]
          },
          success: function(data) {
            var tabelaArtigoListagem = $("#tabelaArtigoListagem").DataTable();
            tabelaArtigoListagem.clear();
            tabelaArtigoListagem.rows.add(data);
            tabelaArtigoListagem.draw();
          }
        });
      }
    });
  }

  function funcaoQueryArtigo(id, parametro, linhaPreco) {
    $.ajax({
      url: "includes/read/queryArtigoList.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id,
        linhaPreco: linhaPreco != null ? linhaPreco : 0
      },
      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"]);
            if (data[key]["precoSemImposto"] != null) {
              parametro.closest('tr').find('.preco').val(parseFloat(data[key]["precoSemImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
              parametro.closest('tr').find('.total').val(((parseFloat(data[key]["precoSemImposto"])) * parametro.closest('tr').find('.qtd').val()) - (((parseFloat(data[key]["precoSemImposto"])) * parametro.closest('tr').find('.qtd').val()) * parametro.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
            } else {
              parametro.closest('tr').find('.preco').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
              parametro.closest('tr').find('.total').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
            }
            parametro.closest('tr').find('.total').val(parseFloat(parametro.closest('tr').find('.total').val()).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
          }
        } 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();
      if (valor == "") {
        valor = 1;
      } else {
        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"); ?>";
  });

  function entidadeCliente() {
    let entidade = document.querySelector("#entidade");
    entidade.parentElement.parentElement.querySelectorAll('small')[0].innerText = "Cliente";
    entidade.placeholder = "Pesquisar Cliente";
  }

  function entidadeFornecedor() {
    let entidade = document.querySelector("#entidade");
    entidade.parentElement.parentElement.querySelectorAll('small')[0].innerText = "Fornecedor";
    entidade.placeholder = "Pesquisar Fornecedor";
  }

  /*$(document).ready(function() {
    $.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) {
        if ("<?php echo $_GET['idDocumento']; ?>" == "vendaFactura") {
          tipoDoc = 1;
          tipoEntidade = 2;
          $('#tipoDocumento').val(tipoDoc);
          $('#tipoDocumento').select2().trigger('change');
          loadEntidade(tipoEntidade);
          entidadeCliente();
          loadTabelaDocumento(tipoDoc);
        } else if ("<?php echo $_GET['idDocumento']; ?>" == "compraFactura") {
          tipoDoc = 23;
          tipoEntidade = 1;
          $('#tipoDocumento').val(tipoDoc);
          $('#tipoDocumento').select2().trigger('change');
          loadEntidade(tipoEntidade);
          entidadeFornecedor();
          loadTabelaDocumento(tipoDoc);
        }
      });
      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() {
    //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", "#btn-print", function(e) {
    var iframe = document.getElementById('layoutDocumento');
    iframe.contentWindow.print();
  });

  $(document).on('click', '.btn-layout', function(e) {
    e.preventDefault();
    var iframe = document.getElementById('layoutDocumento');

    function loadDocumento() {
      iframe.contentWindow.codigoDocumento(idDoc, tipoDocumento.value);
    }
    iframe.onload = loadDocumento;
    iframe.src = this.id;
    $('#modal-layout').modal('show');

  });

  function readLayout(url, tipoLayout) {
    $.ajax({
      url: url,
      type: "head",
      success: function(data) {
        document.querySelector('iframe').src = url;
        $('#modal-layout').modal('show');
      },
      error: function(data) {
        if (data.status === 404) {
          console.log('O arquivo não existe.');
          createLayout(codigoReport, nomeReport, tipoLayout);
        } else {
          console.error('Erro na verificação do arquivo.');
        }
      }
    });
  }

  $(document).on('click', '#tabelaArtigoListagem tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    $('#tabelaArtigoListagem tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
    }
  });

  $(document).on('click', '#tabelaEntidade tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    $('#tabelaEntidade tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
    }
  });

  $(document).on('click', '#tabelaDocumento tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    let btn = document.querySelectorAll(".btn-layout");
    $('#tabelaDocumento tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
      for (let i = 0; i < btn.length; i++) {
        btn[i].removeAttribute("disabled");
      }
      idDoc = $(this).closest('tr').find('td')[0].innerText;
    } else {
      for (let i = 0; i < btn.length; i++) {
        btn[i].setAttribute("disabled", "disabled");
      }
    }
  });

  $(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 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"
        }],
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "language": idiomaPortugues,
        lengthMenu: [
          [7, 25, 50, -1],
          [10, 25, 50, 'All']
        ]
      }).buttons().container().appendTo('#tabelaArtigoListagem_wrapper .col-md-6:eq(0)');
    });
  });

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

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

    for (i = 1; i < tabela.rows.length; i++) {
      tabela.rows[i].ondblclick = function() {
        funcaoQueryEntidade(this.cells[0].innerText);
        $('#modal-entidade').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);
      }
    });
  });

  function loadTabelaDocumento(tipoDocumento) {
    $.ajax({
      url: "includes/read/documentoTipo.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTipoDoc: tipoDocumento
      },
    }).done(function(data) {
      console.log(data);
      $("#tabelaDocumento").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "codigoDocumento"
        }, {
          data: "entregue",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "troco",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "dataDoc"
        }, {
          data: "nomeU"
        }, {
          data: "total",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "nomeE"
        }, {
          data: null,
          render: function(data, type, row) {
            if (data["entregue"] >= data["total"]) {
              return "<small class='badge badge-success'>Pago</small>";
            } else {
              if (data["entregue"] == 0) {
                return "<small class='badge badge-danger'>Por Pagar</small>";
              } else {
                return "<small class='badge badge-warning'>Pago Parcialmente</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-cancel" style="padding: .8rem; border-radius: 5px;">Anular</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item" style="padding: .8rem; border-radius: 5px;">Duplicar</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item" style="padding: .8rem; border-radius: 5px;">Anular e Duplicar</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 2", "csv", "excel", "pdf", "print", "colvis"],
        order: [
          [3, 'asc']
        ]
      }).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-updateUsuario').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 = parseFloat(parametro.closest('tr').querySelector('.total').value).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    }
    totalDocumento();
    viewConfirmacao();
  }

  $(document).on("change", ".imposto", function(e) {
    e.preventDefault();
    let total = 0;
    if ($(this).closest('tr').find('.total').val() != "") {
      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('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100) * parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.'))) + parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')));
          console.log("Linhas: ", total);
        }
      }
      totalSpan.innerText = total;
      //totalDoc = total;
      totalDocumento();
      sumMp();
      totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    }
  });

  $(document).on("click", "#btn", function(e) {
    e.preventDefault();
    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').modal('show');

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

  function pegarHabilitado() {
    $.ajax({
      url: "includes/read/definicao.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        for (key in data) {
          if (data[key]["idDefinicao"] == 10) {
            if (data[key]['valor'] == 1) {
              habilitado = 1;
            } else {
              habilitado = 2;
            }
          }
        }
      }
    });
  }

  $('#tabelaArtigo').on('click', '.btnSearchArtigo', function() {
    let botao = $(this);
    $("#confirmArticle").click(function() {
      var currentRow = $('#tabelaArtigoListagem tbody tr.selected td'),
        currentID = currentRow[0].textContent,
        stock = Number(currentRow[5].textContent);
      let tabela = document.getElementById("tabelaArtigoListagem");

      if (stock > 0 || habilitado == 1) {
        $.ajax({
          url: "includes/read/queryArtigoList.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idArtigo: currentID,
            linhaPreco: linhaPrecoEntidade
          },
          success: function(data) {
            console.log("Esses são os dados: ", data);
            for (var key in data) {
              botao.closest('tr').find('.inputSearchArtigo').val(data[key]["idArtigo"]);
              botao.closest('tr').find('.descricao').val(data[key]["nome"]);
              if (data[key]["precoSemImposto"] != null) {
                botao.closest('tr').find('.preco').val(parseFloat(data[key]["precoSemImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                botao.closest('tr').find('.total').val(((data[key]["precoSemImposto"]) * botao.closest('tr').find('.qtd').val()) - (((data[key]["precoSemImposto"]) * botao.closest('tr').find('.qtd').val()) * botao.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
              } else {
                botao.closest('tr').find('.preco').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                botao.closest('tr').find('.total').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
              }
              botao.closest('tr').find('.total').val(parseFloat(botao.closest('tr').find('.total').val()).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
              $('#modal-artigo').modal('hide');
            }
          }
        }).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);
          }
        });
      } else {
        $(function() {
          booleano = false;
          var Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000
          });
          Toast.fire({
            icon: 'error',
            title: 'Não está habilitado a venda de Stock Negativo.'
          });
        });
      }

    });
  });

  $('#tabelaArtigo').on('click', '.btnSearchArtigo', function() {
    let botao = $(this);

    $('#modal-artigo').modal('show');
    pegarHabilitado();
    $('#tabelaArtigoListagem tbody').on('click', 'td', function() {

      let tabela = document.getElementById("tabelaArtigoListagem");

      for (i = 1; i < tabela.rows.length; i++) {
        tabela.rows[i].ondblclick = function() {
          var stock = Number(this.cells[5].innerText);
          if (stock > 0 || habilitado == 1) {
            $.ajax({
              url: "includes/read/queryArtigoList.inc.php",
              type: "post",
              dataType: "json",
              data: {
                idArtigo: this.cells[0].innerText,
                linhaPreco: linhaPrecoEntidade
              },
              success: function(data) {
                console.log("Esses são os dados: ", data);
                for (var key in data) {
                  botao.closest('tr').find('.inputSearchArtigo').val(data[key]["idArtigo"]);
                  botao.closest('tr').find('.descricao').val(data[key]["nome"]);
                  if (data[key]["precoSemImposto"] != null) {
                    botao.closest('tr').find('.preco').val(parseFloat(data[key]["precoSemImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                    botao.closest('tr').find('.total').val(((data[key]["precoSemImposto"]) * botao.closest('tr').find('.qtd').val()) - (((data[key]["precoSemImposto"]) * botao.closest('tr').find('.qtd').val()) * botao.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
                  } else {
                    botao.closest('tr').find('.preco').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                    botao.closest('tr').find('.total').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                  }
                  botao.closest('tr').find('.total').val(parseFloat(botao.closest('tr').find('.total').val()).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                  $('#modal-artigo').modal('hide');
                }
              }
            }).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);
              }
            });
          } else {
            $(function() {
              booleano = false;
              var Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
              });
              Toast.fire({
                icon: 'error',
                title: 'Não está habilitado a venda de Stock Negativo.'
              });
            });
          }
        }
      }
    });
  });

  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">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <select class="form-control imposto select2" style="width: 100%;" placeholder="Imposto" title="Imposto">
          </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'
      })
    });
    $.ajax({
      url: "includes/read/imposto.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        for (var key in data) {
          select += "<option value=" + data[key]['taxa'] + " data-taxa=" + data[key]['idImposto'] + ">" + 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;
        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;
        var parts = this.value.replace(/\ /g, '').replace(/\,/g, '.').split('.');
        /*if (parts[1].length > 2) {
          var novoValor = parseFloat(this.value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          this.value = novoValor;
        }*/
        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('.desconto').value != "") {
          totalLinhaArtigo(preco[i]);
        }
        //totalLinhaArtigo(preco[i]);
      });
    }

    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]);
        }
        //totalLinhaArtigo(qtd[i]);
      });
    }

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

    for (let i = 0; i < desconto.length; i++) {
      desconto[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('.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]);
        }
        if (this.value.replace(/\ /g, '') > 100) {
          this.value = 100;
        }
        //totalLinhaArtigo(desconto[i]);
      });

      desconto[i].addEventListener("focusout", function(e) {
        e.preventDefault();
        if (desconto[i].value == "") {
          desconto[i].value = "0";
          totalLinhaArtigo(desconto[i]);
        }
      });
    }
  }

  $('#tabelaDocumento').on('click', '.btn-cancel', function(e) {
    e.preventDefault();
    swal.fire({
      title: "Tem a certeza que pretende anular este documento?",
      text: "Documento: " + $(this).closest('tr').find('td')[0].textContent,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: 'Confirmar',
      confirmButtonColor: '#560085',
      cancelButtonText: 'Cancelar',
      cancelButtonColor: '#560085',
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "includes/read/queryCodigoDocumento.inc.php",
          type: "post",
          dataType: "json",
          data: {
            codigo: $(this).closest('tr').find('td')[0].textContent.split("/")[1],
            tipoDocumento: tipoDocumento.value
          },
          success: function(data) {
            let codigo = data[0]['idDocumento'];

            $.ajax({
              url: "includes/update/estadoDocumento.inc.php",
              type: "post",
              dataType: "json",
              data: {
                idDocumento: codigo,
                estado: 0
              },
              success: function(data) {
                swal.fire({
                  title: "Documento Anulado com sucesso!",
                  text: "Documento anulado",
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: '#560085',
                  icon: "success",
                });
              }
            });
          }
        });
      }
    });
  });

  $('#tabelaDocumento').on('click', '.btn-more', function(e) {
    e.preventDefault();
    //console.log("Esse é o td: ", $(this).closest('tr').find('td')[0].textContent.split("/")[1]);
    detalhes($(this).closest('tr').find('td')[0].textContent.split("/")[1], tipoDocumento.value);
  });

  function detalhes(id, tipoDocumento) {
    detalheCabecalho.innerText = "<?php echo $rows[1]['valor']; ?>";
    $.ajax({
      url: "includes/read/queryCodigoDocumento.inc.php",
      type: "post",
      dataType: "json",
      data: {
        codigo: id,
        tipoDocumento: tipoDocumento
      },
      success: function(data) {
        let codigo = data[0]['idDocumento'];
        $.ajax({
          url: "includes/read/queryDocumentoLinha.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idDocumento: codigo,
          },
          success: function(data) {
            let row = "";
            for (var key in data) {
              row += `
            <tr>
              <td>${data[key]['idArtigoAd']}</td>
              <td>${data[key]['descricaoAd']}</td>
              <td>${parseInt(data[key]['qtdAd']).toFixed(0).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
              <td>${parseFloat(data[key]['precoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
              <td>${parseFloat(data[key]['descontoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
              <td>${parseFloat(data[key]['impostoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</td>
              <td>${parseFloat(data[key]['totalAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
            </tr>
            `;
            }
            $("#corpoTabelaDetalhes").html(row);
          }
        }).done(function() {
          $.ajax({
            url: "includes/read/queryDocumento.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idDocumento: codigo,
            },
            success: function(data) {
              console.log("Aqui: ", data);
              detalheDataActual.innerText = "Data Documento: " + data[0]['dataDoc'];
              detalheCodigo.innerText = data[0]['codigoDocumento'];
              detalheDocumento.innerText = data[0]['nomeTd'];
              detalheSerie.innerText = data[0]['serieDocumento'];
              detalhePrazoPagamento.innerText = data[0]['nomePp'];
              detalheVendedor.innerText = data[0]['nomeU'];
              detalheIdEntidade.innerText = data[0]['idEntidade'];
              detalheNome.innerText = data[0]['nomeE'];
              detalheMorada.innerText = data[0]['moradaE'];
              detalheNif.innerText = data[0]['nifE'];

              let row = `
          <tr>
            <th>Entregue</th>
            <td>${parseFloat(data[0]['entregue']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          </tr>
          <tr>
            <th>Troco</th>
            <td>${parseFloat(data[0]['troco']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          </tr>
          <tr>
            <th>Total</th>
            <td>${parseFloat(data[0]['total']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          </tr>
          `;
              $("#detalheTabelaMontante").html(row);
              if (data[0]["entregue"] >= data[0]["total"]) {
                corpoTabelaDetalhes.innerHTML += `<td colspan="7" style="color: #676767a6; font-size: 4rem; border-bottom: 1px solid #dee2e6;">Pago</td>`;
              } else {
                if (data[0]["entregue"] == 0) {
                  corpoTabelaDetalhes.innerHTML += `<td colspan="7" style="color: #676767a6; font-size: 4rem; border-bottom: 1px solid #dee2e6;">Por Pagar</td>`;
                } else {
                  corpoTabelaDetalhes.innerHTML += `<td colspan="7" style="color: #676767a6; font-size: 4rem; border-bottom: 1px solid #dee2e6;">Pago Parcialmente</td>`;
                }
              }
            }
          }).done(function() {
            $('#modal-detalhes').modal('show');
          });
        });
      }
    });
  }

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


  /*$(document).on("click", "#btn-submit", function(e) {
    e.preventDefault();
    if (nomeUsuario.value != '' && genero.value != 0 && idTipoUsuario.value != 0) {
      let img = $("#file")[0].files;
      usuario(img);
    }
  });*/

  function usuario(img) {
    swal.fire({
      title: "Tem a certeza que pretende editar dados?",
      text: "Usuário: " + nome.value,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: 'Confirmar',
      cancelButtonText: 'Cancelar',
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "includes/update/usuario.inc.php",
          type: "post",
          data: {
            idUsuario: idUsuario,
            nome: nome.value,
            nomeUsuario: nomeUsuario.value,
            genero: genero.value,
            email: email.value,
            bi: bi.value,
            idTipoUsuario: idTipoUsuario.value
          },
          success: function(data) {
            console.log(data);
            nomeEdit.innerText = nome.value;
            generoEdit.innerText = genero.value;
            biEdit.innerText = bi.value;
            emailEdit.innerText = email.value;
            nomeUsuarioEdit.innerText = nomeUsuario.value;
            swal.fire({
              title: "Edição efectuada com sucesso!",
              text: "Usuário " + nome.value + " actualizado!",
              icon: "success",
              confirmButtonText: 'Confirmar',
            }).then(() => {
              if (img[0] != null) {
                foto(idUsuario, img);
              }
            });
          },
          error: function(data) {
            swal.fire({
              title: "Erro ao editar Usuário!",
              text: "Erro ao editar Usuário: " + nome.value + " !",
              confirmButtonText: 'Confirmar',
              icon: "error",
            });
          }
        });
      }
    });
  }

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

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

  $(document).on("click", "#btn-delete", function(e) {
    e.preventDefault();
    console.log(idUsuario);
    swal.fire({
        title: "Tem a certeza que pretende eliminar usuario?",
        text: "usuario: " + nome.value,
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: 'Confirmar',
        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",
            });
          }
        }
      });
  });

  $(document).on("click", "#outrasOpcoes", function(e) {
    e.preventDefault();
    document.querySelector('.tooltip-content').classList.toggle("tooltip-show");
  });
</script>