<footer class="footer d-flex flex-column flex-md-row align-items-center justify-content-between">
				<p class="text-muted text-center text-md-left">Copyright © 2021 <a href="https://www.texprint.id" target="_blank">Texprint</a>. All rights reserved</p>
				<p class="text-muted text-center text-md-left mb-0 d-none d-md-block">Handcrafted With <i class="mb-1 text-primary ml-1 icon-small" data-feather="heart"></i></p>
			</footer>
			<!-- partial -->
		
		</div>
	</div>

	<!-- core:js -->
	<script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/core/core.js"></script>
	<!-- endinject -->
  <!-- plugin js for this page -->
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/chartjs/Chart.min.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/jquery.flot/jquery.flot.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/jquery.flot/jquery.flot.resize.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/apexcharts/apexcharts.min.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/progressbar.js/progressbar.min.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/select2/select2.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/dropify/dist/dropify.min.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/vendors/datatables.net/jquery.dataTables.js"></script>
  <script src="https://texapp.is3.cloudhost.id/api/v2/assets/vendors/datatables.net-bs4/dataTables.bootstrap4.js"></script>
<!-- Optional:  polyfill for ES6 Promises for IE11 and Android browser -->

	<!-- end plugin js for this page -->
	<!-- inject:js -->

	<!-- endinject -->
  <!-- custom js for this page -->
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/js/dashboard.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/js/datepicker.js"></script>
  <script src="https://is3.cloudhost.id/texapp/api/v2/assets/js/dropify.js"></script>

	<!-- end custom js for this page -->
<style>
    /* CSS untuk Dropify */
    .dropify-preview {
    max-height: 200px; /* sesuaikan dengan tinggi yang diinginkan */
}


