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

use PhpOffice\PhpPresentation\IOFactory;
use PhpOffice\PhpPresentation\PhpPresentation;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Area;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Bar;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Bar3D;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Line;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Pie;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Pie3D;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Doughnut;
use PhpOffice\PhpPresentation\Shape\Chart\Type\Scatter;
use PhpOffice\PhpPresentation\Shape\Chart\Series;
use PhpOffice\PhpPresentation\Style\Alignment;
use PhpOffice\PhpPresentation\Style\Border;
use PhpOffice\PhpPresentation\Style\Color;
use PhpOffice\PhpPresentation\Style\Fill;
use PhpOffice\PhpPresentation\Style\Shadow;
use PhpOffice\PhpPresentation\Style\Font;
use PhpOffice\PhpPresentation\Shape\Drawing;
use PhpOffice\PhpPresentation\Shape\RichText\Paragraph;
use PhpOffice\PhpPresentation\Style\Bullet;

class GeneratePpt {
	private $utilesController;

	private $typeColors = '';
	private $colorsHex = [];
	private $fontFamily = 'Arial';
	private $fontSize = '18';
	private $colorTituloPortada = '';
	private $colorTitulo = '';
	private $plantillaPortada = '';
	private $plantilla = '';
	private $logo = '';
	private $answersOrder = '';

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

	private function createTitle($objPHPPresentation, $title) {
		// Create slide
		$slide = $objPHPPresentation->createSlide();

		$oShapeDrawing = new Drawing\File();

		$oShapeDrawing->setName('PHPPresentation logo')
			->setDescription('PHPPresentation logo')
			->setPath($this->plantillaPortada)
			->setHeight(800)
			->setWidth(960)
			->setOffsetX(0)
			->setOffsetY(0);

		$slide->addShape($oShapeDrawing);

		//Logo
		$oShapeDrawing = new Drawing\File();

		$oShapeDrawing->setName('PHPPresentation logo')
			->setDescription('PHPPresentation logo')
			->setPath($this->logo)
			->setWidth(200)
			->setOffsetX(750)
			->setOffsetY(20);

		$slide->addShape($oShapeDrawing);

		$shape = $slide->createRichTextShape()
			->setHeight(600)
			->setWidth(900)
			->setOffsetX(10)
			->setOffsetY(50);
		$shape->getActiveParagraph()->getAlignment()
			->setHorizontal(Alignment::HORIZONTAL_CENTER)
			->setVertical(Alignment::HORIZONTAL_CENTER);

		$textRun = $shape->createTextRun($title);
		$textRun->getFont()->setBold(true)
			->setSize(50)
			->setColor(new Color($this->colorTituloPortada))
			->setName($this->fontFamily);

		// Añadir fecha
		$shape = $slide->createRichTextShape()
			->setHeight(100)
			->setWidth(300)
			->setOffsetX(700)
			->setOffsetY(400);
		$shape->getActiveParagraph()->getAlignment()
			->setHorizontal(Alignment::HORIZONTAL_CENTER)
			->setVertical(Alignment::HORIZONTAL_CENTER);

		$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');
		$textRun = $shape->createTextRun($month . ', ' . $year);
		$textRun->getFont()->setBold(false)
			->setName($this->fontFamily)
			->setSize(20)
			->setColor(new Color($this->colorTituloPortada));

		return $slide;
	}

	private function createTemplatedSlide($objPHPPresentation, $title) {
		// Create slide
		$slide = $objPHPPresentation->createSlide();

		$oShapeDrawing = new Drawing\File();
		$oShapeDrawing->setName('PHPPresentation logo')
			->setDescription('PHPPresentation logo')
			->setPath($this->plantilla)
			->setHeight(800)
			->setWidth(960)
			->setOffsetX(0)
			->setOffsetY(0);

		$slide->addShape($oShapeDrawing);

		$shape = $slide->createRichTextShape()
			->setHeight(300)
			->setWidth(900)
			->setOffsetX(10)
			->setOffsetY(10);
		$shape->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

		$textRun = $shape->createTextRun($title);
		$textRun->getFont()->setBold(true)
			->setSize($this->fontSize)
			->setColor(new Color($this->colorTitulo))
			->setName($this->fontFamily);

		return $slide;
	}

