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

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

class ReportsWord {
	private $utilesController;

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

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

	private $fuentePortada = [
		'name' => 'Verdana',
		'size' => 30,
		'color' => '000000',
		'bold' => true
	];

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

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

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

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

	private $filepathLogo = CONSTANTS::PATH_EXPORT_WORD . '/logo.PNG';

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

	private function generateColors($colors, $count) {
		$start = $this->hextorgb($colors[0]);
		$end = $this->hextorgb($colors[1]);

		//Alpha blending amount
		$alpha = 0.0;

		$arrayColors = [];

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

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

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

		return $arrayColors;
	}

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

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

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

	private function titleDocument($document, $title) {
		$propiedades = $document->getDocInfo();
		$propiedades->setTitle('Gráficas');

		$document->addTitleStyle(1, $this->fuentePortada, $this->paragraphPortada);
		$document->addTitleStyle(2, $this->fuenteTitulo);
		$document->addTitleStyle(3, $this->fuenteFecha, $this->paragraphFecha);

		$section = $document->addSection($this->sectionStyle);

		$section->addTitle($title, 1);

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

		$section->addTitle($month . ', ' . $year, 3);
	}

	private function chartPie($section, $title, $labels, $values, $colors) {
		$chart = $section->addChart('pie', $labels, $values);

		$colors = [$colors['colors'][0], $colors['colors'][1]];
		$colors = str_replace('#', '', $colors);
		$chart->getStyle()->setColors($colors);
		$chart->getStyle()->setDataLabelOptions([
			'showPercent' => false,
			'showVal' => true
		]);
		$chart->getStyle()->setWidth(900 * 10000);
		$chart->getStyle()->setHeight(600 * 10000);
		$chart->getStyle()->setShowAxisLabels(true);
		$chart->getStyle()->setShowLegend(true);
		$chart->getStyle()->setTitle($title);
	}

	private function chart($section, $title, $labels, $values, $colors) {
		$chart = $section->addChart('column', $labels, $values);

		if($colors['type'] == 1) {
			$colors = $this->generateColors($colors['colors'], count($labels));
		} else {
			$colors = $this->arrayColors($colors['colors'], count($labels));
		}
		$colors = str_replace('#', '', $colors);
		$chart->getStyle()->setColors($colors);
		$chart->getStyle()->setDataLabelOptions([
			'showPercent' => false,
			'showVal' => true
		]);
		$chart->getStyle()->setWidth(900 * 10000);
		$chart->getStyle()->setHeight(600 * 10000);
		$chart->getStyle()->setShowAxisLabels(true);
		$chart->getStyle()->setValueLabelPosition('low');
		$chart->getStyle()->setCategoryLabelPosition('low');
		$chart->getStyle()->setTitle($title);
	}

	private function newSection($document, $title = null) {
		$section = $document->addSection($this->sectionStyle);
		$header = $section->createHeader();
		$header->addText($title, $this->fuenteTitulo);
		$header->addImage($this->filepathLogo, $this->styleLogo);

		return $section;
	}

	private function wordCloud($section, $image, $user, $i) {
		$Base64Img = $image;
		$baseFromJavascript = $Base64Img;
		$base_to_php = explode(',', $baseFromJavascript);
		$data = base64_decode($base_to_php[1]);
		$fecha = date_create();
		$filename = date_timestamp_get($fecha) . '_wc_' . $i . '_image.png';
		$filepath = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . $filename;

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

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

		array_push($deleteImages, $filepath);

		file_put_contents($filepath, $data);

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

		return $filename;
	}

	private function wordCloudList($section, $words) {
		foreach($words as $other) {
			$sanit = htmlspecialchars($other);
			$sanit = trim($sanit);
			$sanit = preg_replace("/[\r\n|\n|\r]+/", ' ', $sanit);

			$section->addListItem($sanit);
		}
	}

	public function generateReport($data, $colors, $title, $user, $zipName) {
		try {
			$delete = [];
			// Creamos documento
			$document = new \PhpOffice\PhpWord\PhpWord();

			// Creamos graficas generales
			$this->titleDocument($document, $title);

			foreach($data['charts'] as $chart) {
				$section = $this->newSection($document, 'Resultados generales');
				if($chart['typeChart'] == 'pie') {
					$this->chartPie($section, $chart['title'], $chart['labels'], $chart['data'], $colors);
				} else {
					$this->chart($section, $chart['title'], $chart['labels'], $chart['data'], $colors);
				}
			}

			// Creamos graficas de respuestas
			$i = 1;
			foreach($data['questions'] as $question) {
				$section = $this->newSection($document, $i . '. ' . $question['question']);

				// Compobar si hay Word Cloud
				if($question['wc'] == 'true') {
					$image = $this->wordCloud($section, $question['image'], $user, $i);
					array_push($delete, $image);
					$section = $this->newSection($document, $i . '. ' . $question['question']);
					$this->wordCloudList($section, $question['wcAnswers']);
				} else {
					$this->chart($section, $question['title'], $question['labels'], $question['data'], $colors);
				}

				$i++;
			}

			// Guardar el documento
			$document->getCompatibility()->setOoxmlVersion(15);

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

			// Guardar reporte en un zip
			// Carpeta donde guardar los elementos a comprimir
			$fecha = date_create();
			$timestamp = date_timestamp_get($fecha);

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

			$filename = date_timestamp_get($fecha) . 'Analitic_Mostreo.docx';
			$filename = str_replace(' ', '_', $filename);

			$response = [];

			try {
				$objWriter->save($folder . $filename, 'Word2007');
			} catch(Exception $e) {
				$response['word'] = 'KO';
			}

			// Borrar imagenes
			foreach($delete as $row) {
				unlink($folder . $row);
			}

			// Objeto ZIP
			$zip = new ZipArchive();
			try {
				$zip->open($folder . $zipName, ZipArchive::CREATE);
				$zip->addFile($folder . $filename, 'Analitics_Mostreo.docx');
			} catch(Exception $e) {
				$response['word'] = 'KO';
			}
		} catch(Exception $e) {
			return false;
		}
		return true;
	}
}