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

use PhpOffice\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\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\Shape\Drawing;
use PhpOffice\PhpPresentation\Shape\RichText\Paragraph;
use PhpOffice\PhpPresentation\Style\Bullet;

class ReportsPpt {
	private $fontFamily = 'Arial';
	private $utilesController;

	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(CONSTANTS::PATH_EXPORT_WORD . '/plantilla_portada.PNG')
			->setHeight(800)
			->setWidth(960)
			->setOffsetX(0)
			->setOffsetY(0);

		$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)
			->setName($this->fontFamily)
			->setColor(new Color('ffffff'));

		// 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)
			->setSize(20)
			->setName($this->fontFamily)
			->setColor(new Color('ffffff'));

		return $slide;
	}

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

		$oShapeDrawing = new Drawing\File();
		$oShapeDrawing->setName('PHPPresentation logo')
			->setDescription('PHPPresentation logo')
			->setPath(CONSTANTS::PATH_EXPORT_WORD . '/plantilla.PNG')
			->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(12)
			->setName($this->fontFamily)
			->setColor(new Color('ffffff'));

		return $slide;
	}

	private function imageB64(PhpPresentation $objPHPPresentation, $title, $image) {
		global $oFill;
		global $oShadow;
		// Create templated slide
		$currentSlide = $this->createTemplatedSlide($objPHPPresentation, $title);
		$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(100)
			//->setHorizontal(Alignment::HORIZONTAL_CENTER)
		;
		$currentSlide->addShape($shape);
	}

	private function printTable(PhpPresentation $objPHPPresentation, $title, $encuestas, $data) {
		$total = count($encuestas) + 1;
		global $oFill;
		global $oShadow;
		// Create templated slide
		$currentSlide = $this->createTemplatedSlide($objPHPPresentation, $title);
		$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);
		}
		$i = 0;

		$total = count($data[$totalLabels]['answers']['labels']);
		for($i; $i < $total; $i++) {
			$row = $shape->createRow();
			//Label
			$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) {
		// Obtenemos data
		$controller = new Controller;

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

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

		if(count($resultPOST->result) > 0) {
			$max = 10 * 5;
			$array_total = array_chunk($resultPOST->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);

				global $oFill;
				global $oShadow;
				// Create templated slide
				$currentSlide = $this->createTemplatedSlide($objPHPPresentation, $title);
				$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)) {
							$cell->createTextRun($array_cut[$i][$j]->word)->getFont()->setBold(false)->setSize($fontSize)->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) {
		global $oFill;
		global $oShadow;

		// Create templated slide
		$currentSlide = $this->createTemplatedSlide($objPHPPresentation, $title);
		// 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]);

			if($i == ($limit + $start)) {
				$this->printOthers($objPHPPresentation, $title, $data, $i);
				break;
			}
		}
	}

	public function generateReport($data, $user, $survey, $token, $name, $zipName, $fontName) {
		$this->fontFamily = $fontName;

		try {
			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
			$currentSlide = $this->createTitle($objPHPPresentation, $name);

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

			//Printar Totales
			foreach($data['charts'] as $chart) {
				$this->imageB64($objPHPPresentation, $title, $chart['image']);
			}

			$i = 1;
			foreach($data['questions'] as $id => $question) {
				$title = $i . '. ' . $question['question'];
				//Printar Answers
				$this->imageB64($objPHPPresentation, $title, $question['image']);

				if($question['wc'] == 'true') {
					$others = [];

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

					$this->printOthers($objPHPPresentation, $title, $others, 0);

					$this->printTableWC($objPHPPresentation, $title, $survey, $id, $token);
				}
				$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);

			// 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 . $zipName, ZipArchive::CREATE);
			$zip->addFile($carpeta . '/' . $filename, 'Analitics_Mostreo.pptx');
		} catch(Exception $e) {
			return false;
		}

		return true;
	}
}