<?php $page = 'familia';
include('header.php'); ?>

<body class="hold-transition layout-top-nav">
  <div class="wrapper">
    <div class="preloader flex-column justify-content-center align-items-center">
      <img class="animation__shake" src="images/logo/<?php echo $rows[9]['valor']; ?>" alt="AdminLTELogo" height="60" width="60">
    </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-7">
              <div class="card card-default">
                <div class="card-header">
                  <h3 class="card-title">Geral</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">
                  <div class="row">
                    <div class="col-md-2" style="text-align: -webkit-center;">
                      <div class="form-group margem">
                        <div class="wrapper-image">
                          <div class="image-container">
                            <i class="fas fa-image"></i>
                          </div>
                          <label for="file" class="camera-icon">
                            <i class="fas fa-camera"></i>
                          </label>
                          <input type="file" id="file" name="file" accept="image/*" hidden>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group margem" style="margin-bottom: 0;">
                        <small class="not-required">Código</small>
                        <div class="input-group input-group">
                          <input type="text" class="form-control form-control" id="codigo" name="codigo" placeholder="Pesquisar Cliente" title="Pesquisar Cliente">
                          <div class="input-group-append">
                            <button type="button" id="btn-search" 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>
                    <div class="col-md-3">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Tipo</small>
                        <select class="form-control select2" style="width: 100%;" id="Tipo" name="Tipo">
                          <option value="Normal">Normal</option>
                          <option value="Serviço">Serviço</option>
                          <option value="Comentário">Comentário</option>
                        </select>
                        <small>Mensagem de erro</small>
                      </div>
                    </div>
                    <div class="col-md-2">
                    </div>
                    <div class="col-md-2">
                    </div>
                    <div class="col-md-2">
                    </div>
                    <div class="col-md-3">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="required">Nome</small>
                        <input type="text" class="form-control" id="nome" name="nome" placeholder="Nome do Artigo" title="Nome do Artigo" required>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Código de Barras</small>
                        <input type="text" class="form-control" id="codigoBarra" name="codigoBarra" placeholder="Código de Barras" title="Código de Barras" required>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Tipo de Stock</small>
                        <select class="form-control select2" style="width: 100%;" id="tipoStock" name="tipoStock">
                          <option value="Mercadorias">Mercadorias</option>
                          <option value="Matérias primas, subsidiárias e de consumo">Matérias primas, subsidiárias e de consumo</option>
                          <option value="Productos acabados e intermédios">Productos acabados e intermédios</option>
                          <option value="Subproductos, desperdícios e refugos">Subproductos, desperdícios e refugos</option>
                          <option value="Productos e trabalhos em curso">Productos e trabalhos em curso</option>
                          <option value="Activos biológicos">Activos biológicos</option>
                        </select>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <div class="custom-control custom-checkbox">
                          <input class="custom-control-input" type="checkbox" id="controlaStock" value="0">
                          <label for="controlaStock" class="custom-control-label">Controla Stock</label>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="required">Nome Curto</small>
                        <input type="text" class="form-control" id="nomeCurto" name="nomeCurto" placeholder="Nome Curto" title="Nome Curto" required>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="required">Família</small>
                        <select class="form-control select2" style="width: 100%;" id="idFamilia" name="idFamilia">
                          <option value="0">Selecione a Família</option>
                        </select>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Aviso stock minímo</small>
                        <select class="form-control select2" style="width: 100%;" id="avisoStockMinimo" name="avisoStockMinimo">
                          <option value="Usar definições de armazém">Usar definições de armazém</option>
                          <option value="Avisa">Avisa</option>
                          <option value="Não avisa">Não avisa</option>
                        </select>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <div class="custom-control custom-checkbox">
                          <input class="custom-control-input" type="checkbox" id="descontinuado" value="0">
                          <label for="descontinuado" class="custom-control-label">Descontinuado</label>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Data de Criação</small>
                        <input type="date" class="form-control" id="dataActual" name="dataActual" placeholder="Data" title="Data" disabled>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Taxa</small>
                        <select class="form-control select2" style="width: 100%;" id="idTaxa" name="idTaxa">
                          <option value="0">Selecione Taxa</option>
                        </select>
                        <small>Mensagem de erro</small>
                      </div>
                      <div class="form-group" style="margin-bottom: 0;">
                        <small class="not-required">Stock a negativo</small>
                        <select class="form-control select2" style="width: 100%;" id="stockNegativo" name="stockNegativo">
                          <option value="Usar definições de armazém">Usar definições de armazém</option>
                          <option value="Permitido">Permitido</option>
                          <option value="Não Permitido">Não Permitido</option>
                        </select>
                        <small>Mensagem de erro</small>
                      </div>
                    </div>
                    <!-- /.col -->
                  </div>
                  <!-- /.row -->
                </div>
              </div>
            </div>
            <div class="col-md-5">
              <div class="card card-default">
                <div class="card-header">
                  <h3 class="card-title">Preços</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">
                  <div class="row">
                    <div class="col-md-12">
                      <div class="form-group">
                        <table name="tabelaLinhaPreco" id="tabelaLinhaPreco" class="table-sm" style="min-width: 100%; max-width: 100%;">
                          <thead>
                            <tr style="text-align: center;">
                              <th scope="col"></th>
                              <th scope="col">S/Imp.</th>
                              <th scope="col">C/Imp.</th>
                              <th scope="col">Margem</th>
                            </tr>
                          </thead>
                          <tbody id="corpoTabela">
                            <tr style="text-align: center;">
                              <td>Preço de Custo:</td>
                              <td>
                                <div class="">
                                  <div class="form-group" style="margin-bottom: 0;">
                                    <input type="text" class="form-control" id="precoCustoSemImp" name="precoCustoSemImp" placeholder="0,00 Kzs" title="Data">
                                  </div>
                                </div>
                              </td>
                              <td>
                                <div class="">
                                  <div class="form-group" style="margin-bottom: 0;">
                                    <input type="text" class="form-control" id="precoCustoComImp" name="precoCustoComImp" placeholder="0,00 Kzs" title="Data">
                                  </div>
                                </div>
                              </td>
                              <td></td>
                              <td></td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group" style="margin-bottom: 0;">
                        <div class="custom-control custom-checkbox">
                          <input class="custom-control-input" type="checkbox" id="pedePreco" value="0">
                          <label for="pedePreco" class="custom-control-label">Pede preço quando é zero</label>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group" style="margin-bottom: 0;">
                        <div class="custom-control custom-checkbox">
                          <input class="custom-control-input" type="checkbox" id="precoCustoFixo" value="0">
                          <label for="precoCustoFixo" class="custom-control-label">Preço de custo fixo</label>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- /.col -->
                </div>
                <!-- /.row -->
              </div>
            </div>
          </div>
        </div>
        <!-- /.card -->
    </div>
    <!-- /.container-fluid -->
    </section>
  </div>
  <!-- /.content-wrapper -->
  <?php include('footer.php'); ?>
