<?php include('./header.php'); ?>
<style type="text/css">
   .styled {
      display: flex;
      margin-right: 10px;
      align-items: center;
      justify-content: center;
      background-color: #55127C;
      color: #fff !important;
      width: 60px;
      height: 21px;
      font-size: 12px !important;
      aspect-ratio: 1/1;
      border-radius: 0.15rem;
   }

   #corpoP.active thead,
   #corpoR.active thead {
      display: none !important;
   }

   a>* {
      pointer-events: none;
   }

   .separatedLines {
      background-color: #66009f;
      border-radius: 4px 4px 0 0;
      color: #fff;
   }

   .separatedLines th+th {
      /* border-left: solid 1px #c3d4da !important; */
      border-left: solid 1px #fff !important;
   }

   .default-checkbox {
      -webkit-appearance: none;
      appearance: none;
      width: 20px;
      height: 20px;
      border: solid 1px #cad3d4;
      border-radius: 0.15rem;
      background-color: #fff;
      cursor: pointer;
      user-select: none;
      position: relative;
      transition: 0.25s ease-in-out;
      z-index: 10;
      color: #fff;
   }

   .default-checkbox::after {
      content: '\2713';
      position: absolute;
      color: #fff !important;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 12px;
      transition: 0.15s ease-in-out;
      opacity: 0;
      z-index: 11;
   }

   .default-checkbox:checked {
      background-color: #66009f;
   }

   .default-checkbox:checked::after {
      color: #fff !important;
      opacity: 1;
   }

   .separatedLines th:first-child {
      /* text-align: left; */
      /* padding-left: 3.1rem; */
   }

   .logo img {
      width: 150px;
   }

   .container .form-outer {
      width: 100%;
      overflow: hidden;
   }

   .form-outer .formulario {
      display: flex;
      width: 400%;
   }

   .form-outer .formulario .page {
      width: 25%;
      transition: margin-left 0.3s ease-in-out;
   }

   .form-outer .formulario .page .field {
      display: flex;
   }

   .form-outer .formulario .page .field button:hover {
      background-color: #66009f;
      border-color: #66009f;
   }

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

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

   .formulario .page .btns button.next {
      margin-left: 3px !important;
   }

   .container .progress-barra {
      display: flex;
      justify-content: space-between;
   }

   .container .progress-barra .step {
      position: relative;
      text-align: center;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
   }

   .progress-barra .step p {
      font-size: 14px;
      font-weight: 500;
      color: #666;
      margin-bottom: 8px;
      transition: 0.2s;
   }

   .progress-barra .step p.active {
      color: #560085;
   }

   .progress-barra .step .bullet {
      position: relative;
      height: 35px;
      width: 35px;
      border: 2px solid #666;
      display: inline-block;
      border-radius: 50%;
      transition: 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
   }

   .progress-barra .step .bullet.active {
      border-color: #560085;
      background: #560085;
   }

   .progress-barra .step .bullet span {
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
   }

   .progress-barra .step .bullet.active span {
      display: none;
   }

   .progress-barra .step:last-child .bullet:before,
   .progress-barra .step:last-child .bullet:after {
      display: none;
   }

   .progress-barra .step .bullet:before,
   .progress-barra .step .bullet:after {
      position: absolute;
      content: '';
      right: -31.5rem;
      height: 3px;
      width: 31rem;
      background: #666;
   }

   .progress-barra .step .bullet.active:after {
      background: #560085;
      transform: scaleX(0);
      transform-origin: left;
      animation: animate 0.3s linear forwards;
   }

   @keyframes animate {
      100% {
         transform: scaleX(1);
      }
   }

   .progress-barra .step .check {
      position: absolute;
      font-size: 15px;
      color: #666;
      display: none;
   }

   .progress-barra .step .check.active {
      display: block;
      color: #fff;
   }

   .wrapperAccordion {
      width: 100%;
      position: relative;
   }

   .wrapperAccordionHeader {
      display: flex;
      align-items: center;
      padding: 0.475rem 1rem;
      border: 1px solid #8a8a8a;
      margin-top: 0.5rem;
      border-radius: 0.25rem;
      cursor: pointer;
      transition: 0.25s ease-in-out;
      background-color: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
   }

   .wrapperAccordionHeader>* {
      pointer-events: none;
   }

   .wrapperAccordion.active .wrapperAccordionHeader>span:last-child {
      transition: 0.25s ease-in-out;
   }

   .wrapperAccordion.active .wrapperAccordionHeader>span:last-child {
      transform: rotate(-180deg);
   }

   .wrapperAccordion.active .wrapperAccordionHeader,
   .wrapperAccordionHeader:focus,
   .wrapperAccordionHeader:visited {
      box-shadow: 0 0 0 0.2rem rgba(85, 18, 124, 0.2);
   }

   .wrapperAccordion .wrapperAccordionBody {
      height: 0;
      overflow: hidden;
   }

   .wrapperAccordionBody td {
      padding: 10px 0 !important;
   }

   /* .wrapperAccordion.active .wrapperAccordionBody {
      height: auto;
   } */

   .wrapperAccordionHeader .title {
      flex: 1;
      display: flex;
      align-items: center;
      font-weight: bold;
      padding-left: 1rem;
   }
