<?php

	require_once 'config.php';
	require_once 'dbh.inc.php';
	require_once 'checkLogin.php';
	
	
	// EXAMPLE INPUT...
	// array(2) { ["momentID"]=> string(3) "137" ["deleteMoment"]=> string(0) "" }
	
	// WARNING: SHOULD CONFIRM THAT MOMENT BELONGS TO THE CORRECT USER (AUTHENTICATE THE TRANSACTION)


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


		$momentID = mysqli_real_escape_string($connection, trim($_POST['momentID']));
		
		
		// Check that moment ID is not empty string
		if($momentID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify moment ID."));
			exit();
		}
		
		
		// Check that moment is registered in the database
		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 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();
		}
		
		
		
		/*** STEPS ***/

		// DELETE MOMENT-QUESTION RELATIONS
		// DELETE EXPERIENCE-MOMENT RELATION
		// DELETE MOMENT



		// Delete moment-question relations
		$queryUnhookQuestionFromMoment = "DELETE FROM subquestionnair_question WHERE id_subquestionnair = '$momentID';";
		$result = mysqli_query($connection, $queryUnhookQuestionFromMoment) or die("Error: ".mysqli_error($connection));

		// Delete experience-moment relation
		$queryUnhookMomentFromExperience = "DELETE FROM experience_subquestionnair WHERE id_subquestionnair = '$momentID';";
		$result = mysqli_query($connection, $queryUnhookMomentFromExperience) or die("Error: ".mysqli_error($connection));

		// Delete moments
		$queryDeleteMoments = "DELETE FROM subquestionnair WHERE id = '$momentID';";
		$result = mysqli_query($connection, $queryDeleteMoments) or die("Error: ".mysqli_error($connection));
		
		
	
	}