/* CSS untuk memperbesar tampilan gambar di dalam thumbnail */
.dropify-render img {
    width: auto;
    height: 100%;
}

    </style>
	<script>
  $(document).ready(function() {
      

        
            //Select
        $("#submitButtonc").click(function() {
          var dataclient = {
              username: $("#username").val(),
              client_name: $("#client_name").val(),
              password: $("#password").val(),
              client_phone: $("#client_phone").val(),
              client_address: $("#client_address").val(),
              client_email: $("#client_email").val()
          };

          $.ajax({
              url: '<?= site_url('dashboard/clientreg') ?>', // Ganti dengan URL ke endpoint Anda
              type: 'POST',
              data: JSON.stringify(dataclient),
              contentType: 'application/json',
              success: function(response) {
                  console.log('Data berhasil disimpan:', response);
                  var userConfirmation = confirm('Data berhasil disimpan! Apakah Anda ingin me-refresh halaman?');
                  if (userConfirmation) {
                    $('#modalclient').modal('hide');
                    $('.modal-backdrop').remove(); // Remove the backdrop overlay

                    refreshclient ();
                  }
              },
              error: function(error) {
                  console.error('Gagal menyimpan data:', error);
                  var userConfirmation = confirm('Data Gagal disimpan! Apakah Anda ingin me-refresh halaman?');
                  if (userConfirmation) {
                    $('#modalclient').modal('hide');     
                    $('.modal-backdrop').remove(); 
                    refreshclient ();// Remove the backdrop overlay
             }
              }
          });
      });


      

        


        $('.dropify').dropify({
    messages: {
        'default': 'Drag and drop a file here or click',
        'replace': 'Drag and drop or click to replace',
        'remove':  'Remove',
        'error':   'Ooops, something wrong happended.'
    }
});
       

    var chart1; // Global variable for chart
    var chart2; // Global variable for chart
    var chart3; // Global variable for chart
    var chart4; // Global variable for chart


    // Fill select box with years from 2020 to current year
    var currentYear = new Date().getFullYear();
    var select = document.getElementById("tahun");
    for(var i = 2020; i <= currentYear; i++) {
        var option = document.createElement("option");
        option.text = i;
        option.value = i;
        if (i === currentYear) {
            option.selected = true; // Set selected attribute for current year
        }
        select.appendChild(option);
    }

    // Initial chart rendering
    var currentYear = new Date().getFullYear();
    $.ajax({
        url: 'dashboard/chartincome',
        method: 'GET',
        data: {
            year: currentYear
        },
        success: function(response) {
            updateChart1(response.totalIncomeMonthly);
            updateChart2(response.totalOrderMonthly);
            updateChart3(response.chartclient);
            updateChart4(response.recentorders);
            textclient(response.dataclient);
            textorders(response.dataorders);
            console.log(response);


        },
        error: function(xhr, status, error) {
            console.error(error);
        }
    });


    $('.dropify').dropify({
    messages: {
        'default': 'Drag and drop a file here or click',
        'replace': 'Drag and drop or click to replace',
        'remove':  'Remove',
        'error':   'Ooops, something wrong happended.'
    }
});

$('.dropify2').dropify();

    $('#tahun').change(function(){
        var selectedYear = $(this).val();

        $.ajax({
            url: 'dashboard/chartincome',
            type: 'GET',
            data: {
                year: selectedYear
            },
            success: function(response) {
                updateChart1(response.totalIncomeMonthly);
                updateChart2(response.totalOrderMonthly);
                updateChart3(response.chartclient);
                updateChart4(response.recentorders);
                textorders(response.dataorders);

                textclient(response.dataclient);


            },
            error: function(xhr, status, error) {
                console.error(error);
            }
        });
    });


  
    function updateChart1(data) {
		data.forEach(item => {
        item.amount = parseFloat(item.amount).toFixed(2);
    });

        var options = {
            chart: {
                height: 300,
				type: "line",
				parentHeightOffset: 0
			},
			colors: ["#727cf5", "#7ee5e5","#4d8af0"],
			grid: {
			borderColor: "rgba(77, 138, 240, .1)",
			padding: {
				bottom: -6
			}
			},
			stroke: {
			curve: "smooth",
			width: 3
			},
			dataLabels: {
			enabled: false
			},
            series: [{
                name: 'Total Income',
                data: data.map(item => parseFloat(item.amount)) // Data masih dalam bentuk angka
            }],
			markers: {
			size: 0,
			strokeColor: "#fff",
			strokeWidth: 3,
			strokeOpacity: 1,
			fillOpacity: 1,
			hover: {
				size: 6
			}
			},
            xaxis: {
                categories: data.map(item => item.month)
            },
            tooltip: {
                y: {
                    formatter: function(val) {
                        return val.toLocaleString('id-ID', { style: 'currency', currency: 'IDR' });
                    }
                }
            },
        };

        if(chart1) {
            chart1.destroy(); // Destroy previous chart if it exists
        }
        chart1 = new ApexCharts(document.getElementById('chart1'), options);
        chart1.render();
    }

    function updateChart2(data) {
    // Round the numbers to 2 decimal places
		data.forEach(item => {
			item.totalqc = parseFloat(item.totalqc).toFixed(2);
			item.qty = parseFloat(item.qty).toFixed(2);
			item.reject = parseFloat(item.reject).toFixed(2);
		});

		var options = {
			chart: {
				type: 'bar'
			},
			colors: ["#727cf5", "#65B741","#FF9843"],
			series: [{
				name: 'Total QC',
				data: data.map(item => parseFloat(item.totalqc))
			}, {
				name: 'Total Quantity',
				data: data.map(item => parseFloat(item.qty))
			}, {
				name: 'Total Reject',
				data: data.map(item => parseFloat(item.reject))
			}],
			xaxis: {
				categories: data.map(item => item.month)
			},			
			dataLabels: {
			enabled: false
			},
			
		};

		if(chart2) {
			chart2.destroy(); // Destroy previous chart if it exists
		}
		chart2 = new ApexCharts(document.getElementById('chart2'), options);
		chart2.render();
	}

    function updateChart3(data) {
    // Sorting data berdasarkan tanggal secara terbalik (dari yang paling lama)
    data.sort((a, b) => new Date(a.date_created) - new Date(b.date_created));

    var options = {
        chart: {
            type: "line",
            height: 60,
            sparkline: {
                enabled: !0
            }
        },
        series: [{
            name: 'New Client',
            data: data.map(item => item.total_clients) // Data masih dalam bentuk angka
        }],

        stroke: {
            width: 2,
            curve: "smooth"
        },
        markers: {
            size: 0
        },
        xaxis: {
				categories: data.map(item => item.date_created)
			},			
        colors: ["#727cf5"],
       
    };

    if(chart3) {
        chart3.destroy(); // Destroy previous chart if it exists
    }
    chart3 = new ApexCharts(document.getElementById('chart3'), options);
    chart3.render();
}

function updateChart4(data) {
    data.sort((a, b) => new Date(a.tanggal_order) - new Date(b.tanggal_order));
    var options = {
      chart: {
        type: "bar",
        height: 60,
        sparkline: {
          enabled: !0
        }
      },
      plotOptions: {
        bar: {
          columnWidth: "60%"
        }
      },
      colors: ["#727cf5"],
      series: [{
        name: 'Total Orders',
            data: data.map(item => item.qty) // Data masih dalam bentuk angka
      }],
      labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
      xaxis: {
				categories: data.map(item => item.tanggal_order)
			},	

      
    };

    if(chart4) {
        chart4.destroy(); // Destroy previous chart if it exists
    }
    chart4 = new ApexCharts(document.getElementById('chart4'), options);
    chart4.render();
}

function textorders(data) {
    $('#totalOrders').text(data.total_orders_last_10_days);
    var percentageChange2 = data.percentage_change; // Menggunakan variabel yang benar
    var changeClass = (percentageChange2 > 0) ? 'text-success' : ((percentageChange2 < 0) ? 'text-danger' : '');
    $('#percentageChange2').text(percentageChange2.toFixed(1) + '%').addClass(changeClass);

}

function textclient(data) {
        $('#totalClients').text(data.total_clients_last_10_days);
        var percentageChange = data.percentage_change;
        var changeClass = (percentageChange > 0) ? 'text-success' : ((percentageChange < 0) ? 'text-danger' : '');
        $('#percentageChange').text(percentageChange.toFixed(1) + '%').addClass(changeClass);



    }





	});

    

</script>
</body>
</html>    