<?php 

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

	// EXAMPLE INPUT...
	// array(9) { ["id_experience"]=> string(1) "1" ["m_title"]=> string(5) "title" ["m_description"]=> string(11) "description" ["m_date"]=> string(18) "121212-12-12T12:12" ["m_questionnaire"]=> string(1) "1" ["m_question_1"]=> string(1) "3" ["m_question_2"]=> string(1) "5" ["m_question_3"]=> string(2) "11" ["newMoment"]=> string(0) "" }
	
	if(isset($_POST['newMoment'])) {
	
		
		/*** FETCH THE BASIC INFO OF THE NEW QUESTIONNAIRE ***/
		$experienceID = mysqli_real_escape_string($connection, trim($_POST['id_experience']));
		$momentTitle = mysqli_real_escape_string($connection, trim($_POST['m_title']));
		$momentDescription = mysqli_real_escape_string($connection, trim($_POST['m_description']));
		$momentDate = mysqli_real_escape_string($connection, trim($_POST['m_date']));
		$questionnaireID = mysqli_real_escape_string($connection, trim($_POST['m_questionnaire']));




		/*** (START) FIRST BLOCK OF INPUT VALIDATION ***/
	
		// Check that experienceID is not an empty string
		// And that experienceID is in the database
		if($experienceID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience ID."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM experience WHERE id = $experienceID;")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given experience ID ($experienceID) not in database."));
			exit();
		}

		// Check that momentTitle is not an empty string
		// And that momentTitle doesn't exceed 60 characters
		if($momentTitle === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify moment title."));
			exit();
		} else if(mb_strlen($momentTitle) > 60) {
			http_response_code(400);
			echo json_encode(array("error" => "Moment title too long (max. is 60 characters)."));
			exit();
		}

		// Check that momentDescription is not an empty string
		// And that momentDescription doesn't exceed 100 characters
		if($momentDescription === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify moment description."));
			exit();
		} else if(mb_strlen($momentDescription) > 100) {
			http_response_code(400);
			echo json_encode(array("error" => "Moment description too long (max. is 100 characters)."));
			exit();
		}
		
		// Check that momentDate is not an empty string
		// And that momentDate is in appropriate format YYYY-MM-DDThh:mm (e.g. 121212-12-12T12:12)
		// WARNING: only handling AST
		// HELP: https://www.codexworld.com/how-to/validate-date-input-string-in-php/
		
		function validDate($date) {
			$d = date_create_from_format("Y-m-d\TH:i", $date);
			return $d && date_format($d, "Y-m-d\TH:i") === $date;
		}
		
		if($momentDate === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify moment date."));
			exit();
		} else if(!validDate($momentDate)) {
			http_response_code(400);
			echo json_encode(array("error" => "Moment date ($momentDate) given in wrong format (use YYYY-MM-DDTHH:mm instead)."));
			exit();
		}
		
		/*** (END) FIRST BLOCK OF INPUT VALIDATION ***/





		/*** INITIALIZE OTHER VARIABLES ***/
		$questionIDs = array();
		$numberOfQuestions = 0;
		
		
		/*** STORE THE QUESTIONS' DATA ***/
		// WARNING: $start IS VERY SENSITIVE TO NUMBER OF INPUTS GIVEN //
		$start = 5;
		for($i = $start; $i < count($_POST) - 1; $i++) {
		
			$questionIDs[] = mysqli_real_escape_string($connection, trim(array_values($_POST)[$i]));
			$numberOfQuestions++;
			
			// Check that questionID is not an empty string
			// And that the questionID is in the database
			// And that there is not a duplicate questionID in the array (regardless of whether in DB or not)
			// NOTE: array_count_values($arr)[$key] might return null if $key not in $arr
			if($questionIDs[$numberOfQuestions - 1] === "") {
				http_response_code(400);
				echo json_encode(array("error" => "Please specify question ID (in Question #$numberOfQuestions)."));
				exit();
			} else if(mysqli_query($connection, "SELECT * FROM question WHERE id = ".$questionIDs[$numberOfQuestions - 1])->num_rows !== 1) {
				http_response_code(400);
				echo json_encode(array("error" => "Given question ID (".$questionIDs[$numberOfQuestions - 1].") not in database."));
				exit();
			} else if(array_count_values($questionIDs)[$questionIDs[$numberOfQuestions - 1]] !== 1) {
				http_response_code(400);
				echo json_encode(array("error" => "Duplicate question (in Question #$numberOfQuestions)."));
				exit();
			}
			
		}
		
		
		
		
		
		/*** START OF DB QUERIES ***/
// 		exit();
// 		while(TRUE) {
// 			exit();
// 		}
// 		exit();	
		/*** IF IT GOT THROUGH VALIDATION, IT'S TOO LATE ***/
		
		
		

		/*** CREATE MOMENT, RETRIEVE ITS ID (TO USE IT IN TABLES subquestionnair_question AND experience_subquestionnair) AND HOOK TO CURRENT EXPERIENCE ***/
		$queryMoment = "INSERT INTO subquestionnair (title, description, id_questionnair, date_to_administer) VALUES ('$momentTitle','$momentDescription','$questionnaireID','$momentDate');";
		if(!mysqli_query($connection, $queryMoment)) {
			echo $queryMoment . "<br>";
			die("Error: Couldn't create moment with title $momentTitle<br>".mysqli_error($connection));
		}

		$momentID = mysqli_insert_id($connection) or die('Error: '.mysqli_error($connection));
		
		$queryHookMomentToExperience = "INSERT INTO experience_subquestionnair (id_experience, id_subquestionnair) VALUES ('$experienceID', '$momentID');";
		if(!mysqli_query($connection, $queryHookMomentToExperience)) {
			echo $queryHookMomentToExperience . "<br>";
			die("Error: Couldn't hook moment to experience (Moment ID: $momentID, Experience ID: $experienceID)<br>".mysqli_error($connection));
		}
		
		
		// DEBERIA DE POPULAR LA TABLA DE schedule???
		// DEBERIA DE POPULAR LA TABLA DE reminder_subquestionnair??
		
		
		/*** HOOK EACH QUESTION TO NEWLY CREATED MOMENT ***/
		for($i = 0; $i < count($questionIDs); $i++) {
			$queryQuestion = "INSERT INTO subquestionnair_question (id_subquestionnair, id_question) VALUES ('$momentID','".$questionIDs[$i]."');";
			if(!mysqli_query($connection, $queryQuestion)) {
				echo $queryQuestion . "<br>";
				die("Error: Couldn't hook question to moment (Question ID: ".$questionIDs[$i].", Moment ID: $momentID)<br>".mysqli_error($connection));
			}
		}
		
		
		
	}
	
	
?>