function load_well_by_district_id(sel_district_id){
	flushData();
//	alert(sel_district_id);
	//var dist_arr = sel_district_id.split("#");
	var datastr = "sel_district_id="+sel_district_id;
	//alert(datastr);
	$("#gwt_com_old_id_list_holder").load('module/ground_water_ex/gw_old_id_by_district.php',datastr);
}

function load_new_id_by_old_id(well_id){
	flushData();
	$("#gwt_com_well_id").val(well_id);
}

function flushData() {
	$('#gw_weekly_com_graph_holder').html("");
}

$('#gwt_com_from_year').on("keypress",function(){
	flushData();
});

$('#gwt_com_to_year').on("keypress",function(){
	flushData();
});

function load_gwt_weekly_com_graph(){
	var district = $('#gwt_com_district').val();
	var well_id = $('#gwt_com_well_id').val();
    var from_year = $('#gwt_com_from_year').val();
    var to_year = $('#gwt_com_to_year').val();
	if (!well_id) {
		alert('Please Select Well');
		$("#gwt_com_well_id").focus();
		return false;
	}
	else if (!from_year) {
		alert('Please select From Year');
		$("#gwt_com_from_year").focus();
		return false;
	}
	else if (!to_year) {
		alert('Please select To Year');
		$("#gwt_com_to_year").focus();
		return false;
	}
	else{
		var datastr = "well_id="+well_id+"&from_year="+from_year+"&to_year="+to_year;	
		//alert(datastr);
		$('#gw_weekly_com_graph_holder').load('module/ground_water_ex/gwt_weekly_comp_graph_multi_line_holder.php',datastr);
	}
}

function show_com_graph() {
	var district = $('#com_grph_sel_district').val();
	var upzila = $('#com_grph_sel_upazila').val();
	var old_id = $('#com_grph_sel_old_id').val();
	var well_id = $('#com_grph_sel_well_id').val();
    var from_year = $('#com_grph_sel_from_year').val();
    var to_year = $('#com_grph_sel_to_year').val();
	
	var datastr = "well_id="+well_id+"&from_year="+from_year+"&to_year="+to_year;
	//alert(datastr);
	// url: "module/ground_water_ex/gw_weekly_graph_year_wise.php", // Replace with the actual path to your PHP script

	$('#cover-spin').show(0);
	$.ajax({
		type: "post",
		url: "module/ground_water_ex/gw_weekly_graph_comp_graph.php",
		data: datastr,
		success: function (str) {
			//alert(str);
			if ($.trim(str)) {
				//console.log(str);
				$('#cover-spin').hide();
				var data = $.parseJSON(str);

				// Destroy existing chart instance if it exists
				let chartStatus = Chart.getChart("linechart"); // <canvas> id
				if (chartStatus != undefined) {
					chartStatus.destroy();
				}

				// Restructure data for Chart.js
				var chartData = {
					labels: [], // Array to store x-axis labels (distances)
					datasets: [],
				};

				// Iterate through each year in the data
				for (var year in data) {
					if (data.hasOwnProperty(year)) {
						var yearlyData = data[year];

						// Extract distances from the first array (assuming all arrays have the same distances)
						if (chartData.labels.length === 0) {
							chartData.labels = yearlyData.map(function (item) {
								// Extracting only the month and date from the first value (date)
								return item[0];
							});
						}

						// Extract RL values for the current year
						var rlValues = yearlyData.map(function (item) {
							return item[1]; // Extracting the second value (RL value)
						});

						// Add a dataset for the current year
						chartData.datasets.push({
							label: year,
							data: rlValues,
							fill: false,
							borderColor: getRandomColor(),
							spanGaps: true,
						});
					}
				}

				// Assuming you have the necessary variables (statName, station_id, riverName) defined
				var ctx = document.getElementById("gw_weekly_com_curve_chart").getContext("2d");
				lineChart = new Chart(ctx, {
					type: "line",
					data: chartData,
					options: {
						scales: {
							x: {
								display: true,
								title: {
									display: true,
									text: 'Date (Month-Day)', // x-axis label
								},
							},
							y: {
								display: true,
								title: {
									display: true,
									text: 'Water Table (m)', // y-axis label
								},
								beginAtZero: true,
								reverse: true,
							},
						},
						plugins: {
							title: {
								display: true,
								text: ["GW Table (Weekly) Data Yearly Comparison Graph", "Well: "+well_id+" ("+old_id+"), District: "+district+", Upazila:"+upzila+", Time Period: "+ from_year + " to " + to_year],
								font: {
									size: 14, // Adjust the font size as needed
									lineHeight: 1.5
								},
								padding: {
									top: 5,
									bottom: 10
								},				
							},
						},
						// Your other chart options here
					},
				});
			}
		}
	});
		// Function to generate a random color for the chart line
	function getRandomColor() {
		var letters = '0123456789ABCDEF';
		var color = '#';

		// Generate a color
		for (var i = 0; i < 6; i++) {
			color += letters[Math.floor(Math.random() * 16)];
		}

		// Check if the color is whitish (lightness value greater than a threshold)
		if (isWhitish(color, 0.8)) {
			// If whitish, generate a different color
			var newColor = getRandomColor();

			// Return the different color
			return newColor;
		}

		// If not whitish, return the generated color
		return color;
	}

	// Function to check if a color is whitish based on its lightness value
	function isWhitish(hexColor, threshold) {
		// Convert hex to RGB
		var r = parseInt(hexColor.substring(1, 3), 16);
		var g = parseInt(hexColor.substring(3, 5), 16);
		var b = parseInt(hexColor.substring(5, 7), 16);

		// Calculate lightness value
		var lightness = (Math.max(r, g, b) + Math.min(r, g, b)) / 510;

		// Check if lightness is greater than the threshold
		return lightness > threshold;
	}
	
}

function download_gwt_weekly_yearly_com_graph() {
	//alert('download_gww_graph_chart');
	var chartContainer = document.getElementById('gw_weekly_com_curve_chart');
	var canvas = document.createElement('canvas');
	canvas.width = chartContainer.offsetWidth;
	canvas.height = chartContainer.offsetHeight;
	//alert(chartContainer.offsetWidth);
	var ctx = canvas.getContext('2d');
	ctx.fillStyle = 'white';
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	html2canvas(chartContainer).then(function(chartCanvas) {
		ctx.drawImage(chartCanvas, 0, 0);
		canvas.toBlob(function(blob) {
			var link = document.createElement('a');
			link.href = URL.createObjectURL(blob);
			link.download = 'Gw Table Weekly Comparison Graph';
			link.click();
		});
	});
}
