<?php include('header.php'); ?>

<style>
  .nav-item.active {
    background-color: rgba(85, 18, 124, 0.15);
  }

  a * {
    pointer-events: none !important;
  }
</style>

<body class="hold-transition layout-top-nav">
  <div class="wrapper">
    <div class="preloader flex-column justify-content-center align-items-center">
      <img src="images/logo/logobue.svg" alt="LOGO-BUESIMPLES" height="auto" width="350">
    </div>
    <?php include('nav.php'); ?>
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper iframe-mode" data-widget="iframe" data-loading-screen="750">
      <div class="nav navbar navbar-expand navbar-white navbar-light border-bottom p-0">
        <div class="nav-item dropdown">
          <a class="nav-link bg-danger dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Fechar</a>
          <div class="dropdown-menu mt-0">
            <a class="dropdown-item" href="#" data-widget="iframe-close" data-type="all">Fechar Todas</a>
            <a class="dropdown-item" href="#" data-widget="iframe-close" data-type="all-other">Fechar Todas Outras</a>
          </div>
        </div>
        <a class="nav-link bg-light" href="#" data-widget="iframe-scrollleft"><i class="fas fa-angle-double-left"></i></a>
        <ul class="navbar-nav overflow-hidden" role="tablist" id="navTablist">
          <li class="nav-item active" role="presentation"><a href="#" class="btn-iframe-close" data-widget="iframe-close" data-type="only-this"><i class="fas fa-times"></i></a><a class="nav-link active" data-toggle="row" id="tab-index-html" href="#panel-index-html" role="tab" aria-controls="panel-index-html" aria-selected="true">Dashboard</a></li>
        </ul>
        <a class="nav-link bg-light" href="#" data-widget="iframe-scrollright"><i class="fas fa-angle-double-right"></i></a>
        <a class="nav-link bg-light" href="#" data-widget="iframe-fullscreen"><i class="fas fa-expand"></i></a>
      </div>
      <div class="tab-content">
        <div class="tab-empty">
          <img src="images/logo/logobue.svg" alt="AdminLTELogo" height="auto" width="500">
        </div>
        <div class="tab-loading">
        </div>
        <div class="tab-pane fade" id="panel-index-html" role="tabpanel" aria-labelledby="tab-index-html"><iframe src="./dashboard.php"></iframe></div>
      </div>
    </div>
    <aside class="control-sidebar control-sidebar-dark">
      <!-- Control sidebar content goes here -->
    </aside>
    <!-- /.control-sidebar -->

    <!-- Main Footer -->
    <div class="modal fade" id="modal-saft">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <div class="container">
              <div class="progress-barra">
                <div style="position: relative; text-align: center; width: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column;">
                  <p style="margin: 0;">SAFT</p>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-body">
            <div class="container">
              <div class="card-body" style="padding: 0;">
                <div class="formulario">
                  <div class="col-md-12">
                    <div class="row">
                      <div class="col-md-12">
                        <div class="row" style="display: flex; justify-content: center;">
                          <div class="col-md-4">
                            <div class="form-group" style="margin-bottom: 0; text-align: center; display: block;">
                              <small class="not-required">Versão</small>
                              <select class="form-control select2" style="width: 100%;" id="Tipo" name="Tipo">
                                <option value="Normal">SAFT(AO) 1.01</option>
                              </select>
                              <small>Mensagem de erro</small>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="col-md-12">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="required">NIF (Número de Identificação Fiscal)</small>
                          <input type="text" class="form-control" id="nif" name="nif" placeholder="" title="">
                          <small>Mensagem de erro</small>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="required">Nome do Ficheiro</small>
                          <input type="text" class="form-control" id="nomeFicheiro" name="nomeFicheiro" placeholder="Nome do Ficheiro" title="Nome do Ficheiro" required>
                          <small>Mensagem de erro</small>
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Data Inicial</small>
                          <input type="date" class="form-control" id="dataInicial" name="dataInicial" placeholder="Data Inicial" title="Data Inicial">
                          <small>Mensagem de erro</small>
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group" style="margin-bottom: 0;">
                          <small class="not-required">Data Final</small>
                          <input type="date" class="form-control" id="dataFinal" name="dataFinal" placeholder="Data Final" title="Data Final">
                          <small>Mensagem de erro</small>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <div class="col-md-12">
              <div class="row">
                <div class="col-md-6">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </div>
                <div class="col-md-6" style="text-align: end;">
                  <button type="button" class="btn btn-default">Verificar Dados</button>
                  <button type="button" class="btn btn-primary" id="btn-saft">Exportar</button>
                </div>
              </div>
            </div>

          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <div class="modal fade" id="modal-licenciamento">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <div class="container">
              <div class="progress-barra">
                <div style="position: relative; text-align: center; width: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column;">
                  <p style="margin: 0;">LICENCIAMENTO BUÉSIMPLES</p>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-body">
            <div class="container">
              <div class="card-body" style="padding: 0;">
                <div class="login-logo logo" style="padding-top: 20px;">
                  <img style="width: 40%;" src="images/logo/logo.svg" alt="Imagem Buesimples" class="brand-image">
                </div>
                <div class="formulario">
                  <div class="col-md-12">
                    <div class="row">
                      <div class="col-md-12">
                        <div class="row" style="display: flex; justify-content: center;">
                          <div class="col-md-4">
                            <div class="form-group" style="margin-bottom: 0; text-align: center; display: block;">
                              <h6>Válido até <strong><?php echo $rows[12]['valor']; ?></strong></h6>
                              <h6>Licença obtida por:</h6>
                              <h6><strong><?php echo $rows[1]['valor']; ?></strong></h6>
                              <h6><?php echo $rows[3]['valor']; ?></h6>
                              <h6><?php echo $rows[10]['valor']; ?></h6>
                              <h6><?php echo $rows[11]['valor']; ?></h6>
                              <br>
                              <h6>Número de contribuinte: <?php echo $rows[6]['valor']; ?></h6>
                              <h6>Email: <?php echo $rows[5]['valor']; ?></h6>
                              <h6>Número de Telefone: <?php echo $rows[4]['valor']; ?></h6>
                              <br>
                              <h6>Licença vendida pelo parceiro: <strong><?php echo $rows[13]['valor']; ?></strong></h6>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <footer class="main-footer">
      <!-- To the right -->

      <!-- Default to the left -->
      <strong><?php echo $rows[2]['valor']; ?><script>
          document.write(new Date().getFullYear());
        </script> <a href="<?php echo $rows[7]['valor']; ?>" target="_blank"><?php echo $rows[1]['valor']; ?></a>.</strong> Todos os direitos reservados.
      <div class="float-right d-none d-sm-inline-block">
        <p>Validade da Licença - <b><span id="countdown"></span></b></p>
      </div>
    </footer>
    <script>
      var boleano = false;
      const endDate = new Date("<?php echo $rows[12]['valor']; ?>").getTime();

      function updateCountdown() {
        const now = new Date();
        const timeLeft = endDate - now;

        const dias = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
        const horas = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutos = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
        const segundos = Math.floor((timeLeft % (1000 * 60)) / 1000);

        const countdownString = `${dias} dias, ${horas} horas, ${minutos} minutos, ${segundos} segundos`;
        document.getElementById('countdown').textContent = countdownString;

        if (dias <= 60 && boleano == false) {
          Swal.fire({
            title: 'Aviso de expiração de licença!',
            text: `A licença do seu portal expirará dentro de ${dias === 1 ? dias + " dia" : dias + " dias"}.`,
            confirmButtonText: 'Confirmar',
            confirmButtonColor: "#55127c",
            icon: 'warning'
          });
          boleano = true;
        }

        if (timeLeft <= 0 && boleano == false) {
          document.getElementById('countdown').textContent = "Licença expirada!";
          //return;
          Swal.fire({
            title: 'Aviso de expiração de licença!',
            text: `A licença do seu portal encontra-se expirada. Entre em contacto com o seu fornecedor`,
            confirmButtonText: 'Confirmar',
            showConfirmButton: false,
            confirmButtonColor: "#55127c",
            icon: 'error',
            allowOutsideClick: false
          });
          boleano = true;
        }
      }

      setInterval(updateCountdown, 1000);
      updateCountdown();
    </script>
  </div>
  <!-- ./wrapper -->

  <!-- REQUIRED SCRIPTS -->

  <!-- jQuery -->
  <script src="template/plugins/jquery/jquery.min.js"></script>
  <!-- Bootstrap 4 -->
  <script src="template/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
  <!-- AdminLTE App -->
  <script src="template/dist/js/adminlte.min.js"></script>
  <!-- AdminLTE for demo purposes -->
  <script src="template/dist/js/demo.js"></script>
  <script src="template/plugins/select2/js/select2.full.min.js"></script>
  <script src="../js/thousandSeparator.js"></script>
  <script src="../js/sweetalert2.min.js"></script>
  <script src="./template/dist/js/function.js"></script>

  <script>
    $('#navTablist li a').click(function(event) {
      event.preventDefault();

      $('iframe').each(function() {
        this.contentWindow.location.reload();
      });
    });
  </script>

  <script>
    $(function() {
      //Initialize Select2 Elements
      $('.select2').select2()

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

    let btnLogout = document.getElementById("btn-logout");
    btnLogout.addEventListener("click", function(e) {
      e.preventDefault();
      swal.fire({
          title: "Terminar sessão?",
          text: "Tem a certeza que pretende terminar a sessão?",
          icon: "warning",
          showCancelButton: true,
          confirmButtonText: 'Confirmar',
          confirmButtonColor: '#560085',
          cancelButtonText: 'Cancelar',
          cancelButtonColor: '#560085',
        })
        .then((result) => {
          if (result.isConfirmed) {
            window.location.href = "includes/login/logout.inc.php";
          }
        });
    });

    $(document).on("click", "#btn-saft", function(e) {
      e.preventDefault();
      $.ajax({
        url: "./saft/saft.php",
        type: "post",
        dataType: 'json',
        data: {
          dataInicial: dataInicial.value,
          dataFinal: dataFinal.value,
          nomeFicheiro: nomeFicheiro.value
        },
        success: function(response) {
          console.log(response);
          console.log('Conteúdo do XML:', response.xmlString);


          var blob = new Blob([response.xmlString], {
            type: 'application/xml'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = response.filename + '.xml';
          link.textContent = 'Download XML';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        },
        error: function(error) {
          console.error(error);
        }
      });
      swal.fire({
        title: "Ficheiro SAFT Exportado com Sucesso!",
        text: "O seu ficheiro SAFT foi exportando com sucesso",
        confirmButtonText: 'Confirmar',
        confirmButtonColor: '#560085',
        icon: "success",
      });
      $('#modal-saft').modal('hide');
    });

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

    $(document).on("click", "#saftVendaMensal", function(e) {
      nif.value = "<?php echo $rows[6]['valor']; ?>";
      nomeFicheiro.value = "SAFT_AO_VENDAS_" + new Date().getFullYear() + "_" + new Date().getMonth();
      dataInicialFinalMensal();
      $('#modal-saft').modal('show');
    });

    $(document).on("click", "#saftVendaGlobal", function(e) {
      nif.value = "<?php echo $rows[6]['valor']; ?>";
      nomeFicheiro.value = "SAFT_AO_VENDAS_" + new Date().getFullYear();
      dataInicialFinalGlobal();
      $('#modal-saft').modal('show');
    });

    $(document).on("click", "#saftCompraMensal", function(e) {
      nif.value = "<?php echo $rows[6]['valor']; ?>";
      nomeFicheiro.value = "SAFT_AO_COMPRAS_" + new Date().getFullYear() + "_" + new Date().getMonth();
      dataInicialFinalMensal();
      $('#modal-saft').modal('show');
    });

    $(document).on("click", "#saftCompraGlobal", function(e) {
      nif.value = "<?php echo $rows[6]['valor']; ?>";
      nomeFicheiro.value = "SAFT_AO_COMPRAS_" + new Date().getFullYear();
      dataInicialFinalGlobal();
      $('#modal-saft').modal('show');
    });

    function dataInicialFinalMensal() {
      var dataAtual = new Date();
      dataAtual.setMonth(dataAtual.getMonth() - 1);
      dataAtual.setDate(1);
      var dataFormatada = dataAtual.toISOString().split('T')[0];
      dataInicial.value = dataFormatada;

      var dataAtualFinal = new Date();
      dataAtualFinal.setMonth(dataAtualFinal.getMonth());
      dataAtualFinal.setDate(0);
      dataFinal.value = dataAtualFinal.toISOString().split('T')[0];
    }

    function dataInicialFinalGlobal() {
      var dataAtual = new Date();
      dataAtual.setMonth(0);
      dataAtual.setDate(1);
      var dataFormatada = dataAtual.toISOString().split('T')[0];
      dataInicial.value = dataFormatada;

      var dataAtualFinal = new Date();
      dataAtualFinal.setMonth(12);
      dataAtualFinal.setDate(0);
      dataFinal.value = dataAtualFinal.toISOString().split('T')[0];
    }

    $('.content-wrapper').IFrame({
      onTabClick(item) {
        let elemento = item.innerText;
        let iframe = document.querySelector('#' + item.href.split('#')[1]);
        if (elemento == "Factura" || elemento == "Factura (C)") {
          let prazoPagamento = iframe.querySelector('iframe').contentDocument.querySelector('#prazoPagamento');
          let tipoDocumento = iframe.querySelector('iframe').contentDocument.querySelector('#tipoDocumento');
          let tabelaDocumento = iframe.querySelector('iframe').contentDocument.querySelector('#tabelaDocumento');
          selectBoxPrazoPagamento(prazoPagamento);
          tabelaDoc(tabelaDocumento, tipoDocumento.value);
        } else if (elemento == "Factura Recibo" || elemento == "Factura Recibo (C)") {
          selectBoxPrazoPagamento(iframe.querySelector('iframe').contentDocument.querySelector('#prazoPagamento'));
        } else if (elemento == "Recibo" || elemento == "Recibo (C)") {

        }
        /*let elemento = item.innerText;
        let iframe = document.querySelector('#' + item.href.split('#')[1]);
        if(elemento == "Factura" || elemento == "Factura (C)"){
          let prazoPagamento = iframe.querySelector('iframe').contentDocument.querySelector('#prazoPagamento');
          let tipoDocumento = iframe.querySelector('iframe').contentDocument.querySelector('#tipoDocumento');
          let tabelaDocumento = iframe.querySelector('iframe').contentDocument.querySelector('#tabelaDocumento');
          selectBoxPrazoPagamento(prazoPagamento);
          tabelaDoc(tabelaDocumento, tipoDocumento.value);
        } else if(elemento == "Factura Recibo" || elemento == "Factura Recibo (C)"){
          selectBoxPrazoPagamento(iframe.querySelector('iframe').contentDocument.querySelector('#prazoPagamento'));
        } else if(elemento == "Recibo" || elemento == "Recibo (C)"){

        }*/
      }
    });
  </script>


  <script>
    //  Seeder Estados Requisicao

    seedTable('estados', [{
        estado: 'Novo'
      },
      {
        estado: 'Pendente'
      },
      {
        estado: 'Aprovado'
      },
    ]);



    // End Seeder Estados Requisicao





    const itemsInTreeview = ['treeviewItem-1', 'treeviewItem-21', 'treeviewItem-31', 'treeviewItem-42',
      'treeviewItem-47', 'treeviewItem-50', 'treeviewItem-76', 'treeviewItem-93'
    ];
    let currentLink = null;

    $(document).ready(function() {


      $('#navTablist').on('click', 'li', function(evt) {

        const targetBtn = evt.target;
        if ($(targetBtn).hasClass('btn-iframe-close')) {
          let li = $('#navTablist li.active').prev();
          let navLink = li.find('.nav-link');


          changeItemState(navLink.text());

          li.addClass('active');
          navLink.addClass('active');

          console.log("BBBBBBBBBB: ", li);
          console.log("AAAAAAA: ", navLink);

        } else {
          changeItemState($(this).find('.nav-link').text());
        }

      });

    });

    function changeItemState(currentText) {
      // alert(currentText)
      getMenus.forEach(menu => {
        let parentMenu = !menu.parent_id ? menu.item : null

        if (menu.item == currentText) {
          let itemText = getMenus[menu.parent_id - 1].item;

          links.forEach(link => {
            if (parentNode.includes(itemText) && link.innerText == itemText) {
              link.classList.forEach(className => {
                if (itemsInTreeview.includes(className)) {
                  currentLink = link;
                  return;
                }
              });
            }
          });
        }
      });

      links.forEach(ll => ll.classList.remove('selectedAc'));
      $(currentLink).addClass('selectedAc');

      $.each($('iframe'), (key, frame) => {
        const src = $(frame).attr('src');
        $(frame).attr('src', src);
      });
    }
  </script>



</body>

</html>