// ===============================
// chart-penjualan.js (PATCHED)
// ===============================
//
// Perubahan penting:
// - [PATCH #1] Tambah custom tooltip 2 baris (judul xLabel + baris "Total: Rp.xxxx") 
//              untuk grafik Pendapatan & Desain
// - [PATCH #2] Rapikan opsi legend (gabung display:false + onHover cursor pointer)
// - [PATCH #3] Hover cursor di titik data tetap dipertahankan
//
// Catatan warna:
// - Warna garis pendapatan tetap biru rgba(78,115,223,1)
//   -> sudah sama seperti warna "Pendapatan" di grafik Perbandingan.
// 
// File asal: chart-penjualan.js :contentReference[oaicite:0]{index=0}
// ===============================

// Set new default font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';

// ===============================
// UTIL: format angka rupiah di tooltip
// ===============================
function _formatRupiahTooltip(val){
	// number_format() sudah ada di project kamu untuk format ribuan.
	// fallback aman kalau number_format tidak terdefinisi:
	if (typeof number_format === 'function') {
		return 'Rp.' + number_format(val);
	}
	val = Number(val||0);
	return 'Rp ' + val.toLocaleString('id-ID');
}

// ===============================
// GRAFIK DESAIN
// ===============================
function load_chart_desain(bulan, tahun){
	bulan = bulan?bulan:'';
	tahun = tahun?tahun:'';
	$.ajax({
		url: base_url +"penjualan/grafik_desain/",
		method: "POST",
		data:{bulan:bulan,tahun:tahun},
		beforeSend: function () {
			$("#LoadingGrafikDesain").loading();
		},
		success: myCallbackDesain,
		error: function(data) {
			$("#LoadingGrafikDesain").loading('stop');
		}
	});	
}

function myCallbackDesain (data)
{
	var objarr = JSON.parse(data);
	var obj = objarr['omset'];

	var periodeDesain = objarr.bulan+(objarr.tahun ? ' '+objarr.tahun : '');
	$("#nama_bulan_pendapatan").html('Grafik Desain Bulan '+periodeDesain);
	$("#LoadingGrafik .badge-period").text(periodeDesain);

	var tanggal = [];
	var hasil = [];
	for(var i in obj) {
		tanggal.push(obj[i].tanggal);
		hasil.push(obj[i].total);
	}
	
	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: tanggal
	};
	
	var ctx = $("#myAreaChartDesain");

	var myLineChart = new Chart(ctx, {
		id: 'myAreaChartDesain',
		type: 'line',
		data: lineChartData,
		options: {
			responsive: true,

			// === PATCH #1: tooltip custom 2 baris (judul xLabel + Total Rupiah)
			tooltips: {
				backgroundColor: "rgb(255,255,255)",
				bodyFontColor: "#858796",
				titleMarginBottom: 10,
				titleFontColor: '#6e707e',
				titleFontSize: 14,
				borderColor: '#dddfeb',
				borderWidth: 1,
				xPadding: 15,
				yPadding: 15,
				displayColors: false,
				intersect: false,      // <--- PATCH: pakai false biar lebih enak hover
				mode: 'index',
				caretPadding: 10,
				callbacks: {
					// title = baris pertama tooltip ("nama tgl/bulan/tahun")
					title: function(tooltipItems, data){
						// tooltipItems[0].label untuk Chart.js v2
						return tooltipItems[0].label || '';
					},
					// label = baris kedua tooltip ("Total: Rp.xxxx")
					label: function(tooltipItem, chart) {
						var rawVal = tooltipItem.yLabel;
						return 'Total: ' + _formatRupiahTooltip(rawVal);
					}
				}
			},
			// === END PATCH #1

			title: {
				display: false,
				text: 'Rekapitulasi'
			},
			animation: {
				animateScale: true,
				animateRotate: true
			},
			scales: {
				xAxes: [{
					time: {
						unit: 'date'
					},
					gridLines: {
						display: false,
						drawBorder: false
					},
					ticks: {
						maxTicksLimit: 7
					}
				}],
				yAxes: [{
					ticks: {
						maxTicksLimit: 5,
						padding: 10,
						callback: function(value, index, values) {
							return 'Total.' + number_format(value);
						}
					},
					gridLines: {
						color: "rgb(234, 236, 244)",
						zeroLineColor: "rgb(234, 236, 244)",
						drawBorder: false,
						borderDash: [2],
						zeroLineBorderDash: [2]
					}
				}],
			},

			// === PATCH #2: legend digabung + cursor pointer saat hover legend
			legend: {
				display: false,
				onHover: function(e) {
					e.target.style.cursor = 'pointer';
				}
			},
			// === END PATCH #2

			// === PATCH #3: pointer saat hover titik data
			hover: {
				onHover: function(e) {
					var point = this.getElementAtEvent(e);
					if (point.length) e.target.style.cursor = 'pointer';
					else e.target.style.cursor = 'default';
				}
			}
			// === END PATCH #3
		}
		
	}).draw();
	
	$("#LoadingGrafikDesain").loading('stop');
}


