<?php
include_once(dirname(__FILE__) . '/../Controllers/UtilesController.php');
require_once(dirname(__FILE__) . '/../../vendor/autoload.php');
require_once(dirname(__FILE__) . '/../customConfig/Constants.php');
set_time_limit(CONSTANTS::SET_TIME_LIMIT);

use PhpOffice\PhpWord\Shared\Converter;
use PhpOffice\PhpWord\Style\Language;
use PhpOffice\PhpWord\SimpleType\Jc;
use PhpOffice\PhpWord\Style\Chart;

class GenerateWord {
	private $utilesController;

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

	public function rgbtohex($rgb) {
		return sprintf('#%02x%02x%02x', $rgb[0], $rgb[1], $rgb[2]);
	}

	public function hextorgb($hex) {
		list($r, $g, $b) = sscanf($hex, '#%02x%02x%02x');
		return [$r, $g, $b];
	}

	//colorsHex, totalColors
	public function arrayColors($origin_colors, $count) {
		$colors = [];
		$arraylColors = count($colors);
		while($arraylColors < $count) {
			for($i = 0; $i < count($origin_colors); $i++) {
				array_push($colors, $origin_colors[$i]);
				$arraylColors = count($colors);
				if($arraylColors == $count) {
					break;
				}
			}
		}
		return $colors;
	}

	public function generateColors($colors, $count) {
		$start = GenerateWord::hextorgb($colors[0]);
		$end = GenerateWord::hextorgb($colors[1]);

		//Alpha blending amount
		$alpha = 0.0;

		$arrayColors = [];

		for($i = 0; $i < $count; $i++) {
			$c = [];
			$alpha += (1.0 / $count);

			$c[0] = $start[0] * $alpha + (1 - $alpha) * $end[0];
			$c[1] = $start[1] * $alpha + (1 - $alpha) * $end[1];
			$c[2] = $start[2] * $alpha + (1 - $alpha) * $end[2];

			array_push($arrayColors, GenerateWord::rgbtohex($c));
		}

		return $arrayColors;
	}

	public function printWord($data, $wc, $colors, $user, $questions, $typeColors, $generalCharts, $token, $timestamp, $isWc, $isWord, $idTenant) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		$colors = explode(',', $colors);

		$documento = new \PhpOffice\PhpWord\PhpWord();

