

<script src="https://cdn.jsdelivr.net/npm/apexcharts@3.35.0"></script>

<script type="text/javascript">

(function () {
    // Variabel global
    
  let   typeBar   = "WEEK"
  let   chartBar  = null

  jQuery(document).ready(function($) {
    loadPaymentCount()
    loadOutInTotal()

    loadLineOinOut()
  });

  function loadPaymentCount()
  {

      $.ajax({
          url: '<?= base_url() ?>dashboard/get-payment-count', 
          method: "POST", 
          contentType: false, 
          processData: false, 
          data: JSON.stringify({
            month: $('input[name="month_payment"]').val()
          }),
          success: (response) => {
            
              if(response.success){

                  const has   = response.data.has
                  const hasnt = response.data.hasnt

                  $("#parent_payment_count").html(`<hr class="mt-0 mb-2 py-0 mx-2">
                  <div class="w-100 px-1">
                    <div class="px-1 py-1">
                      <div class="d-flex justify-content-between">
                        <div class="d-flex justify-content-center align-items-center pe-1">
                          <i class='bx bx-check-circle text-primary' style="font-size: 34px;"></i>
                        </div>
                        <div class="d-flex align-items-end flex-column pt-1">
                          <span class="pb-1" style="font-size: 12px;">Total Pelanggan Sudah Bayar</span>
                          <h4 class="text-primary text-end">${has}</h4>
                        </div>
                      </div>
                      <hr class="mt-1 mb-3">
                      <div class="d-flex justify-content-between py-1">
                        <div>
                          <span class="pb-1" style="font-size: 12px;">Total Pelanggan Belum Bayar</span>
                          <h4 class="text-secondary">${hasnt}</h4>
                        </div>
                        <div class="d-flex justify-content-center align-items-center pe-1">
                          <i class='bx bx-x-circle text-secondary' style="font-size: 34px;"></i>
                        </div>
                      </div>
                    </div>
                  </div>`)
                  
              }

          },
          error: (jqXHR, textStatus, errorThrown) => {
             
          }
      });
  }


  function loadOutInTotal()
  {

      $.ajax({
          url: '<?= base_url() ?>dashboard/get-out-in-total', 
          method: "POST", 
          contentType: false, 
          processData: false, 
          data: JSON.stringify({
            month: $('input[name="in_out_payment"]').val()
          }),
          success: (response) => {
             
              if(response.success){

                  const totalIn = new Number(response.data.totalIn)
                  const totalOut = new Number(response.data.totalOut)

                  $("#parent_in_out_total").html(`<hr class="mt-4 mb-3 py-0">
                  <div class="w-100 px-1 pb-3 pt-2">
                    <div class="px-1 py-1">
                      <div class="d-flex justify-content-between">
                        <div>
                          <span class="pb-1" style="font-size: 12px;">Total Pemasukan</span>
                          <h4 class="text-success">Rp. ${totalIn.toLocaleString('id-ID')}</h4>
                        </div>
                        <div class="d-flex justify-content-center align-items-center pe-1">
                          <i class='bx bx-arrow-to-bottom text-success' style="font-size: 34px;"></i>
                        </div>
                      </div>
                      <hr class="mb-4 mt-4">
                      <div class="d-flex justify-content-between pb-4">
                        <div class="pt-2">
                          <span class="pb-1" style="font-size: 12px;">Total Pengeluaran</span>
                          <h4 class="text-danger">Rp. ${totalOut.toLocaleString('id-ID')}</h4>
                        </div>
                        <div class="d-flex justify-content-center align-items-center pe-1 pt-2">
                          <i class='bx bx-arrow-to-top text-danger' style="font-size: 34px;"></i>
                        </div>
                      </div>
                    </div>
                  </div>`)
                  
              }

          },
          error: (jqXHR, textStatus, errorThrown) => {
             
          }
      });
  }


  function loadLineOinOut() {
    $.ajax({
        url: '<?= base_url() ?>dashboard/get-line-out-in',
        method: "POST",
        contentType: 'application/json',
        data: JSON.stringify({
            type: typeBar
        }),
        success: (response) => {
            if(response.success) {
                // Format data untuk tooltip
                const formatTooltip = (value) => {
                    return new Intl.NumberFormat('id-ID', {
                        style: 'currency',
                        currency: 'IDR',
                        minimumFractionDigits: 0
                    }).format(value);
                };

                var options_ = {
                    chart: {
                        type: 'bar',
                        height: 280,
                        width: '100%',
                        stacked: false,
                        toolbar: { show: false },
                        zoom: { enabled: false },
                        animations: {
                          enabled: true,
                          easing: 'linear',
                          speed: 300,
                          animateGradually: {
                            enabled: true,
                            delay: 100
                          },
                          dynamicAnimation: {
                            enabled: true,
                            speed: 250
                          }
                        }
                    },
                    series: [{
                        name: 'Pemasukan',
                        data: response.data.in.y
                    }, {
                        name: 'Pengeluaran',
                        data: response.data.out.y
                    }],
                    xaxis: {
                        categories: response.data.in.x,
                        labels: {
                            rotate: -45,
                            style: {
                                fontSize: '10px',
                                fontFamily: 'Arial'
                            }
                        },
                        tooltip: { enabled: false }
                    },
                    yaxis: {
                        labels: {
                            formatter: function(value) {
                                return new Intl.NumberFormat('id-ID').format(value);
                            }
                        }
                    },
                    colors: ['#71dd37', '#ed4228'],
                    plotOptions: {
                        bar: {
                            columnWidth: '45%',
                            borderRadius: 4,
                            dataLabels: {
                                position: 'top'
                            }
                        }
                    },
                    dataLabels: {
                        enabled: false
                    },
                    legend: {
                        position: 'top',
                        horizontalAlign: 'center'
                    },
                    responsive: [{
                        breakpoint: 768,
                        options: {
                            chart: {
                                height: 350
                            },
                            plotOptions: {
                                bar: {
                                    columnWidth: '60%'
                                }
                            },
                            xaxis: {
                                labels: {
                                    rotate: -90,
                                    style: {
                                        fontSize: '8px'
                                    }
                                }
                            }
                        }
                    }],
                    noData: {
                        text: "Loading data...",
                        align: 'center',
                        verticalAlign: 'middle'
                    }
                };

                if (!chartBar) {
                    chartBar = new ApexCharts(document.querySelector("#barChart"), options_);
                    chartBar.render();
                } else {
                    chartBar.updateOptions(options_, true, true);
                }

            }
        },
        error: (jqXHR, textStatus, errorThrown) => {
            console.error("Error:", textStatus, errorThrown);
        }
    });
  }


  $('input[name="month_payment"]').on('change',function(e) {
    loadingLoadPaymentCount()
    loadPaymentCount()
  })

  $('input[name="in_out_payment"]').on('change',function(e) {
    loadingLoadOutInTotal()
    loadOutInTotal()
  })

  $(".btn-filter-line").on('click', function(e) {
      e.preventDefault();
      const thisType = $(this).attr('data-type');
      
      if(thisType.toUpperCase() !== typeBar.toUpperCase()) {
          $('.btn-filter-line').removeClass('btn-primary').addClass('btn-light-primary');
          $(this).removeClass('btn-light-primary').addClass('btn-primary');
          
          typeBar = thisType;
          // Tampilkan loading state
          if(chartBar) {
              chartBar.updateOptions({
                  noData: {
                      text: "Memuat data...",
                      align: 'center'
                  }
              }, false, true);
              
          }
          
          loadLineOinOut();
      }
  });


  function loadingLoadPaymentCount()
  {
    $("#parent_payment_count").html(`<hr class="mt-0 mb-2 py-0 mx-2">
                <div class="w-100 px-1">
                  <div class="px-1 py-1">
                    <!-- Atas -->
                    <div class="d-flex justify-content-between align-items-start">
                      <div class="d-flex justify-content-center align-items-center pe-1">
                        <div class="skeleton-payment skeleton-payment-icon"></div>
                      </div>
                      <div class="d-flex align-items-end flex-column pt-1">
                        <div class="skeleton-payment skeleton-payment-text-sm"></div>
                        <div class="skeleton-payment skeleton-payment-number mt-1"></div>
                      </div>
                    </div>

                    <hr class="mt-1 mb-3">

                    <!-- Bawah -->
                    <div class="d-flex justify-content-between py-1">
                      <div>
                        <div class="skeleton-payment skeleton-payment-text-sm"></div>
                        <div class="skeleton-payment skeleton-payment-number mt-1"></div>
                      </div>
                      <div class="d-flex justify-content-center align-items-center pe-1">
                        <div class="skeleton-payment skeleton-payment-icon"></div>
                      </div>
                    </div>
                  </div>
                </div>`)
  }

  function loadingLoadOutInTotal()
  {
    $("#parent_in_out_total").html(`<!-- Bawah -->
        <div class="d-flex justify-content-between py-4">
          <div>
            <div class="skeleton-payment skeleton-payment-text-sm"></div>
            <div class="skeleton-payment skeleton-payment-number mt-1"></div>
          </div>
          <div class="d-flex justify-content-center align-items-center pe-1">
            <div class="skeleton-payment skeleton-payment-icon"></div>
          </div>
        </div>
        <hr class="mt-3 mb-5">
        <!-- Bawah -->
        <div class="d-flex justify-content-between py-4">
          <div>
            <div class="skeleton-payment skeleton-payment-text-sm"></div>
            <div class="skeleton-payment skeleton-payment-number mt-1"></div>
          </div>
          <div class="d-flex justify-content-center align-items-center pe-1">
            <div class="skeleton-payment skeleton-payment-icon"></div>
          </div>
        </div>`)
  }


  const villages = JSON.parse('<?= json_encode($chartPer->village) ?>')
  const packages = JSON.parse('<?= json_encode($chartPer->package) ?>')





  const villagesValues = villages.map(item=>{
    return Number(item.total)
  })

  const villagesLabels = villages.map(item=>{

      const hex = Math.floor(Math.random() * 0xffffff).toString(16);

      $("#parent_lables_villages").append(`<div class="d-flex align-items-center mb-1">
          <div>
            <div class=" me-1" style="width: 10px; height: 10px; border-radius: 50%; background-color: ${'#' + hex.padStart(6, '0')};"></div>
          </div>
          <span style="font-size: 12px; ">${item.name}</span>
        </div>`)

      return {
        color: '#' + hex.padStart(6, '0'),
        label: item.name
      }
    
  })

  const villagesColors = villagesLabels.map(item=>{
    return item.color
  })


  var optionsVillage = {
    chart: {
      type: 'donut',
      width: '90%',
      height: 175,
    },
    series: villagesValues,
    labels: [],
    colors: villagesColors,
    dataLabels: {
      enabled: true,
      formatter: function (val, opts) {
        // langsung tampilkan nilai mentah, bukan persen
        return opts.w.config.series[opts.seriesIndex];
      },
      style: {
        fontSize: '10px',
        fontWeight: 'bold',
        colors: ['#fff', '#fff'] // bisa disesuaikan biar kontras dengan warna background
      }
    },
    legend: {
      show: false
    },
    plotOptions: {
      pie: {
        donut: {
          size: '25%',
          labels: {
            show: true,
            name: {
              show: false
            },
            value: {
              show: true,
              fontSize: '0',
              fontWeight: 'bold',
              color: '#fff',
              formatter: () => {
                const total = villagesValues.reduce((a, b) => a + b, 0);
                return total + "";
              }
            },
            total: {
              show: true,
              showAlways: true,
              label: '',
              color: '#fff',
              formatter: () => {
                const total = villagesValues.reduce((a, b) => a + b, 0);
                return total + "";
              }
            }
          }
        }
      }
    },
    tooltip: {
      enabled: false
    }
  };

  var village = new ApexCharts(document.querySelector("#donut-chart-village"), optionsVillage);
  village.render();





  const packagesValues = packages.map(item=>{
    return Number(item.total)
  })

  const packagesLabels = packages.map(item=>{

      const hex = Math.floor(Math.random() * 0xffffff).toString(16);


      $("#parent_lables_packages").append(`<div class="d-flex align-items-center mb-1">
          <div>
            <div class=" me-1" style="width: 10px; height: 10px; border-radius: 50%; background-color: ${'#' + hex.padStart(6, '0')};"></div>
          </div>
          <span style="font-size: 12px; ">${item.name}</span>
        </div>`)

      return {
        color: '#' + hex.padStart(6, '0'),
        label: item.name
      }
    
  })

  const packagesColors = packagesLabels.map(item=>{
    return item.color
  })


  var optionsPackage = {
    chart: {
      type: 'donut',
      width: '90%',
      height: 175,
    },
    series: packagesValues,
    labels: [],
    colors: packagesColors,
    dataLabels: {
      enabled: true,
      formatter: function (val, opts) {
        // langsung tampilkan nilai mentah, bukan persen
        return opts.w.config.series[opts.seriesIndex];
      },
      style: {
        fontSize: '10px',
        fontWeight: 'bold',
        colors: ['#fff', '#fff'] // bisa disesuaikan biar kontras dengan warna background
      }
    },
    legend: {
      show: false
    },
    plotOptions: {
      pie: {
        donut: {
          size: '25%',
          labels: {
            show: true,
            name: {
              show: false
            },
            value: {
              show: true,
              fontSize: '0',
              fontWeight: 'bold',
              color: '#fff',
              formatter: () => {
                const total = packagesValues.reduce((a, b) => a + b, 0);
                return total + "";
              }
            },
            total: {
              show: true,
              showAlways: true,
              label: '',
              color: '#fff',
              formatter: () => {
                const total = packagesValues.reduce((a, b) => a + b, 0);
                return total + "";
              }
            }
          }
        }
      }
    },
    tooltip: {
      enabled: false
    }
  };

  var package = new ApexCharts(document.querySelector("#donut-chart-package"), optionsPackage);
  package.render();








})();

</script>