</style>

<link rel="stylesheet" href="template/plugins/toastr/toastr.min.css">

<body class="hold-transition layout-top-nav">
   <div class="wrapper">
      <div class="preloader flex-column justify-content-center align-items-center">
      </div>
      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
         <!-- Content Header (Page header) -->
         <div class="content-header">
            <div class="container-fluid">
            </div><!-- /.container-fluid -->
         </div>
         <!-- /.content-header -->

         <section class="content">
            <div class="container-fluid">
               <div class="row">
                  <!-- SELECT2 EXAMPLE -->
                  <div class="col-md-12">
                     <div class="card card-default">
                        <div class="card-body button-nav">
                           <div class="row float-right">
                              <div class="col-md-12">
                                 <!-- <button class="btn btn-opcao" id="btn-import">Importar Excel</button> -->
                                 <button class="btn btn-opcao" id="btn-preview" disabled>Pré-visualizar</button>
                                 <button class="btn btn-opcao">Importar</button>
                                 <button class="btn btn-opcao botao-activo" disabled id="btnSalvar">Salvar Reconcilhação</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">Reconcilhação Bancária</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;">
                           </table>
                           <div class="wrapperAccordion active" id="accDocP">
                              <div class="wrapperAccordionHeader">
                                 <span class="title d-flex align-items-center">
                                    <span id="arqPen" class="styled"></span>
                                    Arquivos Pendentes
                                 </span>
                                 <span class="fa fa-angle-down"></span>
                              </div>
                              <div class="wrapperAccordionBody">
                                 <table id="tabelaDocP" class="table table-bordered table-striped" style="line-height: 0.8;">
                                    <thead>
                                       <tr style="text-align: center;" class="separatedLines">
                                          <!-- Títulos maiores -->
                                          <th colspan="6">Factura Recibo</th>
                                          <th colspan="2">Referência Bancária</th>
                                          <th colspan="3">
                                             <a href="" class="text-white" id="btnSelecionarTodas">
                                                <small style="font-size: 14px; text-decoration: underline;">Selecionar Todas</small>
                                             </a>
                                          </th>
                                       </tr>
                                       <tr style="text-align: center;">
                                          <!-- Subtítulos correspondentes -->
                                          <th colspan="2">Cod. FR</th>
                                          <th colspan="2">Data Emissão</th>
                                          <th colspan="2">Total Documento</th>
                                          <th colspan="2">Referência</th>
                                          <th colspan="3" title="Opções"><i class="fa-solid fa-screwdriver-wrench"></i></th>
                                       </tr>
                                    </thead>
                                    <tbody class="corpoP"></tbody>
                                 </table>
                              </div>
                           </div>
                           <div class="wrapperAccordion mt-3" id="accDocR">
                              <div class="wrapperAccordionHeader">
                                 <span class="title d-flex align-items-center">
                                    <span id="arqRec" class="styled"></span>
                                    Arquivos Reconcilhados
                                 </span>
                                 <span class="fa fa-angle-down"></span>
                              </div>
                              <div class="wrapperAccordionBody">
                                 <table id="tabelaDocR" class="table table-bordered table-striped" style="line-height: 0.8;">
                                    <thead>
                                       <tr style="text-align: center;" class="separatedLines">
                                          <!-- Títulos maiores -->
                                          <th colspan="6">Factura Recibo</th>
                                          <th colspan="2">Referência Bancária</th>
                                          <th colspan="3">
                                             <a href="#" class="text-white">
                                                <small style="font-size: 14px; pointer-events: none;">Selecionados</small>
                                             </a>
                                          </th>
                                       </tr>
                                       <tr style="text-align: center;">
                                          <!-- Subtítulos correspondentes -->
                                          <th colspan="2">Cod. FR</th>
                                          <th colspan="2">Data Emissão</th>
                                          <th colspan="2">Total Documento</th>
                                          <th colspan="2">Referência</th>
                                          <th colspan="3" title="Opções"><i class="fa-solid fa-screwdriver-wrench"></i></th>
                                       </tr>
                                    </thead>
                                    <tbody id="corpoR"></tbody>
                                 </table>
                              </div>
                           </div>
                        </div>
                        <!-- /.card-body -->
                        <div class="card-footer">
                           Listagem Requisições/Aprovações.
                        </div>
                     </div>
                  </div>
               </div>
               <!-- /.card -->
            </div>
            <!-- /.container-fluid -->
         </section>
         <div class="modal fade" id="modal-documento">
            <div class="modal-dialog modal-md">
               <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>
                  </div>
                  <div class="modal-body">
                     <div class="container">
                        <div class="card-body form-outer" style="padding: 0;">
                           <div class="formulario">
                              <div class="page slidePage">
                                 <div class="row">
                                    <div class="col-12">
                                       <h5 style="margin-bottom: 1rem; justify-content: center;"><span id="doOpcao">Requisição/Aprovação</span> - <span id="codigo">RA0/1</span></h5>
                                    </div>
                                    <div class="col-md-10 mx-auto">
                                       <div class="form-group d-flex align-items-center justify-content-center" style="margin-top: .4rem;">
                                          <div class="custom-control custom-switch">
                                             <input type="checkbox" class="custom-control-input" id="current_or_another" value="0">
                                             <label class="custom-control-label" for="current_or_another" style="cursor: pointer;">Prefiro definir o Proprietário</label>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row">
                                    <div class="col-md-6">
                                       <div class="form-group" style="margin-bottom: 0;">
                                          <small class="required">Código</small>
                                          <input type="text" class="form-control" id="codRubrica" name="nome" placeholder="Código da Rúbrica" title="Código da Rúbrica" required>
                                          <small>Mensagem de erro</small>
                                       </div>
                                    </div>

                                    <div class="col-md-6">
                                       <div class="form-group" style="margin-bottom: 0;">
                                          <small class="required">Classe Movimento</small>
                                          <select class="form-control select2" style="width: 100%;" id="idClasseMovimento" name="idClasseMovimento">
                                             <option value="0">Selecione o Classe movimento</option>
                                          </select>
                                          <small>Mensagem de erro</small>
                                       </div>
                                    </div>

                                    <div class="col-md-6">
                                       <div class="form-group current_owner" style="margin-bottom: 0;">
                                          <small class="required">Proprietário</small>
                                          <input type="text" class="form-control" id="currentOwner" name="currentOwner" placeholder="Proprietário" title="Proprietário" required readonly>
                                          <small>Mensagem de erro</small>
                                       </div>
                                       <div class="form-group d-none another_owner" style="margin-bottom: 0;">
                                          <small class="required">Proprietário</small>
                                          <select class="form-control select2" style="width: 100%;" id="anotherOwner" name="anotherOwner">
                                             <option value="0">Selecione o Proprietário</option>
                                          </select>
                                          <small>Mensagem de erro</small>
                                       </div>
                                    </div>

                                    <div class="col-md-6">
                                       <div class="form-group" style="margin-bottom: 0;">
                                          <small class="required">Aprovador</small>
                                          <select class="form-control select2" style="width: 100%;" id="idAprovador" name="idAprovador">
                                             <option value="0">Selecione o Aprovador</option>
                                          </select>
                                          <small>Mensagem de erro</small>
                                       </div>
                                    </div>

                                    <div class="col-md-6">
                                       <div class="form-group" style="margin-bottom: 0;">
                                          <small class="required">Movimento</small>
                                          <select class="form-control select2" style="width: 100%;" id="idMovimento" name="idMovimento">
                                             <option value="0">Selecione o Movimento</option>
                                          </select>
                                          <small>Mensagem de erro</small>
                                       </div>
                                    </div>

                                    <div class="col-md-6">
                                       <div class="form-group" style="margin-bottom: 0;">
                                          <small class="required">Total</small>
                                          <input type="text" class="form-control" id="totalRubrica" name="totalRubrica" placeholder="Total" title="Total" required>
                                          <small>Mensagem de erro</small>
                                       </div>
                                    </div>

                                    <div class="col-md-6"></div>

                                    <div class="col-12 col-md-6">
                                       <div class="form-group margem">
                                          <small>Mensagem de erro</small>
                                          <div class="form-group field btns">
                                             <button name="btn-submit" id="addReqAp" class="btn btn-block btn-primary" style="margin-top: 0;">
                                                Adicionar
                                             </button>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <div class="modal-footer d-none">
                     <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>

      <!-- /.content-wrapper -->
      <?php include('footer.php'); ?>
