<?php
class PreviewTables {
	// Idea: crear un esqueleto como este para todas las preguntas y registrar en num los resultados
	// question1{
	// 	qid
	// 	question
	// 	type
	// 	results:{
	// 		Answer1:{
	// 			total:{
	// 				total:{
	// 					label: total,
	// 					num: 10,
	// 				}
	// 			},
	// 			age:{
	// 				1820:{
	// 					label: 1820,
	// 					num: 1820,
	// 				},
	// 				2025:{
	// 					label: 2025,
	// 					num: 2025,
	// 				}
	// 			},
	// 			gender:{
	// 				masculino:{
	// 					label: masculino,
	// 					num: 10,
	// 				},
	// 				femenino:{
	// 					label: femenino,
	// 					num: 10,
	// 				}
	// 			}
	// 		}
	// 	}
	// }

	public function formatAnswer($resultPOST) {
		$questions = $resultPOST->questions;
		$answers = $resultPOST->answers;
		$response = null;
		//Iterar por questions, para crear un objecto question con los atributos necesarios
		foreach($questions as $key => $question) {
			$qid = $question->qid;
			if($question->type == 'T') {
				//pregunta tipo T funciona como answer de su respectiva parent_qid
				$parentqid = $question->parent_qid;
				$id = $question->id;
				$newId = substr($id, -5);
				$questionOrder = $question->question_order;
				$headers = $this->getHeaders();
				$response['previewTables'][$parentqid]->results->$newId = $headers;
			} else {
				$response['previewTables'][$qid] = (object)[];
				$response['previewTables'][$qid]->qid = $question->id;
				$response['previewTables'][$qid]->question = $question->question;
				$response['previewTables'][$qid]->type = $question->type;
				$response['previewTables'][$qid]->results = (object)[];
			}
		}

		//Iterar por answers, para colocar cada answer en su pregunta correspondiente
		foreach($answers as $key => $answer) {
			$answerCode = $answer->answer_code;
			$qid = $answer->qid;
			$headers = $this->getHeaders();
			$response['previewTables'][$qid]->results->$answerCode = $headers;
		}

		//TODO: Iterar por los results e ir sumando +1 a las answers específicas de cada question en función de los datos del perfil

		$response['questions'] = $resultPOST->questions;
		$response['answers'] = $resultPOST->answers;
		$response['results'] = $resultPOST->result;

		return $response;
	}

	public function getHeaders() {
		$base = [
			'label' => 'l1',
			'num' => 11
		];

		$total = [
			'total' => $base,
		];
		$age = [
			'1820' => $base,
			'2125' => $base,
		];
		$gender = [
			'male' => $base,
			'female' => $base,
		];
		$sec = [
			'high' => $base,
			'low' => $base,
		];
		$region = [
			'region1' => $base,
			'region2' => $base,
		];

		$headers = [
			'total' => $total,
			'Sexo' => $age,
			'Edad' => $gender,
			'NSE' => $sec,
			'Area' => $region,
		];
		return $headers;
	}
}