<?php include "includes/header.php";?>

<?php include "includes/navbar.php";?>

  <div id="wrapper">

    <!-- Sidebar -->
   <?php include "includes/sidebar.php";?>

    <div id="content-wrapper">

      <div class="container-fluid">

        <!-- Breadcrumbs-->
        <ol class="breadcrumb">
          <li class="breadcrumb-item">
            <a href="#">Ola</a>
          </li>
          <li class="breadcrumb-item active"><?php echo $_SESSION['nome'];?></li>
        </ol>

     
	
    

<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">
  Transacoes
</button>

<!-- The Modal -->
<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Relatorios</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
     
	   <div class='col-sm-8'>
	    <form action="report_data_conta.php" target="_blank" method="post">
		  
		  <div class="form-group">
		   <label for="inicio">Inicio</label>
		    <input type="date" name="inicio" class="form-control" required/>
		  </div>
		  
		  <div class="form-group">
		   <label for="fim">Fim</label>
		    <input type="date" name="fim" class="form-control" required/>
		  </div>
		  
		  <div class="form-group">
		   <label for="local">Conta</label>
		    <select required name="local" class="form-control">
			 <option></option>
			 <?php $loan->selectContaId();?>
			</select>
		  </div>
		  
		  <div class="form-group">
		    <input type="submit" name="submit" class="btn btn-info btn-sm" value="Submit"/>
		  </div>
		 
		</form>
	   </div>
	 
	 
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div> 

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal30">
  30 dias
</button>

<!-- The Modal -->
<div class="modal" id="myModal30">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">30 dias</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
       
	   <div class="container">
	  <div class="col-sm-8">
	   <form action="trinta.php" target="_blank" method="post">
	   
	   <div class="form-group">
		   <label for="local">Conta</label>
		    <select required name="local" class="form-control">
			 <option></option>
			<?php $loan->selectContaId();?>
			</select>
		  </div>
	   
	   <div class="form-group">
		   <input type="submit" name="submit" class="btn btn-info btn-block" value="Submeter"/>
		  </div>
	   
	   </form>
	   </div>
	   </div>
	   
	   
	   
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal90">
 90 dias
</button>

<!-- The Modal -->
<div class="modal" id="myModal90">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">90 dias</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
	  <div class="container">
	  <div class="col-sm-8">
       <form action="noventa.php" target="_blank" method="post">
	   
	   <div class="form-group">
		   <label for="local">Conta</label>
		    <select required name="local" class="form-control">
			 <option></option>
			 <?php $loan->selectContaId();?>
			</select>
		  </div>
	   
	    <div class="form-group">
		   <input type="submit" name="submit" class="btn btn-info btn-block" value="Submeter"/>
		  </div>
	   
	   </form>
	   </div>
	   </div>
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myModal180">
 180 dias
</button>

<!-- The Modal -->
<div class="modal" id="myModal180">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">180 dias</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
	  
	  <div class="container">
	  <div class="col-sm-8">
       <form action="cento_oitenta.php" target="_blank" method="post">	   
	   <div class="form-group">
		   <label for="local">Conta</label>
		    <select required name="local" class="form-control">
			 <option></option>
			 <?php $loan->selectContaId();?>
			</select>
		  </div>
		  
		  <div class="form-group">
		   <input type="submit" name="submit" class="btn btn-info btn-block" value="Submeter"/>
		  </div>
	   
	   </form>
	   </div>
	   </div>
	   
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal365">
 365 dias
</button>

<!-- The Modal -->
<div class="modal" id="myModal365">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">365 dias</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
	  
	  <div class="container">
	  <div class="col-sm-8">
       <form action="trezentos_65.php" target="_blank" method="post">
	   
	   <div class="form-group">
		   <label for="local">Conta</label>
		    <select required name="local" class="form-control">
			 <option></option>
			 <?php $loan->selectContaId();?>
			</select>
		  </div>
	   <div class="form-group">
		   <input type="submit" name="submit" class="btn btn-info btn-block" value="Submeter"/>
		  </div>
	   
	   </form>
	   </div>
	   </div>
	   
	   
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#report2">
  Relatorio de pagamentos
</button>

<!-- The Modal -->
<div class="modal" id="report2">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Relatorios</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
     
	   <div class='col-sm-8'>
	    <form action="report_creditos_data_cliente.php" target="_blank" method="post">
		  
		  <div class="form-group">
		   <label for="inicio">Inicio</label>
		    <input type="date" name="inicio" class="form-control" required/>
		  </div>
		  
		  <div class="form-group">
		   <label for="fim">Fim</label>
		    <input type="date" name="fim" class="form-control" required/>
		  </div>

		  <div class="form-group">
		    <input type="submit" name="submit" class="btn btn-info btn-sm" value="Submit"/>
		  </div>
		 
		</form>
	   </div>
	 
	 
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div> 



<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal1">
  Relatorio de clientes
</button>

