<?php

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


	// EXAMPLE INPUT...
	// array(10) { ["questionID"]=> string(3) "266" ["update_q_premise"]=> string(7) "Saludos" ["update_q_type"]=> string(1) "1" ["update_min_val"]=> string(1) "1" ["update_min_text"]=> string(5) "adios" ["update_max_val"]=> string(1) "5" ["update_max_text"]=> string(4) "hola" ["update_q_category"]=> string(2) "92" ["update_q_subcategory"]=> string(3) "115" ["updateQuestion"]=> string(0) "" }
	
	// WARNING: SHOULD CHECK THAT CATEGORY/SUBCATEGORY GIVEN CORRESPOND TO THE QUESTIONNAIRE ID

	if(isset($_POST['updateQuestion'])) {
	
	
	
		$questionID = mysqli_real_escape_string($connection, trim($_POST['questionID']));

		// Check that question ID is not empty string
		// And that it's registered in the database
		if($questionID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience 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 experience ID ($id) not in database."));
			exit();
		}
	
	
	
		// UPDATE PREMISE
		if(isset($_POST['update_q_premise'])) {
		
			$premise = mysqli_real_escape_string($connection, trim($_POST['update_q_premise']));
			
			// Check that premise is not empty string
			// And that it doesn't exceed 600 characters (database limit)
			if($premise === "") {
				http_response_code(400);
				echo json_encode(array("error" => "Question premise can't be empty."));
				exit();
			} else if(mb_strlen($premise) > 600) {
				http_response_code(400);
				echo json_encode(array("error" => "Question premise too long (max. is 600 characters)."));
				exit();
			}
			
			$query = "UPDATE `question` SET `premise` = '$premise' WHERE `id` = '$questionID';";
			$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
			
		}

	
	
	
		// UPDATE TYPE
		if(isset($_POST['update_q_type'])) {
		
			$typeID = mysqli_real_escape_string($connection, trim($_POST['update_q_type']));
			
			// Check that question type isn not empty string
			// If the question type is neither (invalid; nor "1" nor "2"), let user know (user probably tampered with client-side)
			if($typeID === "" || ($typeID != "1" && $typeID != "2")) {
				http_response_code(400);
				echo json_encode(array("error" => "Please specify a type (1 for scaled, 2 for open)."));
				exit();
			}
			
			
			// If the question type is scaled (e.g. value of "1"), make sure all the min/max settings are valid
			// If the question type is open, we don't have to check for min/max settings
			if($typeID === "1") {
			
			
				// FETCH MIN VAL, MAX VAL, MIN TEXT AND MAX TEXT
				$minVal = mysqli_real_escape_string($connection, trim($_POST['update_min_val']));
				$maxVal = mysqli_real_escape_string($connection, trim($_POST['update_max_val']));
				$minText = mysqli_real_escape_string($connection, trim($_POST['update_min_text']));
				$maxText = mysqli_real_escape_string($connection, trim($_POST['update_max_text']));

			
				// Check if minVal is not 1 (we decided it should be like that)
				if($minVal !== "1") {
					http_response_code(400);
					echo json_encode(array("error" => "Minimum value has to be 1."));
					exit();
				}


				// Check if minText is not an empty string
				if($minText === "") {
					http_response_code(400);
					echo json_encode(array("error" => "Please specify a valid minimum text."));
					exit();
				} else if(mb_strlen($minText) > 40) {
					http_response_code(400);
					echo json_encode(array("error" => "Minimum text '$minText' too long (max. is 40 characters)."));
					exit();
				}
				
				
				// Check if maxVal is greater or equal to 2 (we decided it should be like that)
				// REMINDERS:
					// is_numeric() ensures the string is a number
					// intval() returns truncates "starting numeric-like" numbers (e.g. 1234asdf is 1234)
					// intval() returns 0 if it detects "normal string" (e.g. asdf1234 is 0)
				if(!is_numeric($maxVal)) {
					http_response_code(400);
					echo json_encode(array("error" => "Maximum value has to be numeric."));
					exit();
				} else if(intval($maxVal) < 2) {
					http_response_code(400);
					echo json_encode(array("error" => "Maximum value has to be greater or equal to 2."));
					exit();
				}
				
				
				// Check if maxText is not an empty string
				if($maxText === "") {
					http_response_code(400);
					echo json_encode(array("error" => "Please specify a valid maximum text."));
					exit();
				} else if(mb_strlen($maxText) > 40) {
					http_response_code(400);
					echo json_encode(array("error" => "Maximum text '$maxText' too long (max. is 40 characters)."));
					exit();
				}
				
				
				// Check that maxText and minText are different strings
				if(mb_strtolower($maxText) === mb_strtolower($minText)) {
					http_response_code(400);
					echo json_encode(array("error" => "Labels must be different."));
					exit();
				}
				


				// First change the question type
				$query = "UPDATE `question` SET `id_type` = '$typeID' WHERE `id` = '$questionID'";
				$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
				
				
				// Fetch all the min/max labels and values (if already present)
				if(mysqli_query($connection, "SELECT * FROM question_type WHERE id_question = '$questionID';")->num_rows === 4) {
				
					// Then update all the min/max labels and values
					$query = "UPDATE `question_type` SET value = '$minVal' WHERE `id_type` = '$typeID' AND `id_question` = '$questionID' AND `label` = 'min_val';";
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));

					$query = "UPDATE `question_type` SET value = '$minText' WHERE `id_type` = '$typeID' AND `id_question` = '$questionID' AND `label` = 'min_texto';";				
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));

					$query = "UPDATE `question_type` SET value = '$maxVal' WHERE `id_type` = '$typeID' AND `id_question` = '$questionID' AND `label` = 'max_val';";
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));

					$query = "UPDATE `question_type` SET value = '$maxText' WHERE `id_type` = '$typeID' AND `id_question` = '$questionID' AND `label` = 'max_texto';";				
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));

				
				} else {

					// Then create all the new min/max labels and values
					$query = "INSERT INTO `question_type` (`id_type`, `id_question`, `label`, `value`) VALUES ('$typeID', '$questionID', 'min_val', '$minVal');";
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
				
					$query = "INSERT INTO `question_type` (`id_type`, `id_question`, `label`, `value`) VALUES ('$typeID', '$questionID', 'min_texto', '$minText');";
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
				
					$query = "INSERT INTO `question_type` (`id_type`, `id_question`, `label`, `value`) VALUES ('$typeID', '$questionID', 'max_val', '$maxVal');";
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
				
					$query = "INSERT INTO `question_type` (`id_type`, `id_question`, `label`, `value`) VALUES ('$typeID', '$questionID', 'max_texto', '$maxText');";
					$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
				
				}
				
				
			
			} else if($typeID === "2") {
			
				// First change the question type
				$query = "UPDATE `question` SET `id_type` = '$typeID' WHERE `id` = '$questionID';";
				$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));    
				
				// Then delete the min/max labels and values
				$query = "DELETE FROM `question_type` WHERE `id_question` = '$questionID'";
				$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
				
			}
			
			
			
			


		// UPDATE CATEGORY
		if(isset($_POST['update_q_category'])) {
		
			$categoryID = mysqli_real_escape_string($connection, trim($_POST['update_q_category']));
			
			// Check that category ID is not empty string
			// And that it's registered in the database
			if($categoryID === "") {
				http_response_code(400);
				echo json_encode(array("error" => "Please specify category ID."));
				exit();
			} else if(mysqli_query($connection, "SELECT * FROM category WHERE id = '$categoryID';")->num_rows !== 1) {
				http_response_code(400);
				echo json_encode(array("error" => "Given category ID ($categoryID) not in database."));
				exit();
			}
			
			$query = "UPDATE `question` SET `id_category` = '$categoryID' WHERE `id` = '$questionID';";
			$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
 		   	
		}
	
	
	
		// UPDATE SUBCATEGORY
		if(isset($_POST['update_q_subcategory'])) {
		
			$subcategoryID = mysqli_real_escape_string($connection, trim($_POST['update_q_subcategory']));
			
			// Check that subcategory ID is not empty string
			// And that it's registered in the database
			if($subcategoryID === "") {
				http_response_code(400);
				echo json_encode(array("error" => "Please specify subcategory ID."));
				exit();
			} else if(mysqli_query($connection, "SELECT * FROM subcategory WHERE id = '$subcategoryID';")->num_rows !== 1) {
				http_response_code(400);
				echo json_encode(array("error" => "Given subcategory ID ($subcategoryID) not in database."));
				exit();
			}
		
			$query = "UPDATE `question` SET `id_subcategory` = '$subcategoryID' WHERE `id` = '$questionID';";
			$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection));
			
		}







			
		}
	
	
	
		// UPDATE REFERENCE
// 		if(isset($_POST['newReference'])) {
// 			$query = "UPDATE `question` SET `id_referencia`='".$_POST['newReference']."' WHERE `id`='".$_POST['id']."';";
// 			$result = mysqli_query($connection, $query) or die("Error: ".mysqli_error($connection)); 
// 		}
	
	
	

	
	}