<?php
class Reports {
	public function getData($token, $survey, $perf) {
		$lang = 'ESP';
		// $token = $token;
		$idSurvey = $survey;

		$ctrl = new Controller;
		// Obtener RSC
		$rscSearch = [150, 556, 557, 120, 121];
		$rsc = [];
		$url = CONSTANTS::SERVERAPI . 'getRSC';
		foreach($rscSearch as $id) {
			$params = [
				'token' => $token,
				'rsc' => $id
			];

			$resultPOST = $ctrl->sendCurlPOST($url, $params);
			if($resultPOST->status == 'OK' && is_array($resultPOST->result)) {
				$rsc[$id] = $resultPOST->result[0]->$lang;
			} else {
				$rsc[$id] = 'RSC' . $id;
			}
		}

		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExport';
		$params = [
			'token' => $token,
			'numPreguntasPerfilacionEnAnalyticMostreo' => $perf,
			'survey' => $idSurvey
		];

		$resultPOST = $ctrl->sendCurlPOST($url, $params);

		if($resultPOST->status == 'KO' || !isset($resultPOST->status)) {
			return false;
		}
		$ids = [];
		$data = [];
		$charts = [];
		// Claculo graficas
		$stadistics = [];

		// Sacar literales de los perf
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestra';

		$params = [
			'token' => $token,
			'survey' => $idSurvey,
			'pregunta' => $resultPOST->questions[0]->id,
			'numPreguntasPerfilacionEnAnalyticMostreo' => $perf
		];

		$resultPOST2 = $ctrl->sendCurlPOST($url, $params);

		if($resultPOST2->status == 'KO' || !isset($resultPOST2->status)) {
			return false;
		}

		try {
			$resultPOST2 = $resultPOST2->result->resultado[0];

			for($i = 1; $i <= $perf; $i++) {
				$perfLit = 'perf00' . $i . 'Desc';
				$perfDesc = $resultPOST2->$perfLit;

				$charts['perf00' . $i] = [
					'labels' => [],
					'data' => [],
					'typeChart' => '',
					'image' => '',
					'title' => $perfDesc . ' (%)'
				];
				$stadistics['perf00' . $i] = [];
			}

			foreach($resultPOST->result as $result) {
				for($i = 1; $i <= $perf; $i++) {
					$key = 'perf00' . $i;
					if($result->$key == 'M') {
						$result->$key = $rsc['556'];
						$charts[$key]['type'] = 'pie';
					} else if($result->$key == 'F') {
						$result->$key = $rsc['557'];
						$charts[$key]['typeChart'] = 'pie';
					} else {
						$charts[$key]['typeChart'] = 'bar';
					}
					$isKey = array_key_exists($result->$key, $stadistics['perf00' . $i]);
					if(!$isKey && ($result->$key != 'n/d' || !isset($result->$key))) {
						$stadistics['perf00' . $i][$result->$key] = 1;
					} else {
						$stadistics['perf00' . $i][$result->$key]++;
					}
				}
			}

			for($i = 1; $i <= $perf; $i++) {
				ksort($stadistics['perf00' . $i]);
			}

			// Sacar porcentaje
			$n = count($resultPOST->result);
			foreach($stadistics as $key => $row) {
				foreach($row as $key2 => $value) {
					array_push($charts[$key]['labels'], $key2);
					array_push($charts[$key]['data'], round($value / $n * 100, 1, PHP_ROUND_HALF_DOWN));
				}
			}

			foreach($resultPOST->questions as $question) {
				$isWC = $this->isWordCloud($question->type, $question->parent_qid);

				if($question->type != 'M' || $question->type != '|') {
					$ids[$question->id] = $isWC;
				}

				$row = [
					'qid' => $question->qid,
					'question' => $question->question,
					'type' => $question->type,
					'typeChart' => 'bar',
					'wc' => $isWC,
					'labels' => [],
					'data' => [],
					'codes' => null,
					'multiple' => [],
					'wcAnswers' => [],
					'image' => '',
					'isMultiple' => false,
					'title' => $rsc['150'] . ' (%)'
				];
				if($question->type == '!' || $question->type == 'L') {
					$codes = $this->takeLabels($question->id, $resultPOST->answers);
					$row['codes'] = $codes;
				} else if($question->parent_qid != 0) {
					$row['isMultiple'] = true;
					foreach($data as $key => $value) {
						if(isset($question->parent_qid) && $value['qid'] == $question->parent_qid) {
							$data[$key]['multiple'][$question->id] = $question->question;
						}
					}
				}
				$data[$question->id] = $row;
			}

			// Construir datos para graficas respuestas
			$values = [];

			foreach($resultPOST->result as $row) {
				foreach($ids as $id => $isWc) {
					if($isWc && isset($row->$id)) {
						array_push($data[$id]['wcAnswers'], trim($row->$id));
					} else {
						if(isset($row->$id)) {
							$exist = array_key_exists($id, $values);
							if(!$exist) {
								$values[$id][$row->$id] = 1;
							} else {
								$exist = array_key_exists($row->$id, $values[$id]);
								if(!$exist) {
									$values[$id][$row->$id] = 1;
								} else {
									$values[$id][$row->$id]++;
								}
							}
						}
					}
				}
			}

			foreach($values as $id => $row) {
				// Preparar arrays de las preguntas multiples
				if($data[$id]['type'] == '!' || $data[$id]['type'] == 'L' || $data[$id]['type'] == '5') {
					uksort($row, 'strnatcmp');
				}

				if(!$data[$id]['wc']) {
					foreach($row as $key => $value) {
						if($data[$id]['type'] == '!' || $data[$id]['type'] == 'L') {
							array_push($data[$id]['labels'], $data[$id]['codes'][$key]);
						} else {
							if($data[$id]['type'] == 'Y') {
								if($key == 'Y') {
									$key = $rsc['120'];
								} else if($key == 'N') {
									$key = $rsc['121'];
								}
							}
							array_push($data[$id]['labels'], $key);
						}
						array_push($data[$id]['data'], round($value / array_sum($row) * 100, 1, PHP_ROUND_HALF_DOWN));
					}
				}
			}

			// Limpiar datos no necesarios
			foreach($data as $id => $values) {
				if($values['type'] == 'M' && !$values['isMultiple']) {
					$labels = [];
					$valores = [];
					foreach($data[$id]['multiple'] as $key => $multiple) {
						array_push($labels, $data[$key]['question']);
						$clave = array_search('Y', $data[$key]['labels']);
						array_push($valores, $data[$key]['data'][$clave]);
					}

					$data[$id]['labels'] = $labels;
					$data[$id]['data'] = $valores;
				} else if($values['isMultiple'] || $data[$id]['type'] == '|') {
					unset($data[$id]);
				}
			}

			// Resultado
			$result = [];
			$result['charts'] = $charts;
			$result['questions'] = $data;

			return $result;
		} catch(Exception $e) {
			return false;
		}
	}

	public function isWordCloud($type, $parent) {
		if(($type == 'T' && $parent == 0) || $type == 'U') {
			$isWC = true;
		} else {
			$isWC = false;
		}

		return $isWC;
	}

	public function takeLabels($id, $answers) {
		$labels = [];
		foreach($answers as $answer) {
			if($answer->id == $id) {
				$labels[$answer->answer_code] = $answer->answer;
			}
		}

		return $labels;
	}

	private function takeLabelsArray($id, $answers) {
		$labels = [];
		foreach($answers as $answer) {
			if($answer->id == $id) {
				array_push($labels, $answer->answer);
			}
		}

		return $labels;
	}
}