<?php
session_start();
include("../../php_crud/my_class.php");
$obj = new my_class();
extract($_REQUEST);

$month_day = cal_days_in_month(CAL_GREGORIAN, $month, $year);

$data = array(
	'Title' => '',
	'Regular' => array(),
	'High' => array(),
	'Low' => array(),
);

$wl_cols = "WL, TO_CHAR(SWL_DATE, 'DD/MON/RRRR HH24:MI:SS') AS READ_DATE, DATA_TYPE";
$wl_cond = "STATION_ID='$station_id' AND TO_DATE(SWL_DATE, 'DD-MON-RRRR') BETWEEN TO_DATE('$year-$month-01', 'YYYY-MM-DD') AND TO_DATE('$year-$month-$month_day', 'YYYY-MM-DD') AND (DATA_TYPE='R' OR DATA_TYPE='H' OR DATA_TYPE='L') ORDER BY SWL_DATE ASC";

$wl_data = $obj->View_colmn_By_Cond("HYDROLOGY.SWL_DATA@HYDRO10", $wl_cols, $wl_cond);

$regularValues = array();
$highValues = array();
$lowValues = array();

foreach ($wl_data as $wl_reads) {
	$read_date = $wl_reads['READ_DATE'];
	$sel_reg_wl = $wl_reads['WL'];
	$data_type = $wl_reads['DATA_TYPE'];

	if ($data_type === 'R') {
		$regularValues[] = $sel_reg_wl;
	} elseif ($data_type === 'H') {
		$highValues[] = $sel_reg_wl;
	} elseif ($data_type === 'L') {
		$lowValues[] = $sel_reg_wl;
	}
}

// Distribute values from Regular to High and Low arrays
$regularCount = count($regularValues);
$highCount = $regularCount / 5; // Five Regular data points for one High data point
$stat_cols = "STATION_ID,STATION_NAME,RIVER_NAME,DISTRICT_NAME,UPZL_NAME";
$stat_info = $obj->View_column_details_By_Cond("SW_STATION_AUTO_MANUAL", $stat_cols, "STATION_ID='$station_id'");

$data['Title'] = "Station Name: " . $stat_info['STATION_NAME'] . " (" . $stat_info['STATION_ID'] .
	"), River: " . $stat_info['RIVER_NAME'] . ", District: " . $stat_info['DISTRICT_NAME'] .
	", Upazila: " . $stat_info['UPZL_NAME'];

for ($i = 0; $i < $regularCount; $i++) {
	$data['Regular'][] = $regularValues[$i];

	if ($i % 5 === 0) {
		$data['High'][] = $highValues[$i / 5];
		$data['Low'][] = $lowValues[$i / 5];
	} else {
		$data['High'][] = null;
		$data['Low'][] = null;
	}
}

$graph_data = json_encode($data);
echo $graph_data;