<!-- The Modal -->
<div class="modal" id="myModal1">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Relatorios</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
     
	   <div class='col-sm-8'>
	    <form action="report_cliente.php" target="_blank" method="post">
		  
		  
		  <div class="form-group">
		   <label for="cliente">Nome do Cliente</label>
		    <select required name="cliente" class="form-control">
			 <option></option>
			<?php $clientes->buscaClienteId();?>
			</select>
		  </div>
		  
		  <div class="form-group">
		    <input type="submit" name="submit" class="btn btn-info btn-sm" value="Submit"/>
		  </div>
		 
		</form>
	   </div>
	 
	 
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div> 


<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal_2">
  BM Mensal
</button>

<!-- The Modal -->
<div class="modal" id="myModal_2">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Relatorios</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
     
	   <div class='col-sm-8'>
	    <form action="report_bm_mensal.php" target="_blank" method="post">
		  
		  <div class="form-group">
		   <label for="inicio">Inicio</label>
		    <input type="date" name="inicio" class="form-control" required/>
		  </div>
		  
		  <div class="form-group">
		   <label for="fim">Fim</label>
		    <input type="date" name="fim" class="form-control" required/>
		  </div>
		  
	
		  
		  <div class="form-group">
		    <input type="submit" name="submit" class="btn btn-info btn-sm" value="Submit"/>
		  </div>
		 
		</form>
	   </div>
	 
	 
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div> 


<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal_4">
  BM Trimestral
</button>

<!-- The Modal -->
<div class="modal" id="myModal_4">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Relatorios</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
     
	   <div class='col-sm-8'>
	    <form action="report_bm_trimestral.php" target="_blank" method="post">
		  
		  <div class="form-group">
		   <label for="inicio">Inicio</label>
		    <input type="date" name="inicio" class="form-control" required/>
		  </div>
		  
		  <div class="form-group">
		   <label for="fim">Fim</label>
		    <input type="date" name="fim" class="form-control" required/>
		  </div>
		  
	
		  
		  <div class="form-group">
		    <input type="submit" name="submit" class="btn btn-info btn-sm" value="Submit"/>
		  </div>
		 
		</form>
	   </div>
	 
	 
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div> 

<button type="button" class="btn btn-success btn-sm"><a href="export-data.php" style="text-decoration:none; color:white"><span>Excel Report</span></a></button>


<!-- ========================================== -->
<!-- SEÇÃO DO GRÁFICO INTERATIVO (ADICIONADA)   -->
<!-- ========================================== -->
<br><br>
<div class="card mb-3">
  <div class="card-header bg-dark text-white">
    <i class="fas fa-chart-bar"></i>
    Resumo Geral de Transações, Pagamentos e Créditos
  </div>
  <div class="card-body">
    <div class="row">
      <!-- Painel de Mini Indicadores (Cards) -->
      <div class="col-xl-3 col-sm-6 mb-3">
        <div class="card text-white bg-primary o-hidden h-100">
          <div class="card-body">
            <div class="mr-5">Entradas Totais (Transações)</div>
            <h4 id="txt-entradas">A carregar...</h4>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-sm-6 mb-3">
        <div class="card text-white bg-danger o-hidden h-100">
          <div class="card-body">
            <div class="mr-5">Saídas Totais (Transações)</div>
            <h4 id="txt-saidas">A carregar...</h4>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-sm-6 mb-3">
        <div class="card text-white bg-success o-hidden h-100">
          <div class="card-body">
            <div class="mr-5">Total Recebido (Pagamentos)</div>
            <h4 id="txt-pagamentos">A carregar...</h4>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-sm-6 mb-3">
        <div class="card text-white bg-warning o-hidden h-100">
          <div class="card-body bg-warning text-dark">
            <div class="mr-5">Créditos Pendentes (Em curso)</div>
            <h4 id="txt-creditos">A carregar...</h4>
          </div>
        </div>
      </div>
    </div>

    <!-- Área Real do Gráfico -->
    <div class="row">
      <div class="col-lg-12">
        <canvas id="meuGraficoDinamico" width="100%" height="35"></canvas>
      </div>
    </div>
  </div>
  <div class="card-footer small text-muted">Atualizado dinamicamente com base no banco de dados.</div>
</div>

<?php
// --- CONSULTAS AO BANCO DE DADOS EM PHP ---
// Ajuste a sua conexão de banco de dados se necessário ($conn, $db ou $pdo)
// Usaremos um exemplo padrão que assume que você tem uma conexão ativa.

