<!--- 

Developer: Coralys Cubero Rivera
Fall 2018

This scripts updates any changes made to a questionnaire when editing its information. 



Updated by: Víctor A. Hernández
Summer 2019

--->

<?php

	require_once 'processes/config.php';
	require_once 'processes/dbh.inc.php';

	// IF USER ENTERS PAGE AFTER SUBMIT BUTTON HAS BEEN PRESSED (FROM editQuestionnaire.php), EDIT QUESTIONNAIRE FROM DATABASE
	// ELSE DO NOTHING
	if(isset($_POST['submitQuestionnaire'])) {

		// RECIBIR TODOS LOS INPUTS DE newQuestionnaire.php (TÍTULO, DESCRIPCIÓN Y CADA PREGUNTA A AÑADIRSE AL CUESTIONARSE) 
		$keys = array();
		$values = array();
		foreach($_POST as $key => $value) {
			//echo "$value";
			$keys[] = $key;
			$values[] = $value;
		}
		
		// ######ESTO NO OVERWRITEARÍA LOS FIELDS QUE NO ESTÁN SETEADOS?????#####
		if(isset($_POST['newTitle']) OR isset($_POST['newDescription']) OR isset($_POST['question'])) {
		
			// CAMBIAR EL TÍTULO Y LA DESCRIPCIÓN DEL CUESTIONARIO EN LA TABLA questionair
			$newTitle = $values[0];
			$newDescription = $values[1];
			$id_questionnaire = $values[2];
			$query = "UPDATE `questionnair` SET `q_title`='".$newTitle."', `description`='".$newDescription."' WHERE `id`='".$id_questionnaire."';";
			$result = mysqli_query($connection, $query);
			if(!$result) die("Error: ".mysqli_error($connection));

			// "INSERTAR" CADA PREGUNTA (ADICIONAL) DESEADA AL CUESTIONARIO EN CUESTIÓN (ASOCIANDO LOS ids CON LA TABLA questionnair_question)
			$num_questions = sizeof($values);	
			for ($x = 3; $x < $num_questions - 1; $x++) {
				$query = "INSERT INTO `questionnair_question` (`id_questionnair`, `id_question`) VALUES ('".$id_questionnaire."', '".$values[$x]."');";
				$result = mysqli_query($connection, $query);
				if (!$result) die("Error: ".mysqli_error($connection));
			}
		}

		// WHY NOT USE header INSTEAD OF window.top.location?
		//header('Location: http://emaapp.online/admin_nuevo/questionnaires.php');
		//exit();	
		echo "<script>window.top.location='http://emaapp.online/admin_nuevo/questionnaires.php'</script>";			
	}