var selectedDiv;


function load_ffwc_rf_info(station) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://cdn.jsdelivr.net/npm/chart.js";
  document.head.appendChild(script);

  var stations = document.querySelectorAll(".station-list .station");
  stations.forEach(function (item) {
    item.classList.remove("selected");
  });

  // Set the selected class for the clicked station
  station.classList.add("selected");

  // Update the selectedDiv variable with the clicked station
  selectedDiv = station;

  var key_id = station.getAttribute("data-station-key");
  var stationName = station.getAttribute("data-station-name");
  var riverName = station.getAttribute("data-river-name");

  // var to_date = $("#to_date").val();
  // var from_days = $("#from_date").val();

  var day = $('#day5').val();
	var date = $('#to_date').val();

	var datastr1 = "key_id=" + key_id + "&stationName=" + stationName + "&riverName=" + riverName + "&day=" + day + "&date=" + date;
	var datastr = "key_id=" + key_id + "&day=" + day + "&date=" + date;
  var datastr2 = "key_id=" + key_id + "&from_days=" + day + "&to_date=" + date;

  $("#cover-spin").show(0);
  $("#data_to_show_ffwc_rf").load("module/mobiledatalog/ffwc_rf_datatable.php", datastr1);
  
  $.ajax({
    type: "post",
    url: "module/mobiledatalog/ffwc_rf_graph.php",
    data: datastr2,
    caches: false,
    success: function (str) {
      $("#cover-spin").hide();
      if ($.trim(str)) {
        var rf_data = $.parseJSON(str);

        // Prepare data for Chart.js
        var labels = [];
        var rainfallData = [];

        for (var i = 0; i < rf_data.length; i++) {
          labels.push(rf_data[i][0]); // Date
          rainfallData.push(parseFloat(rf_data[i][1])); // Rainfall value
        }

        // Destroy previous chart instance if exists
        if (window.ffwcRfChart) {
          window.ffwcRfChart.destroy();
        }

        var ctx = document.getElementById('graph_canvas_ffwc_rf').getContext('2d');
        window.ffwcRfChart = new Chart(ctx, {
          type: 'bar', // You can also use 'line' if you prefer
          data: {
            labels: labels,
            datasets: [{
              label: 'Rainfall (mm)',
              data: rainfallData,
              borderColor: '#0039e6',
              backgroundColor: 'rgba(0, 57, 230, 0.1)',
              borderWidth: 1,
              fill: true,
              tension: 0.4
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                title: {
                  display: true,
                  text: 'Date'
                }
              },
              y: {
                title: {
                  display: true,
                  text: 'Rainfall (mm)'
                },
                beginAtZero: true
              }
            },
            plugins: {
              title: {
                display: true,
                text: 'FFWC Rainfall Graph'
              },
              legend: {
                position: 'top'
              }
            }
          }
        });
      }
    }
  });
}


function ffwc_load_rf_station_edit_modal(pk) {
	var pid = pk;
	var datastr = "pk=" + pid;
	if(!pid){
		alert("Data Migration of this particular station is not been done, please wait for the migration to edit this stations data.");
	}
	else{
		$("#ffwc_rf_model_edit_body").load("module/mobiledatalog/ffwc_rf_edit_modal.php", datastr);
	}
	//alert(datastr);
}

function ffwc_load_rf_station_add_modal(key_id) {
	// alert(key_id);
	var keyid = key_id;
	var datastr = "keyid=" + keyid;
	
	$("#ffwc_rf_model_add_body").load("module/mobiledatalog/ffwc_rf_add_modal.php", datastr);
}

function update_rf_data() {
	var operation = "update_rf_data";
	var pk = $('#pk_id').val();
	var rf_data = $('#rf_data').val();
	// alert(wl_data);
	var datastr = "operation=" + operation + "&rf_data=" + rf_data + "&pkid=" + pk;
	alert(datastr);
	$.ajax({
		url: "module/mobiledatalog/ffwc_rf_ajax_update.php",
		datatype: 'post',
		data: datastr,
		success: function (data) {
			//	$('#cover-spin').hide();
			// alert(data);
			//console.log(data);
			if (data !== 1) {
				//alert(datastr);
				alert('Information has been updated successfully');
				$('.modal .close').click();
				// document.getElementById('ffwc_model_edit_body').style.display = 'none';
				load_ffwc_rf_info(selectedDiv);
			}
			else {
				//alert(datastr);
				alert('error occurred');
			}
		}
	});
}



function rainfalldata(){
	var operation = "save_rainfall_data";
	var stationcode = $('#stationcode').val();
	var date_rf = $('#date_rf').val();
	var rainfall = $('#rainfall').val();
	
	if(date_rf==""){
		alert('Please mention the Date');
	 	$('#date_rf').focus();
        return false;
	}
	else if(rainfall==""){
		alert('Please mention the Rainfall');
	 	$('#rainfall').focus();
        return false;
	}
	else{
		var datastr = "operation="+operation+"&date_rf="+date_rf+"&rainfall="+rainfall+"&stationcode="+stationcode;
	//	alert(datastr);
		$('#cover-spin').show();
		$.ajax({
			url: "module/mobiledatalog/ffwc_rf_ajax.php",
			datatype: 'post',
			data: datastr,
			success: function (data) {
				$('#cover-spin').hide();
				//alert(data);
				if (data==1) {
					//alert(datastr);
					alert('Rainfall has been added successfully');
					$('#modal_ffwc_rf_add').modal('hide');
					load_ffwc_rf_info(selectedDiv);
				}
				else {
					alert('error occurred');
				}
			}
		});
	}
}



