<?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\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;

class ReportsExcel {
	private $utilesController;

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

	public function dataExcel($resultPOST) {
		if($resultPOST->status == 'OK') {
			// Preparar array con los id de las preguntas
			$questions = [];
			foreach($resultPOST->questions as $result) {
				$questions[$result->id]['question'] = $result->question;
				$questions[$result->id]['type'] = $result->type;
			}

			// Preparar array con los id de las answrers
			$answers = [];
			foreach($resultPOST->answers as $result) {
				$answers[$result->id][$result->answer_code] = $result->answer;
			}
		}

		// Preparar las arrays con los datos
		$result = [];
		$result['questions'] = $questions;
		$result['answers'] = $answers;

		return $result;
	}

	public function printExcel($data, $user, $name, $zipName) {
		try {
			// Obtenemos informacion de las preguntas
			$codes = $this->dataExcel($data);
			$nameClean = trim(str_replace(' ', '_', $name));

			// Excel
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();
			$sheet->setCellValue('A1', 'Hello World !');

			// Nombre añadido a la primera columna
			$encabezados = ['Nombre', 'Folio', 'Estado', 'Edad', 'Género'];

			// Numero pregunta
			$i = 0;
			$last_id = '';
			foreach($data->questions as $questions) {
				if($questions->parent_qid == 0) {
					$i++;
				}
				$row = $i . ' - ' . trim($questions->question);
				array_push($encabezados, $row);
			}

			// Completar registros usuarios
			$arrayData = [];
			array_push($arrayData, $encabezados);
			foreach($data->result as $result) {
				$data = [];
				// Nombre añadido a la primera columna
				array_push($data, $result->name);
				array_push($data, $result->token);
				array_push($data, $result->perf001);
				array_push($data, $result->perf002);
				array_push($data, $result->perf003);

				foreach($codes['questions'] as $key => $value) {
					if($value['type'] == '!' || $value['type'] == 'L') {
						if($result->$key == '-oth-') {
							$rowValue = 'Otros';
						} else {
							if(isset($result->$key)) {
								$rowValue = trim($codes['answers'][$key][$result->$key]);
							} else {
								$rowValue = '';
							}
						}

						array_push($data, $rowValue);
					} else {
						// Añadido para encuestas tipo 'P'
						if(isset($result->$key)) {
							$comment = $key . 'comment';
							if(isset($result->$comment)) {
								$rowValue = trim($result->$key . ' - ' . $result->$comment);
							} else {
								$rowValue = trim($result->$key);
							}
						} else {
							$rowValue = '';
						}
						array_push($data, $rowValue);
					}
				}
				array_push($arrayData, $data);
			}

			$spreadsheet->getActiveSheet()
				->fromArray(
					$arrayData, // The data to set
					NULL,		// Array values with this value will not be set
					'A1'		// Top left coordinate of the worksheet range where
								// we want to set these values (default is A1)
				);
			// Estilos encabezados
			$letra = $spreadsheet->getActiveSheet()->getHighestColumn();
			$spreadsheet->getActiveSheet()->getStyle('A1:' . $letra . '1')->applyFromArray(
				[
					'fill' => [
						'type' => Fill::FILL_SOLID,
						'color' => [
							'rgb' => 'E5E4E2'
						]
					],
					'font' => [
						'bold' => true
					]
				]
			);

			// Autoajustar celdas
			$column = 'A';
			while($column != $letra) {
				$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
				$column++;
			}
			$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

			$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) . '_' . $nameClean . '.xlsx';

			$writer = new Xlsx($spreadsheet);
			$writer->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, $nameClean . '.xlsx');
		} catch(Exception $e) {
			return false;
		}

		return true;
	}

	public function counterWords($data, $user, $token, $zipName = null) {
		try {
			// Excel
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$letter = 'A';
			$number = 1;

			foreach($data as $question) {
				$arrayData = [];

				$tit = str_replace('=', ' ', $question['title']);
				$title = [htmlspecialchars($tit), ''];
				$header = ['Palabra', 'Contador'];

				array_push($arrayData, $title);
				array_push($arrayData, $header);
				// Obtenemos data
				$controller = new Controller;

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

				$resultPOST = $controller->sendCurlPOST($url, $params);
				if($resultPOST->status == 'OK') {
					if(count($resultPOST->result) > 0) {
						foreach($resultPOST->result as $result) {
							$word = str_replace('=', ' ', $result->word);

							$values = [htmlspecialchars($word), $result->counter];
							array_push($arrayData, $values);
						}
					}
				}
				$cell = $letter . $number;

				$spreadsheet->getActiveSheet()
					->fromArray(
						$arrayData, // The data to set
						NULL,		// Array values with this value will not be set
						$cell		// Top left coordinate of the worksheet range where
									// we want to set these values (default is A1)
					);

				$letter++;
				$letter++;
			}

			// Estilos encabezados
			$letra = $spreadsheet->getActiveSheet()->getHighestColumn();
			$spreadsheet->getActiveSheet()->getStyle('A1:' . $letra . '1')->applyFromArray(
				[
					'fill' => [
						'type' => Fill::FILL_SOLID,
						'color' => [
							'rgb' => 'E5E4E2'
						]
					],
					'font' => [
						'bold' => true
					]
				]
			);

			// Autoajustar celdas
			$column = 'A';
			while($column != $letra) {
				$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
				$column++;
			}
			$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

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

			$writer = new Xlsx($spreadsheet);
			$writer->save($carpeta . '/' . $filename);

			if($zipName) {
				// 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.xlsx');
			}
		} catch(Exception $e) {
			return false;
		}

		return true;
	}
}