<?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>

        <!-- Icon Cards-->
        <div class="row">
		
		
		<?php if($_SESSION['nivel'] == 1 || $_SESSION['nivel']==2){ ?>
		
          <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="card-body-icon">
                  <i class="fas fa-fw fa-comments"></i>
                </div>
                <div class="mr-5">(
				
				<?php 
				$busca_solicitados = "SELECT * FROM creditos WHERE status='aguardar'";
				$yes_we_do = mysqli_query($con,$busca_solicitados);
				$contagem = mysqli_num_rows($yes_we_do);
				
				echo $contagem;
				
				?>
				
				) Creditos solicitados</div>
              </div>
			  
			  <?php if($_SESSION['nivel']==1 || $_SESSION['nivel']==2){?>
			  
              <a class="card-footer text-white clearfix small z-1" href="pedidos_credito.php">
                <span class="float-left">Ver todos</span>
                <span class="float-right">
                  <i class="fas fa-angle-right"></i>
                </span>
              </a>
			  <?php }else{
				  
				  echo "<font color='red'>Link n찾o disponivel para este painel</font>";
			  }?>
			  
			  
            </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">
                <div class="card-body-icon">
                  <i class="fas fa-fw fa-users"></i>
                </div>
                <div class="mr-5">
				
				<?php 
				$contar_cli = "SELECT * FROM clientes WHERE status='Activo'";
				$query_it = mysqli_query($con,$contar_cli);
				$count = mysqli_num_rows($query_it);
				
				echo $count;
				
				?>



				Clientes</div>
              </div>
              <a class="card-footer text-white clearfix small z-1" href="cadastrar_clientes.php">
                <span class="float-left">Ver lista</span>
                <span class="float-right">
                  <i class="fas fa-angle-right"></i>
                </span>
              </a>
            </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="card-body-icon">
                  <i class="fas fa-fw fa-book"></i>
                </div>
                <div class="mr-5">
			


				Relatorios</div>
              </div>
			  
			  <?php if($_SESSION['nivel']==1 || $_SESSION['nivel']==2){?>
              <a class="card-footer text-white clearfix small z-1" href="report.php">
                <span class="float-left">Listar</span>
                <span class="float-right">
                  <i class="fas fa-angle-right"></i>
                </span>
              </a>
			   <?php }else{
				  
				  echo "<font color='red'>Link n찾o disponivel para este painel</font>";
			  }?>
			  
            </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="card-body-icon">
                  <i class="fas fa-fw fa-life-ring"></i>
                </div>
                <div class="mr-5">
				 
				 <?php 
				 
			
			
                $now = date('Y-m-d'); 
				
				$date = new DateTime($now);
                $date->modify('-1 day');
                $mudanca_atras = $date->format('Y-m-d');
                
				
				$date = new DateTime($now);
                $date->modify('+7 day');
                $mudanca_frente = $date->format('Y-m-d');
				
           
				 echo "Alerta de pagamentos ";

			?>			
				
				 </div>
              </div>
			  
			  <?php if($_SESSION['nivel']==1 || $_SESSION['nivel']==2){?>
              <a class="card-footer text-white clearfix small z-1" href="creditos_alerta.php">
                <span class="float-left">Ver todos</span>
                <span class="float-right">
                  <i class="fas fa-angle-right"></i>
                </span>
              </a>
			  <?php }else{
				  
				  echo "<font color='white'>Link n찾o disponivel para este painel</font>";
			  }
        
      }else{
        echo "";
    }?>
			  
			  
            </div>
          </div>
		  
		  
        </div>
        
        <div class="row mb-4">
    <!-- Gr룶죉ico de Barras -->
    <div class="col-md-6 mb-3">
      <div class="card p-3 shadow-sm">
        <h5 class="mb-3">Pagamentos Mensais</h5>
    <canvas id="barChart"></canvas>
      </div>
    </div>
<div class="col-md-6 mb-3 d-flex justify-content-center">
  <div class="card p-3 shadow-sm" style="width: 420px;">
    <h5 class="mb-3">Creditos</h5>
    <canvas id="pieChart" style="height: 250px;"></canvas>
  </div>
</div>
  
  </div>  


<?php

$sql = "SELECT DATE_FORMAT(data, '%Y-%m') AS mes,SUM(valor_pago) AS total_pago
    FROM pagamentos
    WHERE status='Pago'
    GROUP BY mes
    ORDER BY mes ASC
";

$result = $database->query($sql);
$meses = [];
$valores = [];
while($row = $database->fetch_assoc($result)) {
    $mes_formatado = date('M/Y', strtotime($row['mes'].'-01'));
    $meses[] = $mes_formatado;
    $valores[] = $row['total_pago'];
}
?>
<?php
$find = $database->query("SELECT * FROM creditos WHERE status='pendente'");

$emCurso = 0;
$porVencer = 0;
$vencidos = 0;

while($row = $database->fetch_assoc($find)) {
    $data_previsao = $row['data'];
    $Dias = 30; // ou o prazo do tipo de cr룶켨ito
    $date = new DateTime($data_previsao);
    $date->modify('+' . $Dias . ' day');
    $nova_data = $date->format('Y-m-d');

    $dataAtual = new DateTime();
    $dataPrevista = new DateTime($nova_data);
    $intervalo = $dataAtual->diff($dataPrevista);
    $diasRestantes = (int)$intervalo->format('%r%a');

    if ($diasRestantes < 0) {
        $vencidos++;
    } elseif ($diasRestantes <= 5) {
        $porVencer++;
    } else {
        $emCurso++;
    }
}
?>



        <!-- DataTables Example -->
		
        
      </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>

<script>

const meses = <?php echo json_encode($meses); ?>;
const valores = <?php echo json_encode($valores); ?>;

  const ctxBar = document.getElementById("barChart").getContext("2d");
  new Chart(ctxBar, {
    type: "bar",
    data: {
      labels: meses, // substitua pelos meses da DB
      datasets: [{
        label: "Total Pago (MZN)",
        data: valores, // substitua pelos dados da DB
        backgroundColor: "#0d6efd"
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: false } },
      scales: { y: { beginAtZero: true } }
    }
  });

 const dadosCreditos = {
  labels: ["Em Curso", "Por Vencer", "Vencidos"],
  datasets: [{
    label: "Cr룶켨itos",
    data: [
      <?php echo $emCurso; ?>,
      <?php echo $porVencer; ?>,
      <?php echo $vencidos; ?>
    ],
    backgroundColor: ["#198754", "#ffc107", "#dc3545"],
    borderColor: "#fff",
    borderWidth: 2
  }]
};

const ctxPie = document.getElementById("pieChart").getContext("2d");
new Chart(ctxPie, {
  type: "doughnut", // pode ser 'pie' ou 'doughnut'
  data: dadosCreditos,
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: "bottom"
      },
      title: {
        display: true,
        text: "Estado Atual dos Cr룶켨itos"
      }
    }
  }
});

</script>
</body>

</html>