</body>

</html>
<script src="./validation/tipoMatricula.js"></script>
<script>
  let imposto;

  $(document).on("keyup", "#precoCustoSemImp", function(e) {
    e.preventDefault();
    var removeChar = this.value.replace(/[^0-9\.]/g, '');
    var removeDot = removeChar.replace(/\./g, '');
    this.value = removeDot;
    var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    this.value = formatedNumber;
    precoCustoComImp.value = parseInt(this.value.replace(/\./g, '')) + parseInt(this.value.replace(/\./g, '') * imposto.split('.')[0] / 100);
    precoCustoComImp.value = precoCustoComImp.value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
    for (let i = 0; i < tr.length; i++) {
      let input = tr[i].getElementsByTagName("input");
      let sImp = tr[i].querySelectorAll('.sImp');
      let cImp = tr[i].querySelectorAll('.cImp');
      let margem = tr[i].querySelectorAll('.margem');
      
      for(let i = 0; i < sImp.length; i++){
        if(sImp[i].value != ""){
          console.log("Está aqui: ", sImp[i]);
          margem[i].value = (cImp[i].value.replace(/\./g, '') - precoCustoComImp.value.replace(/\./g, '')) / precoCustoComImp.value.replace(/\./g, '') * 100;
        }
      }
    }
  });

  $(document).on("keyup", "#precoCustoComImp", function(e) {
    e.preventDefault();
    var removeChar = this.value.replace(/[^0-9\.]/g, '');
    var removeDot = removeChar.replace(/\./g, '');
    this.value = removeDot;
    var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    //var formatedNumber = parseFloat(this.value).toLocaleString('pt-AO', { minimumFractionDigits: 2 });
    this.value = formatedNumber;
    precoCustoSemImp.value = Math.round(parseFloat(this.value.replace(/\./g, '')) / parseFloat(1 + (imposto.split('.')[0] / 100)));
    precoCustoSemImp.value = precoCustoSemImp.value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
    for (let i = 0; i < tr.length; i++) {
      let input = tr[i].getElementsByTagName("input");
      let sImp = tr[i].querySelectorAll('.sImp');
      let cImp = tr[i].querySelectorAll('.cImp');
      let margem = tr[i].querySelectorAll('.margem');
      
      for(let j = 0; j < sImp.length; j++){
        if(sImp[j].value != ""){
          console.log("Está aqui: ", sImp[j]);
          margem[j].value = (cImp[j].value.replace(/\./g, '') - precoCustoComImp.value.replace(/\./g, '')) / precoCustoComImp.value.replace(/\./g, '') * 100;
        }
      }
    }
  });

  $(document).on("keyup", ".margem", function(e) {
    e.preventDefault();
    var removeChar = this.value.replace(/[^0-9\.]/g, '');
    var removeDot = removeChar.replace(/\./g, '');
    this.value = removeDot;
    var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    this.value = formatedNumber;
    if (precoCustoComImp.value != "" && precoCustoSemImp.value != "") {
      let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
      for (let i = 0; i < tr.length; i++) {
        let input = tr[i].getElementsByTagName("input");
        let sImp = tr[i].querySelectorAll('.sImp');
        let cImp = tr[i].querySelectorAll('.cImp');
        let margem = tr[i].querySelectorAll('.margem');

        for (let i = 0; i < margem.length; i++) {
          margem[i].addEventListener("keyup", function() {
            sImp[i].value = parseFloat(precoCustoSemImp.value.replace(/\./g, '')) + (parseFloat(precoCustoSemImp.value.replace(/\./g, '')) * parseFloat((margem[i].value.replace(/\./g, '') / 100)));
            sImp[i].value = sImp[i].value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");

            cImp[i].value = parseFloat(precoCustoComImp.value.replace(/\./g, '')) + (parseFloat(precoCustoComImp.value.replace(/\./g, '')) * parseFloat((margem[i].value.replace(/\./g, '') / 100)));
            cImp[i].value = cImp[i].value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
          });
        }

      }
    }
  });

  $(document).on("keyup", ".sImp", function(e) {
    e.preventDefault();
    let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
    for (let i = 0; i < tr.length; i++) {
      let input = tr[i].getElementsByTagName("input");
      let sImp = tr[i].querySelectorAll('.sImp');
      let cImp = tr[i].querySelectorAll('.cImp');
      let margem = tr[i].querySelectorAll('.margem');

      for (let i = 0; i < input.length; i++) {
        input[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;
        });
      }

      for (let i = 0; i < sImp.length; i++) {
        sImp[i].addEventListener("keyup", function() {
          cImp[i].value = parseInt(sImp[i].value.replace(/\./g, '')) + parseInt((sImp[i].value.replace(/\./g, '') * imposto.split('.')[0] / 100));
          cImp[i].value = cImp[i].value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
          if (precoCustoComImp.value != "" && precoCustoSemImp.value != "") {
            margem[i].value = (sImp[i].value.replace(/\./g, '') - precoCustoSemImp.value.replace(/\./g, '')) / precoCustoSemImp.value.replace(/\./g, '') * 100;
          }
        });
      }
    }
  });

  $(document).on("keyup", ".cImp", function(e) {
    e.preventDefault();
    let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
    for (let i = 0; i < tr.length; i++) {
      let input = tr[i].getElementsByTagName("input");
      let sImp = tr[i].querySelectorAll('.sImp');
      let cImp = tr[i].querySelectorAll('.cImp');
      let margem = tr[i].querySelectorAll('.margem');

      for (let i = 0; i < input.length; i++) {
        input[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;
        });
      }

      for (let i = 0; i < cImp.length; i++) {
        cImp[i].addEventListener("keyup", function() {
          sImp[i].value = parseInt(cImp[i].value.replace(/\./g, '')) - parseInt((cImp[i].value.replace(/\./g, '') * imposto.split('.')[0] / 100));
          sImp[i].value = sImp[i].value.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
          if (precoCustoComImp.value != "" && precoCustoSemImp.value != "") {
            margem[i].value = (cImp[i].value.replace(/\./g, '') - precoCustoComImp.value.replace(/\./g, '')) / precoCustoComImp.value.replace(/\./g, '') * 100;
          }
        });
      }
    }
  });

  $(document).on("change", "#idTaxa", function(e) {
    e.preventDefault();
    $.ajax({
      url: "includes/read/queryValorImposto.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTaxa: this.value,
      },
      success: function(data) {
        imposto = data[0]["taxaImposto"];
        console.log(imposto);
      }
    });
  });

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

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

  function linhaPreco() {
    $.ajax({
      url: "includes/read/definicao.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        console.log("Dados: ", data[0]["valor"]);
        for (let i = 0; i < data[0]["valor"]; i++) {
          let select = `
        <tr style="text-align: center;" class="trPreco">
          <td>P.Venda (${i + 1}):</td>
          <td>
            <div class="">
              <div class="form-group" style="margin-bottom: 0;">
                <input type="text" class="form-control sImp" id="dataActual" name="dataActual" placeholder="0,00 Kzs" title="Sem Imposto">
              </div>
            </div>
          </td>
          <td>
            <div class="">
              <div class="form-group" style="margin-bottom: 0;">
                <input type="text" class="form-control cImp" id="dataActual" name="dataActual" placeholder="0,00 Kzs" title="Com Imposto">
              </div>
            </div>
          </td>
          <td>
            <div class="">
              <div class="form-group" style="margin-bottom: 0;">
                <input type="text" class="form-control margem" id="dataActual" name="dataActual" placeholder="0,00 Kzs" title="Margem de Lucro">
              </div>
            </div>
          </td>
        </tr>
        `;
          $("#corpoTabela").append(select);
        }

        $("#corpoTabela").append(`<tr style="text-align: center;">
          <td>Comissão:</td>
          <td>
            <div class="">
              <div class="form-group" style="margin-bottom: 0;">
                <input type="text" class="form-control" id="comissao" name="comissao" placeholder="0,00 Kzs" title="Data">
              </div>
            </div>
          </td>
          <td></td>
          <td></td>
          <td></td>
        </tr>`);
      }
    }).done(function(data) {
      let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
      for (let i = 0; i < tr.length; i++) {
        let input = tr[i].getElementsByTagName("input");
        console.log("tr: ", tr[i], " ", i);

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

        }
      }
    });
  }

  $(document).ready(function() {
    formArtigoButton();
    listagemTaxa();
    listagemFamilia();
    codigoArtigo();
    linhaPreco();
    dataActual.value = "<?php echo date("Y-m-d"); ?>";
  });

  $(window.parent.document).on("click", "#btn-submit", function(e) {
    e.preventDefault();
    if (nome.value != '' && nomeCurto.value != '' && idFamilia.value != 0) {
      let img = $("#file")[0].files;
      artigo(img);
    }
  });

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

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

  function insertPreco(idArtigo) {
    let tr = document.querySelectorAll("#tabelaLinhaPreco .trPreco");
    for (let i = 0; i < tr.length; i++) {
      let input = tr[i].getElementsByTagName("input");
      console.log("tr: ", tr[i], " ", i);

      $.ajax({
        url: "includes/create/precoArtigo.inc.php",
        type: "post",
        data: {
          idArtigo: idArtigo,
          semImposto: input[0].value.replace(/\./g, ''),
          comImposto: input[1].value.replace(/\./g, ''),
          margem: input[2].value.replace(/\./g, '')
        },
        success: function(data) {
          console.log("Resultados: ", data);
          
        }
      });
    }
  }

  function artigo(img) {
    $.ajax({
      url: "includes/create/artigo.inc.php",
      type: "post",
      data: {
        idFamilia: idFamilia.value,
        nome: nome.value,
        nomeCurto: nomeCurto.value,
        codigoBarra: codigoBarra.value,
        unidadeVenda: 0,
        descontinuado: descontinuado.value,
        controlaStock: controlaStock.value,
        precoCustoSemImp: precoCustoSemImp.value.replace(/\./g, ''),
        precoCustoComImp: precoCustoComImp.value.replace(/\./g, ''),
        comissao: comissao.value
      },
      success: function(data) {
        swal.fire({
          title: "Cadastro efectuado com sucesso!",
          text: "Entidade " + nome.value + " cadastrada!",
          confirmButtonText: 'Confirmar',
          icon: "success",
        }).then(() => {
          insertPreco(data);
          if (img[0] != null) {
            foto(data, img);
          }
        });

        $('#idFamilia').val(0);
        $('#idFamilia').select2().trigger('change');

        nome.value = "";
        nome.className = "form-control";
        nomeCurto.value = "";
        nomeCurto.className = "form-control";
        codigoBarra.value = "";
        codigoBarra.className = "form-control";
        //unidadeVenda.value = "";
        //unidadeVenda.className = "form-control";

        controlaStock.checked = false;
        descontinuado.checked = false;
      },
      error: function(data) {
        swal.fire({
          title: "Erro ao Cadastrar nome!",
          text: "Erro ao Cadastrar nome: " + nome.value + " !",
          confirmButtonText: 'Confirmar',
          icon: "error",
        });
      }
    }).done(function(data) {
      formArtigoButton();
      listagemFamilia();
      codigoArtigo();
      dataActual.value = "<?php echo date("Y-m-d"); ?>";
      console.log(data);
    });
  }
</script>