</body>

<script src="../pos/javascript/function.js"></script>
<script src="template/plugins/toastr/toastr.min.js"></script>

</html>
<script>
   $(document).ready(function() {

      $('#accDocP .wrapperAccordionBody').css('height', 'auto');
      // setAccordionPadding('#accDocP')

      $('.wrapperAccordionHeader').click(function(e) {
         // switchItems();
         var pai = $(this).parent();
         $(pai).toggleClass('active');
         // setAccordionPadding(pai);

         var next = $(this).next();
         if ($(next).height() == 0) {
            var currentH = $(next).css('height', 'auto').height();
            $(next).css('height', '0');
            $(next).animate({
               height: currentH
            }, 500);
         } else {
            // $(next).css('height', '0');
            $(next).animate({
               height: 0
            }, 500);
         }
      });
   });




   let allFR = [];
   let statusRow = [0, 1];
   let pendingFR = [];
   let reconciliadoFR = [];
   funcaoSelect("../pos/includes/select.inc.php", "post", "json", "viewreconciliacao", function(docData) {
      let frData = docData.map(data => {
         if (data.estado == 0) {
            pendingFR.push(data)
         } else {
            reconciliadoFR.push(data);
         }
      });

      function switchItems() {
         if ($('#accDocP').hasClass('active')) {
            $('#accDocP').removeClass('active');
            $('#accDocP .wrapperAccordionBody').css('height', '0');
            $('#accDocR').addClass('active');
            $('#accDocR .wrapperAccordionBody').css('height', 'auto');
         } else {
            $('#accDocP').addClass('active');
            $('#accDocP .wrapperAccordionBody').css('height', 'auto');
            $('#accDocR').removeClass('active');
            $('#accDocR .wrapperAccordionBody').css('height', '0');
         }
      }

      arqPen.innerText = '';
      arqRec.innerText = '';
      arqPen.innerText = pendingFR.length;
      arqRec.innerText = reconciliadoFR.length;

      if (pendingFR.length == 0) {
         $('#accDocP').removeClass('active');
         $('#accDocP .wrapperAccordionBody').css('height', '0');
      }

      if (pendingFR.length == 0 && reconciliadoFR.length > 0) {
         $('#accDocR').addClass('active');
         $('#accDocR .wrapperAccordionBody').css('height', 'auto');
      }


      $("#tabelaDocP").DataTable({
         select: 'single',
         data: pendingFR,
         columns: [{
               data: "codigo",
            },
            {
               data: "dataEmissao"
            },
            {
               data: "totalDocumento"
            },
            {
               data: "referencia"
            },
            {
               data: null,
               render: function(data, type, row) {
                  return `<input type="checkbox" id="this-row-${data.idDocumento}" class="default-checkbox form-input-checkbox">`;
               }
            }
         ],
         columnDefs: [{
            targets: -1,
            orderable: false
         }],
         responsive: true,
         lengthChange: false,
         autoWidth: false,
         language: idiomaPortugues,
         lengthMenu: [
            [7, 25, 50, -1],
            [10, 25, 50, 'All']
         ],
         buttons: ["copy", "csv", "excel", "pdf", "print", "colvis"],
         initComplete: function() {
            $('#tabelaDocP').css('padding', '1rem');
         }
      }).buttons().container().appendTo('#tabelaDocP .col-md-6:eq(0)');


      function tableStyle($table) {
         $table.addClass('áctive');

         const allTableRows = $table.find('tbody tr');
         if (allTableRows.length > 0) {
            $.each(allTableRows, (index, tr) => {
               $(tr).css('text-align', 'center');
               var td = $(tr).find('td');
               if (td.length > 1) {
                  td[0].setAttribute('colspan', 2);
                  td[1].setAttribute('colspan', 2);
                  td[2].setAttribute('colspan', 2);
                  td[3].setAttribute('colspan', 2);
                  td[4].setAttribute('colspan', 3);
               } else {
                  td[0].setAttribute('colspan', 11);
               }
            });
         }

      }

      $("#tabelaDocR").DataTable({
         select: 'single',
         data: reconciliadoFR,
         columns: [{
               data: "codigo"
            },
            {
               data: "dataEmissao"
            },
            {
               data: "totalDocumento"
            },
            {
               data: "referencia"
            },
            {
               data: null,
               render: function(data, type, row) {
                  return `<input type="checkbox" class="default-checkbox" checked style="pointer-events: none; opacity: 0.5">`;
               }
            }
         ],
         columnDefs: [{
            targets: -1,
            orderable: false
         }],
         responsive: true,
         lengthChange: false,
         autoWidth: false,
         language: idiomaPortugues,
         lengthMenu: [
            [7, 25, 50, -1],
            [10, 25, 50, 'All']
         ],
         buttons: ["copy", "csv", "excel", "pdf", "print", "colvis"]
      }).buttons().container().appendTo('#tabelaDocR .col-md-6:eq(0)');

      tableStyle($('#tabelaDocP'));
      tableStyle($('#tabelaDocR'));
      $('.dataTables_filter').css('padding', '1rem 0');
      $('.table.table-bordered.table-striped.dataTable.no-footer.dtr-inline.áctive').css({
         margin: '1rem auto 2rem',
         width: '100%'
      });

      $('#btnSelecionarTodas').click(function(e) {
         e.preventDefault();

         var smallElement = $(this).find('small');
         var trTable = document.querySelectorAll('.form-input-checkbox');
         if (trTable.length > 0) {
            if (smallElement.text() == 'Selecionar Todas') {
               smallElement.text('Deselecionar Todas');
               trTable.forEach(input => {
                  if (!input.checked) {
                     input.checked = true;
                  }
               });
            } else {
               smallElement.text('Selecionar Todas');
               trTable.forEach(input => {
                  if (input.checked) {
                     input.checked = false;
                  }
               });
               if (!$('#btnSalvar').hasClass('disabled')) {
                  $('#btnSalvar').addClass('disabled')
               }
            }
         } else {
            toastr.error('Não existe nenhum contéudo nesta tabela');
         }
         marcadoPeloMenos1();
      });

      var checks = document.querySelectorAll('.form-input-checkbox');
      var btnSave = document.querySelector('#btnSalvar');
      let toStoreInDB = [];
      var count = -1;

      function marcadoPeloMenos1(updateInDB = false) {
         count = 0;
         if (checks.length > 0) {
            checks.forEach(check => {
               if (check.checked) {
                  count++;
                  if (updateInDB) {
                     toStoreInDB.push({
                        idDocumento: $(check).attr('id').split('-')[2]
                     });
                  }
               }
            });
            if (count > 0) {
               if ($(btnSave).attr('disabled')) {
                  $(btnSave).attr('disabled', false);
               }
               return;
            } else {
               $(btnSave).attr('disabled', true);
            }

         }

      }
      checks.forEach(check => {
         $(check).change(function(e) {
            marcadoPeloMenos1();
         });
      });

      $(btnSave).click(function(e) {
         let countSuccess = 0;
         marcadoPeloMenos1(true);
         console.log(toStoreInDB);

         if (toStoreInDB.length > 0) {

            let promises = [];


            toStoreInDB.forEach(item => {

               let promise = new Promise((resolve, reject) => {
                  funcaoUpdate("../pos/includes/update.inc.php", "post", "json", "reconciliacao", {
                     estado: 1
                  }, item, function success(data) {
                     countSuccess += 1;
                     resolve()
                  }, (error) => {
                     swal.fire({
                        title: "Reconciliação",
                        text: "Algo deu errado ao tentar reconciliar os arquivos!",
                        confirmButtonText: 'Confirmar',
                        confirmButtonColor: '#560085',
                        icon: "error",
                     });
                     reject()
                  }, (done) => {});
               });

               promises.push(promise)
            });


            Promise.all(promises).then(() => {
               if (countSuccess > 0) {
                  swal.fire({
                     title: "Reconciliação",
                     text: "Arquivos reconciliados com sucesso!",
                     confirmButtonText: 'Confirmar',
                     confirmButtonColor: '#560085',
                     icon: "success",
                  }).then((result) => {
                     if (result.isConfirmed) {
                        reloadFrame("formRecocilhacaoBancaria.php");
                     }
                  });
               }
            }).catch(() => {

            });
         } else {
            swal.fire({
               title: "Reconciliação",
               text: "Selecione pelo menos 1 Arquivo para continuar",
               confirmButtonText: 'Confirmar',
               confirmButtonColor: '#560085',
               icon: "warning",
            });
         }
      });


      if (count == -1 && !$(btnSave).attr('disabled')) {
         $(btnSave).attr('disabled', true);
      }
      // alert(checks.length)

   }, (error) => {
      console.log("Error: ", error);
   }, (done) => {});
</script>
<script src="./validation/parametroArtigo.js"></script>