load_chart_perbulan();
 
var buyersChart = null;
function load_chart_perbulan(){
	var tahun = $("#periode_beli").val();
	$.ajaxQueue({
		url: base_url +"grafik/perbulan",
		method: "POST",
		data:{tahun:tahun},
		beforeSend: function(){	 
			$("#ChartKonsumenLoading").loading();
		},
		success: function(data_chart) {
		    const comparisonData = data_chart;
			
			const months = comparisonData.map(data => data.month);
			const newBuyers = comparisonData.map(data => parseInt(data.new_buyers) || 0);
			const oldBuyers = comparisonData.map(data => parseInt(data.old_buyers) || 0);
			
			// var objarr = JSON.parse(data);
			// var obj = objarr['omset'];
			
			$("#nama_bulan_konsumen").html('Grafik Kedatangan konsumen Tahun '+tahun);
			// var title = [];
			// var hasil = [];
			// for(var i in obj) {
			// title.push(obj[i].title);
			// hasil.push(obj[i].harga);
			// }
			
			// var lineChartData  = {
			// datasets: [{
			// data: hasil,
			// lineTension: 0.3,
			// backgroundColor: "rgba(78, 115, 223, 0.5)",
			// borderColor: "rgba(78, 115, 223, 1)",
			// pointRadius: 3,
			// pointBackgroundColor: "rgba(78, 115, 223, 1)",
			// pointBorderColor: "rgba(78, 115, 223, 1)",
			// pointHoverRadius: 3,
			// pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
			// pointHoverBorderColor: "rgba(78, 115, 223, 1)",
			// pointHitRadius: 10,
			// pointBorderWidth: 2,
			// label: 'Total'
			// }],
			// labels: title
			// };
            // if(buyersChart!=null){
				// buyersChart.destroy();
			// }
			var ctx = $("#ChartKonsumen");
			const buyersChart = new Chart(ctx, {
				type: 'bar',
				data: {
					labels: months.map(m => "Bulan " + m), // Append '月' for clarity
					datasets: [
						{
							label: 'New Buyers',
							data: newBuyers,
							backgroundColor: 'rgba(75, 192, 192, 0.5)',
							borderColor: 'rgba(75, 192, 192, 1)',
							borderWidth: 1
						},
						{
							label: 'Old Buyers',
							data: oldBuyers,
							backgroundColor: 'rgba(153, 102, 255, 0.5)',
							borderColor: 'rgba(153, 102, 255, 1)',
							borderWidth: 1
						}
					]
				},
				options: {
					scales: {
						y: {
							beginAtZero: true,
							title: {
								display: true,
								text: 'Number of Buyers'
							}
						},
						x: {
							title: {
								display: true,
								text: 'Bulan'
							}
						}
					}
				}
			});
			$("#ChartKonsumenLoading").loading("stop");
		},//end
		error: function(data) {
			// console.log(data);
			$("#ChartKonsumenLoading").loading("stop");
		}
	});	
}