<?php include("header.php"); ?>
<!DOCTYPE html>
<html lang="pt">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="template/plugins/fontawesome-free/css/all.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <!-- Tempusdominus Bootstrap 4 -->
  <link rel="stylesheet" href="template/plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
  <!-- iCheck -->
  <link rel="stylesheet" href="template/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- JQVMap -->
  <link rel="stylesheet" href="template/plugins/jqvmap/jqvmap.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="template/dist/css/adminlte.min.css">
  <!-- overlayScrollbars -->
  <link rel="stylesheet" href="template/plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
  <!-- Daterange picker -->
  <link rel="stylesheet" href="template/plugins/daterangepicker/daterangepicker.css">
  <!-- summernote -->
  <link rel="stylesheet" href="template/plugins/summernote/summernote-bs4.min.css">
  <!-- style -->
  <link rel="stylesheet" href="template/dist/css/style.css?v=1">

  <style>
    table th:last-child,
    table td:last-child {
      border-right: none !important;
    }

    .bg-secondary {
      background-color: #fff !important;
    }

    .bg-secondary * {
      color: #000;
    }

    .even {
      background-color: #f2f2f2 !important;
    }

    .badge-danger {
      background-color: rgba(167, 73, 218, 0.25) !important;
    }
  </style>

</head>

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

      <!-- Main content -->
      <section class="content">
        <div class="container-fluid">

          <!-- Small boxes (Stat box) -->
          <div class="row">
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalVenda"></h3>

                  <p>Total de Vendas</p>
                </div>
                <div class="icon">
                  <i class="ion ion-stats-bars"></i>
                </div>
                <a href="#" class="small-box-footer" id="btn-totalVenda">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalRecebimento"></h3>

                  <p>Total de Recebimentos</p>
                </div>
                <div class="icon">
                  <i class="ion ion-cash"></i>
                </div>
                <a href="#" id="btn-totalRecebimento" class="small-box-footer">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalCompra"></h3>

                  <p>Total de Compras</p>
                </div>
                <div class="icon">
                  <i class="ion ion-bag"></i>
                </div>
                <a href="#" id="btn-totalCompra" class="small-box-footer">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalPagamento"></h3>

                  <p>Total de Pagamentos</p>
                </div>
                <div class="icon">
                  <i class="ion ion-card"></i>
                </div>
                <a href="#" id="btn-totalPagamento" class="small-box-footer">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
          </div>
          <!-- /.row -->

          <!-- Small boxes (Stat box) -->
          <div class="row">
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalStock"></h3>

                  <p>Total stock</p>
                </div>
                <div class="icon">
                  <i class="ion ion-ios-analytics"></i>
                </div>
                <a href="#" class="small-box-footer" id="btn-totalVenda">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalPatrimonio">21</h3>

                  <p>Disponibilidade</p>
                </div>
                <div class="icon">
                  <i class="ion ion-briefcase"></i>
                </div>
                <a href="#" id="btn-totalRecebimento" class="small-box-footer">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalTrabalhador"></h3>

                  <p>Despesas Operacionais</p>
                </div>
                <div class="icon">
                  <i class="ion ion-man"></i>
                </div>
                <a href="#" id="btn-totalCompra" class="small-box-footer">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
            <div class="col-lg-3 col-6">
              <!-- small box -->
              <div class="small-box" style="background-color: #8900d5 !important; color: #fff !important;">
                <div class="inner">
                  <h3 id="totalClienteFornecedor"><span id="tc"></span>/<span id="tf"></span> </h3>

                  <p>Rentabilidade</p>
                </div>
                <div class="icon">
                  <i class="ion ion-person"></i>
                </div>
                <a href="#" id="btn-totalPagamento" class="small-box-footer">Pré-visualizar <i class="fas fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <!-- ./col -->
          </div>
          <!-- /.row -->


          <!-- Main row -->
          <div class="row">
            <!-- Left col -->
            <section class="col-lg-6 connectedSortable">
              <!-- Custom tabs (Charts with tabs)-->
              <div class="card">
                <div class="card-header border-0">
                  <h3 class="card-title">
                    <i class="fas fa-th mr-1"></i>
                    Gráfico de Vendas e Recebimentos
                  </h3>

                  <div class="card-tools">
                    <button type="button" class="btn btn-sm" data-card-widget="collapse">
                      <i class="fas fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-sm" data-card-widget="remove">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                <div class="card-body">
                  <div class="col" id="divGraficoVenda"></div>
                </div>
                <!-- /.card-body -->
                <div class="card-footer bg-transparent">
                  <div class="row">

                    <!-- ./col -->
                  </div>
                  <!-- /.row -->
                </div>
                <!-- /.card-footer -->
              </div>

              <!--<div class="card">
                <div class="card-header">
                  <h3 class="card-title">
                    <i class="fas fa-chart-pie mr-1"></i>
                    Gráfico de Vendas
                  </h3>
                  <div class="card-tools">
                    <ul class="nav nav-pills ml-auto">
                      <li class="nav-item">
                        <a class="nav-link active" href="#revenue-chart" data-toggle="tab">Total por Mês</a>
                      </li>
                      <li class="nav-item">
                        <a class="nav-link" href="#sales-chart" data-toggle="tab">Total por Família</a>
                      </li>
                    </ul>
                  </div>
                <div class="card-body">
                  <div class="tab-content p-0">
                    <div class="chart tab-pane active" id="revenue-chart" style="position: relative; height: 300px;">
                      <canvas id="revenue-chart-canvas" height="300" style="height: 300px;"></canvas>
                    </div>
                    <div class="chart tab-pane" id="sales-chart" style="position: relative; height: 300px;">
                      <canvas id="sales-chart-canvas" height="300" style="height: 300px;"></canvas>
                    </div>
                  </div>
                </div>
              </div>-->
              <!-- /.card -->

              <!-- TO DO List -->
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title">
                    <!-- <i class="ion ion-clipboard mr-1"></i> -->
                    Inadimplência (idade de saldos)
                  </h3>

                  <!-- <div class="card-tools">
                    <ul class="pagination pagination-sm">
                      <li class="page-item"><a href="#" class="page-link">&laquo;</a></li>
                      <li class="page-item"><a href="#" class="page-link">1</a></li>
                      <li class="page-item"><a href="#" class="page-link">2</a></li>
                      <li class="page-item"><a href="#" class="page-link">3</a></li>
                      <li class="page-item"><a href="#" class="page-link">&raquo;</a></li>
                    </ul>
                  </div> -->
                </div>
                <!-- /.card-header -->

                <div class="card-body">
                  <?php $count = 0;
                  for ($i = 30; $i <= 180; $i += 30) :  ?>
                    <div class="row bg-secondary py-2 <?= $count % 2 == 0 ? 'even' : '' ?>">
                      <div class="col-2">
                        <span class="handle">
                          <i class="fas fa-ellipsis-v"></i>
                          <i class="fas fa-ellipsis-v"></i>
                        </span>
                      </div>
                      <div class="col-3"> <span class="text">Saldo</span> </div>
                      <div class="col-3 text-center">
                        <small class="badge badge-danger px-2 py-2 w-10 d-flex align-center justify-content-center">
                          <span>
                            <?php 
                              // $result = ($i == 150) ? "Para cima" : "{$i} Dias";
                              // $cacl = 0;
                              if ($i == 180) {
                                $calc = 360 ;
                                $result = " Para cima";
                              } else if ($i == 150) {
                                $calc = 180 ;
                                $result = 180*2 . " Dias";
                              } else if ($i == 120) {
                                $calc = 90 ; 
                                $result = $i + 60 . " Dias";
                              } else {
                                $calc = $i - 30;
                                $result = $i . " Dias";
                              }
                              $toPrint  =  $calc . ' - ' . $result;
                              echo $toPrint;
                            ?>
                          </span>
                        </small>
                      </div>
                      <div class="col-4 text-right">
                        <span class="text-bold" id="idade-<?php  echo $i ?>">AO 0,00</span>
                      </div>
                    </div>
                  <?php $count++;
                  endfor;  ?>
                </div>
                <!-- /.card-body -->
              </div>
              <!-- /.card -->
            </section>
            <!-- /.Left col -->
            <!-- right col (We are only adding the ID to make the widgets sortable)-->
            <section class="col-lg-6  connectedSortable">

              <div class="card">
                <div class="card-header border-0">
                  <h3 class="card-title">
                    <i class="fas fa-th mr-1"></i>
                    Gráfico de Compras e Pagamentos
                  </h3>

                  <div class="card-tools">
                    <button type="button" class="btn btn-sm" data-card-widget="collapse">
                      <i class="fas fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-sm" data-card-widget="remove">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                <div class="card-body">
                  <div class="col" id="divGraficoCompra"></div>
                </div>
                <!-- /.card-body -->
                <div class="card-footer bg-transparent">
                  <div class="row">

                    <!-- ./col -->
                  </div>
                  <!-- /.row -->
                </div>
                <!-- /.card-footer -->
              </div>
              <!-- solid sales graph -->
              <!--<div class="card bg-gradient-info">
                <div class="card-header border-0">
                  <h3 class="card-title">
                    <i class="fas fa-th mr-1"></i>
                    Gráfico de Compras/Ano
                  </h3>

                  <div class="card-tools">
                    <button type="button" class="btn bg-info btn-sm" data-card-widget="collapse">
                      <i class="fas fa-minus"></i>
                    </button>
                    <button type="button" class="btn bg-info btn-sm" data-card-widget="remove">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                <div class="card-body">
                  <canvas class="chart" id="line-chart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
                </div>
                <div class="card-footer bg-transparent">
                  <div class="row">
                  </div>
                </div>
              </div>-->
              <!-- /.card -->

              <!-- Calendar -->
              <div class="card bg-gradient-success d-none" style="background: #560085 linear-gradient(180deg,#410064,#560085) repeat-x !important; color: #fff !important;">
                <div class="card-header border-0">

                  <h3 class="card-title">
                    <i class="far fa-calendar-alt"></i>
                    Calendário
                  </h3>
                  <!-- tools card -->
                  <div class="card-tools">
                    <!-- button with a dropdown -->
                    <div class="btn-group">
                      <button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown" data-offset="-52" style="background-color: #560085; border-color: #560085;">
                        <i class="fas fa-bars"></i>
                      </button>
                      <div class="dropdown-menu" role="menu">
                        <a href="#" class="dropdown-item">Adicionar Novo Evento</a>
                        <a href="#" class="dropdown-item">Apagar Eventos</a>
                        <div class="dropdown-divider"></div>
                        <a href="#" class="dropdown-item">Ver Calendário</a>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-sm" data-card-widget="collapse" style="background-color: #560085 !important; border-color: #560085 !important;">
                      <i class="fas fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-success btn-sm" data-card-widget="remove" style="background-color: #560085; border-color: #560085;">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                  <!-- /. tools -->
                </div>
                <!-- /.card-header -->
                <div class="card-body pt-0">
                  <!--The calendar -->
                  <div id="calendar" style="width: 100%"></div>
                </div>
                <!-- /.card-body -->
              </div>
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title">
                    <!-- <i class="ion ion-clipboard mr-1"></i> -->
                    Impostos a pagar
                  </h3>

                  <!-- <div class="card-tools">
                    <ul class="pagination pagination-sm">
                      <li class="page-item"><a href="#" class="page-link">&laquo;</a></li>
                      <li class="page-item"><a href="#" class="page-link">1</a></li>
                      <li class="page-item"><a href="#" class="page-link">2</a></li>
                      <li class="page-item"><a href="#" class="page-link">3</a></li>
                      <li class="page-item"><a href="#" class="page-link">&raquo;</a></li>
                    </ul>
                  </div> -->
                </div>
                <!-- /.card-header -->

                <?php
                $impostos =
                  [
                    [
                      'II 	- Impostos Industrial',
                      '0,00'
                    ],
                    [
                      'IRT 	- Imposto sobre rendimento de trabalho',
                      '0,00'
                    ],
                    [
                      'IS 	- Imposo de Selo',
                      '0,00'
                    ],
                    [
                      'IVA	- Imposto sobre valor acrescentado ',
                      '0,00'
                    ],
                    [
                      'ISP 	- Imposto sobre serviços prestados ',
                      '0,00'
                    ],
                    [
                      'IVM 	- Imposto sobre veículos motorizados ',
                      '0,00'
                    ],
                    [
                      'SAT	- Seguro de acidentes de trabalho ',
                      '0,00'
                    ],
                  ];
                ?>

                <div class="card-body">
                  <?php $count = 0;
                  foreach ($impostos as $imposto) :  ?>
                    <div class="row bg-secondary py-2 <?= $count % 2 == 0 ? 'even' : '' ?>">
                      <div class="col-1">
                        <span class="handle">
                          <i class="fas fa-ellipsis-v"></i>
                          <i class="fas fa-ellipsis-v"></i>
                        </span>
                      </div>
                      <div class="col-6"> <span class="text"><?= $imposto[0] ?></span> </div>
                      <div class="col-1 text-center">
                        <small class="px-2 py-2 w-10 d-flex align-center justify-content-center osys-grid">
                          </span>
                        </small>
                      </div>
                      <div class="col-4 text-right">
                        <span class="text-bold">AO <?= $imposto[1] ?></span>
                      </div>
                    </div>
                  <?php $count++;
                  endforeach;  ?>
                </div>
                <!-- /.card-body -->
              </div>

              <!-- /.card -->
            </section>
            <!-- right col -->
          </div>
          <!-- /.row (main row) -->
        </div><!-- /.container-fluid -->
      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <!-- Control Sidebar -->
    <aside class="control-sidebar control-sidebar-dark">
      <!-- Control sidebar content goes here -->
    </aside>
    <!-- /.control-sidebar -->
  </div>
  <div class="modal fade" id="modal-venda">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Vendas</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="tabelaVenda" 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>
              </tr>
            </thead>
            <tbody id="corpoTabela" style="text-align: center;">
            </tbody>
          </table>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
  </div>
  <div class="modal fade" id="modal-recebimento">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Recebimentos</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="tabelaRecebimento" 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>
              </tr>
            </thead>
            <tbody id="corpoTabela" style="text-align: center;">
            </tbody>
          </table>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
  </div>
  <div class="modal fade" id="modal-compra">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Compras</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="tabelaCompra" 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>
              </tr>
            </thead>
            <tbody id="corpoTabela" style="text-align: center;">
            </tbody>
          </table>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
  </div>
  <div class="modal fade" id="modal-pagamento">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Pagamentos</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="tabelaPagamento" 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>
              </tr>
            </thead>
            <tbody id="corpoTabela" style="text-align: center;">
            </tbody>
          </table>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
  </div>
  <!-- ./wrapper -->

  <!-- jQuery -->
  <script src="template/plugins/jquery/jquery.min.js"></script>
  <!-- jQuery UI 1.11.4 -->
  <script src="template/plugins/jquery-ui/jquery-ui.min.js"></script>
  <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
  <script>
    $.widget.bridge('uibutton', $.ui.button)
  </script>
  <!-- Bootstrap 4 -->
  <script src="template/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
  <!-- ChartJS -->
  <script src="template/plugins/chart.js/Chart.min.js"></script>
  <!-- Sparkline -->
  <script src="template/plugins/sparklines/sparkline.js"></script>
  <!-- JQVMap -->
  <script src="template/plugins/jqvmap/jquery.vmap.min.js"></script>
  <script src="template/plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
  <!-- jQuery Knob Chart -->
  <script src="template/plugins/jquery-knob/jquery.knob.min.js"></script>
  <!-- daterangepicker -->
  <script src="template/plugins/moment/moment.min.js"></script>
  <script src="template/plugins/daterangepicker/daterangepicker.js"></script>
  <!-- Tempusdominus Bootstrap 4 -->
  <script src="template/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
  <!-- Summernote -->
  <script src="template/plugins/summernote/summernote-bs4.min.js"></script>
  <!-- overlayScrollbars -->
  <script src="template/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
  <!-- AdminLTE App -->
  <script src="template/dist/js/adminlte.js"></script>
  <!-- AdminLTE for demo purposes -->
  <script src="template/dist/js/demo.js"></script>
  <!-- AdminLTE dashboard demo (This is only for demo purposes) -->
  <script src="template/dist/js/pages/dashboard.js"></script>

  <script src="./template/plugins/datatables/jquery.dataTables.min.js"></script>
  <script src="./template/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
  <script src="./template/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
  <script src="./template/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
  <script src="./template/plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
  <script src="./template/plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
  <script src="./template/plugins/jszip/jszip.min.js"></script>
  <script src="./template/plugins/pdfmake/pdfmake.min.js"></script>
  <script src="./template/plugins/pdfmake/vfs_fonts.js"></script>
  <script src="./template/plugins/datatables-buttons/js/buttons.html5.min.js"></script>
  <script src="./template/plugins/datatables-buttons/js/buttons.print.min.js"></script>
  <script src="./template/plugins/datatables-buttons/js/buttons.colVis.min.js"></script>
  <script src="./template/dist/js/currency.js?v=1"></script>
  <script src="./javascript/function.js"></script>
  <script>
    $(document).ready(function() {
      $.ajax({
        url: "includes/read/totalVenda.inc.php",
        type: "post",
        dataType: "json",
        success: function(data) {
          if (data[0]["contador"] != null) {
            totalVenda.innerText = parseFloat(data[0]["contador"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
          } else {
            totalVenda.innerText = "0,00 Kzs";
          }
          totalVenda.innerText = tNumberFormatter(totalVenda.innerText.replace(' ', ''));
        }
      });
    });

    const idTotalStock = document.querySelector('#totalStock');

    function updateTotalStock() {
      const storedValue = window.localStorage.getItem('totalStock');
      if (storedValue !== null) {
        idTotalStock.innerText = tNumberFormatter(storedValue.replace(' ', ''));
      }
    }

    updateTotalStock();
    window.addEventListener('storage', function(event) {
      if (event.key === 'totalStock') {
        updateTotalStock();
      }
    });



    $(document).ready(function() {
      $.ajax({
        url: "includes/read/totalRecebimento.inc.php",
        type: "post",
        dataType: "json",
        success: function(data) {
          if (data[0]["contador"] != null) {
            totalRecebimento.innerText = parseFloat(data[0]["contador"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
            console.log(totalRecebimento.innerText)
          } else {
            totalRecebimento.innerText = "0,00 Kzs";
          }
          totalRecebimento.innerText = tNumberFormatter(totalRecebimento.innerText.replace(' ', ''));
        }
      });


      funcaoSelect("../pos/includes/select.inc.php", "post", "json", "idadesaldos", function success(data) {
          
          if (data[0]["idade30"] != null) {
            $("#idade-30").text(parseFloat(data[0]["idade30"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }else{
            $("#idade-30").text(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }

          if (data[0]["idade60"] != null) {
            $("#idade-60").text(parseFloat(data[0]["idade60"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }else{
            $("#idade-60").text(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }
          if (data[0]["idade90"] != null) {
            $("#idade-90").text(parseFloat(data[0]["idade90"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }else{
            $("#idade-90").text(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }
          if (data[0]["idade180"] != null) {
            $("#idade-120").text(parseFloat(data[0]["idade180"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }else{
            $("#idade-120").text(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }
          if (data[0]["idade360"] != null) {
            $("#idade-150").text(parseFloat(data[0]["idade360"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }else{
            $("#idade-150").text(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }
          if (data[0]["idadecima"] != null) {
            $("#idade-180").text(parseFloat(data[0]["idadecima"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }else{
            $("#idade-180").text(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs");
          }
         
        },
        function error(data) {
            erro(data);
        },
        function done(data) {
            
        });

    });

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/totalCompra.inc.php",
        type: "post",
        dataType: "json",
        success: function(data) {
          if (data[0]["contador"] != null) {
            totalCompra.innerText = parseFloat(data[0]["contador"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
          } else {
            totalCompra.innerText = "0,00 Kzs";
          }
          totalCompra.innerText = tNumberFormatter(totalCompra.innerText.replace(' ', ''));
        }
      });
    });

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/totalPagamento.inc.php",
        type: "post",
        dataType: "json",
        success: function(data) {
          if (data[0]["contador"] != null) {
            totalPagamento.innerText = parseFloat(data[0]["contador"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
          } else {
            totalPagamento.innerText = "0,00 Kzs";
          }
          totalPagamento.innerText = tNumberFormatter(totalPagamento.innerText.replace(' ', ''));
        }
      });
    });


    $(document).ready(function() {
      $.ajax({
        url: "includes/read/usuario.inc.php",
        type: "get",
        dataType: "json",
        success: function(data) {
          var total = data.length;
          $('#totalTrabalhador').text(
            total <= 9 ? `0${total}` : total
          );
        }
      });
    });

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/entidade.inc.php",
        type: "post",
        dataType: "json",
        data: {
          tipoEntidade: 2
        },
        success: function(data) {
          var countCliente = 0;

          $.each(data, (chave, valor) => {
            if (valor.estado == '1') {
              countCliente++;
            }
          });
          $('#tc').text(countCliente);
        }
      });
      $.ajax({
        url: "includes/read/entidade.inc.php",
        type: "post",
        dataType: "json",
        data: {
          tipoEntidade: 1
        },
        success: function(data) {
          var countFornecedor = 0;

          $.each(data, (chave, valor) => {
            if (valor.estado == '1') {
              countFornecedor++;
            }
          });
          $('#tf').text(countFornecedor);
        }
      });
    });


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

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

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

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

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/chartVenda.inc.php",
        type: "post",
        dataType: "json",
        success: function(data) {
          console.log("Pegar venda: ", data);
          let venda = "";
          let mesVenda = "";
          for (let i = 0; i < data[0].length; i++) {
            venda += `${data[0][i]['total']}`;
            mesVenda += `"${data[0][i]['mes']}"`;
            if (i < data[0].length - 1) {
              venda += ",";
              mesVenda += ",";
            }
          }

          let recebimento = "";
          let mesRecebimento = "";

          for (let i = 0; i < data[1].length; i++) {
            recebimento += `${data[1][i]['total']}`;
            mesRecebimento += `"${data[0][i]['mes']}"`;
            if (i < data[1].length - 1) {
              recebimento += ",";
              mesRecebimento += ",";
            }
          }

          let config = {
            type: "bar",
            data: {
              labels: JSON.parse(`[${mesVenda}]`),

              datasets: [{
                  label: "Vendas",
                  backgroundColor: "#560085",
                  borderColor: "#560085",
                  data: JSON.parse(`[${venda}]`)
                },
                {
                  label: "Recebimentos",
                  backgroundColor: "#A749DA",
                  borderColor: "#A749DA",
                  data: JSON.parse(`[${recebimento}]`)
                }
              ]
            },
            options: {
              scales: {
                yAxes: [{
                  ticks: {
                    beginAtZero: true,
                  },
                }, ],
              },
              legend: {
                display: true
              }
            }
          };

          let grafico = `<canvas class="chart" id="graficoVenda"></canvas>`;
          $("#divGraficoVenda").html(grafico);
          var ctx = document.getElementById('graficoVenda').getContext('2d');
          new Chart(ctx, config);
        }
      });
      $.ajax({
        url: "includes/read/chartCompra.inc.php",
        type: "post",
        dataType: "json",
        success: function(data) {
          console.log("Pegar compra: ", data);
          let compra = "";
          let mesCompra = "";
          for (let i = 0; i < data[0].length; i++) {
            compra += `${data[0][i]['total']}`;
            mesCompra += `"${data[0][i]['mes']}"`;
            if (i < data[0].length - 1) {
              compra += ",";
              mesCompra += ",";
            }
          }

          let recebimento = "";
          let mesRecebimento = "";

          for (let i = 0; i < data[1].length; i++) {
            recebimento += `${data[1][i]['total']}`;
            mesRecebimento += `"${data[0][i]['mes']}"`;
            if (i < data[1].length - 1) {
              recebimento += ",";
              mesRecebimento += ",";
            }
          }

          let config = {
            type: "bar",
            data: {
              labels: JSON.parse(`[${mesCompra}]`),

              datasets: [{
                  label: "Compras",
                  backgroundColor: "#560085",
                  borderColor: "#560085",
                  data: JSON.parse(`[${compra}]`)
                },
                {
                  label: "Recebimentos",
                  backgroundColor: "#A749DA",
                  borderColor: "#A749DA",
                  data: JSON.parse(`[${recebimento}]`)
                }
              ]
            },
            options: {
              scales: {
                yAxes: [{
                  ticks: {
                    beginAtZero: true,
                  },
                }, ],
              },
              legend: {
                display: true
              }
            }
          };



          let grafico = `<canvas class="chart" id="graficoCompra"></canvas>`;
          $("#divGraficoCompra").html(grafico);
          var ctx = document.getElementById('graficoCompra').getContext('2d');
          new Chart(ctx, config);
        }
      });
      $.ajax({
        url: "includes/read/listagemTotalVenda.inc.php",
        type: "post",
        dataType: "json"
      }).done(function(data) {
        $("#tabelaVenda").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>";
                }
              }
            }
          }],
          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"],
          order: [
            [3, 'asc']
          ]
        }).buttons().container().appendTo('#tabelaVenda_wrapper .col-md-6:eq(0)');
      });
    });

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/listagemTotalRecebimento.inc.php",
        type: "post",
        dataType: "json"
      }).done(function(data) {
        $("#tabelaRecebimento").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>";
                }
              }
            }
          }],
          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"],
          order: [
            [3, 'asc']
          ]
        }).buttons().container().appendTo('#tabelaRecebimento_wrapper .col-md-6:eq(0)');
      });
    });

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/listagemTotalCompra.inc.php",
        type: "post",
        dataType: "json"
      }).done(function(data) {
        $("#tabelaCompra").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>";
                }
              }
            }
          }],
          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"],
          order: [
            [3, 'asc']
          ]
        }).buttons().container().appendTo('#tabelaCompra_wrapper .col-md-6:eq(0)');
      });
    });

    $(document).ready(function() {
      $.ajax({
        url: "includes/read/listagemTotalPagamento.inc.php",
        type: "post",
        dataType: "json"
      }).done(function(data) {
        $("#tabelaPagamento").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>";
                }
              }
            }
          }],
          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"],
          order: [
            [3, 'asc']
          ]
        }).buttons().container().appendTo('#tabelaPagamento_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"
      }
    }

    function funcaoSelect(url, type, dataType, tabela, success, error, done) {
            $.ajax({
                url: url,
                type: type,
                dataType: dataType,
                data: {
                    tabela: tabela
                },
                success: function (data) {
                    success(data);
                },
                error: function (data) {
                    error(data);
                }
            }).done(function (data) {
                done(data);
            });
        }
  </script>
</body>

</html>