<?php
include_once(dirname(__FILE__) . '/UtilesController.php');

class TemplatesController {
	private $utilesController;

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

	// Crear nueva plantilla
	public function insertTemplate($client) {
		$url = CONSTANTS::SERVERAPI . 'getCMBPConfig';
		$params = [
			'token' => $client['token']
		];

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

		if($resultPOST->status != 'OK') {
			return $resultPOST;
		}

		$maxSize = $resultPOST->result[0]->upload_max_filesize_bytes;

		// Crear registro
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'name' => $client['name'],
			'description' => $client['description'],
			'country' => $client['country'],
			'template' => ''
		];

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

		// Registro de errores
		if($resultPOST->status != 'OK') {
			return $resultPOST;
		}

		$idTemplate = $resultPOST->idTemplate;

		// Guardar archivo
		// Ruta del documento
		$documentPathDir = CONSTANTS::PATH_EXPORT_WORD . '/templates';

		// Carpeta de documento
		if(!file_exists($documentPathDir)) {
			$createFile = $this->utilesController->createDirectory($documentPathDir);

			if($createFile['status'] != 'OK') {
				return $createFile;
			}
		}

		foreach($_FILES as $key => $value) {
			// Comprobar el tamaño del documento
			if($_FILES[$key]['size'] > $maxSize) {
				$resultPOST->status = 'KO';
				$resultPOST->result = 'The file is too large';
				return $resultPOST;
			}

			// Comprobación de nombre original
			$strangerCharts = ['?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', '\'', '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+'];
			for($i = 0; $i < count($strangerCharts); $i++) {
				if(strpos($_FILES[$key]['name'], $strangerCharts[$i]) !== false) {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file name is not correct';
					return $resultPOST;
				}
			}

			// Modificación del nombre del documento
			$newname = str_replace('-', '_', $_FILES[$key]['name']);
			$newname = str_replace(' ', '_', $newname);
			$newname = $idTemplate . '_' . $newname;

			// Lista de extensiones permitidas
			$safeList = ['lss'];
			$nameArray = explode('.', $newname);
			$lastPosition = count($nameArray) - 1;
			$extension = $nameArray[$lastPosition];
			$extension = strtolower($extension);
			if(!in_array($extension, $safeList)) {
				$resultPOST->status = 'KO';
				$resultPOST->result = 'The extension name is not correct';
				return $resultPOST;
			}

			// Mover el documento a la carpeta del proyecto
			if(!move_uploaded_file($_FILES[$key]['tmp_name'], $documentPathDir . '/' . $newname)) {
				$resultPOST->status = 'KO';
				$resultPOST->result = 'The document could not be saved';
				return $resultPOST;
			}
		}

		// Editar plantilla con el nuevo nombre de template
		$url = CONSTANTS::SERVERAPI . 'updateTemplate';
		$params = [
			'token' => $client['token'],
			'idTemplate' => $idTemplate,
			'name' => $client['name'],
			'description' => $client['description'],
			'country' => $client['country'],
			'template' => $newname
		];

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

		return $resultPOST;
	}

	// Eliminar plantilla
	public function deleteTemplate($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['templates'] != '[]') {
			foreach($client['templates'] as $template) {
				$params = [
					'token' => $client['token'],
					'idTemplate' => $template['id']
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}

				unlink(CONSTANTS::PATH_EXPORT_WORD . '/templates/' . $template['file']);
			}
		} else {
			$resultPOST = [
				'status' => 'OK'
			];
		}

		return $resultPOST;
	}

	// Petición de plantilla por id
	public function getTemplatesByID($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idTemplate' => $client['idTemplate']
		];

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

		return $resultPOST;
	}

	// Editar plantilla
	public function updateTemplate($client) {
		// Si se modifica el archivo
		if(isset($_FILES) && count($_FILES) > 0) {
			$url = CONSTANTS::SERVERAPI . 'getCMBPConfig';
			$params = [
				'token' => $client['token']
			];

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

			if($resultPOST->status != 'OK') {
				return $resultPOST;
			}

			$maxSize = $resultPOST->result[0]->upload_max_filesize_bytes;

			// Guardar archivo
			// Ruta del documento
			$documentPathDir = CONSTANTS::PATH_EXPORT_WORD . '/templates';

			// Carpeta de documento
			if(!file_exists($documentPathDir)) {
				$createFile = $this->utilesController->createDirectory($documentPathDir);

				if($createFile['status'] == 'KO') {
					return $createFile;
				}
			}

			foreach($_FILES as $key => $value) {
				// Comprobar el tamaño del documento
				if($_FILES[$key]['size'] > $maxSize) {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file is too large';
					return $resultPOST;
				}

				// Comprobación de nombre original
				$strangerCharts = ['?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', '\'', '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+'];
				for($i = 0; $i < count($strangerCharts); $i++) {
					if(strpos($_FILES[$key]['name'], $strangerCharts[$i]) !== false) {
						$resultPOST->status = 'KO';
						$resultPOST->result = 'The file name is not correct';
						return $resultPOST;
					}
				}

				// Modificación del nombre del documento
				$newname = str_replace('-', '_', $_FILES[$key]['name']);
				$newname = str_replace(' ', '_', $newname);
				$newname = $client['idTemplate'] . '_' . $newname;

				// Lista de extensiones permitidas
				$safeList = ['lss'];
				$nameArray = explode('.', $newname);
				$lastPosition = count($nameArray) - 1;
				$extension = $nameArray[$lastPosition];
				$extension = strtolower($extension);
				if(!in_array($extension, $safeList)) {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The extension name is not correct';
					return $resultPOST;
				}

				// Mover el documento a la carpeta del proyecto	
				if(!move_uploaded_file($_FILES[$key]['tmp_name'], $documentPathDir . '/' . $newname)) {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The document could not be saved';
					return $resultPOST;
				}
			}

			unlink(CONSTANTS::PATH_EXPORT_WORD . '/templates/' . $client['templateOld']);
		} else {
			$newname = $client['templateOld'];
		}

		// Editar registro
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idTemplate' => $client['idTemplate'],
			'name' => $client['name'],
			'description' => $client['description'],
			'country' => $client['country'],
			'template' => $newname
		];

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

		return $resultPOST;
	}
}