{% extends "admin/change_list.html" %}
{% load static %}
{% block content %}
    <!--
    <div style="margin-bottom: 30px; padding: 20px; background-color: #eef;">
        <h3>Tableau des cotisations</h3>
        <p>Nombre total : {{ cl.result_count }}</p>
    </div>
-->
<div class="col-lg-12 d-flex flex-wrap">

<div class="col-lg-4">

  <div>
    <div> <small> Filtrer </small> </div>
    <div>
      <select readonly class="form-control my-1">
        <option value="month">Mois</option>
        <!-- <option value="week">Semaine</option>
        <option value="day">Jour</option> -->
      </select>
    </div>

  </div>
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <button class="btn btn-outline-primary" onclick="changeYear(-1)">←</button>
      <h4 class="mb-0" id="amonthYear"> 2025 </h4>
      <button class="btn btn-outline-primary" onclick="changeYear(1)">→</button>
    </div>
    <div class="calendar-widget card-body">
      <div class="row fw-bold text-center pb-2s">
        <div data-i="1" class="col btn p-1 border m-1">Jan</div>
        <div data-i="2" class="col btn p-1 border m-1">Fev</div>
        <div data-i="3" class="col btn p-1 border m-1">Mar</div>
        <div data-i="4" class="col btn p-1 border m-1">Avr</div>
        <div data-i="5" class="col btn p-1 border bg-primary m-1">Mai</div>
        <div data-i="6" class="col btn p-1 border m-1">Jui</div>
      </div>
      <div class="row fw-bold text-center border-bottom pb-2">
        <div data-i="7" class="col btn p-1 border m-1">Jul</div>
        <div data-i="8" class="col btn p-1 border m-1">Aou</div>
        <div data-i="9" class="col btn p-1 border m-1">Sep</div>
        <div data-i="10" class="col btn p-1 border m-1">Oct</div>
        <div data-i="11" class="col btn p-1 border m-1">Nov</div>
        <div data-i="12" class="col btn p-1 border m-1">Dec</div>
      </div>
        <!--
        <div class="row flex-wrap calendar" id="calendarDates"></div>
      -->
    </div>
  </div>


</div>

  <div class="col-lg-4">
    <div> Comptes ayant cotises <b> ce Mois </b> </div>
    
    <div class="card">
      <div class="card-body">
        <div> <canvas style="max-height: 200px;" id="ctx2"></canvas> </div>
      </div>
    </div>

  </div>

  <div class="col-lg-4">
    <div> Cotisation de <b> ce Mois </b> </div>
    
    <div class="card">
      <div class="card-body">
        <div class="d-flex justify-content-between"> 
          <div class="h4"> <span id="cotisation_nb">300000</span> FCFA</div>
          <div> <i class="fas fa-angle-up text-success"></i></div>
        </div>
      </div>
    </div>

  </div>

<div class="p-1 col-lg-12">
  <div class="card">
    <div class="card-body">
      <div> <canvas id="ctx"></canvas> </div>

    </div>

  </div>
</div>

</div>

