<?php

	require_once 'config.php';
	require_once 'dbh.inc.php';
	require_once 'checkLogin.php';
	
	
	// EXAMPLE INPUT...
	// array(3) { ["momentID"]=> string(3) "137" ["questionID"]=> string(3) "266" ["removeQuestionFromMoment"]=> string(0) "" }


	if(isset($_POST['removeQuestionFromMoment'])) {
		


		$momentID = mysqli_real_escape_string($connection, trim($_POST['momentID']));
		$questionID = mysqli_real_escape_string($connection, trim($_POST['questionID']));
		
		
		
		// Check that moment ID is not empty string
		// And that it's registered in the database
		if($momentID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify moment ID."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM subquestionnair WHERE id = '$momentID';")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given moment ID ($momentID) not in database."));
			exit();
		}
		
		
		
		// Check that question ID is not empty string
		// And that it's registered in the database
		// And that it belongs to the Questionnaire the Moment belongs to
		if($questionID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify question ID."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM question WHERE id = '$questionID';")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given question ID ($questionID) not in database."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM question WHERE id = '$questionID' AND id IN (SELECT id_question FROM questionnair_question WHERE id_questionnair = (SELECT id_questionnair FROM subquestionnair WHERE id = '$momentID'));")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given question ID ($questionID) is outside the Moment's corresponding Questionnair's scope."));
			exit();
		}
		
		
		// Check that the moment hasn't been answered yet
		if(mysqli_query($connection, "SELECT * FROM student_subquestionnair WHERE id_subquestionnair = '$momentID';")->num_rows !== 0) {
			http_response_code(400);
			echo json_encode(array("error" => "Moment already active, deletion denied."));
			exit();
		}

	
	
		// Remove question from moment
		$query = "DELETE FROM subquestionnair_question WHERE id_subquestionnair = '$momentID' AND id_question = '$questionID';";
		$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
		
	

	
	}