		$propiedades = $documento->getDocInfo();
		$propiedades->setTitle('Gráficas');

		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 500,
			'marginLeft' => 1000,
			'vAlign' => 'center'
		];

		$sectionStyleList = [
			'orientation' => 'landscape',
			'marginTop' => 1500,
			'marginLeft' => 1000,
			'colsNum' => 2
		];

		# Títulos. Solo modificando depth (el número)
		$fuentePortada = [
			'name' => 'Verdana',
			'size' => 30,
			'color' => '000000',
			'bold' => true
		];

		$paragraphPortada = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(1, $fuentePortada, $paragraphPortada);

		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];

		$documento->addTitleStyle(2, $fuenteTitulo);

		$fuenteFecha = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];

		$paragraphFecha = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(3, $fuenteFecha, $paragraphFecha);

		$seccion = $documento->addSection($sectionStyle);

		$name = $data[0]['data'][0]['surveyDesc'];
		$seccion->addTitle($name, 1);

		// Añadir fecha
		$meses_ES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
		$meses_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		$month = str_replace($meses_EN, $meses_ES, date('F'));
		$year = date('Y');
		$seccion->addTitle($month . ', ' . $year, 3);

		$deleteImages = [];
		$i = 0;

		$filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/logo_rep.PNG';
		$styleLogo = [
			'alignment' => 'right',
			'wrappingStyle' => 'behind',
			'width' => 50
		];

		//Graficas generales
		$title = 'Resultados generales';
		$seccion = $documento->addSection($sectionStyle);
		// Add header
		$header = $seccion->createHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		$etiquetas = $generalCharts['gender']['labels'];
		$series = $generalCharts['gender']['value'];

		$grafica = $seccion->addChart('pie', $etiquetas, $series);
		$colores = [$colors[0], $colors[1]];
		$colores = str_replace('#', '', $colores);
		$grafica->getStyle()->setColors($colores); // Asignar colores

		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);
		$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
		$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setShowLegend(true);
		$grafica->getStyle()->setTitle('Género (%)');

		$seccion = $documento->addSection($sectionStyle);
		// Add header
		$header = $seccion->createHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		// Graficos por edades
		$etiquetas = $generalCharts['age']['labels'];
		$series = $generalCharts['age']['value'];

		$grafica = $seccion->addChart('column', $etiquetas, $series);

		if($typeColors == 1) {
			$colores = GenerateWord::generateColors($colors, count($etiquetas));
		} else {
			$colores = GenerateWord::arrayColors($colors, count($etiquetas));
		}
		$colores = str_replace('#', '', $colores);

		$grafica->getStyle()->setColors($colores); // Asignar colores

		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);

		$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
		$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto

		// etiquetas ejes
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setValueLabelPosition('low');
		$grafica->getStyle()->setCategoryLabelPosition('low');
		$grafica->getStyle()->setTitle('Edades (%)');

		$seccion = $documento->addSection($sectionStyle);
		// Add header
		$header = $seccion->createHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		// Graficos por estados
		$etiquetas = $generalCharts['states']['labels'];
		$series = $generalCharts['states']['value'];

		$grafica = $seccion->addChart('column', $etiquetas, $series);

		if($typeColors == 1) {
			$colores = GenerateWord::generateColors($colors, count($etiquetas));
		} else {
			$colores = GenerateWord::arrayColors($colors, count($etiquetas));
		}
		$colores = str_replace('#', '', $colores);

		$grafica->getStyle()->setColors($colores); // Asignar colores

		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);
		$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
		$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setTitle('Estados (%)');

		$excelWC = [];

		foreach($data as $row) {
			$title = $i + 1 . '. ' . $questions[$i];

			// Comprobar si hay respustas de Otros
			if($wc[$i] != 'no' && $wc[$i] != 'image') {
				$seccion = $documento->addSection($sectionStyle);

				// Add header
				$header = $seccion->addHeader();

				$header->addText($title, $fuenteTitulo);
				$header->addImage($filepathLogo, $styleLogo);

				// Crear imagenes WordCloud
				$Base64Img = $wc[$i];

				$baseFromJavascript = $Base64Img;

				$base_to_php = explode(',', $baseFromJavascript);

				$data = base64_decode($base_to_php[1]);
				$fecha = date_create();

				$filepath = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . date_timestamp_get($fecha) . '_wc_' . $i . '.png';

				$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/' . $user;
				if(!file_exists($carpeta)) {
					$createFile = $this->utilesController->createDirectory($carpeta);

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

				array_push($deleteImages, $filepath);

				file_put_contents($filepath, $data);

				$seccion->addImage($filepath, [
					'alignment' => 'center',
					'width' => 600
				]);

				$seccion = $documento->addSection($sectionStyleList);
				foreach($row['data'] as $other) {
					$sanit = htmlspecialchars($other['answerothers']);
					$sanit = trim($sanit);
					$sanit = preg_replace("/[\r\n|\n|\r]+/", ' ', $sanit);

					$seccion->addListItem($sanit);
				}

				// Añadir tabla con contador palabras 
				if(isset($row['data'][0]['survey']) && isset($row['data'][0]['question'])) {
					$survey = $row['data'][0]['survey'];
					$pregunta = $row['data'][0]['question'];

					// Tabla con el detalle del word cloud
					$dataExcel = [
						'title' => $title,
						'pregunta' => $pregunta,
						'survey' => $survey
					];

					array_push($excelWC, $dataExcel);

					$controller = new Controller;
				}
			} else if($wc[$i] == 'no') {
				$seccion = $documento->addSection($sectionStyle);

				// Add header
				$header = $seccion->createHeader();
				$header->addText($title, $fuenteTitulo);
				$header->addImage($filepathLogo, $styleLogo);

				// Graficos por respuestas
				$etiquetas = [];
				foreach($row['answers']['labels'] as $key => $value) {
					$value = str_replace('&', ' and ', $value);

					array_push($etiquetas, $value);
				}
				$series = $row['answers']['datasets']['data'];

				$grafica = $seccion->addChart('column', $etiquetas, $series);
				if($typeColors == 1) {
					$colores = GenerateWord::generateColors($colors, count($etiquetas));
				} else {
					$colores = GenerateWord::arrayColors($colors, count($etiquetas));
				}

				$colores = str_replace('#', '', $colores);
				$grafica->getStyle()->setColors($colores); // Asignar colores

				$grafica->getStyle()->setDataLabelOptions(['showPercent' => true, 'showVal' => true]);
				$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
				$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
				$grafica->getStyle()->setShowAxisLabels(true);

				$grafica->getStyle()->setTitle('Respuestas (%)');
			}

			$i++;
		}

		# Para que no diga que se abre en modo de compatibilidad
		$documento->getCompatibility()->setOoxmlVersion(15);

		# Guardarlo
		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($documento, 'Word2007');

		$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/' . $user;

		if(!file_exists($carpeta)) {
			$createFile = $this->utilesController->createDirectory($carpeta);

			if($createFile['status'] == 'KO') {
				return 'The folder has not been created';
			}
		}
		$fecha = date_create();
		$filename = date_timestamp_get($fecha) . 'Analitic_Mostreo.docx';

		$filename = str_replace(' ', '_', $filename);

		$objWriter->save(CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . $filename, 'Word2007');

		$response['word'] = $filename;
		foreach($deleteImages as $detete) {
			unlink($detete);
		}

		$excel = new GenerateExcel;
		$response['excel'] = $excel->counterWords($excelWC, $user, $token);

		// Guardar reporte en un zip
		// Carpeta donde guardar los elementos a comprimir
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/';
		if(!file_exists($folder)) { // Si no existe, se crea
			$createFile = $this->utilesController->createDirectory($folder);

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

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

			if($isWord == 'true') {
				$zip->addFile($carpeta . '/' . $filename, 'Analitics_Mostreo.docx');
			}
			if($isWc == 'true') {
				$zip->addFile($carpeta . '/' . $response['excel'], 'Analitics_Mostreo.xlsx');
			}
		} catch(Exception $e) {
			//
		}

		return $response;
	}

	public function printWordPerf($response, $colors, $user, $typeColors, $timestamp, $idTenant) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		$colors = explode(',', $colors);

		$documento = new \PhpOffice\PhpWord\PhpWord();

		$propiedades = $documento->getDocInfo();
		$propiedades->setTitle('Gráficas');

		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 500,
			'marginLeft' => 1000,
			'vAlign' => 'center'
		];

		$sectionStyleList = [
			'orientation' => 'landscape',
			'marginTop' => 1500,
			'marginLeft' => 1000,
			'colsNum' => 2
		];

		// Títulos. Solo modificando depth (el número)
		$fuentePortada = [
			'name' => 'Verdana',
			'size' => 30,
			'color' => '000000',
			'bold' => true
		];

		$paragraphPortada = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(1, $fuentePortada, $paragraphPortada);
		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];
		$documento->addTitleStyle(2, $fuenteTitulo);
		$fuenteFecha = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];
		$paragraphFecha = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];
		$documento->addTitleStyle(3, $fuenteFecha, $paragraphFecha);
		$seccion = $documento->addSection($sectionStyle);

		$filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/logo_rep.PNG';
		$styleLogo = [
			'alignment' => 'right',
			'marginTop' => -100,
			'wrappingStyle' => 'behind',
			'width' => 50
		];

		$name = $response['result'][0]['data'][0]->surveyDesc;
		$seccion->addTitle($name, 1);
		// Añadir fecha
		$meses_ES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
		$meses_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		$month = str_replace($meses_EN, $meses_ES, date('F'));
		$year = date('Y');
		$seccion->addTitle($month . ', ' . $year, 3);

		$deleteImages = [];
		$i = 0;
		foreach($response['questions'][0] as $row) {
			$title = $i + 1 . '. ' . $row . ' (%)';

			$seccion = $documento->addSection($sectionStyle);

			// Add header
			$header = $seccion->createHeader();
			$header->addText($title, $fuenteTitulo);
			$header->addImage($filepathLogo, $styleLogo);

			// Graficos por respuestas
			$etiquetas = $response['result'][$i]['answers']['labels'];
			$series = $response['result'][$i]['answers']['datasets']['data'];

			$grafica = $seccion->addChart('column', $etiquetas, $series);
			if($typeColors == 1) {
				$colores = GenerateWord::generateColors($colors, count($etiquetas));
			} else {
				$colores = GenerateWord::arrayColors($colors, count($etiquetas));
			}

			$colores = str_replace('#', '', $colores);
			$grafica->getStyle()->setColors($colores); // Asignar colores

			$grafica->getStyle()->setDataLabelOptions(['showPercent' => true, 'showVal' => true]);
			$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
			$grafica->getStyle()->setShowAxisLabels(true);

			$grafica->getStyle()->setTitle('');

			$i++;
		}

		# Para que no diga que se abre en modo de compatibilidad
		$documento->getCompatibility()->setOoxmlVersion(15);

		# Guardarlo
		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($documento, 'Word2007');

		$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/' . $user;

		if(!file_exists($carpeta)) {
			$createFile = $this->utilesController->createDirectory($carpeta);

			if($createFile['status'] == 'KO') {
				return 'The folder has not been created';
			}
		}
		$fecha = date_create();
		$filename = date_timestamp_get($fecha) . 'Analitic_Mostreo.docx';

		$filename = str_replace(' ', '_', $filename);

		$objWriter->save(CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . $filename, 'Word2007');

		$response = $filename;

		foreach($deleteImages as $detete) {
			unlink($detete);
		}

		// Guardar reporte en un zip
		// Carpeta donde guardar los elementos a comprimir
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/';
		if(!file_exists($folder)) { // Si no existe, se crea
			$createFile = $this->utilesController->createDirectory($folder);

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

		// Objeto ZIP
		$zip = new ZipArchive();
		$zip->open($folder . $timestamp . '_Analitics_Mostreo.zip', ZipArchive::CREATE);
		$zip->addFile($carpeta . '/' . $filename, 'Analitics_Mostreo.docx');

		return $response;
	}

	public function printWordPermanent($response, $colors, $user, $typeColors, $idTenant, $survey, $stampMision, $project) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// Array de colores
		$colors = explode(',', $colors);

		$documento = new \PhpOffice\PhpWord\PhpWord();

		$propiedades = $documento->getDocInfo();
		$propiedades->setTitle('Gráficas');

		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 500,
			'marginLeft' => 1000,
			'vAlign' => 'center'
		];

		// Títulos. Solo modificando depth (el número)
		$fuentePortada = [
			'name' => 'Verdana',
			'size' => 30,
			'color' => '000000',
			'bold' => true
		];

		$paragraphPortada = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(1, $fuentePortada, $paragraphPortada);

		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];

		$documento->addTitleStyle(2, $fuenteTitulo);

		$fuenteFecha = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];

		$paragraphFecha = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(3, $fuenteFecha, $paragraphFecha);

		$seccion = $documento->addSection($sectionStyle);

		$name = $response['result'][0]['data'][0]->surveyDesc;
		$seccion->addTitle($name, 1);

		// Añadir fecha
		$meses_ES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
		$meses_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		$month = str_replace($meses_EN, $meses_ES, date('F'));
		$year = date('Y');
		$seccion->addTitle($month . ', ' . $year, 3);

		$filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/logo_rep.PNG';

		$styleLogo = [
			'alignment' => 'right',
			'wrappingStyle' => 'behind',
			'width' => 50
		];

		//Gráficas generales
		$title = 'Resultados generales';

		// Gráfico de género
		$seccion = $documento->addSection($sectionStyle);

		$header = $seccion->addHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		$etiquetas = $response['resume']['gender']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $response['resume']['gender']['value'];
		$graphTitle = 'Género (%)';

		$seccion = GenerateWord::piePermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);

		// Gráficos por edades
		$seccion = $documento->addSection($sectionStyle);

		$header = $seccion->addHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		$etiquetas = $response['resume']['age']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $response['resume']['age']['value'];
		$graphTitle = 'Edades (%)';

		$seccion = GenerateWord::columnPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);

		// Gráficos por estados
		$seccion = $documento->addSection($sectionStyle);

		$header = $seccion->addHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		$etiquetas = $response['resume']['states']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $response['resume']['states']['value'];
		$graphTitle = 'Estados (%)';

		$seccion = GenerateWord::columnPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);

		// Gráficos por NSE
		$seccion = $documento->addSection($sectionStyle);

		$header = $seccion->addHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		$etiquetas = $response['resume']['nse']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $response['resume']['nse']['value'];
		$graphTitle = 'NSE (%)';

		$seccion = GenerateWord::columnPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);

		// Gráficos de preguntas
		$i = 0;
		foreach($response['questions'][0] as $row) {
			// Para que se salte por ahora wordcloud, carga de imágenes y pregunta tipo '8'
			if($response['wordCloud'][$i] == 'yes' || $response['wordCloud'][$i] == 'image' || $response['typeQuestion'][$i] == '8' || $response['typeQuestion'][$i] == ';') {
				$i++;
				continue;
			}

			$title = $i + 1 . '. ' . $row . ' (%)';

			$seccion = $documento->addSection($sectionStyle);

			// Add header
			$header = $seccion->addHeader();
			$header->addText($title, $fuenteTitulo);
			$header->addImage($filepathLogo, $styleLogo);

			// Graficos por respuestas
			$etiquetas = $response['result'][$i]['answers']['labels'];
			for($j = 0; $j < count($etiquetas); $j++) {
				$etiquetas[$j] = str_replace('&', '&amp;', $etiquetas[$j]);
			}
			$series = $response['result'][$i]['answers']['datasets']['data'];
			$graphTitle = '';

			// Tipos de gráficas
			if($response['typeQuestion'][$i] == 'Y') {
				$seccion = GenerateWord::piePermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
			} else {
				$seccion = GenerateWord::columnPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
			}

			$i++;
		}

		# Para que no diga que se abre en modo de compatibilidad
		$documento->getCompatibility()->setOoxmlVersion(15);

		# Guardarlo
		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($documento, 'Word2007');

		// Creación de carpeta
		$folderSave = CONSTANTS::PATH_EXPORT_WORD . '/reports/' . $project . '_' . $stampMision . '_' . $survey . '/';

		if(!file_exists($folderSave)) {
			$createFile = $this->utilesController->createDirectory($folderSave);

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

		$filename = 'Analitics_Mostreo.docx';

		$objWriter->save($folderSave . $filename, 'Word2007');

		$response = $filename;

		return $response;
	}

	public function generatePermanentWordWithWordcloud($token, $reportData, $colorsHex, $typeColors, $user, $idTenant, $survey, $stampMision, $project, $briefing, $fontName) {
		// Array de colores
		$colors = explode(',', $colorsHex);

		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// CREACIÓN DEL OBJETO
		$documento = new \PhpOffice\PhpWord\PhpWord();

		$propiedades = $documento->getDocInfo();
		$propiedades->setTitle('Gráficas');

		// Ruta y estilo de logo
		$filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/logo_rep.PNG';

		$styleLogo = [
			'alignment' => 'right',
			'wrappingStyle' => 'behind',
			'width' => 50
		];

		// Estilo de página general con alineación vertical
		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 1000,
			'marginBottom' => 1000,
			'marginLeft' => 1000,
			'marginRight' => 1000,
			'vAlign' => 'center'
		];

		// Estilo de página general sin alineación vertical
		$sectionWhithOutVAlignStyle = [
			'orientation' => 'landscape',
			'marginTop' => 1000,
			'marginBottom' => 1000,
			'marginLeft' => 1000,
			'marginRight' => 1000
		];

		// Estilo de página general con alineación verticla y 2 columnas
		$section2ColumnsStyle = [
			'orientation' => 'landscape',
			'colsNum' => 2,
			'marginTop' => 1000,
			'marginBottom' => 1000,
			'marginLeft' => 1000,
			'marginRight' => 1000,
			'vAlign' => 'center'
		];

		// PORTADA
		$seccion = $documento->addSection($sectionStyle);

		// Título principal de portada
		$fuentePortada = [
			'name' => 'Verdana',
			'size' => 30,
			'color' => '000000',
			'bold' => true
		];

		$paragraphPortada = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(1, $fuentePortada, $paragraphPortada);

		$nameCount = 0;
		$name = $reportData['result'][$nameCount]['data'][0]['surveyDesc'];

		while(!$name) {
			$nameCount++;
			$name = $reportData['result'][$nameCount]['data'][0]['surveyDesc'];
		}

		$seccion->addTitle($name, 1);

		// Título secundario de portada (fecha)
		$fuenteFecha = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];

		$paragraphFecha = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(2, $fuenteFecha, $paragraphFecha);

		// Añadir fecha
		$meses_ES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
		$meses_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		$month = str_replace($meses_EN, $meses_ES, date('F'));
		$year = date('Y');
		$seccion->addTitle($month . ', ' . $year, 2);

		// FUENTES - GENERAL
		// Títulos en header de sección
		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => true
		];

		$documento->addTitleStyle(3, $fuenteTitulo);

		// BRIEFING
		$charactersCount = 0;
		foreach($briefing as $key => $value) {
			$charactersCount += strlen($briefing[$key]['text']);
		}

		if($charactersCount > 0) {
			// Plantilla de briefing todo en una
			$seccion = $documento->addSection($sectionWhithOutVAlignStyle);

			$title = 'Briefing';

			$header = $seccion->addHeader();
			$header->addText($title, $fuenteTitulo);
			$header->addImage($filepathLogo, $styleLogo);

			$elementsArray = ['applicantName', 'brandsInvolved', 'projectDescription', 'background', 'businessObjective', 'investigationObjective', 'actionStandard', 'favorableResults', 'notFavorableResults'];

			foreach($elementsArray as $value) {
				// Creación de texto continuado y diferentes estilos
				$textrun = $seccion->createTextRun();

				$textrun->addText(
					$briefing[$value]['title'] . ': ',
					[
						'name' => 'Verdana',
						'size' => 12,
						'color' => '000000',
						'bold' => true
					]
				);

				$textrun->addText(
					$briefing[$value]['text'],
					[
						'name' => 'Verdana',
						'size' => 12,
						'color' => '000000',
						'bold' => false
					]
				);

				// Salto de línea
				$seccion->addTextBreak(1, ['size' => 2]);
			}
		}
		// Posibilidad de cortarlo como en el reporte de powerpoint

		// RESULTADOS GENERALES 1/2
		// Plantilla
		$seccion = $documento->addSection($section2ColumnsStyle);

		$title = 'Resultados generales';

		$header = $seccion->addHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		// Salto de líneas
		$seccion->addTextBreak(3);

		// Crear tabla
		$table = $seccion->addTable();

		// Crear fila
		$table->addRow();

		// Iconos de género - Masculino
		$table->addCell(20000)->addImage(
			CONSTANTS::PATH_EXPORT_WORD . '/icons/icon_male.png',
			[
				'width' => 80,
				'height' => 80
			]
		);

		// Valor - Masculino
		$table->addCell(200, ['valign' => 'center'])->addText(
			$reportData['resume']['gender']['value'][0] . '%',
			[
				'name' => 'Verdana',
				'size' => 18,
				'color' => '000000',
				'bold' => true
			],
			[
				'align' => 'center'
			]
		);

		// Iconos de género - Femenino
		$table->addCell(20000)->addImage(
			CONSTANTS::PATH_EXPORT_WORD . '/icons/icon_female.png',
			[
				'width' => 80,
				'height' => 80
			]
		);

		// Valor - Femenino
		$table->addCell(200, ['valign' => 'center'])->addText(
			$reportData['resume']['gender']['value'][1] . '%',
			[
				'name' => 'Verdana',
				'size' => 18,
				'color' => '000000',
				'bold' => true
			]
		);

		// Salto de 2 líneas
		$seccion->addTextBreak(2);

		// Edades en columnas 3D
		$etiquetas = $reportData['resume']['ageRange']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $reportData['resume']['ageRange']['value'];
		$graphTitle = 'EDAD (%)';

		$seccion = GenerateWord::column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle, 'ages');

		// Salto de líneas
		$seccion->addTextBreak(6);

		// NSE en pie 3D
		$etiquetas = $reportData['resume']['nse']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $reportData['resume']['nse']['value'];
		$graphTitle = 'NSE (%)';

		$seccion = GenerateWord::pie3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle, 'nse');

		// RESULTADOS GENERALES 2/2
		// Plantilla
		$seccion = $documento->addSection($section2ColumnsStyle);

		$title = 'Resultados generales';

		$header = $seccion->addHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		// Heat Map
		$seccion->addImage(
			base64_decode(preg_replace('/^(.*base64,)/m', '', $reportData['heatMaps'][0])),
			[
				'width' => 350
			]
		);

		// Estados en columnas 3D
		$etiquetas = $reportData['resume']['states']['labels'];
		for($i = 0; $i < count($etiquetas); $i++) {
			$etiquetas[$i] = str_replace('&', '&amp;', $etiquetas[$i]);
		}
		$series = $reportData['resume']['states']['value'];
		$graphTitle = 'ESTADOS (%)';

		$seccion = GenerateWord::column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle, 'states');

		// GRÁFICOS DE PREGUNTAS
		$i = 0;
		$numberPage = 1;
		$questName = '';
		// Array para preguntas tipo 'F'
		$idControl = '';
		$seriesLabelsArray = [];
		$nameArray = [];
		$typeQ = '';
		$graphTitle = '';
		// Control para número de barras por página
		$controlArrayElements = 7;
		foreach($reportData['questions'][0] as $question) {
			// Para que se salte por ahora las preguntas tipo '8', 'G' y ';'
			if($reportData['typeQuestion'][$i] == '8' || $reportData['typeQuestion'][$i] == ';' || $reportData['typeQuestion'][$i] == 'G') {
				$i++;
				continue;
			}

			if($reportData['wordcloudImgArray'][$i]['wordCloud'] == '0') {
				if($reportData['typeQuestion'][$i] == '|' || $reportData['typeQuestion'][$i] == '7' || $reportData['typeQuestion'][$i] == 'J') {
					// Pregunta de subida de archivo sin OCR
					$i++;
					continue;
				}

				// Plantilla
				$seccion = $documento->addSection($sectionStyle);

				$title = $numberPage . '. ' . $question . ' (%)';

				$header = $seccion->addHeader();
				$header->addText($title, $fuenteTitulo);
				$header->addImage($filepathLogo, $styleLogo);

				$etiquetas = $reportData['result'][$i]['answers']['labels'];
				$series = $reportData['result'][$i]['answers']['datasets']['data'];

				// Tipos de gráficas
				if($reportData['typeQuestion'][$i] == 'Y' || $reportData['typeQuestion'][$i] == 'G') {
					$seccion = GenerateWord::pie3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
				} else if($reportData['typeQuestion'][$i] == '3' || $reportData['typeQuestion'][$i] == '5') {
					// Formato columnas 3D
					array_multisort($etiquetas, SORT_ASC, $series);
					$seccion = GenerateWord::column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
				} else if($reportData['typeQuestion'][$i] == 'A' || $reportData['typeQuestion'][$i] == 'B' || $reportData['typeQuestion'][$i] == 'F' || $reportData['typeQuestion'][$i] == 'R') {
					// Formato columnas 3D
					if($reportData['typeQuestion'][$i] != 'R') {
						array_multisort($etiquetas, SORT_ASC, $series);
					} else {
						for($i = 0; $i < count($etiquetas); $i++) {
							$etiquetas[$i] = $i + 1;
						}
					}
					$seccion = GenerateWord::column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);

					// VER ARRIBA
				} else if($reportData['typeQuestion'][$i] == '2' || $reportData['typeQuestion'][$i] == '4' || $reportData['typeQuestion'][$i] == '!' || $reportData['typeQuestion'][$i] == 'L' || $reportData['typeQuestion'][$i] == 'M' || $reportData['typeQuestion'][$i] == 'R') {
					if($reportData['typeQuestion'][$i] == '2') {
						for($k = 0; $k < count($etiquetas); $k++) {
							$etiquetas[$k] = explode(' ', $etiquetas[$k])[0];
						}

						array_multisort($etiquetas, SORT_ASC, $series);
					}

					$seccion = GenerateWord::column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
				} else if($reportData['typeQuestion'][$i] == '6' || $reportData['typeQuestion'][$i] == 'K' || $reportData['typeQuestion'][$i] == 'N') {
					// Crear tabla
					$tableG = $seccion->addTable();

					// Crear fila
					$tableG->addRow();

					array_multisort($etiquetas, SORT_ASC, $series);

					// Celda de gráfica
					$graphCell = $tableG->addCell(4000, ['valign' => 'center']);

					// Gráfica
					GenerateWord::column3DPermanentGraphic($graphCell, $etiquetas, $series, $colors, $typeColors, $graphTitle, 'table');

					// Crear tabla de valores matemáticos
					$tableCell = $tableG->addCell(3000, ['valign' => 'center'])->addTable();

					// Valores
					$min = $etiquetas[0];
					$max = $etiquetas[count($etiquetas) - 1];
					$modaQuantity = max($series);
					$modaIndex = array_search($modaQuantity, $series);
					$moda = $etiquetas[$modaIndex];

					$labelsSeries = [];
					for($n = 0; $n < count($etiquetas); $n++) {
						$labelsSeries[$etiquetas[$n]] = $series[$n];
					}

					$totalKeyValue = 0;
					foreach($labelsSeries as $key => $value) {
						$totalKeyValue += $key * $value;
					}
					$average = round($totalKeyValue / 100, 1);

					$names = ['Mínimo', 'Máximo', 'Promedio', 'Moda'];
					$values = [$min, $max, $average, $moda];

					for($m = 0; $m < count($names); $m++) {
						// Crear fila
						$tableCell->addRow();

						$tableCell->addCell(2000, ['valign' => 'center'])->addText(
							$names[$m],
							[
								'name' => 'Verdana',
								'size' => 12,
								'color' => '000000',
								'bold' => true
							]
						);

						$tableCell->addCell(2000, ['valign' => 'center'])->addText(
							$values[$m],
							[
								'name' => 'Verdana',
								'size' => 12,
								'color' => '000000',
								'bold' => false
							],
							[
								'align' => 'center'
							]
						);
					}
				} else {
					$seccion = GenerateWord::columnPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
				}
			} else if($reportData['wordcloudImgArray'][$i]['wordCloud'] == '3') {
				// Especial para las preguntas tipo 'P'
				$etiquetas = $reportData['result'][$i]['answers']['labels'];
				$series = $reportData['result'][$i]['answers']['datasets']['data'];

				for($p = 0; $p < count($etiquetas); $p++) {
					// Plantilla
					$seccion = $documento->addSection($sectionStyle);

					$title = $numberPage . '. ' . $question . ' - ' . $etiquetas[$p] . ' (%)';

					$header = $seccion->addHeader();
					$header->addText($title, $fuenteTitulo);
					$header->addImage($filepathLogo, $styleLogo);

					// Generar en una página, gráfica de columnas 3D con un solo valor, tabla de palabras y wordcloud
					GenerateWord::column3DAndWordcloudWithTableOnePage($seccion, $etiquetas[$p], $series[$p], $reportData['wordcloudImgArray'][$i]['element'][$p], $survey, $reportData['wordCloud'][$i][$p], $token, $idTenant, $colors, $typeColors);
				}
			} else {
				if($reportData['wordcloudImgArray'][$i]['wordCloud'] == '2') {
					// Plantilla
					$seccion = $documento->addSection($sectionStyle);

					$title = $numberPage . '. ' . $question . ' (%)';

					$header = $seccion->addHeader();
					$header->addText($title, $fuenteTitulo);
					$header->addImage($filepathLogo, $styleLogo);

					$etiquetas = $reportData['result'][$i]['answers']['labels'];
					$series = $reportData['result'][$i]['answers']['datasets']['data'];

					if($reportData['typeQuestion'][$i] == 'O' || $reportData['typeQuestion'][$i] == 'P') {
						$seccion = GenerateWord::column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle);
					}
				}

				// Plantilla
				$seccion = $documento->addSection($sectionStyle);

				$title = $numberPage . '. ' . $reportData['questions'][0][$i];

				$header = $seccion->addHeader();
				$header->addText($title, $fuenteTitulo);
				$header->addImage($filepathLogo, $styleLogo);

				// Crear wordcloud y tabla en una única página
				$seccion = GenerateWord::wordcloudWithTableOnePage($seccion, $reportData['wordcloudImgArray'][$i]['element'], $survey, $reportData['questionID'][$i], $token, $idTenant);
			}

			$i++;
			$numberPage++;
		}

		# Para que no diga que se abre en modo de compatibilidad
		$documento->getCompatibility()->setOoxmlVersion(15);

		# Guardarlo
		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($documento, 'Word2007');

		// Creación de carpeta
		$folderSave = CONSTANTS::PATH_EXPORT_WORD . '/reports/' . $project . '_' . $stampMision . '_' . $survey . '/';

		if(!file_exists($folderSave)) {
			$createFile = $this->utilesController->createDirectory($folderSave);

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

		$filename = 'Analitics_Mostreo.docx';

		$objWriter->save($folderSave . $filename, 'Word2007');

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

		return $response;
	}

	private function wordcloudWithTableOnePage($seccion, $image, $survey, $pregunta, $token, $idTenant) {
		// Crear tabla
		$tableG = $seccion->addTable();

		// Crear fila
		$tableG->addRow();

		// Obtenemos data
		$controller = new Controller;

		$url = CONSTANTS::SERVERAPI . 'getAnalyticsTagCloudMostreo';
		$params = [
			'token' => $token,
			'survey' => $survey,
			'pregunta' => $pregunta
		];

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

		if(count($resultPOST->result) > 0) {
			// Control de numero de palabras a representar
			$topWords = 10;
			if(count($resultPOST->result) <= $topWords) {
				$result = $resultPOST->result;
			} else {
				$result = array_slice($resultPOST->result, 0, $topWords);
			}

			$max = 10 * 5;
			$array_total = array_chunk($result, $max);

			foreach($array_total as $array_div) {
				$nWords = count($array_div);
				$limit = 10;
				$nColumns = $nWords / $limit; // Como max 5

				if(is_int($nColumns)) {
					$nColumns = intval($nWords / $limit);
				} else {
					$nColumns = intval($nWords / $limit + 1);
				}

				$array_cut = array_chunk($array_div, $limit);

				// Crear tabla de palabras
				$table = $tableG->addCell(4000, ['valign' => 'center'])->addTable();

				// Crear fila
				$table->addRow();

				// Título - Palabra
				$table->addCell(2000, ['valign' => 'center'])->addText(
					'Palabra',
					[
						'name' => 'Verdana',
						'size' => 12,
						'color' => '000000',
						'bold' => true
					],
					[
						'align' => 'center'
					]
				);

				// Título - Contador
				$table->addCell(2000, ['valign' => 'center'])->addText(
					'Contador',
					[
						'name' => 'Verdana',
						'size' => 12,
						'color' => '000000',
						'bold' => true
					],
					[
						'align' => 'center'
					]
				);

				for($j = 0; $j < count($array_cut[0]); $j++) {
					// Crear fila
					$table->addRow();

					for($i = 0; $i < count($array_cut); $i++) {
						if(isset($array_cut[$i][$j]->word)) {
							// Control de longitud
							if(strlen($array_cut[$i][$j]->word) > 48) {
								$fontSizeEsp = 4;
							} else if(strlen($array_cut[$i][$j]->word) > 36) {
								$fontSizeEsp = 6;
							} else if(strlen($array_cut[$i][$j]->word) > 24) {
								$fontSizeEsp = 8;
							} else if(strlen($array_cut[$i][$j]->word) > 12) {
								$fontSizeEsp = 10;
							} else {
								$fontSizeEsp = 12;
							}

							// Palabra
							$table->addCell(2000, ['valign' => 'center'])->addText(
								$array_cut[$i][$j]->word,
								[
									'name' => 'Verdana',
									'size' => $fontSizeEsp,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						} else {
							// Palabra
							$table->addCell(2000, ['valign' => 'center'])->addText(
								'',
								[
									'name' => 'Verdana',
									'size' => 12,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						}

						if(isset($array_cut[$i][$j]->counter)) {
							// Contador
							$table->addCell(200, ['valign' => 'center'])->addText(
								$array_cut[$i][$j]->counter,
								[
									'name' => 'Verdana',
									'size' => 12,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						} else {
							// Contador
							$table->addCell(200, ['valign' => 'center'])->addText(
								'',
								[
									'name' => 'Verdana',
									'size' => 12,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						}
					}
				}
			}
		}

		// Celda de imagen
		$tableG->addCell(4000, ['valign' => 'center'])->addImage(
			base64_decode(preg_replace('/^(.*base64,)/m', '', $image)),
			[
				'width' => 550
			]
		);

		return $seccion;
	}

	private function column3DAndWordcloudWithTableOnePage($seccion, $etiqueta, $serie, $image, $survey, $pregunta, $token, $idTenant, $colors, $typeColors) {
		// Crear tabla
		$tableG = $seccion->addTable();

		// Crear fila
		$tableG->addRow();

		// Celda de gráfica
		$graphCell = $tableG->addCell(2000, ['valign' => 'center']);

		// Gráfica
		$etiquetas[0] = $etiqueta;
		$series[0] = $serie;
		GenerateWord::column3DPermanentGraphic($graphCell, $etiquetas, $series, $colors, $typeColors, '', 'typeP');

		// Obtenemos data
		$controller = new Controller;

		$url = CONSTANTS::SERVERAPI . 'getAnalyticsTagCloudMostreo';
		$params = [
			'token' => $token,
			'survey' => $survey,
			'pregunta' => $pregunta
		];

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

		if(count($resultPOST->result) > 0) {
			// Control de numero de palabras a representar
			$topWords = 10;
			if(count($resultPOST->result) <= $topWords) {
				$result = $resultPOST->result;
			} else {
				$result = array_slice($resultPOST->result, 0, $topWords);
			}

			$max = 10 * 5;
			$array_total = array_chunk($result, $max);

			foreach($array_total as $array_div) {
				$nWords = count($array_div);
				$limit = 10;
				$nColumns = $nWords / $limit; // Como max 5

				if(is_int($nColumns)) {
					$nColumns = intval($nWords / $limit);
				} else {
					$nColumns = intval($nWords / $limit + 1);
				}

				$array_cut = array_chunk($array_div, $limit);

				// Crear tabla de palabras
				$table = $tableG->addCell(3000, ['valign' => 'center'])->addTable();

				// Crear fila
				$table->addRow();

				// Título - Palabra
				$table->addCell(1400, ['valign' => 'center'])->addText(
					'Palabra',
					[
						'name' => 'Verdana',
						'size' => 12,
						'color' => '000000',
						'bold' => true
					],
					[
						'align' => 'center'
					]
				);

				// Título - Contador
				$table->addCell(1400, ['valign' => 'center'])->addText(
					'Contador',
					[
						'name' => 'Verdana',
						'size' => 12,
						'color' => '000000',
						'bold' => true
					],
					[
						'align' => 'center'
					]
				);

				for($j = 0; $j < count($array_cut[0]); $j++) {
					// Crear fila
					$table->addRow();

					for($i = 0; $i < count($array_cut); $i++) {
						if(isset($array_cut[$i][$j]->word)) {
							// Control de longitud
							if(strlen($array_cut[$i][$j]->word) > 48) {
								$fontSizeEsp = 4;
							} else if(strlen($array_cut[$i][$j]->word) > 36) {
								$fontSizeEsp = 6;
							} else if(strlen($array_cut[$i][$j]->word) > 24) {
								$fontSizeEsp = 8;
							} else if(strlen($array_cut[$i][$j]->word) > 12) {
								$fontSizeEsp = 10;
							} else {
								$fontSizeEsp = 12;
							}

							// Palabra
							$table->addCell(1400, ['valign' => 'center'])->addText(
								$array_cut[$i][$j]->word,
								[
									'name' => 'Verdana',
									'size' => $fontSizeEsp,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						} else {
							// Palabra
							$table->addCell(1400, ['valign' => 'center'])->addText(
								'',
								[
									'name' => 'Verdana',
									'size' => 12,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						}

						if(isset($array_cut[$i][$j]->counter)) {
							// Contador
							$table->addCell(1400, ['valign' => 'center'])->addText(
								$array_cut[$i][$j]->counter,
								[
									'name' => 'Verdana',
									'size' => 12,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						} else {
							// Contador
							$table->addCell(1400, ['valign' => 'center'])->addText(
								'',
								[
									'name' => 'Verdana',
									'size' => 12,
									'color' => '000000',
									'bold' => false
								],
								[
									'align' => 'center'
								]
							);
						}
					}
				}
			}
		}

		// Celda de imagen
		$tableG->addCell(10000, ['valign' => 'center'])->addImage(
			base64_decode(preg_replace('/^(.*base64,)/m', '', $image)),
			[
				'width' => 350,
				'align' => 'center'
			]
		);
	}

	public function piePermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle) {
		$grafica = $seccion->addChart('pie', $etiquetas, $series);

		if($typeColors == 1) {
			$colores = GenerateWord::generateColors($colors, count($etiquetas));
		} else {
			$colores = GenerateWord::arrayColors($colors, count($etiquetas));
		}
		$colores = str_replace('#', '', $colores);

		$grafica->getStyle()->setColors($colores); // Asignar colores
		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);
		$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
		$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setShowLegend(true);
		$grafica->getStyle()->setTitle($graphTitle);

		return $seccion;
	}

	public function pie3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle, $general = false) {
		$graphStyle = [
			'3d' => true
		];
		$grafica = $seccion->addChart('pie', $etiquetas, $series, $graphStyle);

		if($typeColors == 1) {
			$colores = GenerateWord::generateColors($colors, count($etiquetas));
		} else {
			$colores = GenerateWord::arrayColors($colors, count($etiquetas));
		}
		$colores = str_replace('#', '', $colores);

		$grafica->getStyle()->setColors($colores); // Asignar colores
		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);
		if($general == 'nse') {
			$grafica->getStyle()->setWidth(450 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(300 * 10000); // Asignar Alto
		} else {
			$grafica->getStyle()->setWidth(950 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
		}
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setShowLegend(true);
		$grafica->getStyle()->setTitle($graphTitle);

		return $seccion;
	}

	public function columnPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle) {
		$grafica = $seccion->addChart('column', $etiquetas, $series);

		if($typeColors == 1) {
			$colores = GenerateWord::generateColors($colors, count($etiquetas));
		} else {
			$colores = GenerateWord::arrayColors($colors, count($etiquetas));
		}
		$colores = str_replace('#', '', $colores);

		$grafica->getStyle()->setColors($colores); // Asignar colores
		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);
		$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
		$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto

		// Etiquetas de los ejes
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setValueLabelPosition('low');
		$grafica->getStyle()->setCategoryLabelPosition('low');
		$grafica->getStyle()->setTitle($graphTitle);

		return $seccion;
	}

	public function column3DPermanentGraphic($seccion, $etiquetas, $series, $colors, $typeColors, $graphTitle, $general = false) {
		$graphStyle = [
			'3d' => true
		];
		$grafica = $seccion->addChart('column', $etiquetas, $series, $graphStyle);

		if($typeColors == 1) {
			$colores = GenerateWord::generateColors($colors, count($etiquetas));
		} else {
			$colores = GenerateWord::arrayColors($colors, count($etiquetas));
		}
		$colores = str_replace('#', '', $colores);

		$grafica->getStyle()->setColors($colores); // Asignar colores
		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);

		if($general == 'states') {
			$grafica->getStyle()->setWidth(460 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(320 * 10000); // Asignar Alto
		} else if($general == 'ages') {
			$grafica->getStyle()->setWidth(450 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(300 * 10000); // Asignar Alto
		} else if($general == 'table') {
			$grafica->getStyle()->setWidth(750 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(550 * 10000); // Asignar Alto
		} else if($general == 'typeP') {
			$grafica->getStyle()->setWidth(250 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(540 * 10000); // Asignar Alto
		} else {
			$grafica->getStyle()->setWidth(950 * 10000); // Asignar ancho
			$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
		}

		$grafica->getStyle()->set3d(true);

		// Etiquetas de los ejes
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setValueLabelPosition('low');
		$grafica->getStyle()->setCategoryLabelPosition('low');
		$grafica->getStyle()->setTitle($graphTitle);

		return $seccion;
	}

	public function printWordComparative2($data, $encuestas, $questions, $wc, $colors, $user, $generalCharts, $paramsWc, $token, $timestamp, $isWord, $isWc, $idTenant) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);
		$colors = explode(',', $colors);

		$documento = new \PhpOffice\PhpWord\PhpWord();

		$propiedades = $documento->getDocInfo();
		$propiedades->setTitle('Gráficas');
		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 500,
			'marginLeft' => 1000,
			'vAlign' => 'center'
		];

		$sectionStyleList = [
			'orientation' => 'landscape',
			'marginTop' => 1500,
			'marginLeft' => 1000,
			'colsNum' => 2
		];

		# Títulos. Solo modificando depth (el número)
		$fuentePortada = [
			'name' => 'Verdana',
			'size' => 30,
			'color' => '000000',
			'bold' => true
		];

		$paragraphPortada = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];

		$documento->addTitleStyle(1, $fuentePortada, $paragraphPortada);
		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];
		$documento->addTitleStyle(2, $fuenteTitulo);

		$seccion = $documento->addSection($sectionStyle);
		$fuenteFecha = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];
		$paragraphFecha = [
			'alignment' => 'center',
			'textAlignment' => 'center'
		];
		$documento->addTitleStyle(3, $fuenteFecha, $paragraphFecha);

		$name = 'Reporte ';
		$iName = 0;
		foreach($encuestas as $encuesta) {
			$name = $name . $encuesta;
			if($iName < count($encuestas) - 1) {
				$name = $name . ', ';
			}
			$iName++;
		}
		$seccion->addTitle($name, 1);
		// Añadir fecha
		$meses_ES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
		$meses_EN = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		$month = str_replace($meses_EN, $meses_ES, date('F'));
		$year = date('Y');
		$seccion->addTitle($month . ', ' . $year, 3);

		$filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/logo_rep.PNG';
		$styleLogo = [
			'alignment' => 'right',
			'wrappingStyle' => 'behind',
			'width' => 50
		];

		//Graficas generales
		$title = 'Resultados generales';

		$etiquetas = $generalCharts['gender']['labels'];
		$series = $generalCharts['gender']['values'];

		GenerateWord::stackedcolumn($documento, $title, $encuestas, $series, $etiquetas, $colors, 'Género (%)', $idTenant);

		$etiquetas = $generalCharts['age']['labels'];
		$series = $generalCharts['age']['values'];

		GenerateWord::stackedcolumn($documento, $title, $encuestas, $series, $etiquetas, $colors, 'Edad (%)', $idTenant);

		$etiquetas = $generalCharts['states']['labels'];
		$series = $generalCharts['states']['values'];

		GenerateWord::stackedcolumn($documento, $title, $encuestas, $series, $etiquetas, $colors, 'Estados (%)', $idTenant);

		$deleteImages = [];
		$i = 0;
		$iwc = 0;
		$elements = count($questions);
		$totalsurveys = count($encuestas) - 1;
		//Iteracion preguntas
		$fecha = date_create();

		foreach($data as $row) {
			$title = $i + 1 . '. ' . $questions[0][$i];

			// Comprobar si hay respustas de Otros
			if($wc[$i] != 'no') {
				// Hay WordCloud
				$seccion = $documento->addSection($sectionStyle);
				// Add header
				$header = $seccion->createHeader();
				$header->addText($title, $fuenteTitulo);
				$header->addImage($filepathLogo, $styleLogo);

				$Base64Img = $wc[$i];

				$baseFromJavascript = $Base64Img;

				$base_to_php = explode(',', $baseFromJavascript);

				$data = base64_decode($base_to_php[1]);

				$filepath = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . date_timestamp_get($fecha) . '_wc_' . $i . '.png';
				$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/' . $user;
				if(!file_exists($carpeta)) {
					$createFile = $this->utilesController->createDirectory($carpeta);

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

				array_push($deleteImages, $filepath);

				file_put_contents($filepath, $data);

				$seccion->addImage($filepath, [
					'alignment' => 'center',
					'width' => 600
				]);

				$seccion = $documento->addSection($sectionStyleList);
				$others = [];
				$position = count($row) - 1;

				foreach($row[$position]['answers']['others'] as $answers) {
					$sanit = htmlspecialchars($answers);
					$sanit = trim($sanit);
					$sanit = preg_replace("/[\r\n|\n|\r]+/", ' ', $sanit);
					$seccion->addListItem($sanit);
				}

				// Añadir tabla con contador palabras
				$survey = $paramsWc[$iwc][0];
				$pregunta = $paramsWc[$iwc][1];
				$controller = new Controller;
				$url = CONSTANTS::SERVERAPI . 'getAnalyticsTagCloudMostreo';
				$params = [
					'survey' => $survey,
					'pregunta' => $pregunta,
					'token' => $token
				];

				$resultPOST = $controller->sendCurlPOST($url, $params);
				if(count($resultPOST->result) > 0) {
					//Tablas
					$estiloSeccionTabla = [
						'orientation' => 'landscape',
						'marginTop' => 2500,
						'marginLeft' => 1000
					];

					$estiloTabla = [
						'borderColor' => '000000',
						'alignment' => Jc::CENTER,
						'borderSize' => 5,
						'orientation' => 'landscape',
						'marginTop' => 2500,
						'marginLeft' => 1000
					];

					if(count($resultPOST->result) > 0) {
						$max = 20 * 6;
						$array_total = array_chunk($resultPOST->result, $max);

						foreach($array_total as $array_div) {
							$nWords = count($array_div);
							$limit = 20;
							$nColumns = $nWords / $limit; // Como max 5

							if(is_int($nColumns)) {
								$nColumns = intval($nWords / $limit);
							} else {
								$nColumns = intval($nWords / $limit + 1);
							}

							$array_cut = array_chunk($array_div, $limit);
							$seccion = $documento->addSection($sectionStyle);
							// Add header
							$header = $seccion->createHeader();
							$header->addText($title, $fuenteTitulo);
							$header->addImage($filepathLogo, $styleLogo);

							$documento->addTableStyle('estiloTabla', $estiloTabla);

							$tabla = $seccion->addTable('estiloTabla'); # Agregar tabla con el estilo que guardamos antes
							$tabla->addRow(); # Agregar fila
							for($r = 0; $r < $nColumns; $r++) {
								$celda = $tabla->addCell(); # Agregar celda
								$celda->addText('Palabra', ['bold' => true]);
								$celda = $tabla->addCell(); # Agregar celda
								$celda->addText('Contador', ['bold' => true]);
							}

							// Creamos datos
							for($j = 0; $j < count($array_cut[0]); $j++) {
								$tabla->addRow(); # Agregar fila

								for($o = 0; $o < count($array_cut); $o++) {
									$celda = $tabla->addCell(); # Agregar celda
									if(isset($array_cut[$o][$j]->word)) {
										$celda->addText($array_cut[$o][$j]->word);
									} else {
										$celda->addText('');
									}

									$celda = $tabla->addCell(); # Agregar celda
									if(isset($array_cut[$o][$j]->counter)) {
										$celda->addText($array_cut[$o][$j]->counter);
									} else {
										$celda->addText('');
									}
								}
							}
						}
					}
				}

				$iwc++;
			} else {
				// No hay wordcloud
				// Graficos por respuestas
				$etiquetas = $row[$totalsurveys]['answers']['labels'];
				$series = [];
				// Segmentar la data
				$total_elements = count($etiquetas) - 1;
				for($j = 0; $j <= $total_elements; $j++) {
					$values = [];
					for($x = 0; $x <= $totalsurveys; $x++) {
						if(!is_null($row[$x])) {
							array_push($values, $row[$x]['answers']['datasets']['data'][$j]);
						} else {
							array_push($values, 0);
						}
					};

					array_push($series, $values);
				}

				GenerateWord::stackedcolumn($documento, $title, $encuestas, $series, $etiquetas, $colors, 'Respuestas (%)', $idTenant);

				//Tablas
				$estiloSeccionTabla = [
					'orientation' => 'landscape',
					'marginTop' => 2500,
					'marginLeft' => 1000
				];

				$estiloTabla = [
					'borderColor' => '000000',
					'alignment' => Jc::CENTER,
					'borderSize' => 5,
					'orientation' => 'landscape',
					'marginTop' => 2500,
					'marginLeft' => 1000
				];

				$seccion = $documento->addSection($estiloSeccionTabla);

				// Add header
				$header = $seccion->createHeader();
				$header->addText($title, $fuenteTitulo);
				$header->addImage($filepathLogo, $styleLogo);

				// Guardarlo para usarlo más tarde
				$documento->addTableStyle('estiloTabla', $estiloTabla);

				$tabla = $seccion->addTable('estiloTabla'); # Agregar tabla con el estilo que guardamos antes
				$tabla->addRow(); # Agregar fila
				$celda = $tabla->addCell(); # Agregar celda
				$celda->addText('');
				foreach($encuestas as $encuesta) {
					$celda = $tabla->addCell(); # Agregar celda
					$celda->addText($encuesta);
				}

				$iEtiq = 0;
				foreach($etiquetas as $etiqueta) {
					$tabla->addRow(); # Agregar fila
					$celda = $tabla->addCell(); # Agregar celda
					$celda->addText($etiqueta);
					$iSerie = 0;
					for($iSerie; $iSerie < count($encuestas); $iSerie++) {
						$celda = $tabla->addCell(); # Agregar celda
						$celda->addText($series[$iEtiq][$iSerie]);
					}
					$iEtiq++;
				}
			}

			$i++;
		}

		# Para que no diga que se abre en modo de compatibilidad
		$documento->getCompatibility()->setOoxmlVersion(15);

		# Guardarlo
		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($documento, 'Word2007');

		$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/' . $user;

		if(!file_exists($carpeta)) {
			$createFile = $this->utilesController->createDirectory($carpeta);

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

		$filename = date_timestamp_get($fecha) . '_Analitic_Acumulativo_Mostreo.docx';

		$filename = str_replace(' ', '_', $filename);

		$objWriter->save(CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . $filename, 'Word2007');

		$response = $filename;

		foreach($deleteImages as $detete) {
			unlink($detete);
		}

		// Guardar reporte en un zip
		// Carpeta donde guardar los elementos a comprimir
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/';
		if(!file_exists($folder)) { // Si no existe, se crea
			$createFile = $this->utilesController->createDirectory($folder);

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

		// Objeto ZIP
		$zip = new ZipArchive();
		$zip->open($folder . $timestamp . '_Analitic_Acumulativo_Mostreo.zip', ZipArchive::CREATE);
		if($isWord == 'true') {
			$zip->addFile($carpeta . '/' . $filename, 'Analitic_Acumulativo_Mostreo.docx');
		}
		if($isWc == 'true') {
			$zip->addFile($carpeta . '/' . $response['excel'], 'Analitic_Acumulativo_Mostreo.xlsx');
		}

		return $response;
	}

	private function stackedcolumn($documento, $title, $etiquetas, $series, $label, $colores, $titleAnswer, $idTenant) {
		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 500,
			'marginLeft' => 1000,
			'vAlign' => 'center'
		];

		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];

		$filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/logo_rep.PNG';
		$styleLogo = [
			'alignment' => 'right',
			'wrappingStyle' => 'behind',
			'width' => 50
		];

		$seccion = $documento->addSection($sectionStyle);

		// Add header
		$header = $seccion->createHeader();
		$header->addText($title, $fuenteTitulo);
		$header->addImage($filepathLogo, $styleLogo);

		$colores = GenerateWord::generateColors($colores, count($label));
		$colores = str_replace('#', '', $colores);

		$grafica = $seccion->addChart('percent_stacked_column', $etiquetas, $series[0], null, $label[0]);

		for($i = 1; $i < count($series); $i++) {
			$grafica->addSeries($etiquetas, $series[$i], $label[$i]);
		}

		$grafica->getStyle()->setDataLabelOptions(['showPercent' => false, 'showVal' => true]);
		$grafica->getStyle()->setWidth(900 * 10000); // Asignar ancho
		$grafica->getStyle()->setHeight(600 * 10000); // Asignar Alto
		$grafica->getStyle()->setShowAxisLabels(true);
		$grafica->getStyle()->setTitle($titleAnswer);
		$grafica->getStyle()->setShowLegend(true);
	}

	public function printWordComparative($name, $questions, $data, $labels, $colors, $wordCloud, $idTenant) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);
		$documento = new \PhpOffice\PhpWord\PhpWord();
		$colores = ['FF0000', '0000FF'];

		$propiedades = $documento->getDocInfo();
		$propiedades->setTitle('Gráficas');

		$fuenteTitulo = [
			'name' => 'Verdana',
			'size' => 12,
			'color' => '000000',
			'bold' => false
		];
		$sectionStyle = [
			'orientation' => 'landscape',
			'marginTop' => 500,
			'marginLeft' => 1000,
			'vAlign' => 'center'
		];

		//Titulo
		$documento->addTitleStyle(2, $fuenteTitulo);
		$seccion = $documento->addSection($sectionStyle);
		$report_title = 'Reporte comparativo ';
		foreach($name as $row) {
			$report_title .= ', ' . $row;
		}
		$seccion->addTitle($report_title, 2);

		$i = 0;
		foreach($questions as $question) {
			// Inicio preguntas
			$answerStacked = [];
			$estadoStacked = [];
			$edadStacked = [];
			$generoStacked = [];

			$answerStackedLabel = [];
			$estadoStackedLabel = [];
			$edadStackedLabel = [];
			$generoStackedLabel = [];

			$j = 0;
			foreach($data as $result) {
				//Inicio encuesta
				$answerStacked[$j] = [];
				$estadoStacked[$j] = [];
				$edadStacked[$j] = [];
				$generoStacked[$j] = [];

				$answerStackedLabel[$j] = [];
				$estadoStackedLabel[$j] = [];
				$edadStackedLabel[$j] = [];
				$generoStackedLabel[$j] = [];

				$answer = [];
				$estado = [];
				$edad = [];
				$genero = [];

				foreach($labels as $key) {
					$answerLabel[$key] = 0;
				}

				foreach($result as $row) {
					$estadoLabel = [];
					$edadLabel = [];
					$generoLabel = [];

					$answerLabel[$row->answer]++;

					//respuesta
					array_push($answer, $row->answer);
					//estado
					array_push($estado, $row->perf001);
					//edad
					array_push($edad, $row->perf002);
					//genero
					array_push($genero, $row->perf003);
				}

				// Acumulado respusetas
				$answers = $answerLabel;

				$answer = [];
				$answers_total = 0;
				foreach($answers as $key => $value) {
					$answers_total += $value;
				}
				foreach($answers as $key => $value) {
					$percent = $value / $answers_total;
					$percent = round($percent * 100, 1);
					array_push($answer, $percent);
				}

				array_push($answerStacked[$j], $answer);
				array_push($answerStackedLabel[$j], $labels);

				// Acumulado estado
				asort($estado);
				$estados = array_count_values($estado);
				$estado = [];
				$estados_total = 0;
				foreach($estados as $key => $value) {
					$estados_total += $value;
				}

				foreach($estados as $key => $value) {
					$percent = $value / $estados_total;
					$percent = round($percent * 100, 1);
					array_push($estado, $percent);
					array_push($estadoLabel, $key);
				}
				array_push($estadoStacked[$j], $estado);
				array_push($estadoStackedLabel[$j], $estadoLabel);

				// Acumulado edad
				asort($edad);
				$edades = array_count_values($edad);
				$edad = [];
				$edades_total = 0;
				foreach($edades as $key => $value) {
					$edades_total += $value;
				}

				foreach($edades as $key => $value) {
					$percent = $value / $edades_total;
					$percent = round($percent * 100, 1);
					array_push($edad, $percent);
					array_push($edadLabel, $key);
				}
				array_push($edadStacked[$j], $edad);
				array_push($edadStackedLabel[$j], $edadLabel);

				// Acumulado genero
				asort($genero);
				$generos = array_count_values($genero);
				$genero = [];
				$generos_total = 0;
				foreach($generos as $key => $value) {
					$generos_total += $value;
				}

				foreach($generos as $key => $value) {
					$percent = $value / $generos_total;
					$percent = round($percent * 100, 1);
					array_push($genero, $percent);
					array_push($generoLabel, $key);
				}
				array_push($generoStacked[$j], $genero);
				array_push($generoStackedLabel[$j], $generoLabel);

				$j++;
			};

			// Fin preguntas
			$i++;
		}

		// Data para graficas
		// Respuestas
		$answers = [];
		$i = 0;
		foreach($answerStacked as $result) {
			foreach($result[0] as $row) {
				$answers[$i] = [];
				$i++;
			}
			break;
		}

		foreach($answerStacked as $result) {
			$i = 0;
			foreach($result[0] as $row) {
				array_push($answers[$i], $row);
				$i++;
			}
		}

		// Estado
		$estado = [];
		$i = 0;
		foreach($estadoStacked as $result) {
			foreach($result[0] as $row) {
				$estado[$i] = [];
				$i++;
			}
			break;
		}

		foreach($estadoStacked as $result) {
			$i = 0;
			foreach($result[0] as $row) {
				array_push($estado[$i], $row);
				$i++;
			}
		}

		// Edad
		$edad = [];
		$i = 0;
		foreach($edadStacked as $result) {
			foreach($result[0] as $row) {
				$edad[$i] = [];
				$i++;
			}
			break;
		}

		foreach($edadStacked as $result) {
			$i = 0;
			foreach($result[0] as $row) {
				array_push($edad[$i], $row);
				$i++;
			}
		}

		// Genero
		$genero = [];
		$i = 0;
		foreach($generoStacked as $result) {
			foreach($result[0] as $row) {
				$genero[$i] = [];
				$i++;
			}
			break;
		}

		foreach($generoStacked as $result) {
			$i = 0;
			foreach($result[0] as $row) {
				array_push($genero[$i], $row);
				$i++;
			}
		}

		$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($documento, 'Word2007');

		//Respuestas
		GenerateWord::stackedcolumn($documento, $question, $name, $answers, $answerStackedLabel, $colores, 'Respuestas (%)', $idTenant);
		//Genero
		GenerateWord::stackedcolumn($documento, $question, $name, $genero, $generoStackedLabel, $colores, 'Género (%)', $idTenant);
		//Edad
		GenerateWord::stackedcolumn($documento, $question, $name, $edad, $edadStackedLabel, $colores, 'Edades (%)', $idTenant);
		//Estados
		GenerateWord::stackedcolumn($documento, $question, $name, $estado, $estadoStackedLabel, $colores, 'Estados (%)', $idTenant);

		$filename = 'Reporte.docx';

		$objWriter->save(CONSTANTS::PATH_EXPORT_WORD . '/' . $filename, 'Word2007');

		$response = $filename;
	}
}