// ===============================
// GRAFIK PENDAPATAN (per hari di bulan aktif)
// ===============================
function load_chart(bulan, tahun){
	bulan = bulan?bulan:'';
	tahun = tahun?tahun:'';
	$.ajax({
		url: base_url +"penjualan/grafik/",
		method: "POST",
		data:{bulan:bulan,tahun:tahun},
		beforeSend: function () {
			$("#LoadingGrafik").loading();
		},
		success: myCallback,
		error: function(data) {
			$("#LoadingGrafik").loading('stop');
		}
	});	
}

var myLineChart=null;
function myCallback (data)
{
	var objarr = JSON.parse(data);
	var obj = objarr['omset'];

	var periodePendapatan = objarr.bulan+(objarr.tahun ? ' '+objarr.tahun : '');
	$("#nama_bulan_pendapatan").html('Grafik Pendapatan Bulan '+periodePendapatan);
	$("#LoadingGrafik .badge-period").text(periodePendapatan);
	$("#dropdownMenuPendapatan").html(objarr.bulan + ' <span class="caret"></span>');

	var tanggal = [];
	var hasil = [];
	for(var i in obj) {
		tanggal.push(obj[i].tanggal);
		hasil.push(obj[i].total);
	}
	
	$(".myAreaChart").attr("id",objarr.bulan);

	var lineChartData  = {
		datasets: [{
			data: hasil,

			// warna biru: ini sudah sama dengan warna "Pendapatan" di grafik Perbandingan
			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: tanggal
	};

	if (myLineChart!=null){
		myLineChart.destroy();
	}
	
	var ctx = $("#"+objarr.bulan);
	
	myLineChart = new Chart(ctx, {
		id: objarr.bulan,
		type: 'line',
		data: lineChartData,
		options: {
			responsive: true,

			// === PATCH #1 (sama konsepnya kayak di grafik desain):
			tooltips: {
				backgroundColor: "rgb(255,255,255)",
				bodyFontColor: "#858796",
				titleMarginBottom: 10,
				titleFontColor: '#6e707e',
				titleFontSize: 14,
				borderColor: '#dddfeb',
				borderWidth: 1,
				xPadding: 15,
				yPadding: 15,
				displayColors: false,
				intersect: false,
				mode: 'index',
				caretPadding: 10,
				callbacks: {
					title: function(tooltipItems, data){
						return tooltipItems[0].label || '';
					},
					label: function(tooltipItem, chart) {
						var rawVal = tooltipItem.yLabel;
						return 'Total: ' + _formatRupiahTooltip(rawVal);
					}
				}
			},
			// === END PATCH #1

			title: {
				display: false,
				text: 'Rekapitulasi'
			},
			animation: {
				animateScale: true,
				animateRotate: true
			},
			scales: {
				xAxes: [{
					time: {
						unit: 'date'
					},
					gridLines: {
						display: false,
						drawBorder: false
					},
					ticks: {
						autoSkip: false,
						fontSize: 8,
						maxRotation: 45,
						minRotation: 30
					}
				}],
				yAxes: [{
					ticks: {
						maxTicksLimit: 5,
						padding: 10,
						callback: function(value, index, values) {
							return 'Rp.' + number_format(value);
						}
					},
					gridLines: {
						color: "rgb(234, 236, 244)",
						zeroLineColor: "rgb(234, 236, 244)",
						drawBorder: false,
						borderDash: [2],
						zeroLineBorderDash: [2]
					}
				}],
			},

			// === PATCH #2: legend gabungan
			legend: {
				display: false,
				onHover: function(e) {
					e.target.style.cursor = 'pointer';
				}
			},
			// === END PATCH #2

			// === PATCH #3: pointer ketika hover titik data
			hover: {
				onHover: function(e) {
					var point = this.getElementAtEvent(e);
					if (point.length) e.target.style.cursor = 'pointer';
					else e.target.style.cursor = 'default';
				}
			}
			// === END PATCH #3
		}
	});
	
	$("#LoadingGrafik").loading('stop');
}	
