<?php
include_once(dirname(__FILE__) . '/UtilesController.php');
include_once(dirname(__FILE__) . '/../Model/GeneratePpt.php');

class MissionsReportController {
	private $utilesController;

	function __construct() {
		$this->utilesController = new UtilesController();
	}

	// Datos de reporte
	public function getAnalyticsMuestraToExport($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExport';
		$params = [
			'token' => $client['token'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPregPerf'],
			'survey' => $client['survey'],
			'mision' => $client['idmision'],
			'project' => $client['project'],
			'continuingMission' => $client['isContinuing']
		];

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

		return $resultPOST;
	}

	// Generar reporte multimedia
	public function getMultimediaReport($client) {
		$dataAnalytics = $this->getAnalyticsMuestraToExport($client);

		if($dataAnalytics->status != 'OK') {
			return $dataAnalytics;
		}

		$surveys = [];
		$questOrder = [];
		foreach($dataAnalytics->questions as $questions) {
			if($questions->type == '|' || $questions->type == '7' || $questions->type == 'J') {
				array_push($surveys, $questions->id);
				$questOrder[$questions->id] = 'Q' . $questions->question_order;
			}
		}

		if(count($surveys) > 0) {
			$images = [];
			foreach($surveys as $survey) {
				$images[$survey] = [];
				foreach($dataAnalytics->result as $element) {
					if($client['isContinuing'] == '1') {
						foreach($element as $resultContinuing) {
							foreach($resultContinuing as $result) {
								if(isset($result->$survey)) {
									$image = json_decode($result->$survey);
									if(isset($image[0])) {
										$data = [
											'name' => $image[0]->filename,
											'ext' => $image[0]->ext,
											'user' => str_replace(':', '-', str_replace(' ', '_', $result->submitdate)) . '_' . $result->token,
											'rechazada' => $result->rechazada
										];
										array_push($images[$survey], $data);
									}
								}
							}
						}
					} else {
						foreach($element as $result) {
							if(isset($result->$survey)) {
								$image = json_decode($result->$survey);
								if(isset($image[0])) {
									$data = [
										'name' => $image[0]->filename,
										'ext' => $image[0]->ext,
										'user' => $result->token,
										'rechazada' => $result->rechazada
									];
									array_push($images[$survey], $data);
								}
							}
						}
					}
				}
			}
		} else {
			$response['status'] = 'OK';
			$response['result'] = 'No files';
			return $response;
		}

		// Carpeta donde guardar los elementos a comprimir dependiendo de la llamada - Formato: idproject_stampmission_idencuesta
		$folderZip = CONSTANTS::PATH_EXPORT_WORD . '/reports/' . $client['project'] . '_' . $client['stampMision'] . '_' . $client['survey'] . '/';

		if(!file_exists($folderZip)) {
			// Si no existe la carpeta se crea
			$createFile = $this->utilesController->createDirectory($folderZip);

			if($createFile['status'] == 'KO') {
				return 'The folder has not been created';
			}
		} else {
			unlink($folderZip . 'media.zip');
		}

		// Objeto ZIP
		$zip = new ZipArchive();
		$zip->open($folderZip . 'media.zip', ZipArchive::CREATE);

		$response = [];
		if(count($images) > 0) {
			foreach($images as $key => $value) {
				// Carpeta donde guardar los elementos a comprimir
				$folder = CONSTANTS::PATH_EXPORT_WORD . '/' . $client['user'] . '/' . $questOrder[$key];

				if(!file_exists($folder)) {
					// Si no existe la carpeta se crea
					$createFile = $this->utilesController->createDirectory($folder);

					if($createFile['status'] == 'KO') {
						return 'The folder has not been created';
					}
				}

				foreach($value as $image) {
					$serverUrl = $folder . '/' . $image['user'] . '.' . $image['ext'];

					// Ruta de imagen
					$url = CONSTANTS::SERVERSURVEYSINTERNAL . '/upload/surveys/' . $client['survey'] . '/files/' . $image['name'];
					// Ruta de imagen local
					// $url = CONSTANTS::SERVERSURVEYS . 'upload/surveys/' . $client['survey'] . '/files/' . $image['name'];

					// Copia en servidor
					$command = 'cp -rf ' . $url . ' ' . $serverUrl;
					$shell_result_output = shell_exec(escapeshellcmd($command));
					// Copia en local
					// copy($url, $serverUrl);

					// Destino
					if($image['rechazada'] == '1') {
						$destination = 'multimedia/' . $questOrder[$key] . '/rejected/' . $image['user'] . '.' . $image['ext'];
					} else {
						$destination = 'multimedia/' . $questOrder[$key] . '/' . $image['user'] . '.' . $image['ext'];
					}

					$zip->addFile($serverUrl, $destination);
				}
			}

			$response['status'] = 'OK';
			$response['result'] = 'Images generated';
		} else {
			$response['status'] = 'OK';
			$response['result'] = 'No files';
		}

		return $response;
	}

	// Generar reporte en excel
	public function generateExcelReport($client) {
		$dataAnalytics = $this->getAnalyticsMuestraToExport($client);

		if($dataAnalytics->status != 'OK') {
			return $dataAnalytics;
		}

		$nperf = $client['numPregPerf'];
		$user = $client['user'];
		$name = $client['nameMission'];
		$timestamp = $client['timestamp'];

		$response = [
			'status' => 'OK',
			'response' => ''
		];

		$permanent = true;

		$excel = new GenerateExcel();
		$response['response'] = $excel->printExcel($dataAnalytics, $user, $name, $timestamp, $nperf, $client['excelDataOpt'], $client['headersExcel'], $client['questionIdOut'], $client['consumo'], $permanent, $client['project'], $client['stampMision'], $client['isContinuing']);

		return $response;
	}

	// Generar excel de wordcloud
	public function generateWordcloudExcel($client) {
		$client['isContinuing'] = '0';
		$dataAnalytics = $this->getAnalyticsMuestraToExport($client);

		if($dataAnalytics->status != 'OK') {
			return $dataAnalytics;
		}

		// Tipos de pregunta con wordcloud
		$wordcloudTypeArray = ['U', 'T', 'Q', 'S', 'O'];

		$wordcloudQuests = [];

		$size = count($dataAnalytics->questions);
		for($i = 0; $i < $size; $i++) {
			if((in_array($dataAnalytics->questions[$i]->type, $wordcloudTypeArray) && $dataAnalytics->questions[$i]->type_parent == '') || $dataAnalytics->questions[$i]->type_parent == 'P') {
				$quest = [
					'title' => $dataAnalytics->questions[$i]->question,
					'pregunta' => $dataAnalytics->questions[$i]->id,
					'survey' => $dataAnalytics->questions[$i]->sid
				];

				array_push($wordcloudQuests, $quest);
			}
		}

		$savePath = CONSTANTS::PATH_EXPORT_WORD . '/reports/' . $client['project'] . '_' . $client['stampMision'] . '_' . $client['survey'];
		if(!file_exists($savePath)) {
			// Si no existe la carpeta se crea
			$createFile = $this->utilesController->createDirectory($savePath);

			if($createFile['status'] == 'KO') {
				$response = [
					'status' => 'KO',
					'response' => 'The folder has not been created'
				];

				return $response;
			}
		}

		$excel = new GenerateExcel;
		$result = $excel->counterWords($wordcloudQuests, $client['user'], $client['token'], null, true, $savePath);

		$response = [
			'status' => $result == 'OK' ? $result : 'KO',
			'response' => $savePath . '/wordcloud_count.xlsx'
		];

		return $response;
	}

	// Generar datos de reporte
	public function generatePermanentReportData($client) {
		$client['isContinuing'] = '0';
		$dataAnalytics = $this->getAnalyticsMuestraToExport($client);

		if($dataAnalytics->status != 'OK') {
			return $dataAnalytics;
		}
        elseif(count($dataAnalytics->result) == 0) {
			$noUsers = [
				'status' => 'OK',
				'result' => 'No users'
			];
			return $noUsers;
		}

		// Ver método 'requestAllGraphs' en Controller.php

		// ¿Es pregunta de respuesta multiple?
		$isTypeM = [];
		// Posibles respuestas
		$labels = [];
		// Respuestas de asesores
		$allQuestData = [];
		// Response WordCloud
		$response['wordCloud'] = [];
		// Response tipo de pregunta
		$response['typeQuestion'] = [];
		// ID de pregunta
		$response['questionID'] = [];
		// OCR de pregunta
		$response['ocr'] = [];
		// QID de la pregunta
		$response['qid'] = [];
		// Todas las preguntas
		$allQuestions = [];
		// Control tipo de preguntas
		$controlPreguntas = ['6', 'A', 'B', 'C', 'E', 'F', 'H', 'K', 'Q', ':'];
		// Control códigos de respuesta - (TODO: Ampliar / Cambiar por expresión regular)
		$codigos = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'A15', 'A16', 'A17', 'A18', 'A19', 'A20'];
		// Control título preguntas tipo 'R'
		$titleTypeR = '';

		// Preguntas
		foreach($dataAnalytics->questions as $question) {
			if(($question->type == 'C' && $question->parent_type == 'Y') || ($question->type == 'T' && $question->type_parent == 'B')) {
				continue;
			}

			// --- Generación de datos para Wordclouds ---
			// Para poder generar un wordcloud se tiene que hacer una llamada previamente al servicio 'getAnalyticsMuestra' para que genere los datos relacionados con el wordcloud

			// Tipos de pregunta con wordcloud
			$wordcloudTypeArray = ['U', 'T', 'Q', 'S', 'O', 'P'];
			if(in_array($question->type, $wordcloudTypeArray) && $question->type_parent == '') {
				$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestra';
				$params = [
					'token' => $client['token'],
					'survey' => $client['survey'],
					'pregunta' => $question->id,
					'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPregPerf']
				];

				// Este result no se utiliza para nada más
				$phantomResult = $this->utilesController->sendCurlPOST($url, $params);

				// Registro de errores
				if($phantomResult->status != 'OK') {
					return $phantomResult;
				}
			}

			// Control preguntas con SQ
			if(strpos(strval($question->id), 'SQ') == true && !in_array($question->type, $controlPreguntas) && $question->type !== 'C') {
				$preguntaAEliminar = explode('SQ', $question->id);

				array_push($labels[$preguntaAEliminar[0]], trim($question->question));
			}

			// Control preguntas tipo '6', 'A', 'B', 'C', 'E', 'F', 'H', 'K'
			if((strpos(strval($question->id), 'SQ') == true && in_array($question->type, $controlPreguntas)) || $question->type == 'R') {
				array_push($labels[$question->id], trim($question->question));
			}

			// Control de preguntas de respuesta múltiple
			if(strpos(strval($question->id), 'SQ') == false || in_array($question->type, $controlPreguntas)) {
				array_push($allQuestions, $question->question);
				$labels[$question->id] = [];

				if($question->type == 'M') {
					array_push($isTypeM, 'si');
				} else {
					array_push($isTypeM, 'no');
				}

				array_push($response['typeQuestion'], $question->type);
				array_push($response['questionID'], $question->id);
				array_push($response['qid'], $question->qid);
				array_push($response['ocr'], $question->qidTieneCaptureOCR);

				// Wordclouds y labels
				switch($question->type) {
					case 'C':
						$sQuestionId = $question->id;
						$labels[$sQuestionId] = ['YES', 'NO', 'UNCERTAIN'];
						array_push($response['wordCloud'], 'no');
						break;
					case 'G':
						$sQuestionId = $question->id;
						$labels[$sQuestionId] = ['FEMENINO', 'MASCULINO'];
						array_push($response['wordCloud'], 'no');
						break;
					case 'Y':
						$sQuestionId = $question->id;
						$labels[$sQuestionId] = ['YES', 'NO'];
						array_push($response['wordCloud'], 'no');
						break;
					case '2':
						$sQuestionId = $question->id;
						if(count($labels[$sQuestionId]) == 0) {
							foreach($dataAnalytics->result as $userNLabels) {
								if($userNLabels->$sQuestionId != null && $userNLabels->$sQuestionId != '') {
									array_push($labels[$sQuestionId], $userNLabels->$sQuestionId);
								}
							}
							$labels[$sQuestionId] = array_values(array_unique($labels[$sQuestionId]));
						}
						array_push($response['wordCloud'], 'no');
						break;
					case 'N':
						$sQuestionId = $question->id;
						if(count($labels[$sQuestionId]) == 0) {
							foreach($dataAnalytics->result as $key => $userAnswersData) {
								foreach($userAnswersData as $userNLabels) {
									if($userNLabels->$sQuestionId != null && $userNLabels->$sQuestionId != '' && (int)$userNLabels->$sQuestionId != 0) {
										array_push($labels[$sQuestionId], (int)$userNLabels->$sQuestionId);
									}
								}
							}
							$labels[$sQuestionId] = array_values(array_unique($labels[$sQuestionId]));
						}
						array_push($response['wordCloud'], 'no');
						break;
					case 'T':
					case 'U':
					case 'Q':
					case 'S':
						array_push($response['wordCloud'], 'yes');
						break;
					case '|':
					case '7':
					case 'J':
						array_push($response['wordCloud'], 'image');
						break;
					case 'R':
						array_push($response['wordCloud'], 'no');
						break;
					case 'O':
						array_push($response['wordCloud'], 'plus');
						break;
					case 'P':
						$subPArrary = [];
						foreach($dataAnalytics->result as $element) {
							foreach($element as $key => $value) {
								if(strpos($key, $question->id) !== false && strpos($key, 'comment') === false && strpos($key, 'other') === false) {
									array_push($subPArrary, $key);
								}
							}
							break;
						}

						if (empty($subPArrary)) {
							$response['wordCloud'][] = 'no';
						} else {
							$response['wordCloud'][] = $subPArrary;
						}
						break;
					case ':':
						$sQuestionId = $question->id;
						$arrayAux = [];
						$arraySQMultipleChoice = [];
						foreach ($dataAnalytics->answers as $element) {
							if ($sQuestionId == $element->id) {
								array_push($arrayAux, $element->code);
							}
						}

						$arraySQMultipleChoice[$sQuestionId] = $arrayAux;
						array_push($response['wordCloud'], 'no');
						break;
					default:
						array_push($response['wordCloud'], 'no');
						break;
				}
			}

			$allAnswersByQuestion = [];
			$sQuestionId = $question->id;

			if(strpos(strval($sQuestionId), 'SQ') != true || in_array($question->type, $controlPreguntas)) {
				$allQuestData[$sQuestionId] = [];
			}

            //var_dump($dataAnalytics);
			// Por cada pregunta, se recogen las respuestas de cada usuario del 'result'
			foreach($dataAnalytics->result as $userAnswersData) {
                foreach($userAnswersData as $userAnswer) {
                    // Control respuestas por código
                    if(in_array($userAnswer->$sQuestionId, $codigos)) { // WARNING_ERROR
                        // Controlar cuando es caso 'R'
                        if($question->type != 'R' || true) {
                            if($userAnswer->$sQuestionId != null) {
                                // Para las respuestas que tengan código
                                foreach($dataAnalytics->answers as $respuesta) {
                                    if($respuesta->id == $sQuestionId && $userAnswer->$sQuestionId == $respuesta->answer_code) {
                                        $oAnswer = $respuesta->answer;
                                        $oAnswerother = $respuesta->answer;
                                        $oTipoPregunta = $respuesta->type;
                                        if(is_float($oAnswer) == true) {
                                            $oAnswer = (int)$oAnswer;
                                            $oAnswerother = (int)$respuesta->answer;
                                        }
                                        $oMuestra['answer'] = trim($oAnswer);
                                        $oMuestra['answerothers'] = trim($oAnswerother);
                                        $oMuestra['tipoPregunta'] = $oTipoPregunta;
                                        break;
                                    }
                                }
                            }
                        } else {
                            // Control respuestas por código de preguntas tipo 'R'
                            if($userAnswer->$sQuestionId != null) {
                                foreach($dataAnalytics->questions as $questionData) {
                                    if($questionData->answer_code == $userAnswer->$sQuestionId && $questionData->title == $titleTypeR) {
                                        $oMuestra['answer'] = trim($questionData->answer);
                                        $oMuestra['answerothers'] = trim($questionData->answer);
                                        $oMuestra['tipoPregunta'] = $questionData->type_parent;
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        // Control preguntas SQ que no sean del tipo '6', 'A', 'B', 'C', 'E', 'F', 'H', 'K', ':'
                        if(strpos(strval($question->id), 'SQ') == true && !in_array($question->type, $controlPreguntas)) {
                            if($userAnswer->$sQuestionId != null) { // WARNING_ERROR
                                foreach($dataAnalytics->questions as $questionData) {
                                    if($questionData->id == $sQuestionId) {
                                        $oMuestra['answer'] = trim($questionData->question);
                                        $oMuestra['answerothers'] = trim($questionData->question);
                                        if(is_float($oMuestra['answer']) == true) {
                                            $oMuestra['answer'] = (int)$oMuestra['answer'];
                                            $oMuestra['answerothers'] = (int)$oMuestra['answerothers'];
                                        }
                                        $oMuestra['tipoPregunta'] = $questionData->type_parent;
                                        break;
                                    }
                                }
                            }
                        } else if(strpos(strval($question->id), 'SQ') == true && in_array($question->type, $controlPreguntas) && $question->type !== 'C' && $question->type !== ':') {
                            // Control preguntas SQ tipo '6', 'A', 'B', 'C', 'E', 'F', 'H', 'K'
                            if($userAnswer->$sQuestionId != null) {
                                foreach($dataAnalytics->answers as $respuesta) {
                                    if($respuesta->id == $sQuestionId && $userAnswer->$sQuestionId == $respuesta->answer_code) {
                                        $oAnswer = $respuesta->answer;
                                        $oAnswerother = $respuesta->answer;
                                        $oTipoPregunta = $respuesta->type;
                                        if($oTipoPregunta == null) {
                                            $oTipoPregunta = '';
                                        }
                                        if(is_float($oAnswer) == true) {
                                            $oAnswer = (int)$oAnswer;
                                            $oAnswerother = (int)$respuesta->answer;
                                        }
                                        $oMuestra['answer'] = trim($oAnswer);
                                        $oMuestra['answerothers'] = trim($oAnswerother);
                                        $oMuestra['tipoPregunta'] = $oTipoPregunta;
                                        break;
                                    }
                                }
                            }
                        } else {
							if ($question->type == ':') {
								foreach($arraySQMultipleChoice[$sQuestionId] as $elementSQMultipleChoice) {
									$key_elem = $sQuestionId . '_' . $elementSQMultipleChoice;
									if ($userAnswer->$key_elem != null) {
										foreach ($dataAnalytics->answers as $respuesta) {
											if ($respuesta->id == $sQuestionId && $elementSQMultipleChoice == $respuesta->answer_code) {
												$oAnswer = $respuesta->answer;
												$oAnswerother = $respuesta->answer;

												$oMuestra['answer'] = trim($oAnswer);
												$oMuestra['answerothers'] = trim($oAnswerother);
												$oMuestra['tipoPregunta'] = '';
												$oMuestra['userEmail'] = $userAnswer->token;
												$oMuestra['user'] = $userAnswer->token;
												$oMuestra['perf001'] = $userAnswer->perf001;
												$oMuestra['perf002'] = $userAnswer->perf002;
												if ($userAnswer->perf002Range != null && $userAnswer->perf002Range != '') {
													$oMuestra['perf002Range'] = $userAnswer->perf002Range;
												} else {
													$oMuestra['perf002Range'] = 0;
												}
												$oMuestra['perf003'] = $userAnswer->perf003;
												$oMuestra['perf004'] = $userAnswer->perf004;
												$oMuestra['perf004'] = $userAnswer->perf004Range;
												$oMuestra['question'] = $sQuestionId;
												$oMuestra['survey'] = $client['survey'];
												$oMuestra['surveyDesc'] = $client['idmision'];
												array_push($allAnswersByQuestion, (object)$oMuestra);
												break;
											}
										}
									}
								}
							}
							else {
								if($userAnswer->$sQuestionId != null) {
									$oAnswer = $userAnswer->$sQuestionId;
									$oAnswerother = $userAnswer->$sQuestionId;
									$oTipoPregunta = $question->type;
									if($oTipoPregunta == null) {
										$oTipoPregunta = '';
									}
									if(is_float($oAnswer) == true) {
										$oAnswer = (int)$oAnswer;
										$oAnswerother = (int)$oAnswerother;
									}
									$oMuestra['answer'] = trim($oAnswer);
									$oMuestra['answerothers'] = trim($oAnswerother);
									$oMuestra['tipoPregunta'] = $oTipoPregunta;
								}
							}
                        }
                    }

                    if($userAnswer->$sQuestionId != null) { // WARNING_ERROR
                        $oMuestra['userEmail'] = $userAnswer->token;
                        $oMuestra['user'] = $userAnswer->token;
                        $oMuestra['perf001'] = $userAnswer->perf001;
                        $oMuestra['perf002'] = $userAnswer->perf002;
                        if($userAnswer->perf002Range != null && $userAnswer->perf002Range != '') {
                            $oMuestra['perf002Range'] = $userAnswer->perf002Range;
                        } else {
                            $oMuestra['perf002Range'] = 0;
                        }
                        $oMuestra['perf003'] = $userAnswer->perf003;
                        $oMuestra['perf004'] = $userAnswer->perf004;
                        $oMuestra['perf004'] = $userAnswer->perf004Range;
                        $oMuestra['question'] = $sQuestionId;
                        $oMuestra['survey'] = $client['survey'];
                        $oMuestra['surveyDesc'] = $client['idmision'];
                        array_push($allAnswersByQuestion, (object)$oMuestra);
                    }
                }
            }

			// En el caso de preguntas SQ que no sean del tipo '6', 'A', 'B', 'C', 'E', 'F', 'H' o 'K', se agrupan todos los datos en la pregunta padre
			if(strpos(strval($sQuestionId), 'SQ') == true && !in_array($question->type, $controlPreguntas)) {
				$preguntaSinSQ = explode('SQ', $sQuestionId);
				foreach($allAnswersByQuestion as $val) {
					array_push($allQuestData[$preguntaSinSQ[0]], $val);
				}
			} else {
				foreach($allAnswersByQuestion as $val) {
					array_push($allQuestData[$sQuestionId], $val);
				}
			}
		}

		// Añadido para Gráfica de NSE
		$numPerf = $client['numPregPerf'];

		if($client['isPerf'] == 1) {
			$response['perf'] = true;
		} else {
			$response['perf'] = false;
		}

		$allGender['labels'] = [];
		$allGender['values'] = [];
		$allAge['labels'] = [];
		$allAge['values'] = [];
		$allAgeRange['labels'] = [];
		$allAgeRange['values'] = [];
		$allStates['labels'] = [];
		$allStates['values'] = [];
		$allNSE['labels'] = [];
		$allNSE['values'] = [];

		foreach($dataAnalytics->answers as $answer) {
			// Para saltar las respuestas que tengan código = '0'
			if($answer->answer_code == '0') {
				continue;
			}

			array_push($labels[$answer->id], trim($answer->answer));
		}

		$response['result'] = [];
		$response['questions'] = [];
		$iTypeM = 0;
		foreach($allQuestData as $key => $value) {
			$analyticGraph = new AnalyticGraph();
			if($isTypeM[$iTypeM] == 'si') {
				$typeM = true;
			} else {
				$typeM = false;
			}

			$type = '';
			$result = $analyticGraph->dataFormatOptions($value, $labels[$key], $typeM, $type, $numPerf);

			// Preparar array global
			array_push($response['result'], $result);
			$iTypeM++;
		}
		array_push($response['questions'], $allQuestions);

		// Sacar porcentajes generales
		$resume = [
			'gender' => [],
			'age' => [],
			'ageRange' => [],
			'states' => [],
			'nse' => []
		];

		$totalDiv = 0;

		foreach($response['result'] as $totalChart) {
			// Comprobar si alguien ha contestado
			if(count($totalChart['data']) > 0) {
				$totalDiv++;
			}

			// Edad
			$dataResume = $totalChart['age']['datasets']['data'];
			$labelsResume = $totalChart['age']['labels'];
			$n = count($labelsResume);
			for($j = 0; $j < $n; $j++) {
				$key = array_key_exists($labelsResume[$j], $resume['age']);
				if(!$key) {
					$resume['age'][$labelsResume[$j]] = $dataResume[$j];
				} else {
					$resume['age'][$labelsResume[$j]] += $dataResume[$j];
				}
			}

			// Rango de Edad
			$dataResume = $totalChart['ageRange']['datasets']['data'];
			$labelsResume = $totalChart['ageRange']['labels'];

			$n = count($labelsResume);
			for($j = 0; $j < $n; $j++) {
				$key = array_key_exists($labelsResume[$j], $resume['ageRange']);
				if(!$key) {
					$resume['ageRange'][$labelsResume[$j]] = $dataResume[$j];
				} else {
					$resume['ageRange'][$labelsResume[$j]] += $dataResume[$j];
				}
			}

			// Estado
			$dataResume = $totalChart['states']['datasets']['data'];
			$labelsResume = $totalChart['states']['labels'];
			$n = count($labelsResume);
			for($j = 0; $j < $n; $j++) {
				$key = array_key_exists($labelsResume[$j], $resume['states']);
				if(!$key) {
					$resume['states'][$labelsResume[$j]] = $dataResume[$j];
				} else {
					$resume['states'][$labelsResume[$j]] += $dataResume[$j];
				}
			}

			// Genero
			$dataResume = $totalChart['gender']['datasets']['data'];
			$labelsResume = $totalChart['gender']['labels'];
			$n = count($labelsResume);
			for($j = 0; $j < $n; $j++) {
				$key = array_key_exists($labelsResume[$j], $resume['gender']);
				if(!$key) {
					$resume['gender'][$labelsResume[$j]] = $dataResume[$j];
				} else {
					$resume['gender'][$labelsResume[$j]] += $dataResume[$j];
				}
			}

			// NSE
			$dataResume = $totalChart['nse']['datasets']['data'];
			$labelsResume = $totalChart['nse']['labels'];
			$n = count($labelsResume);
			for($j = 0; $j < $n; $j++) {
				$key = array_key_exists($labelsResume[$j], $resume['nse']);
				if(!$key) {
					$resume['nse'][$labelsResume[$j]] = $dataResume[$j];
				} else {
					$resume['nse'][$labelsResume[$j]] += $dataResume[$j];
				}
			}
		}

		if($totalDiv > 0) {
			foreach($resume['age'] as $key => $value) {
				$resume['age'][$key] = round(($resume['age'][$key] / $totalDiv), 1);
			}

			foreach($resume['ageRange'] as $key => $value) {
				$resume['ageRange'][$key] = round(($resume['ageRange'][$key] / $totalDiv), 1);
			}

			foreach($resume['gender'] as $key => $value) {
				$resume['gender'][$key] = round(($resume['gender'][$key] / $totalDiv), 1);
			}

			foreach($resume['states'] as $key => $value) {
				$resume['states'][$key] = round(($resume['states'][$key] / $totalDiv), 1);
			}

			foreach($resume['nse'] as $key => $value) {
				$resume['nse'][$key] = round(($resume['nse'][$key] / $totalDiv), 1);
			}

			$total = [
				'gender' => [
					'labels' => [],
					'value' => []
				],
				'age' => [
					'labels' => [],
					'value' => []
				],
				'ageRange' => [
					'labels' => [],
					'value' => []
				],
				'states' => [
					'labels' => [],
					'value' => []
				],
				'nse' => [
					'labels' => [],
					'value' => []
				]
			];

			foreach($resume['age'] as $key => $value) {
				array_push($total['age']['labels'], $key);
				array_push($total['age']['value'], $value);
			}
			foreach($resume['ageRange'] as $key => $value) {
				array_push($total['ageRange']['labels'], $key);
				array_push($total['ageRange']['value'], $value);
			}
			foreach($resume['gender'] as $key => $value) {
				array_push($total['gender']['labels'], $key);
				array_push($total['gender']['value'], $value);
			}
			foreach($resume['states'] as $key => $value) {
				array_push($total['states']['labels'], $key);
				array_push($total['states']['value'], $value);
			}
			foreach($resume['nse'] as $key => $value) {
				array_push($total['nse']['labels'], $key);
				array_push($total['nse']['value'], $value);
			}
			$response['resume'] = $total;
		}

		$response['status'] = 'OK';
		return $response;
	}

	// Añadir wordcloud en powerpoint permanente
	public function generatePermanentPowerpointWithWordcloud($client) {
		$analyticGraph = new GeneratePpt();

		// Parámetros de plantilla
		if($client['plantillaReportes'] == '0') {
			$template = [
				'typeColors' => $client['typeColors'], // 0/1
				'colorsHex' => $client['colorsHex'], // '#ff0000,#3700ff,#00ff04,#eeff00'
				'fontName' => $client['fontName'],
				'fontSize' => $client['fontSize'],
				'answersOrder' => 'default',
				'colorTituloPortada' => '#ffffff',
				'colorTitulo' => '#ffffff',
				'plantillaPortada' => CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $client['idTenant'] . '/plantilla_portada.PNG',
				'plantilla' => CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $client['idTenant'] . '/plantilla.PNG',
				'logo' => CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $client['idTenant'] . '/logo_rep.PNG',
				'type3' => '',
				'type4' => '',
				'type5' => '',
				'typeINTERROGANTE' => '',
				'typeL' => '',
				'typeO' => '',
				'typeY' => '',
				'typeM' => ''
			];
		} else {
			if($client['plantillaReportes']['rangoColores'] == '1') {
				$colorsHex = $client['plantillaReportes']['colorInicio'] . ',' . $client['plantillaReportes']['colorFinal'];
			} else {
				$colorsHex = $client['plantillaReportes']['coloresComponenRango'];
			}

			$template = [
				'typeColors' => $client['plantillaReportes']['rangoColores'],
				'colorsHex' => $colorsHex,
				'fontName' => $client['plantillaReportes']['tipoFuente'],
				'fontSize' => $client['plantillaReportes']['tamanoFuente'],
				'answersOrder' => $client['plantillaReportes']['answersOrder'],
				'colorTituloPortada' => $client['plantillaReportes']['colorTituloPortada'],
				'colorTitulo' => $client['plantillaReportes']['colorTitulo'],
				'plantillaPortada' => CONSTANTS::PATH_EXPORT_WORD . '/' . $client['plantillaReportes']['plantillaPortada'],
				'plantilla' => CONSTANTS::PATH_EXPORT_WORD . '/' . $client['plantillaReportes']['plantilla'],
				'logo' => CONSTANTS::PATH_EXPORT_WORD . '/' . $client['plantillaReportes']['logo'],
				'type3' => $client['plantillaReportes']['type3'],
				'type4' => $client['plantillaReportes']['type4'],
				'type5' => $client['plantillaReportes']['type5'],
				'typeINTERROGANTE' => $client['plantillaReportes']['typeINTERROGANTE'],
				'typeL' => $client['plantillaReportes']['typeL'],
				'typeO' => $client['plantillaReportes']['typeO'],
				'typeY' => $client['plantillaReportes']['typeY'],
				'typeM' => $client['plantillaReportes']['typeM']
			];
		}

		$response = $analyticGraph->generatePermanentPowerpointWithWordcloud($client['token'], $client['reportData'], $client['idTenant'], $client['survey'], $client['stampMision'], $client['project'], $client['briefing'], $template, $client['user'], $client['param4']);

		return $response;
	}

	// Añadir wordcloud en word permanente
	public function generatePermanentWordWithWordcloud($client) {
		$analyticGraph = new GenerateWord();

		$response = $analyticGraph->generatePermanentWordWithWordcloud($client['token'], $client['reportData'], $client['colorsHex'], $client['typeColors'], $client['user'], $client['idTenant'], $client['survey'], $client['stampMision'], $client['project'], $client['briefing'], $client['fontName']);

		return $response;
	}

	// Descargar reportes permanentes
	public function downloadPermanentReports($client) {
		// Carpeta donde se localizan los reportes
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/reports/' . $client['project'] . '_' . $client['stampMision'] . '_' . $client['survey'] . '/';

		// Nombre de la misión
		$name = str_replace(' ', '_', $client['name']);

		// Número de reportes
		$reports = [];
		// Multimedia
		if($client['reports']['images']) {
			array_push($reports, [$folder . '/media.zip', $name . '_media.zip']);
		}
		// Excel
		if($client['reports']['excel']) {
			array_push($reports, [$folder . '/data.xlsx', $name . '_data.xlsx']);
		}
		// Excel de wordcloud
		if($client['reports']['wc']) {
			array_push($reports, [$folder . '/wordcloud_count.xlsx', $name . '_wordcloud_count.xlsx']);
		}
		// Powerpoint
		if($client['reports']['ppt']) {
			array_push($reports, [$folder . '/Analitics_Mostreo.pptx', $name . '_analitics_Mostreo.pptx']);
		}
		// Word
		if($client['reports']['word']) {
			array_push($reports, [$folder . '/Analitics_Mostreo.docx', $name . '_analitics_Mostreo.docx']);
		}

		if(count($reports) > 1) {
			// Borrar archivo .zip anterior
			unlink($folder . 'Analitics_Mostreo.zip');

			// Objeto ZIP
			$zip = new ZipArchive();
			$zip->open($folder . 'Analitics_Mostreo.zip', ZipArchive::CREATE);

			for($i = 0; $i < count($reports); $i++) {
				$zip->addFile($reports[$i][0], $reports[$i][1]);
			}

			$response['status'] = 'OK';
			$response['name'] = 'Analitics_Mostreo.zip';
			$response['result'] = 'reports/' .$client['project'] . '_' . $client['stampMision'] . '_' . $client['survey'] . '/' . 'Analitics_Mostreo.zip';
		} else {
			rename($reports[0][0], $folder . $reports[0][1]);

			$response['status'] = 'OK';
			$response['name'] = $reports[0][1];
			$response['result'] = 'reports/' .$client['project'] . '_' . $client['stampMision'] . '_' . $client['survey'] . '/' . $reports[0][1];
		}

		return $response;
	}
}