<?php 

	require_once 'config.php';
	require_once 'dbh.inc.php';
	require_once 'checkLogin.php';	
	
	// EXAMPLE INPUT...
	// array(3) { ["fromQuestionnaireID"]=> string(1) "1" ["toExperienceID"]=> string(1) "11" ["duplicateQuestionnaire"]=> string(1) "" }

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

		/*** FETCH INPUT ***/
		$fromQuestionnaireID = mysqli_real_escape_string($connection, trim($_POST['fromQuestionnaireID']));
		$toExperienceID = mysqli_real_escape_string($connection, trim($_POST['toExperienceID']));
		$projectID = mysqli_real_escape_string($connection, trim($_POST['projectID']));
		
		
		// Check that questionnaire ID is not empty string
		// And that it's registered in the database
		if($fromQuestionnaireID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify questionnaire ID."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM questionnair WHERE id = '$fromQuestionnaireID';")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given questionnaire ID ($fromQuestionnaireID) not in database."));
			exit();
		}
		
		
		// Check that experience ID is not empty string
		// And that it's registered in the database
		if($toExperienceID === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience ID."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM experience WHERE id = '$toExperienceID';")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given experience ID ($toExperienceID) not in database."));
			exit();
		}
		
		
		
		
		// IF EXPERIENCE BELONGS TO PROJECT, JUST MAKE A "SHALLOW DUPLICATE"
		if(mysqli_query($connection, "SELECT * FROM project_experience WHERE id_project = '$projectID' AND id_experience = '$toExperienceID';")->num_rows === 1) {
	
			$queryHookOldQuestionnaireToExperience = "INSERT INTO experience_questionnair (`id_experience`, `id_questionnair`) VALUES ('$toExperienceID', '$fromQuestionnaireID');";
			if(!mysqli_query($connection, $queryHookOldQuestionnaireToExperience)) {
				echo $queryHookOldQuestionnaireToExperience . "<br>";
				die("Error: Couldn't hook questionnaire to experience<br>".mysqli_error($connection));
			}
			exit();
			
		}
		
		
		
		
		
		/*** FETCH THE QUESTIONNAIRE INFO ***/
		$queryOldQuestionnaire = "SELECT * FROM questionnair WHERE id = '$fromQuestionnaireID';";
		$resultOldQuestionnaire = mysqli_query($connection, $queryOldQuestionnaire) or die("Error: Couldn't fetch questionnaire info from given ID<br>".mysqli_error($connection));
		$rowOldQuestionnaire = mysqli_fetch_assoc($resultOldQuestionnaire);
		
		
		/*** DUPLICATE QUESTIONNAIRE, RETRIEVE ITS ID (TO USE IT IN TABLES experience_questionnair AND questionnair_question) AND HOOK TO CURRENT EXPERIENCE ***/
		$queryQuestionnaire = "INSERT INTO questionnair (`q_title`, `description`) VALUES ('".$rowOldQuestionnaire['q_title']."', '".$rowOldQuestionnaire['description']."');";
		if(!mysqli_query($connection, $queryQuestionnaire)) {
			echo $queryQuestionnaire . "<br>";
			die("Error: Couldn't create questionnaire<br>".mysqli_error($connection));
		}

		$questionnaireID = mysqli_insert_id($connection) or die("Error: Couldn't fetch questionnaire id after creating it<br>".mysqli_error($connection));

		$queryHookQuestionnaireToExperience = "INSERT INTO experience_questionnair (`id_experience`, `id_questionnair`) VALUES ('$toExperienceID', '$questionnaireID');";
		if(!mysqli_query($connection, $queryHookQuestionnaireToExperience)) {
			echo $queryHookQuestionnaireToExperience . "<br>";
			die("Error: Couldn't hook questionnaire to experience<br>".mysqli_error($connection));
		}




		/*** DUPLICATE REFERENCES AND RETRIEVE THEIR ID (TO USE IT IN TABLE question) ***/
		$queryGetReferences = "SELECT DISTINCT q.id_referencia, r.referencia FROM question q JOIN reference r ON q.id_referencia = r.id WHERE q.id IN (SELECT id_question FROM questionnair_question WHERE id_questionnair = '$fromQuestionnaireID');";
		$resultGetReferences = mysqli_query($connection, $queryGetReferences);
		$oldToNewReference = array();
		while($reference = mysqli_fetch_assoc($resultGetReferences)) {
		
			$queryReference = "INSERT INTO reference (`referencia`) VALUES ('" . $reference['referencia'] . "');";
			if(!mysqli_query($connection, $queryReference)) {
				http_response_code(400);
				die(json_encode(array("error" => "Error: Couldn't create questionnaire reference<br>".mysqli_error($connection)."<br>Query: $queryReference")));
			}
			
			$referenceID = mysqli_insert_id($connection) or die(json_encode(array("error" => "Error: Couldn't fetch reference id after creating it<br>".mysqli_error($connection))));
			
			// LINK OLD REFERENCE ID TO NEW REFERENCE ID
			$oldToNewReference[$reference['id_referencia']] = $referenceID;
			
		}


		/*** DUPLICATE CATEGORIES AND RETRIEVE THEIR ID (TO USE IT IN TABLE question AND subcategory) ***/
		$queryGetCategories = "SELECT DISTINCT q.id_category, c.categoria FROM question q JOIN category c ON q.id_category = c.id WHERE q.id IN (SELECT id_question FROM questionnair_question WHERE id_questionnair = '$fromQuestionnaireID');";
		$resultGetCategories = mysqli_query($connection, $queryGetCategories);
		$oldToNewCategory = array();
		while($category = mysqli_fetch_assoc($resultGetCategories)) {
		
			$queryCategory = "INSERT INTO category (`categoria`) VALUES ('" . $category['categoria'] . "');";
			if(!mysqli_query($connection, $queryCategory)) {
				http_response_code(400);
				die(json_encode(array("error" => "Error: Couldn't create questionnaire category<br>".mysqli_error($connection)."<br>Query: $queryCategory")));
			}
			
			$categoryID = mysqli_insert_id($connection) or die(json_encode(array("error" => "Error: Couldn't fetch category id after creating it<br>".mysqli_error($connection))));
			
			// LINK OLD CATEGORY ID TO NEW CATEGORY ID
			$oldToNewCategory[$category['id_category']] = $categoryID;
			
		}


		/*** DUPLICATE SUBCATEGORIES AND RETRIEVE THEIR ID (TO USE IT IN TABLE question) ***/
		$queryGetSubcategories = "SELECT DISTINCT q.id_subcategory, s.subcategoria, s.id_categoria FROM question q JOIN subcategory s ON q.id_subcategory = s.id WHERE q.id IN (SELECT id_question FROM questionnair_question WHERE id_questionnair = '$fromQuestionnaireID');";
		$resultGetSubcategories = mysqli_query($connection, $queryGetSubcategories);
		$oldToNewSubcategory = array();
		while($subcategory = mysqli_fetch_assoc($resultGetSubcategories)) {
		
			$querySubcategory = "INSERT INTO subcategory (`subcategoria`, `id_categoria`) VALUES ('" . $subcategory['subcategoria'] . "', '" . $oldToNewCategory[$subcategory['id_categoria']] . "');";
			if(!mysqli_query($connection, $querySubcategory)) {
				http_response_code(400);
				die(json_encode(array("error" => "Error: Couldn't create questionnaire subcategory<br>".mysqli_error($connection)."<br>Query: $querySubcategory. Dump: ".var_export($oldToNewCategory, true))));
			}
			
			$subcategoryID = mysqli_insert_id($connection) or die(json_encode(array("error" => "Error: Couldn't fetch subcategory id after creating it<br>".mysqli_error($connection))));
			
			// LINK OLD SUBCATEGORY ID TO NEW SUBCATEGORY ID
			$oldToNewSubcategory[$subcategory['id_subcategory']] = $subcategoryID;
			
		}



		
		$queryForQuestions = "SELECT id_question FROM questionnair_question WHERE id_questionnair = '$fromQuestionnaireID';";
		$resultForQuestions = mysqli_query($connection, $queryForQuestions);
		
		/*** CREATE QUESTIONS ONE BY ONE, RETRIEVE THEIR RESPECTIVE IDs (TO USE IN TABLES question_type AND questionnair_question), ENTER THE MIN/MAX VALUES/TEXTS, AND HOOK QUESTION TO QUESTIONNAIR ***/
		while($rowForQuestions = mysqli_fetch_assoc($resultForQuestions)) {
			
			
			// FETCH THE INFO FOR A GIVEN QUESTION
			$queryOldQuestion = "SELECT * FROM question WHERE id = " . $rowForQuestions['id_question'];
			$resultOldQuestion = mysqli_query($connection, $queryOldQuestion);
			$rowOldQuestion = mysqli_fetch_assoc($resultOldQuestion);
			
			
			// DUPLICATE QUESTION
			$queryQuestion = "INSERT INTO question (`premise`, `id_category`, `id_subcategory`, `id_type`, `id_referencia`) VALUES ('" . mysqli_real_escape_string($connection, $rowOldQuestion['premise']) . "', '" . $oldToNewCategory[$rowOldQuestion['id_category']] . "', '" . $oldToNewSubcategory[$rowOldQuestion['id_subcategory']] . "', '" . $rowOldQuestion['id_type'] . "', '" . $oldToNewReference[$rowOldQuestion['id_referencia']] . "');";
			if(!mysqli_query($connection, $queryQuestion)) {
				echo $queryQuestion . "<br>";
				die("Error: Couldn't duplicate question with id ".$rowForQuestions['id_question']."<br>".mysqli_error($connection));
			}
			
			// FETCH DUPLICATE QUESTION ID
 			$questionID = mysqli_insert_id($connection) or die("Error: Couldn't fetch new question id (from old question id ".$rowForQuestions['id_question'].")<br>".mysqli_error($connection));


			// IF QUESTION IS SCALED, DUPLICATE MIN/MAX VALUES/TEXT
			if($rowOldQuestion['id_type'] == '1') {
			
			
				// FETCH THE QUESTION TYPES FOR A GIVEN QUESTION
				$queryOldQuestionTypes = "SELECT * FROM question_type WHERE id_question = " . $rowForQuestions['id_question'];
				$resultOldQuestionTypes = mysqli_query($connection, $queryOldQuestionTypes);
				
				
				// LOOP THROUGH ALL QUESTION TYPES 
				while($rowOldQuestionTypes = mysqli_fetch_assoc($resultOldQuestionTypes)) {
					
					$queryMinVal = "INSERT INTO question_type (`id_type`, `id_question`, `label`, `value`) VALUES ('".$rowOldQuestionTypes['id_type']."', '$questionID', '".$rowOldQuestionTypes['label']."', '".$rowOldQuestionTypes['value']."');";
					if(!mysqli_query($connection, $queryMinVal)) {
						echo $queryMinVal . "<br>";
						die("Error: Couldn't duplicate question ".$rowOldQuestionTypes['label']." (from old question with id ".$rowForQuestions['id_question'].")<br>".mysqli_error($connection));
					}
				
				}

				
			}
			
			$queryHookQuestionToQuestionnaire = "INSERT INTO questionnair_question (`id_questionnair`, `id_question`) VALUES ('$questionnaireID', '$questionID');";
			if(!mysqli_query($connection, $queryHookQuestionToQuestionnaire)) {
				echo $queryHookQuestionToQuestionnaire . "<br>";
				die("Error: Couldn't hook question to questionnaire  (Question ID: ".$questionID.")<br>".mysqli_error($connection));
			}
		
		}
		
		


		
		
// 		header('Location: ../questionnaires.php');
// 		exit();



	}



?>