{{ block.super }}
<script src="{% static 'hub/js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'hub/js/chart.js' %}"></script>
<script>
  var list_mois = ["","Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre"]
  var actuMonth = new Date().getMonth()+1;

  const monthYear = document.getElementById('monthYear');
  const calendarDates = document.getElementById('calendarDates');
  let currentDate = new Date();

  function renderCalendar(date) {
    const year = date.getFullYear();
    const month = date.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
      const startDay = (firstDay.getDay() + 6) % 7; // Lundi = 0

      //monthYear.textContent = `${date.toLocaleString('fr-FR', { month: 'long' })} ${year}`;
      //calendarDates.innerHTML = '';

      for (let i = 0; i < startDay; i++) {
        const emptyDiv = document.createElement('div');
        emptyDiv.className = "col day";
        //calendarDates.appendChild(emptyDiv);
      }

      for (let i = 1; i <= lastDay.getDate(); i++) {
        const div = document.createElement('div');
        div.className = 'col day';
        const today = new Date();
        if (i === today.getDate() && month === today.getMonth() && year === today.getFullYear()) {
          div.classList.add('today');
        }
        div.innerText = i;
        //calendarDates.appendChild(div);
      }
    }

    function changeYear(offset) {
      amonthYear = document.getElementById("amonthYear");
      var val = parseInt(amonthYear.textContent) ;
      val += offset;
      amonthYear.textContent = val;
      //currentDate.setMonth(currentDate.getMonth() + offset);
      //renderCalendar(currentDate);
    }

    renderCalendar(currentDate);

  function loadAjaxFunction0(is_edit=0,comptes=null,arg_datas=null){
    if ( is_edit == 0)
    {
      ctx = document.getElementById("ctx");
      ctx = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: [
            {% for c in cl.result_list %}
            "{{c.versement.compte}}",
            {% endfor %}
          ],
          datasets: [{
            label: 'Montant cotisé : Mai 2025',
            data: [
            {% for c in cl.result_list %}
            "{{c.versement.montant}}",
            {% endfor %}
            ],
            //Array(12).fill(0),  // 12 valeurs à zéro
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
            borderColor: 'rgba(54, 162, 235, 1)' 
          }]
        },
        options: {
          indexAxis: 'x',  // ➤ Barres horizontales
          scales: {
            x: {
              beginAtZero: true,
              title: {
                display: true,
                text: 'Montant (FCFA)'
              }
            },
            y: {
              title: {
                display: true,
                text: 'Mois'
              }
            }
          },
          plugins: {
            title: {
              display: false,
              text: 'Répartition mensuelle des cotisations'
            }
          }
        }
      });

    }
    else{
        $.ajax({
          url: '/ajax/cotisation/versements_get_data/',
          data: {
            'month':actuMonth,    
          },
          async:true,
          dataType: 'json',
          success: function(data){
            ctx.data.labels = []
            ctx.data.datasets[0].data = [];
            ctx.data.datasets[0].label = "Montant cotisé : "+list_mois[actuMonth] + " " + new Date().getFullYear()
            for (var j=0;j<data.cotisations.length;j++){
              ctx.data.labels.push(data.cotisations[j].versement__compte__nom_prenom)
              ctx.data.datasets[0].data.push(data.cotisations[j].versement__montant)
            }
            ctx.update();            
          },
          error: function(data){

          }
      }); 
    }
  }

  function nb_cotisations_month(a_ok,b_non){
    ctx2 = document.getElementById("ctx2");
    ctx2 = new Chart(ctx2, {
      type: 'pie',
      data: {
        labels: [
          "Ok","Pas Encore"
        ],
        datasets: [{
          label: 'Comptes ayant deje cotisé',
          data: [
          a_ok,b_non
          ],
      backgroundColor: [
        'rgb(54, 162, 235)',
        'rgb(255, 99, 132)',
        'rgb(255, 205, 86)'
      ],
        }]
      }
    });
  }



// AJAX FUNCTIONS
function loadAjaxFunction1(is_loaded=false){
  $.ajax({
          url: '/ajax/cotisation/versements_count/',
          data: {
            'month':actuMonth,    
          },
          async:true,
          dataType: 'json',
          success: function(data){
            if (is_loaded == false){
              nb_cotisations_month(data.cts,data.no_cts)
            }
            else{
              ctx2.data.datasets[0].data = [data.cts,data.no_cts];
              ctx2.update();
            }
          },
          error: function(data){

          }
  });  
}

function loadAjaxFunction2(is_loaded=false){
  $.ajax({
          url: '/ajax/cotisation/versements_total/',
          data: {
            'month':actuMonth,    
          },
          async:true,
          dataType: 'json',
          success: function(data){
            if (is_loaded == false){
              $("#cotisation_nb").text(data.total);
            }
            else{
              $("#cotisation_nb").text(data.total);
            }
          },
          error: function(data){

          }
  });  
}

loadAjaxFunction0();
loadAjaxFunction1();
loadAjaxFunction2();

$(".calendar-widget .col").click( function(){ 
  $(".calendar-widget .col").removeClass("bg-primary")
  actuMonth =  parseInt( $(this).attr("data-i") );
  $(this).addClass("bg-primary");
  loadAjaxFunction1(true);
  loadAjaxFunction2(true);
  loadAjaxFunction0(1);

});

</script>
  {% endblock %}

