<?php

// This script fetches how many people have answered a given moment
// and spits out a json with an array of people count, moment ID, and date


	require_once 'processes/config.php';
	require_once 'processes/dbh.inc.php';
	require_once 'processes/checkLogin.php';


$experienceID = mysqli_real_escape_string($connection, trim($_POST['experienceID']));

// Old Query
// (Note: only the tuple (momentID, date) is unique, so same moments yet different dates appear separated from each other)
/*
$sql = "SELECT COUNT(id_student) AS `count`, id_subquestionnair AS momentID, DATE(answered_date) AS `date`
		FROM `student_subquestionnair`
		WHERE id_subquestionnair IN
				(SELECT id_subquestionnair
				 FROM experience_subquestionnair
				 WHERE id_experience = '$experienceID')
		GROUP BY id_subquestionnair, DATE(answered_date)
		ORDER BY DATE(answered_date) ASC";
*/
		
// Fixed Query
// (Note: used date_to_administer instead of date_answered to avoid splitting (momentID, date) tuples)
/*
$sql = "SELECT COUNT(SS.id_student) AS `count`, SS.id_subquestionnair AS momentID, DATE(SQ.date_to_administer) AS `date`
		FROM `student_subquestionnair` AS SS RIGHT JOIN `subquestionnair` AS SQ
	    WHERE SS.id_subquestionnair = SQ.id
		AND SS.id_subquestionnair IN
				(SELECT id_subquestionnair
				 FROM experience_subquestionnair
				 WHERE id_experience = '$experienceID')
		GROUP BY SS.id_subquestionnair, DATE(SQ.date_to_administer)
		ORDER BY DATE(SQ.date_to_administer) ASC";
*/

// Re-fixed Query
// (Note: display 0 for those moments that haven't been answered as of "today")
$sql = "SELECT COUNT(SS.id_student) AS `count`, SQ.id AS momentID, DATE(SQ.date_to_administer) AS `date`, SQ.title AS momentTitle
		FROM `student_subquestionnair` AS SS RIGHT JOIN `subquestionnair` AS SQ
	    ON SS.id_subquestionnair = SQ.id
		WHERE SQ.id IN
				(SELECT id_subquestionnair
				 FROM experience_subquestionnair
				 WHERE id_experience = '$experienceID')
        AND DATE(SQ.date_to_administer) <= CURRENT_DATE
		GROUP BY SQ.id, DATE(SQ.date_to_administer)
		ORDER BY DATE(SQ.date_to_administer) ASC";

$result = mysqli_query($connection, $sql);


// Prepare Result (fetch max score at once)
$maxScore = 0;
while($row = mysqli_fetch_object($result)) {
	
	// Fetch Max Score (for formating chart purposes)
	if($maxScore < $row->count) {
		$maxScore = $row->count;
	}
	
	// Format Date as "<abbreviated month> <day of the month without leading zero>"
	$row->date = date('M j', strtotime($row->date));
	
	// Append to array	
	$data[] = $row;
}

// EXAMPLE:
// $temp = [
// 	[
// 		'count' => 1,
// 		'momentID' => 133,
// 		'date' => '2020-03-12'
// 	]
// ];

$payload = [
	'maxScore' => $maxScore,
	'data' => $data
];

echo json_encode($payload);