<!--- 

Developer: Coralys Cubero Rivera
Fall 2018

This scripts inserts a new questionnaire into our system, including each of its questions. 



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 newQuestionnaire.php), INSERT QUESTIONNAIRE TO 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 CUESTIONARIO) 
		$keys = array();
		$values = array();
		foreach($_POST as $key => $value) {
			$keys[] = $key;
			$values[] = $value;
		}
		
		// INSERTAR A TABLA questionair EL TÍTULO Y LA DESCRIPCIÓN DEL CUESTIONARIO NUEVO
		$q_title = $values[0]; // usar POST['q_title'];
		$q_description = $values[1]; // usar POST['q_description'];
		$query = "INSERT INTO `questionnair` (`title`, `description`) VALUES ('".$q_title."', '".$q_description."');";
		if(!mysqli_query($connection, $query)) die("Error: ".mysqli_error($connection));
		
		// BUSCAR id DEL CUESTIONARIO ACABADO DE INSERTAR
		$query = "SELECT `id` FROM `questionnair` WHERE `title`='".$q_title."';";
		$result = mysqli_query($connection, $query);
		if(!$result) die("Error: ".mysqli_error($connection));
		//$row = mysqli_fetch_array($result);
		//$id_questionnaire = $row[0];
		foreach($result as $questionnaire) $questionnaire_id = $questionnaire["id"];
		
		// "INSERTAR" CADA PREGUNTA DESEADA AL CUESTIONARIO NUEVO (ASOCIANDO LOS ids A TRAVÉS DE LA TABLA questionnair_question)
		// WARNING: ESTO NO PROVEE PROTECCIÓN POR SI EL VALUE DEL SELECT ES '' (PREGUNTA INVÁLIDA) O SI HAY UNA PREGUNTA REPETIDA
		$num_questions = sizeof($values);
		for($x = 2; $x < $num_questions - 1; $x++) {
			$query = "INSERT INTO `questionnair_question` (`id_questionnair`, `id_question`) VALUES ('".$questionnaire_id."', '".$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>";
	}