	private function fnSlide_Pie(PhpPresentation $objPHPPresentation, $title, $data, $title_chart, $colors, $idTenant) {
		global $oFill;
		global $oShadow;

		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

		// Generate sample data for second chart
		$seriesData = $data;

		//Colores
		$colors = str_replace('#', '', $colors);

		// Create a pie chart (that should be inserted in a shape)
		$pieChart = new Pie();
		$pieChart->setExplosion(15);
		$series = new Series($title_chart, $seriesData);
		$series->getDataPointFill(0)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colors[0]));
		$series->getDataPointFill(1)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colors[1]));
		$series->setShowPercentage(true);
		$series->setShowValue(false);
		$series->setShowSeriesName(false);
		$series->setShowCategoryName(true);
		$series->setDlblNumFormat('%d');
		$pieChart->addSeries($series);

		// Create a shape (chart)
		$shape = $currentSlide->createChartShape();
		$shape->setName($title_chart)
			->setResizeProportional(false)
			->setHeight(600)
			->setWidth(900)
			->setOffsetX(20)
			->setOffsetY(100);
		$shape->setFill($oFill);
		$shape->getTitle()->setText($title_chart);
		$shape->getTitle()->setOffsetX(120);
		$shape->getTitle()->setOffsetY(0);
		$shape->getTitle()->getFont()->setItalic(true)->setName($this->fontFamily);
		$shape->getTitle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
		$shape->getPlotArea()->setType($pieChart);
		$shape->getPlotArea()->setOffsetY(100);
		$shape->getLegend()->getBorder()->setLineStyle(Border::LINE_SINGLE);
		$shape->getLegend()->getFont()->setItalic(true)->setName($this->fontFamily);
	}

	private function imageB64(PhpPresentation $objPHPPresentation, $title, $image, $idTenant) {
		global $oFill;
		global $oShadow;

		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);
		$image = str_replace('image/png', 'image/jpeg', $image);

		// Add a file drawing (JPEG) to the slide
		$shape = new Drawing\Base64();
		$shape->setName('Word Cloud')
			->setDescription('Word Cloud')
			->setData($image)
			->setResizeProportional(false)
			->setHeight(400)
			->setWidth(800)
			->setOffsetX(70)
			->setOffsetY(110);

		$currentSlide->addShape($shape);
	}

	private function generalChartsGrouped(PhpPresentation $objPHPPresentation, $title, $images, $idTenant, $genderData, $j) {
		global $oFill;
		global $oShadow;

		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

		for($i=0; $i < count($images); $i++) {
			$images[$i] = str_replace('image/png', 'image/jpeg', $images[$i]);
		}
		// Add a file drawing (JPEG) to the slide

		// Heat Map
		$shapeHeatMap = new Drawing\Base64();
		$shapeHeatMap->setName('Heat Map')
			->setDescription('Heat Map')
			->setData($images[$j])
			->setResizeProportional(false)
			->setHeight(260)
			->setWidth(400)
			->setOffsetX(0)
			->setOffsetY(90);

		// Iconos género
		// Masculino
		$rutaMasc = CONSTANTS::PATH_EXPORT_WORD . '/icons/icon_male.png';
		$shapeMasc = new Drawing\File();
		$shapeMasc->setName('Male')
			->setDescription('Male')
			->setPath($rutaMasc)
			->setResizeProportional(false)
			->setHeight(35)
			->setWidth(35)
			->setOffsetX(405)
			->setOffsetY(210);

		$textMasc = $currentSlide->createRichTextShape()
			->setHeight(60)
			->setWidth(60)
			->setOffsetX(450)
			->setOffsetY(210);
		$textMasc->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

		$textRun = $textMasc->createTextRun($genderData[0] . '%');
		$textRun->getFont()->setBold(true)
			->setSize(12);

		// Femenino
		$rutaFem = CONSTANTS::PATH_EXPORT_WORD . '/icons/icon_female.png';
		$shapeFem = new Drawing\File();
		$shapeFem->setName('Female')
			->setDescription('Female')
			->setPath($rutaFem)
			->setResizeProportional(false)
			->setHeight(35)
			->setWidth(35)
			->setOffsetX(405)
			->setOffsetY(290);

		$textFem = $currentSlide->createRichTextShape()
			->setHeight(60)
			->setWidth(60)
			->setOffsetX(450)
			->setOffsetY(290);
		$textFem->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

		$textRun = $textFem->createTextRun($genderData[1] . '%');
		$textRun->getFont()->setBold(true)
			->setSize(12);

		// Estados
		$shapeEstados = new Drawing\Base64();
		$shapeEstados->setName('States')
			->setDescription('States')
			->setData($images[2])
			->setResizeProportional(false)
			->setHeight(400)
			->setWidth(450)
			->setOffsetX(500)
			->setOffsetY(95);

		$textFem = $currentSlide->createRichTextShape()
			->setHeight(60)
			->setWidth(120)
			->setOffsetX(695)
			->setOffsetY(105);
		$textFem->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

		$textRun = $textFem->createTextRun('ESTADOS');
		$textRun->getFont()->setBold(true)
			->setSize(14);

		// Edades
		$shapeEdades = new Drawing\Base64();
		$shapeEdades->setName('Ages')
			->setDescription('Ages')
			->setData($images[1])
			->setResizeProportional(false)
			->setHeight(200)
			->setWidth(400)
			->setOffsetX(50)
			->setOffsetY(340);

		$currentSlide->addShape($shapeHeatMap);
		$currentSlide->addShape($shapeMasc);
		$currentSlide->addShape($shapeFem);
		$currentSlide->addShape($shapeEstados);
		$currentSlide->addShape($shapeEdades);
	}

	private function printTable(PhpPresentation $objPHPPresentation, $title, $encuestas, $data, $idTenant) {
		global $oFill;
		global $oShadow;

		$total = count($encuestas) + 1;

		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);
		$shape = $currentSlide->createTableShape($total);
		$shape->setHeight(600);
		$shape->setWidth(900);
		$shape->setOffsetX(40);
		$shape->setOffsetY(80);
		$row = $shape->createRow();
		$totalLabels = count($data) - 1;
		$fontSize = 10;
		$widthCol = 400;

		// Get the first cell
		$cellA1 = $row->nextCell();
		$cellA1->getActiveParagraph()->getAlignment()
			->setHorizontal(Alignment::HORIZONTAL_CENTER)
			->setVertical(Alignment::VERTICAL_CENTER)
			->setMarginBottom(0)
			->setMarginLeft(0)
			->setMarginRight(0)
			->setMarginTop(0);
		$cellA1->setWidth($widthCol);
		$cellA1->createTextRun('')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

		$totalEncuestas = count($encuestas);
		$widthRow = (900 - $widthCol) / $totalEncuestas;

		foreach($encuestas as $column) {
			// Get the second cell
			$cell = $row->nextCell();

			$cell->getActiveParagraph()->getAlignment()
				->setHorizontal(Alignment::HORIZONTAL_CENTER)
				->setVertical(Alignment::VERTICAL_CENTER)
				->setMarginBottom(0)
				->setMarginLeft(0)
				->setMarginRight(0)
				->setMarginTop(0);
			$cell->setWidth($widthRow);

			$cell->createTextRun($column)->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);
		}

		$total = count($data[$totalLabels]['answers']['labels']);
		for($i = 0; $i < $total; $i++) {
			$row = $shape->createRow();
			// Labels
			$value = $data[$totalLabels]['answers']['labels'][$i];
			$cell = $row->nextCell();
			$cell->getActiveParagraph()->getAlignment()
				->setHorizontal(Alignment::HORIZONTAL_CENTER)
				->setVertical(Alignment::VERTICAL_CENTER)
				->setMarginBottom(0)
				->setMarginLeft(0)
				->setMarginRight(0)
				->setMarginTop(0);

			$cell->createTextRun($value)->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);

			// Values
			foreach($data as $values) {
				// Get the second cell
				$cell = $row->nextCell();
				if(is_null($values)) {
					$value = '-';
				} else {
					$value = $values['answers']['datasets']['data'][$i];
				}

				$cell->getActiveParagraph()->getAlignment()
					->setHorizontal(Alignment::HORIZONTAL_CENTER)
					->setVertical(Alignment::VERTICAL_CENTER)
					->setMarginBottom(0)
					->setMarginLeft(0)
					->setMarginRight(0)
					->setMarginTop(0);

				$cell->createTextRun($value)->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
			}
		}
	}

	private function printTableWC(PhpPresentation $objPHPPresentation, $title, $survey, $pregunta, $token, $idTenant) {
		// 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);

			$counter = 0;
			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);

				// Create templated slide
				$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);
				$shape = $currentSlide->createTableShape($nColumns * 2);
				$shape->setHeight(600);
				$shape->setWidth(900);
				$shape->setOffsetX(40);
				$shape->setOffsetY(80);
				$row = $shape->createRow();
				$fontSize = 12;

				for($i = 0; $i < $nColumns; $i++) {
					// Get the first cell
					$cellA1 = $row->nextCell();
					$cellA1->getActiveParagraph()->getAlignment()
						->setHorizontal(Alignment::HORIZONTAL_CENTER)
						->setVertical(Alignment::VERTICAL_CENTER)
						->setMarginBottom(0)
						->setMarginLeft(0)
						->setMarginRight(0)
						->setMarginTop(0);
					$cellA1->createTextRun('Palabra')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

					// Get the second cell
					$cell = $row->nextCell();

					$cell->getActiveParagraph()->getAlignment()
						->setHorizontal(Alignment::HORIZONTAL_CENTER)
						->setVertical(Alignment::VERTICAL_CENTER)
						->setMarginBottom(0)
						->setMarginLeft(0)
						->setMarginRight(0)
						->setMarginTop(0);

					$cell->createTextRun('Contador')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);
				}

				// Creamos datos
				for($j = 0; $j < count($array_cut[0]); $j++) {
					$row = $shape->createRow();

					for($i = 0; $i < count($array_cut); $i++) {
						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(0)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(0);
						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;
							}

							$cell->createTextRun($array_cut[$i][$j]->word)->getFont()->setBold(false)->setSize($fontSizeEsp)->setName($this->fontFamily);
						} else {
							$cell->createTextRun('')->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						}

						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(0)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(0);

						if(isset($array_cut[$i][$j]->counter)) {
							$cell->createTextRun($array_cut[$i][$j]->counter)->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						} else {
							$cell->createTextRun('')->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						}
					}
				}
			}
		}
	}

	private function printOthers(PhpPresentation $objPHPPresentation, $title, $data, $start, $idTenant) {
		global $oFill;
		global $oShadow;

		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

		// Create a shape (text)
		$shape = $currentSlide->createRichTextShape();
		$shape->setHeight(600);
		$shape->setWidth(900);
		$shape->setOffsetX(20);
		$shape->setOffsetY(80);
		$shape->getActiveParagraph()->getBulletStyle()->setBulletType(Bullet::TYPE_BULLET);

		$limit = 25;
		for($i = $start; $i < count($data); $i++) {
			$shape->createParagraph()->createTextRun($data[$i])->getFont()->setName($this->fontFamily);

			if($i == ($limit + $start)) {
				GeneratePpt::printOthers($objPHPPresentation, $title, $data, $i, $idTenant);

				break;
			}
		}
	}

	public function printPowerPoint($name, $questions, $data, $colors, $word_cloud, $idTenant) {
		// buscar colores
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

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

		// Create new PHPPresentation object
		$objPHPPresentation = new PhpPresentation();

		// Set properties
		$objPHPPresentation->getDocumentProperties()->setCreator('PHPOffice');

		// Remove first slide
		$objPHPPresentation->removeSlideByIndex(0);

		// Set Style
		$oFill = new Fill();
		$oFill->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('000000')); // Fondo

		$oShadow = new Shadow();
		$oShadow->setVisible(true)->setDirection(45)->setDistance(10);

		// Portada
		$currentSlide = GeneratePpt::createTitle($objPHPPresentation, $name, $idTenant);

		$i = 0;
		// Separar por encuestas
		foreach($data as $key => $survey) {
			$title = $i + 1 . '. ' . $questions[$i];

			// Comprobar si hay respustas de Otros
			$printWordCloud = true;
			foreach($survey['respuestas'] as $others) {
				if($others['answer'] != 'Others') {
					$printWordCloud = false;
					break;
				}
			}

			if($printWordCloud) {
				//Printar Word Cloud
				GeneratePpt::imageB64($objPHPPresentation, $title, $word_cloud[$key], $idTenant);
				GeneratePpt::printOthers($objPHPPresentation, $title, $survey['respuestasOtros'], 0, $idTenant);
			} else {
				//Printar grafica
				$respuestas = $survey['respuestas'];

				// Obtener una lista de columnas
				foreach($respuestas as $key => $row) {
					$order[$key] = $row['order'];
					$answer[$key] = $row['answer'];
				}

				// Ordenar los datos con volumen descendiente, edicion ascendiente
				// Agregar $datos como el último parámetro, para ordenar por la llave común
				array_multisort($order, SORT_ASC, $answer, SORT_ASC, $respuestas);
				$respuestas_sort = [];
				foreach($respuestas as $row) {
					array_push($respuestas_sort, $row['answer']);
				}
				$serieData = $respuestas_sort;
				$serieData = array_count_values($serieData);
				$respuestas_total = 0;

				//Calculo porcentajes
				foreach($serieData as $key => $value) {
					$respuestas_total += $value;
				}
				foreach($serieData as $key => $value) {
					$percent = $value / $respuestas_total;
					$percent = round($percent * 100, 1);
					$serieData[$key] = $percent;
				}
			}

			// Graficos por genero
			$genero = $survey['genero'];
			asort($genero);
			$serieData = array_count_values($genero);
			//Genero
			GeneratePpt::fnSlide_Pie($objPHPPresentation, $title, $serieData, 'Género (%)', $colors, $idTenant);

			// Graficos por edades
			$genero = $survey['genero'];
			asort($genero);
			$serieData = array_count_values($genero);
			//Edades
			$edades = $survey['edades'];
			asort($edades);
			$serieData = array_count_values($edades);
			$edad_total = 0;
			foreach($serieData as $key => $value) {
				$edad_total += $value;
			}
			foreach($serieData as $key => $value) {
				$percent = $value / $edad_total;
				$percent = round($percent * 100, 1);
				$serieData[$key] = $percent;
			}

			// Graficos por estados
			$estados = $survey['estados'];
			asort($estados);
			$serieData = array_count_values($estados);
			//Estados
			$estados = $survey['estados'];
			asort($estados);
			$serieData = array_count_values($estados);
			$estados_total = 0;
			foreach($serieData as $key => $value) {
				$estados_total += $value;
			}
			foreach($serieData as $key => $value) {
				$percent = $value / $estados_total;
				$percent = round($percent * 100, 1);
				$serieData[$key] = $percent;
			}

			$i++;
		}

		$carpeta = CONSTANTS::PATH_EXPORT_WORD;

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

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

		$filename = 'Reporte_' . $name . '.pptx';

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

		$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
		$oWriterPPTX->save(CONSTANTS::PATH_EXPORT_WORD . '/' . $filename);

		$response = $filename;

		return $response;
	}

	public function printPowerPointImages($images, $data, $questions, $wc, $user, $generalCharts, $token, $timestamp, $isWc, $fontFamily, $idTenant, $genderData) {
		$this->fontFamily = $fontFamily;

		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// Create new PHPPresentation object
		$objPHPPresentation = new PhpPresentation();
		$objPHPPresentation->getLayout()->setDocumentLayout('screen16x9');

		// Set properties
		$objPHPPresentation->getDocumentProperties()->setCreator('PHPOffice');

		// Remove first slide
		$objPHPPresentation->removeSlideByIndex(0);

		// Set Style
		$oFill = new Fill();
		$oFill->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('000000')); //Fondo

		$oShadow = new Shadow();
		$oShadow->setVisible(true)->setDirection(45)->setDistance(10);

		// Portada
		$name = $data[0]['data'][0]['surveyDesc'];

		$currentSlide = GeneratePpt::createTitle($objPHPPresentation, $name, $idTenant);

		// Diapositiva con las graficas generales
		$title = 'Resultados generales';

		// En vez de crear una diapositiva por cada resultado general, se juntan todas en una misma diapositiva
		for($i = 4; $i < count($generalCharts); $i++) {
			GeneratePpt::generalChartsGrouped($objPHPPresentation, $title, $generalCharts, $idTenant, $genderData, $i);
		}

		if($generalCharts[3] != 'emptyNSE') {
			GeneratePpt::imageB64($objPHPPresentation, $title, $generalCharts[3], $idTenant);
		}

		// Mapa pantalla completa
		for($i = 4; $i < count($generalCharts); $i++) {
				GeneratePpt::imageB64($objPHPPresentation, $title, $generalCharts[$i], $idTenant);
		}

		// Rangos de edad en pantalla completa
		GeneratePpt::imageB64($objPHPPresentation, $title, $generalCharts[1], $idTenant);

		//Resto diapositivas
		$excelWC = [];

		$i = 0;
		foreach($images as $image) {
			$title = ($i + 1) . '-' . $questions[0][$i];

			//Printar Answers
			GeneratePpt::imageB64($objPHPPresentation, $title, $image['data']['imgAnswer'], $idTenant);

			if($wc[$i] == 'yes') {
				$others = [];

				foreach($data[$i]['data'] as $answers) {
					$sanit = htmlspecialchars($answers['answerothers']);
					$sanit = trim($sanit);
					$sanit = preg_replace("/[\r\n|\n|\r]+/", ' ', $sanit);
					array_push($others, htmlspecialchars($sanit));
				}

				if(isset($images[$i]['id']) && isset($data[$i]['data'][0]['survey'])) {
					$pregunta = $images[$i]['id'];
					$survey = $data[$i]['data'][0]['survey'];

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

					array_push($excelWC, $dataExcel);
					GeneratePpt::printTableWC($objPHPPresentation, $title, $survey, $pregunta, $token, $idTenant);
				}
			}
			$i++;
		}

		$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) . '_Analitics_Mostreo.pptx';
		$filename = str_replace(' ', '_', $filename);

		$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
		$oWriterPPTX->save($carpeta . '/' . $filename);

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

		// 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.pptx');
		if($isWc == 'true') {
			$zip->addFile($carpeta . '/' . $response['excel'], 'Analitics_Mostreo.xlsx');
		}

		return $response;
	}

	public function generateDinamicReport($dataReport) {
		$this->fontFamily = $dataReport['defaultTemplate']['tipoFuente'];
		$this->fontSize = $dataReport['defaultTemplate']['tamanoFuente'];
		$this->colorTituloPortada = 'FF' . str_replace('#', '', $dataReport['defaultTemplate']['colorTituloPortada']); // Look the Color construct, this is not hexadecimal but argb. Add 'FF' in front off your color
		$this->colorTitulo = 'FF' . str_replace('#', '', $dataReport['defaultTemplate']['colorTitulo']); // Look the Color construct, this is not hexadecimal but argb. Add 'FF' in front off your color
		$this->plantillaPortada = CONSTANTS::PATH_EXPORT_WORD . '/' . $dataReport['defaultTemplate']['plantillaPortada'];
		$this->plantilla = CONSTANTS::PATH_EXPORT_WORD . '/' . $dataReport['defaultTemplate']['plantilla'];
		$this->logo = CONSTANTS::PATH_EXPORT_WORD . '/' . $dataReport['defaultTemplate']['logo'];

		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// CREACIÓN DEL OBJETO
		$objPHPPresentation = new PhpPresentation($this->fontFamily);
		$objPHPPresentation->getLayout()->setDocumentLayout('screen16x9');

		// Set properties
		$objPHPPresentation->getDocumentProperties()->setCreator('PHPOffice');

		// Remove first slide
		$objPHPPresentation->removeSlideByIndex(0);

		// Set Style
		$oFill = new Fill();
		$oFill->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('000000')); //Fondo

		$oShadow = new Shadow();
		$oShadow->setVisible(true)->setDirection(45)->setDistance(10);

		// PORTADA
		$name = $dataReport['missionName'];

		$currentSlide = GeneratePpt::createTitle($objPHPPresentation, $name);

		$size = count($dataReport['reportData']);

		// Gráficas
		for($i = 0; $i < $size; $i++) {
			$title = $dataReport['reportData'][$i]['name'] . ' (%)';

			$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $dataReport['idTenant']);

			$subtitle = '';
			$shape = $currentSlide->createRichTextShape()
				->setHeight(40)
				->setWidth(700)
				->setOffsetX(75)
				->setOffsetY(90);
			$shape->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

			$textRun = $shape->createTextRun($subtitle);
			$textRun->getFont()->setBold(true)
				->setSize(11)
				->setColor(new Color('666666'))
				->setName($this->fontFamily);

			$type = $dataReport['reportData'][$i]['data']['type'];
			$etiquetas = $dataReport['reportData'][$i]['data']['labels'];
			$series = $dataReport['reportData'][$i]['data']['data'];
			$colores = $dataReport['reportData'][$i]['data']['colors'];
			$subLabels = $dataReport['reportData'][$i]['data']['subLabels'];

			$graph = $currentSlide->createChartShape();
			$graph->getTitle()->setVisible(false);
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);

			$typeChart = new Bar3D();

			if($type == 'normal') {
				$series = $series[0];

				$seriesData = [];
				for($j = 0; $j < count($etiquetas); $j++) {
					$seriesData["$etiquetas[$j]\0"] = $series[$j];
				}

				$graph->getLegend()->setVisible(false);
				
				$data = new Series('Data', $seriesData);
				$data->setLabelPosition(Series::LABEL_OUTSIDEEND);
				$data->getFont()->setName($this->fontFamily);
		
				for($n = 0; $n < count($colores); $n++) {
					$data->getDataPointFill($n)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF' . str_replace('#', '', $colores[$n])));
				}
		
				$typeChart->addSeries($data);
			} else if($type == 'grouped') {
				$seriesDataArray = [];
				for($s = 0; $s < count($series); $s++) {
					$seriesData = [];
					for($j = 0; $j < count($etiquetas); $j++) {
						$seriesData["$etiquetas[$j]\0"] = $series[$s][$j];
					}
					array_push($seriesDataArray, $seriesData);
				}

				for($g = 0; $g < count($seriesDataArray); $g++) {
					$seriesX = new Series($subLabels[$g], $seriesDataArray[$g]);
					$seriesX->setLabelPosition(Series::LABEL_OUTSIDEEND);
					$seriesX->getFont()->setName($this->fontFamily);
					$seriesX->setShowSeriesName(false);
					$seriesX->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF' . str_replace('#', '', $colores[$g])));
					$seriesX->setShowValue(true);
					$seriesX->setShowPercentage(false);

					$typeChart->addSeries($seriesX);
				}

				$graph->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');
				$graph->getLegend()->setPosition('t');
			} else if($type == 'stacked') {
				$seriesDataArray = [];
				for($s = 0; $s < count($series); $s++) {
					$seriesData = [];
					for($j = 0; $j < count($etiquetas); $j++) {
						$seriesData["$etiquetas[$j]\0"] = $series[$s][$j];
					}
					array_push($seriesDataArray, $seriesData);
				}

				$typeChart->setBarGrouping(Bar::GROUPING_STACKED);

				for($g = 0; $g < count($seriesDataArray); $g++) {
					$seriesX = new Series($subLabels[$g], $seriesDataArray[$g]);
					$seriesX->setLabelPosition(Series::LABEL_OUTSIDEEND);
					$seriesX->getFont()->setName($this->fontFamily);
					$seriesX->setShowSeriesName(false);
					$seriesX->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF' . str_replace('#', '', $colores[$g])));
					$seriesX->setShowValue(true);
					$seriesX->setShowPercentage(false);

					$typeChart->addSeries($seriesX);
				}

				$graph->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');
				$graph->getLegend()->setPosition('t');
			}

			$graph->getPlotArea()->setType($typeChart);
			$graph->getPlotArea()->getAxisX()->setTitle('');
			$graph->getPlotArea()->getAxisX()->getOutline()->setWidth(10);
			$graph->getPlotArea()->getAxisX()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
			$graph->getPlotArea()->getAxisY()->setTitle('');
			$graph->getPlotArea()->getAxisY()->getOutline()->setWidth(10);
			$graph->getPlotArea()->getAxisY()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
			$graph->getView3D()->setRightAngleAxes(true);
			$graph->getView3D()->setRotationX(5);
			$graph->getView3D()->setRotationY(20);
			$graph->getView3D()->setHeightPercent(null);
		}

		// Creación de carpeta
		$folderSave = CONSTANTS::PATH_EXPORT_WORD . '/reports/dinamic/';

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

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

		$fecha = date_create();
		$filename = date_timestamp_get($fecha) . '_dynamic_sampling.pptx';

		$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
		$oWriterPPTX->save($folderSave . '/' . $filename);

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

		return $response;
	}

	public function generatePermanentPowerpointWithWordcloud($token, $reportData, $idTenant, $survey, $stampMision, $project, $briefing, $template, $user, $numPerf) {
		$this->typeColors = $template['typeColors'];
		$this->colorsHex = explode(',', $template['colorsHex']);
		$this->fontFamily = $template['fontName'];
		$this->fontSize = $template['fontSize'];
		$this->colorTituloPortada = 'FF' . str_replace('#', '', $template['colorTituloPortada']); // Look the Color construct, this is not hexadecimal but argb. Add 'FF' in front off your color 
		$this->colorTitulo = 'FF' . str_replace('#', '', $template['colorTitulo']); // Look the Color construct, this is not hexadecimal but argb. Add 'FF' in front off your color 
		$this->plantillaPortada = $template['plantillaPortada'];
		$this->plantilla = $template['plantilla'];
		$this->logo = $template['logo'];
		$this->answersOrder = $template['answersOrder'];

        LogController::logTraceLine();

		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// CREACIÓN DEL OBJETO
		$objPHPPresentation = new PhpPresentation($this->fontFamily);
		$objPHPPresentation->getLayout()->setDocumentLayout('screen16x9');

		// Set properties
		$objPHPPresentation->getDocumentProperties()->setCreator('PHPOffice');

		// Remove first slide
		$objPHPPresentation->removeSlideByIndex(0);

		// Set Style
		$oFill = new Fill();
		$oFill->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('000000')); //Fondo

		$oShadow = new Shadow();
		$oShadow->setVisible(true)->setDirection(45)->setDistance(10);

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

        $reportData['result'][$nameCount]['data'][0]['surveyDesc'];
        LogController::logTraceLine();

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

        LogController::logTraceLine();

		$currentSlide = GeneratePpt::createTitle($objPHPPresentation, $name);

		// BRIEFING
		$title = 'Briefing';

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

		if($charactersCount <= 700 && $charactersCount > 0) {
			// Plantilla de briefing todo en una
			$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title);

			$textBriefing = $currentSlide->createRichTextShape()
				->setHeight(430)
				->setWidth(860)
				->setOffsetX(50)
				->setOffsetY(100);

			$textBriefing->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

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

			foreach($elementsArray as $value) {
				$textRun = $textBriefing->createTextRun($briefing[$value]['title'] . ': ');
				$textRun->getFont()->setBold(true)->setSize(12)->setName($this->fontFamily);

				$textRun = $textBriefing->createTextRun($briefing[$value]['text'] . "\n\n");
				$textRun->getFont()->setBold(false)->setSize(12)->setName($this->fontFamily);
			}
		} else if($charactersCount > 700) {
			// Plantilla de briefing 1/2
			$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title);

			$textBriefing = $currentSlide->createRichTextShape()
				->setHeight(430)
				->setWidth(860)
				->setOffsetX(50)
				->setOffsetY(100);

			$textBriefing->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$elementsArray = ['applicantName', 'brandsInvolved', 'projectDescription', 'background'];

			foreach($elementsArray as $value) {
				$textRun = $textBriefing->createTextRun($briefing[$value]['title'] . ': ');
				$textRun->getFont()->setBold(true)->setSize(12)->setName($this->fontFamily);

				$textRun = $textBriefing->createTextRun($briefing[$value]['text'] . "\n\n");
				$textRun->getFont()->setBold(false)->setSize(12)->setName($this->fontFamily);
			}

			// Plantilla de briefing 2/2
			$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title);

			$textBriefing = $currentSlide->createRichTextShape()
				->setHeight(430)
				->setWidth(860)
				->setOffsetX(50)
				->setOffsetY(100);

			$textBriefing->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$elementsArray = ['businessObjective', 'investigationObjective', 'actionStandard', 'favorableResults', 'notFavorableResults'];

			foreach($elementsArray as $value) {
				$textRun = $textBriefing->createTextRun($briefing[$value]['title'] . ': ');
				$textRun->getFont()->setBold(true)->setSize(12)->setName($this->fontFamily);

				$textRun = $textBriefing->createTextRun($briefing[$value]['text'] . "\n\n");
				$textRun->getFont()->setBold(false)->setSize(12)->setName($this->fontFamily);
			}
		}

		if($numPerf > 0) {
			// RESULTADOS GENERALES 1/2
			$title = 'Resultados generales';

			// Género, Edad y NSE
			$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title);

			// Iconos de género - Masculino
			$rutaMasc = CONSTANTS::PATH_EXPORT_WORD . '/icons/icon_male.png';
			$shapeMasc = new Drawing\File();
			$shapeMasc->setName('Male')
				->setDescription('Male')
				->setPath($rutaMasc)
				->setResizeProportional(false)
				->setHeight(80)
				->setWidth(80)
				->setOffsetX(70)
				->setOffsetY(120);

			$textMasc = $currentSlide->createRichTextShape()
				->setHeight(50)
				->setWidth(80)
				->setOffsetX(160)
				->setOffsetY(140);
			$textMasc->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$textRun = $textMasc->createTextRun($reportData['resume']['gender']['value'][0] . '%');
			$textRun->getFont()->setBold(true)->setSize(18)->setName($this->fontFamily);

			// Iconos de género - Femenino
			$rutaFem = CONSTANTS::PATH_EXPORT_WORD . '/icons/icon_female.png';
			$shapeFem = new Drawing\File();
			$shapeFem->setName('Female')
				->setDescription('Female')
				->setPath($rutaFem)
				->setResizeProportional(false)
				->setHeight(80)
				->setWidth(80)
				->setOffsetX(280)
				->setOffsetY(120);

			$textFem = $currentSlide->createRichTextShape()
				->setHeight(50)
				->setWidth(80)
				->setOffsetX(370)
				->setOffsetY(140);
			$textFem->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$textRun = $textFem->createTextRun($reportData['resume']['gender']['value'][1] . '%');
			$textRun->getFont()->setBold(true)->setSize(18)->setName($this->fontFamily);

			$currentSlide->addShape($shapeMasc);
			$currentSlide->addShape($shapeFem);

			// Edades en columnas 3D
			$textAge = $currentSlide->createRichTextShape()
				->setHeight(50)
				->setWidth(140)
				->setOffsetX(220)
				->setOffsetY(240);
			$textAge->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$textRun = $textAge->createTextRun('EDAD (%)');
			$textRun->getFont()->setBold(true)->setSize(16)->setName($this->fontFamily);

			$etiquetas = $reportData['resume']['ageRange']['labels'];
			$series = $reportData['resume']['ageRange']['value'];

			if (count($etiquetas) == 0 && count($series) == 0) { //avoid error on open ppt
				$etiquetas = [''];
				$series = [0];
			}

			$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series, 'ages');

			// NSE en pie 3D
			$textAge = $currentSlide->createRichTextShape()
				->setHeight(60)
				->setWidth(140)
				->setOffsetX(630)
				->setOffsetY(140);
			$textAge->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$textRun = $textAge->createTextRun('NSE (%)');
			$textRun->getFont()->setBold(true)->setSize(16)->setName($this->fontFamily);

			$etiquetas = $reportData['resume']['nse']['labels'];
			$series = $reportData['resume']['nse']['value'];

			$currentSlide = GeneratePpt::pie3DPermanentGraphic($currentSlide, $etiquetas, $series, 'nse');

			// RESULTADOS GENERALES 2/2
			$title = 'Resultados generales';

			// Heat map y estados
			$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title);

			// Heat Map
			$shapeHeatMap = new Drawing\Base64();
			$shapeHeatMap->setName('Heat Map')
				->setDescription('Heat Map')
				->setData($reportData['heatMaps'][0])
				->setResizeProportional(false)
				->setHeight(240)
				->setWidth(370)
				->setOffsetX(40)
				->setOffsetY(180);

			$currentSlide->addShape($shapeHeatMap);

			// Estados en columnas 3D
			$textStates = $currentSlide->createRichTextShape()
				->setHeight(60)
				->setWidth(160)
				->setOffsetX(610)
				->setOffsetY(140);
			$textStates->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

			$textRun = $textStates->createTextRun('ESTADOS (%)');
			$textRun->getFont()->setBold(true)->setSize(16)->setName($this->fontFamily);

			$etiquetas = $reportData['resume']['states']['labels'];
			$series = $reportData['resume']['states']['value'];

			$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series, 'states');
		}

		// GRÁFICOS DE PREGUNTAS
		$i = 0;
		$numberPage = 1;
		$questName = '';
		// Array para preguntas tipo 'F'
		$idControl = '';
		$seriesLabelsArray = [];
		$nameArray = [];
		$typeQ = '';
		// 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;
				} else if($reportData['typeQuestion'][$i] == 'A' || $reportData['typeQuestion'][$i] == 'B' || $reportData['typeQuestion'][$i] == 'F' || $reportData['typeQuestion'][$i] == 'R') {
					$etiquetas = $reportData['result'][$i]['answers']['labels'];
					$series = $reportData['result'][$i]['answers']['datasets']['data'];

					if($reportData['typeQuestion'][$i] != 'R') {
						array_multisort($etiquetas, SORT_ASC, $series);

						// $response = $this->orderQuestionAnswers($etiquetas, $series, $reportData['typeQuestion'][$i]);

						// $etiquetas = $response['labels'];
						// $series = $response['series'];
					}

					$colunName = $reportData['qid'][$i];

					if($idControl == '' || $colunName == $idControl) {
						if($idControl == '') {
							$typeQ = $reportData['typeQuestion'][$i];
						}

						$idControl = $colunName;

						$q = strrpos($question, ' - ');
						$questName = substr($question, 0, $q);
						$sectionName = strip_tags(substr($question, ($q + 3)));

						$element = [
							'etiquetas' => $etiquetas,
							'series' => $series
						];
						array_push($seriesLabelsArray, $element);
						array_push($nameArray, $sectionName);

						// Para el caso de que sea la última pregunta
						$indexLastSQ = array_search($colunName, array_reverse($reportData['qid'], true));
						if($i == $indexLastSQ) { //fix for printing this questions type!
							$title = $numberPage . '. ' . $questName . ' (%)';
							
							$nameArrayPart = [];
							$seriesLabelsArrayPart = [];
							// Control para número de barras por página
							$control = $controlArrayElements;
							for($p = 0; $p < count($nameArray); $p++) {
								array_push($nameArrayPart, $nameArray[$p]);
								array_push($seriesLabelsArrayPart, $seriesLabelsArray[$p]);

								if($p == (count($nameArray) - 1)) {
									$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

									$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);
								} else if($p == $control) {
									$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

									$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);

									$nameArrayPart = [];
									$seriesLabelsArrayPart = [];
									$control += $controlArrayElements + 1;
								}
							}
						}

						$i++;
						continue;
					} else if($colunName != $idControl && count($seriesLabelsArray) > 0) {
						$title = $numberPage . '. ' . $questName . ' (%)';

						$nameArrayPart = [];
						$seriesLabelsArrayPart = [];
						// Control para número de barras por página
						$control = $controlArrayElements;
						for($p = 0; $p < count($nameArray); $p++) {
							array_push($nameArrayPart, $nameArray[$p]);
							array_push($seriesLabelsArrayPart, $seriesLabelsArray[$p]);

							if($p == (count($nameArray) - 1)) {
								$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

								$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);
							} else if($p == $control) {
								$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

								$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);

								$nameArrayPart = [];
								$seriesLabelsArrayPart = [];
								$control += $controlArrayElements + 1;
							}
						}

						$idControl = $colunName;

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

						array_multisort($etiquetas, SORT_ASC, $series);

						$element = [
							'etiquetas' => $etiquetas,
							'series' => $series
						];
						array_push($seriesLabelsArray, $element);

						$nameArray = [];
						$q = strrpos($question, ' - ');
						$sectionName = strip_tags(substr($question, ($q + 3)));
						array_push($nameArray, $sectionName);

						$i++;
						$numberPage++;
						continue;
					}
				} else if($idControl != '' && count($seriesLabelsArray) > 0) {
					$title = $numberPage . '. ' . $questName . ' (%)';

					$nameArrayPart = [];
					$seriesLabelsArrayPart = [];
					// Control para número de barras por página
					$control = $controlArrayElements;
					for($p = 0; $p < count($nameArray); $p++) {
						array_push($nameArrayPart, $nameArray[$p]);
						array_push($seriesLabelsArrayPart, $seriesLabelsArray[$p]);

						if($p == (count($nameArray) - 1)) {
							$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

							$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);
						} else if($p == $control) {
							$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

							$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);

							$nameArrayPart = [];
							$seriesLabelsArrayPart = [];
							$control += $controlArrayElements + 1;
						}
					}

					$idControl = '';
					$seriesLabelsArray = [];
					$nameArray = [];

					$numberPage++;
				}

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

				$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

				$subtitle = '';
				$shape = $currentSlide->createRichTextShape()
					->setHeight(40)
					->setWidth(700)
					->setOffsetX(75)
					->setOffsetY(90);
				$shape->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

				$textRun = $shape->createTextRun($subtitle);
				$textRun->getFont()->setBold(true)
					->setSize(11)
					->setColor(new Color('666666'))
					->setName($this->fontFamily);

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

				$response = $this->orderQuestionAnswers($etiquetas, $series, $reportData['typeQuestion'][$i]);
				
				$etiquetas = $response['labels'];
				$series = $response['series'];

				if (count($etiquetas) == 0 && count($series) == 0) { //avoid error on open ppt
					$etiquetas = [''];
					$series = [0];
				}

				// Tipos de gráficas
				if($reportData['typeQuestion'][$i] == 'Y' || $reportData['typeQuestion'][$i] == 'G') {
					if($reportData['typeQuestion'][$i] == 'Y' && $template['typeY'] == 'columns') {
						$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if($reportData['typeQuestion'][$i] == 'Y' && $template['typeY'] == 'bars') {
						$currentSlide = GeneratePpt::bar3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if($reportData['typeQuestion'][$i] == 'Y' && $template['typeY'] == 'line') {
						$currentSlide = GeneratePpt::linePermanentGraphic($currentSlide, $etiquetas, $series);
					} else if($reportData['typeQuestion'][$i] == 'Y' && $template['typeY'] == 'doughnut') {
						$currentSlide = GeneratePpt::doughnutPermanentGraphic($currentSlide, $etiquetas, $series);
					} else {
						$currentSlide = GeneratePpt::pie3DPermanentGraphic($currentSlide, $etiquetas, $series);
					}
				} else if($reportData['typeQuestion'][$i] == '3' || $reportData['typeQuestion'][$i] == '5') {
					if(($reportData['typeQuestion'][$i] == '3' && $template['type3'] == 'columns') || ($reportData['typeQuestion'][$i] == '5' && $template['type5'] == 'columns')) {
						$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '3' && $template['type3'] == 'bars') || ($reportData['typeQuestion'][$i] == '5' && $template['type5'] == 'bars')) {
						$currentSlide = GeneratePpt::bar3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '3' && $template['type3'] == 'line') || ($reportData['typeQuestion'][$i] == '5' && $template['type5'] == 'line')) {
						$currentSlide = GeneratePpt::linePermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '3' && $template['type3'] == 'pie') || ($reportData['typeQuestion'][$i] == '5' && $template['type5'] == 'pie')) {
						$currentSlide = GeneratePpt::pie3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '3' && $template['type3'] == 'doughnut') || ($reportData['typeQuestion'][$i] == '5' && $template['type5'] == 'doughnut')) {
						$currentSlide = GeneratePpt::doughnutPermanentGraphic($currentSlide, $etiquetas, $series);
					} else {
						$currentSlide = GeneratePpt::oneBar3DStackedPermanentGraphic($currentSlide, $question, $etiquetas, $series);
					}
				} 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);
					}

					if(($reportData['typeQuestion'][$i] == '4' && $template['type4'] == 'bars') ||
						($reportData['typeQuestion'][$i] == '!' && $template['typeINTERROGANTE'] == 'bars') ||
						($reportData['typeQuestion'][$i] == 'L' && $template['typeL'] == 'bars') ||
						($reportData['typeQuestion'][$i] == 'M' && $template['typeM'] == 'bars')) {
						$currentSlide = GeneratePpt::bar3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '4' && $template['type4'] == 'line') ||
						($reportData['typeQuestion'][$i] == '!' && $template['typeINTERROGANTE'] == 'line') ||
						($reportData['typeQuestion'][$i] == 'L' && $template['typeL'] == 'line') ||
						($reportData['typeQuestion'][$i] == 'M' && $template['typeM'] == 'line')) {
						$currentSlide = GeneratePpt::linePermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '4' && $template['type4'] == 'pie') ||
						($reportData['typeQuestion'][$i] == '!' && $template['typeINTERROGANTE'] == 'pie') ||
						($reportData['typeQuestion'][$i] == 'L' && $template['typeL'] == 'pie') ||
						($reportData['typeQuestion'][$i] == 'M' && $template['typeM'] == 'pie')) {
						$currentSlide = GeneratePpt::pie3DPermanentGraphic($currentSlide, $etiquetas, $series);
					} else if(($reportData['typeQuestion'][$i] == '4' && $template['type4'] == 'doughnut') ||
						($reportData['typeQuestion'][$i] == '!' && $template['typeINTERROGANTE'] == 'doughnut') ||
						($reportData['typeQuestion'][$i] == 'L' && $template['typeL'] == 'doughnut') ||
						($reportData['typeQuestion'][$i] == 'M' && $template['typeM'] == 'doughnut')) {
						$currentSlide = GeneratePpt::doughnutPermanentGraphic($currentSlide, $etiquetas, $series);
					} else {
						$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series);
					}
				} else if($reportData['typeQuestion'][$i] == '6' || $reportData['typeQuestion'][$i] == 'K' || $reportData['typeQuestion'][$i] == 'N') {
					// array_multisort($etiquetas, SORT_ASC, $series);
					// Gráfica
					$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series, 'table');

					// Tabla
					$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];

					$shape = $currentSlide->createTableShape(2);
					$shape->setHeight(600);
					$shape->setWidth(200);
					$shape->setOffsetX(670);
					$shape->setOffsetY(220);
					$fontSize = 12;

					for($m = 0; $m < count($names); $m++) {
						$row = $shape->createRow();
						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(10)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(10);
						$cell->createTextRun($names[$m])->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(10)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(10);
						$cell->createTextRun($values[$m])->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
					}
				} else {
					$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series);
				}
			} else if($reportData['wordcloudImgArray'][$i]['wordCloud'] == '3') {
				// Control de preguntas terminadas de los tipos A, B, F o R
				if($idControl != '' && count($seriesLabelsArray) > 0) {
					$title = $numberPage . '. ' . $questName . ' (%)';

					$nameArrayPart = [];
					$seriesLabelsArrayPart = [];
					// Control para número de barras por página
					$control = $controlArrayElements;
					for($p = 0; $p < count($nameArray); $p++) {
						array_push($nameArrayPart, $nameArray[$p]);
						array_push($seriesLabelsArrayPart, $seriesLabelsArray[$p]);

						if($p == (count($nameArray) - 1)) {
							$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

							$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);
						} else if($p == $control) {
							$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

							$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);

							$nameArrayPart = [];
							$seriesLabelsArrayPart = [];
							$control += $controlArrayElements + 1;
						}
					}

					$idControl = '';
					$seriesLabelsArray = [];
					$nameArray = [];

					$numberPage++;
				}

				// 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++) {
					$title = $numberPage . '. ' . $question . ' - ' . $etiquetas[$p] . ' (%)';

					// Generar en una página, gráfica de columnas 3D con un solo valor, tabla de palabras y wordcloud
					GeneratePpt::column3DAndWordcloudWithTableOnePage($objPHPPresentation, $title, $etiquetas[$p], $series[$p], $reportData['wordcloudImgArray'][$i]['element'][$p], $survey, $reportData['wordCloud'][$i][$p], $token, $idTenant);
				}
			} else {
				// Control de preguntas terminadas de los tipos A, B, F o R
				if($idControl != '' && count($seriesLabelsArray) > 0) {
					$title = $numberPage . '. ' . $questName . ' (%)';

					$nameArrayPart = [];
					$seriesLabelsArrayPart = [];
					// Control para número de barras por página
					$control = $controlArrayElements;
					for($p = 0; $p < count($nameArray); $p++) {
						array_push($nameArrayPart, $nameArray[$p]);
						array_push($seriesLabelsArrayPart, $seriesLabelsArray[$p]);

						if($p == (count($nameArray) - 1)) {
							$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

							$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);
						} else if($p == $control) {
							$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

							$currentSlide = GeneratePpt::bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);

							$nameArrayPart = [];
							$seriesLabelsArrayPart = [];
							$control += $controlArrayElements + 1;
						}
					}

					$idControl = '';
					$seriesLabelsArray = [];
					$nameArray = [];

					$numberPage++;
				}

				if($reportData['wordcloudImgArray'][$i]['wordCloud'] == '2') {
					$title = $numberPage . '. ' . $question . ' (%)';

					$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

					$subtitle = '';
					$shape = $currentSlide->createRichTextShape()
						->setHeight(40)
						->setWidth(700)
						->setOffsetX(75)
						->setOffsetY(90);
					$shape->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

					$textRun = $shape->createTextRun($subtitle);
					$textRun->getFont()->setBold(true)
						->setSize(11)
						->setColor(new Color('666666'))
						->setName($this->fontFamily);

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

					if($reportData['typeQuestion'][$i] == 'O' || $reportData['typeQuestion'][$i] == 'P') {
						if($reportData['typeQuestion'][$i] == 'O' && $template['typeO'] == 'bars') {
							$currentSlide = GeneratePpt::bar3DPermanentGraphic($currentSlide, $etiquetas, $series);
						} else if($reportData['typeQuestion'][$i] == 'O' && $template['typeO'] == 'line') {
							$currentSlide = GeneratePpt::linePermanentGraphic($currentSlide, $etiquetas, $series);
						} else if($reportData['typeQuestion'][$i] == 'O' && $template['typeO'] == 'pie') {
							$currentSlide = GeneratePpt::pie3DPermanentGraphic($currentSlide, $etiquetas, $series);
						} else if($reportData['typeQuestion'][$i] == 'O' && $template['typeO'] == 'doughnut') {
							$currentSlide = GeneratePpt::doughnutPermanentGraphic($currentSlide, $etiquetas, $series);
						} else {
							$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series);
						}
					}
				}

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

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

			$i++;
			$numberPage++;
		}

		// 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.pptx';

		$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
		$oWriterPPTX->save($folderSave . '/' . $filename);

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

		return $response;
	}

	private function wordcloudWithTableOnePage(PhpPresentation $objPHPPresentation, $title, $image, $survey, $pregunta, $token, $idTenant) {
		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);
		$image = str_replace('image/png', 'image/jpeg', $image);

		// Add a file drawing (JPEG) to the slide
		$shape = new Drawing\Base64();
		$shape->setName('Word Cloud')
			->setDescription('Word Cloud')
			->setData($image)
			->setResizeProportional(false)
			->setHeight(420)
			->setWidth(650)
			->setOffsetX(270)
			->setOffsetY(100);

		$currentSlide->addShape($shape);

		// 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);

			$counter = 0;
			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);

				// Create templated slide
				$shape = $currentSlide->createTableShape($nColumns * 2);
				$shape->setHeight(600);
				$shape->setWidth(200);
				$shape->setOffsetX(40);
				$shape->setOffsetY(100);
				$row = $shape->createRow();
				$fontSize = 12;

				for($i = 0; $i < $nColumns; $i++) {
					// Get the first cell
					$cellA1 = $row->nextCell();
					$cellA1->getActiveParagraph()->getAlignment()
						->setHorizontal(Alignment::HORIZONTAL_CENTER)
						->setVertical(Alignment::VERTICAL_CENTER)
						->setMarginBottom(0)
						->setMarginLeft(0)
						->setMarginRight(0)
						->setMarginTop(0);
					$cellA1->createTextRun('Palabra')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

					// Get the second cell
					$cell = $row->nextCell();

					$cell->getActiveParagraph()->getAlignment()
						->setHorizontal(Alignment::HORIZONTAL_CENTER)
						->setVertical(Alignment::VERTICAL_CENTER)
						->setMarginBottom(0)
						->setMarginLeft(0)
						->setMarginRight(0)
						->setMarginTop(0);

					$cell->createTextRun('Contador')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);
				}

				// Creamos datos
				for($j = 0; $j < count($array_cut[0]); $j++) {
					$row = $shape->createRow();

					for($i = 0; $i < count($array_cut); $i++) {
						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(0)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(0);

						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;
							}

							$cell->createTextRun($array_cut[$i][$j]->word)->getFont()->setBold(false)->setSize($fontSizeEsp)->setName($this->fontFamily);
						} else {
							$cell->createTextRun('')->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						}

						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(0)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(0);

						if(isset($array_cut[$i][$j]->counter)) {
							$cell->createTextRun($array_cut[$i][$j]->counter)->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						} else {
							$cell->createTextRun('')->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						}
					}
				}
			}
		}
	}

	private function column3DAndWordcloudWithTableOnePage(PhpPresentation $objPHPPresentation, $title, $etiqueta, $serie, $image, $survey, $pregunta, $token, $idTenant) {
		// Create templated slide
		$currentSlide = GeneratePpt::createTemplatedSlide($objPHPPresentation, $title, $idTenant);

		$subtitle = '';
		$shape = $currentSlide->createRichTextShape()
			->setHeight(40)
			->setWidth(700)
			->setOffsetX(75)
			->setOffsetY(90);
		$shape->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

		$textRun = $shape->createTextRun($subtitle);
		$textRun->getFont()->setBold(true)
			->setSize(11)
			->setColor(new Color('666666'))
			->setName($this->fontFamily);

		// Gráfica
		$etiquetas[0] = $etiqueta;
		$series[0] = $serie;
		$currentSlide = GeneratePpt::column3DPermanentGraphic($currentSlide, $etiquetas, $series, 'typeP');

		// Tabla de wordcloud
		$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);

				$shape = $currentSlide->createTableShape($nColumns * 2);
				$shape->setHeight(600);
				$shape->setWidth(200);
				$shape->setOffsetX(270);
				$shape->setOffsetY(100);
				$row = $shape->createRow();
				$fontSize = 12;

				for($i = 0; $i < $nColumns; $i++) {
					// Get the first cell
					$cellA1 = $row->nextCell();
					$cellA1->getActiveParagraph()->getAlignment()
						->setHorizontal(Alignment::HORIZONTAL_CENTER)
						->setVertical(Alignment::VERTICAL_CENTER)
						->setMarginBottom(0)
						->setMarginLeft(0)
						->setMarginRight(0)
						->setMarginTop(0);
					$cellA1->createTextRun('Palabra')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

					// Get the second cell
					$cell = $row->nextCell();

					$cell->getActiveParagraph()->getAlignment()
						->setHorizontal(Alignment::HORIZONTAL_CENTER)
						->setVertical(Alignment::VERTICAL_CENTER)
						->setMarginBottom(0)
						->setMarginLeft(0)
						->setMarginRight(0)
						->setMarginTop(0);

					$cell->createTextRun('Contador')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);
				}

				// Creamos datos
				for($j = 0; $j < count($array_cut[0]); $j++) {
					$row = $shape->createRow();

					for($i = 0; $i < count($array_cut); $i++) {
						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(0)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(0);

						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;
							}

							$cell->createTextRun($array_cut[$i][$j]->word)->getFont()->setBold(false)->setSize($fontSizeEsp)->setName($this->fontFamily);
						} else {
							$cell->createTextRun('')->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						}

						$cell = $row->nextCell();
						$cell->getActiveParagraph()->getAlignment()
							->setHorizontal(Alignment::HORIZONTAL_CENTER)
							->setVertical(Alignment::VERTICAL_CENTER)
							->setMarginBottom(0)
							->setMarginLeft(0)
							->setMarginRight(0)
							->setMarginTop(0);

						if(isset($array_cut[$i][$j]->counter)) {
							$cell->createTextRun($array_cut[$i][$j]->counter)->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						} else {
							$cell->createTextRun('')->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
						}
					}
				}
			}
		}

		// Imagen de wordcloud
		$image = str_replace('image/png', 'image/jpeg', $image);

		// Add a file drawing (JPEG) to the slide
		$shape = new Drawing\Base64();
		$shape->setName('Word Cloud')
			->setDescription('Word Cloud')
			->setData($image)
			->setResizeProportional(false)
			->setHeight(420)
			->setWidth(420)
			->setOffsetX(490)
			->setOffsetY(100);

		$currentSlide->addShape($shape);
	}

	public function piePermanentGraphic($currentSlide, $etiquetas, $series, $colors, $typeColors) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');

		$graph->setName('Data');
		$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);
		$typeChart = new pie();
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_INSIDEEND);

		if($typeColors == 1) {
			$colores = GeneratePpt::generateColors($colors, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($colors, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);

		return $currentSlide;
	}

	public function pie3DPermanentGraphic($currentSlide, $etiquetas, $series, $general = false) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');
		$graph->getLegend()->getFont()->setName($this->fontFamily);

		if($general == 'nse') {
			$graph->setName('NSE')
			->setDescription('NSE')
			->setResizeProportional(false)
			->setHeight(300)
			->setWidth(450)
			->setOffsetX(490)
			->setOffsetY(170);
		} else {
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);
		}

		$typeChart = new pie3D();
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_INSIDEEND);
		$data->getFont()->setName($this->fontFamily);

		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getView3D()->setRotationX(30);
		$graph->getView3D()->setPerspective(30);

		return $currentSlide;
	}

	public function doughnutPermanentGraphic($currentSlide, $etiquetas, $series) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');
		$graph->getLegend()->getFont()->setName($this->fontFamily);

		$graph->setName('Data');
		$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);

		$typeChart = new doughnut();
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_INSIDEEND);
		$data->getFont()->setName($this->fontFamily);

		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getView3D()->setRotationX(30);
		$graph->getView3D()->setPerspective(30);

		return $currentSlide;
	}

	public function columnPermanentGraphic($currentSlide, $etiquetas, $series, $colors, $typeColors, $general = false) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->setVisible(false);

		if($general) {
			$graph->setName('Ages')
				->setDescription('Ages')
				->setResizeProportional(false)
				->setHeight(180)
				->setWidth(400)
				->setOffsetX(50)
				->setOffsetY(360);
		} else {
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);
		}

		$typeChart = new Bar();
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_OUTSIDEEND);

		if($typeColors == 1) {
			$colores = GeneratePpt::generateColors($colors, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($colors, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getPlotArea()->getAxisX()->setTitle('');
		$graph->getPlotArea()->getAxisX()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisX()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisX()->setFormatCode('General');
		$graph->getPlotArea()->getAxisY()->setTitle('');
		$graph->getPlotArea()->getAxisY()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisY()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisY()->setFormatCode('General');

		return $currentSlide;
	}

	public function column3DPermanentGraphic($currentSlide, $etiquetas, $series, $general = false) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->setVisible(false);

		if($general == 'states') {
			$graph->setName('States')
				->setDescription('States')
				->setResizeProportional(false)
				->setHeight(200)
				->setWidth(510)
				->setOffsetX(440)
				->setOffsetY(190);
		} else if($general == 'ages') {
			$graph->setName('Ages')
				->setDescription('Ages')
				->setResizeProportional(false)
				->setHeight(240)
				->setWidth(450)
				->setOffsetX(50)
				->setOffsetY(270);
		} else if($general == 'table') {
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(400)->setWidth(600)->setOffsetX(70)->setOffsetY(110);
		} else if($general == 'typeP') {
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(420)->setWidth(200)->setOffsetX(50)->setOffsetY(100);
		} else {
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);
		}

		$typeChart = new Bar3D();
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_OUTSIDEEND);
		$data->getFont()->setName($this->fontFamily);

		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getPlotArea()->getAxisX()->setTitle('');
		$graph->getPlotArea()->getAxisX()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisX()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisX()->setFormatCode('General');
		$graph->getPlotArea()->getAxisY()->setTitle('');
		$graph->getPlotArea()->getAxisY()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisY()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisY()->setFormatCode('General');
		$graph->getView3D()->setRightAngleAxes(true);
		$graph->getView3D()->setRotationX(5);
		$graph->getView3D()->setRotationY(20);
		$graph->getView3D()->setHeightPercent(null);

		return $currentSlide;
	}

	public function barPermanentGraphic($currentSlide, $etiquetas, $series, $colors, $typeColors, $general = false) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->setVisible(false);

		if($general) {
			$graph->setName('States')
				->setDescription('States')
				->setResizeProportional(false)
				->setHeight(400)
				->setWidth(450)
				->setOffsetX(500)
				->setOffsetY(95);
		} else {
			$graph->setName('Data');
			$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);
		}

		$typeChart = new Bar();
		$typeChart->setBarDirection(Bar::DIRECTION_HORIZONTAL);
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_OUTSIDEEND);

		if($typeColors == 1) {
			$colores = GeneratePpt::generateColors($colors, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($colors, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getPlotArea()->getAxisX()->setTitle('');
		$graph->getPlotArea()->getAxisX()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisX()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisX()->setFormatCode('General');
		$graph->getPlotArea()->getAxisY()->setTitle('');
		$graph->getPlotArea()->getAxisY()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisY()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisY()->setFormatCode('General');

		return $currentSlide;
	}

	public function bar3DPermanentGraphic($currentSlide, $etiquetas, $series) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->setVisible(false);

		$graph->setName('Data');
		$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);

		$typeChart = new Bar3D();
		$typeChart->setBarDirection(Bar3D::DIRECTION_HORIZONTAL);
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_OUTSIDEEND);
		$data->getFont()->setName($this->fontFamily);

		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($etiquetas));
		}

		for($i = 0; $i < count($colores); $i++) {
			$data->getDataPointFill($i)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
		}

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getPlotArea()->getAxisX()->setTitle('');
		$graph->getPlotArea()->getAxisX()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisX()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisX()->setFormatCode('General');
		$graph->getPlotArea()->getAxisY()->setTitle('');
		$graph->getPlotArea()->getAxisY()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisY()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisY()->setFormatCode('General');
		$graph->getView3D()->setRightAngleAxes(true);
		$graph->getView3D()->setRotationX(5);
		$graph->getView3D()->setRotationY(20);
		$graph->getView3D()->setHeightPercent(null);

		return $currentSlide;
	}

	public function oneBar3DStackedPermanentGraphic($currentSlide, $question, $etiquetas, $series) {
		array_multisort($etiquetas, SORT_ASC, $series);

		$seriesDataArray = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData = [
				$question => $series[$i]
			];
			array_push($seriesDataArray, $seriesData);
		}

		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($etiquetas));
		}

		// Create a bar chart (that should be inserted in a shape)
		$StackedBarChart = new Bar3D();
		$StackedBarChart->setBarDirection(Bar3D::DIRECTION_HORIZONTAL);

		for($i = 0; $i < count($seriesDataArray); $i++) {
			$value = $i + 1;
			$seriesX = new Series($value, $seriesDataArray[$i]);
			$seriesX->getFont()->setName($this->fontFamily);
			$seriesX->setShowSeriesName(false);
			$seriesX->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$i]));
			$seriesX->setShowValue(true);
			$seriesX->setShowPercentage(false);

			$StackedBarChart->addSeries($seriesX);
		}

		$StackedBarChart->setBarGrouping(Bar::GROUPING_STACKED);

		// Create a shape (chart)
		$shape = $currentSlide->createChartShape();
		$shape->setName('Data');
		$shape->setResizeProportional(false)->setHeight(400)->setWidth(700)->setOffsetX(50)->setOffsetY(110);
		$shape->getTitle()->setText('');
		$shape->getTitle()->getFont()->setItalic(true);
		$shape->getTitle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
		$shape->getPlotArea()->getAxisX()->setTitle('');
		$shape->getPlotArea()->getAxisX()->setFormatCode('General');
		$shape->getPlotArea()->getAxisY()->setTitle('');
		$shape->getPlotArea()->getAxisY()->setFormatCode('General');
		$shape->getPlotArea()->setType($StackedBarChart);
		$shape->getView3D()->setRightAngleAxes(true);
		$shape->getView3D()->setRotationX(20);
		$shape->getView3D()->setRotationY(20);
		$shape->getView3D()->setHeightPercent(null);
		$shape->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');
		$shape->getLegend()->setPosition('b');

		// Crear tabla de promedio
		$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);

		$shape = $currentSlide->createTableShape(2);
		$shape->setHeight(100);
		$shape->setWidth(200);
		$shape->setOffsetX(720);
		$shape->setOffsetY(290);
		$fontSize = 12;

		// Promedio
		$row = $shape->createRow();
		$cellA1 = $row->nextCell();
		$cellA1->getActiveParagraph()->getAlignment()
			->setHorizontal(Alignment::HORIZONTAL_CENTER)
			->setVertical(Alignment::VERTICAL_CENTER)
			->setMarginBottom(10)
			->setMarginLeft(0)
			->setMarginRight(0)
			->setMarginTop(10);
		$cellA1->createTextRun('Promedio')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

		$cell = $row->nextCell();
		$cell->getActiveParagraph()->getAlignment()
			->setHorizontal(Alignment::HORIZONTAL_CENTER)
			->setVertical(Alignment::VERTICAL_CENTER)
			->setMarginBottom(10)
			->setMarginLeft(0)
			->setMarginRight(0)
			->setMarginTop(10);
		$cell->createTextRun($average)->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);

		return $currentSlide;
	}

	public function bar3DStackedPermanentGraphicSlide($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ) {
		$subtitle = '';
		$shape = $currentSlide->createRichTextShape()
			->setHeight(40)
			->setWidth(700)
			->setOffsetX(75)
			->setOffsetY(90);
		$shape->getActiveParagraph()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

		$textRun = $shape->createTextRun($subtitle);
		$textRun->getFont()->setBold(true)
			->setSize(11)
			->setColor(new Color('666666'))
			->setName($this->fontFamily);

		$currentSlide = GeneratePpt::bar3DStackedPermanentGraphic($currentSlide, $nameArrayPart, $seriesLabelsArrayPart, $typeQ);
	}

	public function bar3DStackedPermanentGraphic($currentSlide, $nameArray, $seriesLabelsArray, $typeQ) {
		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($seriesLabelsArray[0]['etiquetas']));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($seriesLabelsArray[0]['etiquetas']));
		}

		$seriesDataArray = [];
		for($i = 0; $i < count($seriesLabelsArray[0]['etiquetas']); $i++) {
			if($typeQ == 'R') {
				$seriesDataArray[($i + 1)] = [];
			} else {
				$seriesDataArray[$seriesLabelsArray[0]['etiquetas'][$i]] = [];
			}

			for($j = 0; $j < count($nameArray); $j++) {
				if($typeQ == 'R') {
					$seriesDataArray[($i + 1)][$nameArray[$j]] = $seriesLabelsArray[$j]['series'][$i];
				} else {
					$seriesDataArray[$seriesLabelsArray[0]['etiquetas'][$i]][$nameArray[$j]] = $seriesLabelsArray[$j]['series'][$i];
				}
			}
		}

		// Create a bar chart (that should be inserted in a shape)
		$StackedBarChart = new Bar3D();
		$StackedBarChart->setBarDirection(Bar3D::DIRECTION_HORIZONTAL);

		$count = 0;
		foreach($seriesDataArray as $key => $value) {
			$seriesX = new Series($key, $value);
			$seriesX->getFont()->setName($this->fontFamily);
			$seriesX->setShowSeriesName(false);
			$seriesX->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[$count]));
			$seriesX->setShowValue(true);
			$seriesX->setShowPercentage(false);

			$StackedBarChart->addSeries($seriesX);

			$count++;
		}

		$StackedBarChart->setBarGrouping(Bar::GROUPING_STACKED);

		// Create a shape (chart)
		$shape = $currentSlide->createChartShape();
		$shape->setName('Data');
		if($typeQ == 'F' || $typeQ == 'R') {
			$shape->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);
		} else {
			$shape->setResizeProportional(false)->setHeight(400)->setWidth(680)->setOffsetX(40)->setOffsetY(110);
		}
		$shape->getTitle()->setText('');
		$shape->getTitle()->getFont()->setItalic(true);
		$shape->getTitle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
		$shape->getPlotArea()->getAxisX()->setTitle('');
		$shape->getPlotArea()->getAxisY()->setTitle('');
		$shape->getPlotArea()->setType($StackedBarChart);
		$shape->getView3D()->setRightAngleAxes(true);
		$shape->getView3D()->setRotationX(20);
		$shape->getView3D()->setRotationY(20);
		$shape->getView3D()->setHeightPercent(null);
		$shape->getLegend()->getBorder()->setLineStyle()->setLineWidth(0)->getColor()->setARGB('FFFFFFFF');
		$shape->getLegend()->setPosition('b');
		$shape->getPlotArea()->getAxisX()->setFormatCode('General');
		$shape->getPlotArea()->getAxisY()->setFormatCode('General');

		// Creación de tabla de promedios para preguntas tipo 'A' y 'B'
		if($typeQ != 'F' && $typeQ != 'R') {
			// Array de promedios
			$averageArray = [];

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

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

				array_push($averageArray, $average);
			}

			// Crear tabla de promedio
			$shape = $currentSlide->createTableShape(2);
			$shape->setHeight(100);
			$shape->setWidth(200);
			switch(count($nameArray)) {
				case 10:
					$shape->setOffsetY(117);
					break;
				case 9:
					$shape->setOffsetY(135);
					break;
				case 8:
					$shape->setOffsetY(155);
					break;
				case 7:
					$shape->setOffsetY(175);
					break;
				case 6:
					$shape->setOffsetY(193);
					break;
				case 5:
					$shape->setOffsetY(212);
					break;
				case 4:
					$shape->setOffsetY(232);
					break;
				case 3:
					$shape->setOffsetY(247);
					break;
				case 2:
					$shape->setOffsetY(270);
					break;
				case 1:
					$shape->setOffsetY(287);
					break;
				default:
					$shape->setOffsetY(117);
					break;
			}
			$shape->setOffsetX(710);
			$fontSize = 10;

			for($j = (count($nameArray) - 1); $j >= 0; $j--) {
				$row = $shape->createRow();
				$cellA1 = $row->nextCell();
				$cellA1->getActiveParagraph()->getAlignment()
					->setHorizontal(Alignment::HORIZONTAL_CENTER)
					->setVertical(Alignment::VERTICAL_CENTER)
					->setMarginBottom(6)
					->setMarginLeft(0)
					->setMarginRight(0)
					->setMarginTop(6);
				$cellA1->createTextRun('Promedio')->getFont()->setBold(true)->setSize($fontSize)->setName($this->fontFamily);

				$cell = $row->nextCell();
				$cell->getActiveParagraph()->getAlignment()
					->setHorizontal(Alignment::HORIZONTAL_CENTER)
					->setVertical(Alignment::VERTICAL_CENTER)
					->setMarginBottom(6)
					->setMarginLeft(0)
					->setMarginRight(0)
					->setMarginTop(6);
				$cell->createTextRun($averageArray[$j])->getFont()->setBold(false)->setSize($fontSize)->setName($this->fontFamily);
			}
		}

		return $currentSlide;
	}

	public function linePermanentGraphic($currentSlide, $etiquetas, $series) {
		$seriesData = [];
		for($i = 0; $i < count($etiquetas); $i++) {
			$seriesData["$etiquetas[$i]\0"] = $series[$i];
		}

		$graph = $currentSlide->createChartShape();
		$graph->getTitle()->setVisible(false);
		$graph->getLegend()->setVisible(false);

		$graph->setName('Data');
		$graph->setResizeProportional(false)->setHeight(400)->setWidth(800)->setOffsetX(70)->setOffsetY(110);

		$typeChart = new Line();
		$data = new Series('Data', $seriesData);
		$data->setLabelPosition(Series::LABEL_OUTSIDEEND);
		$data->getFont()->setName($this->fontFamily);

		if($this->typeColors == 1) {
			$colores = GeneratePpt::generateColors($this->colorsHex, count($etiquetas));
		} else {
			$colores = GeneratePpt::arrayColors($this->colorsHex, count($etiquetas));
		}

		$data->getDataPointFill(0)->setFillType(Fill::FILL_SOLID)->setStartColor(new Color($colores[0]));

		$typeChart->addSeries($data);
		$graph->getPlotArea()->setType($typeChart);
		$graph->getPlotArea()->getAxisX()->setTitle('');
		$graph->getPlotArea()->getAxisX()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisX()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));
		$graph->getPlotArea()->getAxisY()->setTitle('');
		$graph->getPlotArea()->getAxisY()->getOutline()->setWidth(10);
		$graph->getPlotArea()->getAxisY()->getOutline()->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('FF000000'));

		return $currentSlide;
	}

	public function printPowerPointImagesPerf($images, $data, $questions, $user, $timestamp, $idTenant) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// Create new PHPPresentation object
		$objPHPPresentation = new PhpPresentation();
		$objPHPPresentation->getLayout()->setDocumentLayout('screen16x9');

		// Set properties
		$objPHPPresentation->getDocumentProperties()->setCreator('PHPOffice');

		// Remove first slide
		$objPHPPresentation->removeSlideByIndex(0);

		// Set Style
		$oFill = new Fill();
		$oFill->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('000000')); //Fondo

		$oShadow = new Shadow();
		$oShadow->setVisible(true)->setDirection(45)->setDistance(10);

		// Portada
		$name = $data[0]['data'][0]['surveyDesc'];

		$currentSlide = GeneratePpt::createTitle($objPHPPresentation, $name, $idTenant);

		$i = 0;
		foreach($images as $image) {
			$title = ($i + 1) . '-' . $questions[0][$i] . ' (%)';

			//Printar Answers
			GeneratePpt::imageB64($objPHPPresentation, $title, $image, $idTenant);
			$i++;
		}

		$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) . '_Analitics_Mostreo.pptx';
		$filename = str_replace(' ', '_', $filename);

		$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
		$oWriterPPTX->save($carpeta . '/' . $filename);

		$response = $filename;

		// 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.pptx');

		return $response;
	}

	public function printPowerPointImagesComparative($images, $data, $questions, $wc, $user, $encuestas, $paramsWc, $generalCharts, $token, $timestamp, $isWc, $idTenant) {
		set_time_limit(CONSTANTS::SET_TIME_LIMIT);

		// Create new PHPPresentation object
		$objPHPPresentation = new PhpPresentation();
		$objPHPPresentation->getLayout()->setDocumentLayout('screen16x9');

		// Set properties
		$objPHPPresentation->getDocumentProperties()->setCreator('PHPOffice');

		// Remove first slide
		$objPHPPresentation->removeSlideByIndex(0);

		// Set Style
		$oFill = new Fill();
		$oFill->setFillType(Fill::FILL_SOLID)->setStartColor(new Color('000000')); //Fondo

		$oShadow = new Shadow();
		$oShadow->setVisible(true)->setDirection(45)->setDistance(10);

		// Portada
		$name = 'Reporte ';
		$iName = 0;
		foreach($encuestas as $encuesta) {
			$name = $name . $encuesta;
			if($iName < count($encuestas) - 1) {
				$name = $name . ', ';
			}
			$iName++;
		}

		$this->plantillaPortada = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/00000000000000/plantilla_portada.PNG';
		$this->logo = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/00000000000000/logo_rep.PNG';
		$this->plantilla = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/00000000000000/plantilla.PNG';

		$currentSlide = GeneratePpt::createTitle($objPHPPresentation, $name, $idTenant);

		//Printar graficas generales
		$title = 'Resultados generales';

		foreach($generalCharts as $chart) {
			GeneratePpt::imageB64($objPHPPresentation, $title, $chart, $idTenant);
		}

		$i = 0;
		$iwc = 0;
		foreach($images as $image) {
			$title = ($i + 1) . '-' . $questions[0][$i];

			//Printar Answers
			GeneratePpt::imageB64($objPHPPresentation, $title, $image['data']['imgAnswer'], $idTenant);

			if($wc[$i] == 'yes') {
				$others = [];
				$position = count($data[$i]) - 1;

				foreach($data[$i][$position]['answers']['others'] as $answers) {
					$sanit = htmlspecialchars($answers);
					$sanit = trim($sanit);
					$sanit = preg_replace("/[\r\n|\n|\r]+/", ' ', $sanit);
					array_push($others, htmlspecialchars($sanit));
				}

				// Tabla con el detalle del word cloud
				$survey = $paramsWc[$iwc][0];
				$pregunta = $paramsWc[$iwc][1];

				GeneratePpt::printTableWC($objPHPPresentation, $title, $survey, $pregunta, $token, $idTenant);
				$iwc++;
			} else {
				GeneratePpt::printTable($objPHPPresentation, $title, $encuestas, $data[$i], $idTenant);
			}
			$i++;
		}

		$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_Acumulativo_Mostreo.pptx';

		$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
		$oWriterPPTX->save($carpeta . '/' . $filename);

		$response = $filename;

		// 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);
		$zip->addFile($carpeta . '/' . $filename, 'Analitic_Acumulativo_Mostreo.pptx');
		if($isWc == 'true') {
			$zip->addFile($carpeta . '/' . $response['excel'], 'Analitic_Acumulativo_Mostreo.xlsx');
		}

		return $response;
	}

	public function generateColors($colors, $count) {
		$start = GeneratePpt::hextorgb($colors[0]);
		$end = GeneratePpt::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, GeneratePpt::rgbtohex($c));
		}

		return $arrayColors;
	}

	public function arrayColors($origin_colors, $count) {
		$colors = [];
		$arraylColors = count($colors);
		while($arraylColors < $count) {
			for($i = 0; $i < count($origin_colors); $i++) {
				$addColor = str_replace('#', 'FF', $origin_colors[$i]);
				array_push($colors, $addColor);
				$arraylColors = count($colors);
				if($arraylColors == $count) {
					break;
				}
			}
		}

		return $colors;
	}

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

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

	private function orderQuestionAnswers($etiquetas, $series, $type) {

		$data = [
			'labels' => $etiquetas,
			'series' => $series
		];

		if ($this->answersOrder == 'default') return $data;

		$orderType = '';
		switch ($this->answersOrder) {
			case 'big_to_small':
				$orderType = SORT_DESC;
				break;
			case 'small_to_big':
				$orderType = SORT_ASC;
				break;
		}

		if ($type == 'A' || $type == 'B' || $type == 'F') {
			return $data;
		} else if ($type == 'R') {
			return $data;
		} else {
			array_multisort($series, $orderType, $etiquetas);
		}

		$data['labels'] = $etiquetas;
		$data['series'] = $series;

		return $data;
	}

}