try {
    // 1. Soma de Entradas e Saídas da tabela `transacoes`
    $query_trans = mysqli_query($con, "SELECT SUM(entrada) AS total_entrada, SUM(saida) AS total_saida FROM transacoes");
    $dados_trans = mysqli_fetch_assoc($query_trans);
    $total_entrada = $dados_trans['total_entrada'] ?? 0;
    $total_saida = $dados_trans['total_saida'] ?? 0;

    // 2. Soma de Pagamentos da tabela `pagamentos`
    $query_pag = mysqli_query($con, "SELECT SUM(valor_pago) AS total_pago FROM pagamentos");
    $dados_pag = mysqli_fetch_assoc($query_pag);
    $total_pagamentos = $dados_pag['total_pago'] ?? 0;

    // 3. Créditos Pendentes vs Pagos da tabela `creditos`
    $query_cred_pendente = mysqli_query($con, "SELECT SUM(total) AS total_pendente FROM creditos WHERE status = 'pendente'");
    $dados_cred_pendente = mysqli_fetch_assoc($query_cred_pendente);
    $total_cred_pendente = $dados_cred_pendente['total_pendente'] ?? 0;

    $query_cred_pago = mysqli_query($con, "SELECT SUM(total) AS total_pago FROM creditos WHERE status = 'Pago'");
    $dados_cred_pago = mysqli_fetch_assoc($query_cred_pago);
    $total_cred_pago = $dados_cred_pago['total_pago'] ?? 0;

} catch (Exception $e) {
    // Valores de fallback (caso a conexão falhe ou use outra variável)
    $total_entrada = 50000;
    $total_saida = 15000;
    $total_pagamentos = 38000;
    $total_cred_pendente = 205120;
    $total_cred_pago = 74610;
}
?>

<!-- Script que desenha o Gráfico interativo usando Chart.js -->
<script>
document.addEventListener("DOMContentLoaded", function(){
    // Formatar os valores PHP para passar para o Javascript
    var totalEntrada = <?php echo floatval($total_entrada); ?>;
    var totalSaida = <?php echo floatval($total_saida); ?>;
    var totalPagamentos = <?php echo floatval($total_pagamentos); ?>;
    var totalCredPendente = <?php echo floatval($total_cred_pendente); ?>;
    var totalCredPago = <?php echo floatval($total_cred_pago); ?>;

    // Atualiza os textos dos mini-cards superiores
    document.getElementById('txt-entradas').innerText = totalEntrada.toLocaleString('pt-PT', { style: 'currency', currency: 'MZN' });
    document.getElementById('txt-saidas').innerText = totalSaida.toLocaleString('pt-PT', { style: 'currency', currency: 'MZN' });
    document.getElementById('txt-pagamentos').innerText = totalPagamentos.toLocaleString('pt-PT', { style: 'currency', currency: 'MZN' });
    document.getElementById('txt-creditos').innerText = totalCredPendente.toLocaleString('pt-PT', { style: 'currency', currency: 'MZN' });

    // Renderiza o gráfico do Chart.js
    var ctx = document.getElementById("meuGraficoDinamico").getContext('2d');
    var meuGrafico = new Chart(ctx, {
        type: 'bar', // Tipo de gráfico misto (Barras e Linha)
        data: {
            labels: ["Entradas (Caixa)", "Saídas (Caixa)", "Pagamentos Recebidos", "Créditos Concedidos (Pagos)", "Créditos em Curso (Pendentes)"],
            datasets: [{
                label: 'Valores em Meticais (MZN)',
                data: [totalEntrada, totalSaida, totalPagamentos, totalCredPago, totalCredPendente],
                backgroundColor: [
                    'rgba(40, 167, 69, 0.7)',  // Verde para Entradas
                    'rgba(220, 53, 69, 0.7)',   // Vermelho para Saídas
                    'rgba(23, 162, 184, 0.7)',  // Azul-turquesa para Pagamentos
                    'rgba(0, 123, 255, 0.7)',   // Azul escuro para Créditos Pagos
                    'rgba(255, 193, 7, 0.7)'    // Amarelo para Créditos Pendentes
                ],
                borderColor: [
                    'rgba(40, 167, 69, 1)',
                    'rgba(220, 53, 69, 1)',
                    'rgba(23, 162, 184, 1)',
                    'rgba(0, 123, 255, 1)',
                    'rgba(255, 193, 7, 1)'
                ],
                borderWidth: 1.5
            }]
        },
        options: {
            responsive: true,
            legend: {
                display: false // Oculta a legenda redundante já que os labels explicam tudo
            },
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true,
                        callback: function(value, index, values) {
                            return value.toLocaleString('pt-PT') + ' MZN';
                        }
                    }
                }]
            },
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                        return 'Total: ' + valor.toLocaleString('pt-PT', { style: 'currency', currency: 'MZN' });
                    }
                }
            }
        }
    });
});
</script>
<!-- ========================================== -->

      </div>
      <!-- /.container-fluid -->

      <!-- Sticky Footer -->
     <?php include "includes/footer.php";?>

    </div>
    <!-- /.content-wrapper -->

  </div>
  <!-- /#wrapper -->

  <!-- Scroll to Top Button-->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <!-- Logout Modal-->
<?php include "includes/logout_modal.php"; ?>

  <!-- Bootstrap core JavaScript-->
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

  <!-- Core plugin JavaScript-->
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

  <!-- Page level plugin JavaScript-->
  <script src="vendor/chart.js/Chart.min.js"></script>
  <script src="vendor/datatables/jquery.dataTables.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.js"></script>

  <!-- Custom scripts for all pages-->
  <script src="js/sb-admin.min.js"></script>

  <!-- Demo scripts for this page-->
  <script src="js/demo/datatables-demo.js"></script>
  <script src="js/demo/chart-area-demo.js"></script>

</body>

</html>
