<?php
class UtilesController {
	public function sendCurlPOST($url, $params) {
		// Get cURL resource
		$curl = curl_init();
		// Set some options - we are passing in a useragent too here
		curl_setopt_array($curl, [
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_URL => $url,
			CURLOPT_POST => 1,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_POSTFIELDS => $params,
			CURLOPT_SSL_VERIFYPEER => false
		]);
		// Send the request & save response to $resp
		$resp = curl_exec($curl);
		// Close request to clear up some resources
		curl_close($curl);

		$response = json_decode($resp);

		// Control de errores cuando no es 'KO'
		if($response == NULL) {
			$nombre_archivo = CONSTANTS::REGISTER_LOGS_SERVICE_PATH . 'curl_errors.log';

			if($archivo = fopen($nombre_archivo, 'a')) {
				fwrite($archivo, date('Y-m-d H:i:s') . "\t|| " . $url . " \n" . strip_tags($resp) . " \n");
				fclose($archivo);
			}
		} else {
			// Registro de errores
			if($response->status != 'OK') {
				if(isset($response->result)) {
					$result = $response->result;
				} else {
					$result = 'ERROR';
				}

				if($result == 'Not authorized or session token has expired') {
					$response->result = '##change##';
				} else {
					$serviceName = str_replace(CONSTANTS::SERVERAPI, '', $url);
					if($serviceName != 'getLicencesByCountry') {
						$this->setCMBPLOG($params['token'], 'SERVICE', $serviceName, $result, '', '1');
					}
				}
			}
		}

		return $response;
	}

	public function basicOneParameterService($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

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

		return $resultPOST;
	}

	// Configuración de BOTS para usuarios o grupos
	public function getBotConfig($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idUserOrGroup' => $client['idUserOrGroup'],
			'isGroup' => $client['isGroup']
		];

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

		return $resultPOST;
	}

	// Configuración de asistente de voz para usuarios o grupos
	public function getVoiceAssistantConfig($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idUserOrGroup' => $client['idUserOrGroup'],
			'isGroup' => $client['isGroup']
		];

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

		return $resultPOST;
	}

	// Envío de notificaciones múltiples
	public function postMessageMultiple($client, $data, $token) {
		if(!isset($token)) {
			$token = $client['token'];

			// Array de usuarios a enviar
			$send = [];
			foreach($client['emailsToSend'] as $user) {
				array_push($send, $user['id']);
			}

			$url = CONSTANTS::SERVERAPI . $client['action'];
			$params = [
				'token' => $token,
				'from' => $client['from'],
				'emailsToSend' => json_encode($send),
				'message' => $client['message'],
				'idlist' => $client['idlist'],
				'silent' => $client['silent'],
				'misionStamp' => $client['misionStamp'],
				'idProject' => $client['idProject'],
				'initMision' => $client['initMision'],
				'finMision' => $client['finMision'],
				'isMision' => $client['isMision'],
				'cumplidaMision' => $client['cumplidaMision'],
				'noCumplidaMision' => $client['noCumplidaMision'],
				'cupoMision' => $client['cupoMision'],
				'validationMision' => $client['validationMision']
			];
		} else {
			$url = CONSTANTS::SERVERAPI . 'postMessageMultiple';
			$params = [
				'token' => $token,
				'from' => $data['from'],
				'emailsToSend' 	=> $data['emailsToSend'],
				'message' => $data['message'],
				'idlist' => $data['idlist'],
				'idProject' => (isset($data['idProject']) ? $data['idProject'] : '')
			];
		}

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

		return $resultPOST;
	}

	// Idiomas
	public function getIdiomas($client) {
		$url = CONSTANTS::SERVERAPI . 'getIdiomas';
		$params = [
			'token' => $client['token']
		];

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

		return $resultPOST;
	}

	// Paises
	public function getPaises($client) {
		$url = CONSTANTS::SERVERAPI . 'getPaises';
		$params = [
			'token' => $client['token']
		];

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

		return $resultPOST;
	}

	// Información de un país por su iso
	public function getPaisByID($client) {
		$url = CONSTANTS::SERVERAPI . 'getPaisByID';
		$params = [
			'token' => $client['token'],
			'isocode' => $client['isocode']
		];

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

		return $resultPOST;
	}

	// Función para reemplazar letras no permitidas
	public function removeAccents($string) {
		$accentedLetters = ['á', 'é', 'í', 'ó', 'ú', 'Á', 'É', 'Í', 'Ó', 'Ú', 'ñ', 'À', 'Ã', 'Ì', 'Ò', 'Ù', 'Ã™', 'Ã ', 'Ã¨', 'Ã¬', 'Ã²', 'Ã¹', 'ç', 'Ç', 'Ã¢', 'ê', 'Ã®', 'Ã´', 'Ã»', 'Ã‚', 'ÃŠ', 'ÃŽ', 'Ã”', 'Ã›', 'ü', 'Ã¶', 'Ã–', 'Ã¯', 'Ã¤', '«', 'Ò', 'Ã', 'Ã„', 'Ã‹'];
		$newLetters = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U', 'n', 'N', 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u', 'c', 'C', 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U', 'u', 'o', 'O', 'i', 'a', 'e', 'U', 'I', 'A', 'E'];

		$newString = str_replace($accentedLetters, $newLetters, $string);

		return $newString;
	}

	public function convertImageJPG($originalImage, $outputImage, $quality) {
		// jpg, png, gif or bmp?
		$exploded = explode('.',$originalImage);
		$ext = $exploded[count($exploded) - 1];

		if(preg_match('/jpg|jpeg/i',$ext))
			$imageTmp=imagecreatefromjpeg($originalImage);
		else if(preg_match('/png/i',$ext))
			$imageTmp=imagecreatefrompng($originalImage);
		else if(preg_match('/gif/i',$ext))
			$imageTmp=imagecreatefromgif($originalImage);
		else if(preg_match('/bmp/i',$ext))
			$imageTmp=imagecreatefrombmp($originalImage);
		else
			return 0;

		// Quality is a value from 0 (worst) to 100 (best)
		imagejpeg($imageTmp, $outputImage, $quality);
		imagedestroy($imageTmp);

		return 1;
	}

	public function createImageFromSource($source, $type) {
		// JPG
		if(preg_match('/jpg|jpeg/', $type)) $data = imagecreatefromjpeg($source);
		// PNG
		if(preg_match('/png/', $type)) $data = imagecreatefrompng($source);
		// WEBP
		if(preg_match('/webp/', $type)) $data = imagecreatefromwebp($source);
		// GIF
		if(preg_match('/gif/', $type)) $data = imagecreatefromgif($source);

		return $data;
	}

	public function resizeImage($original_image_data, $original_width, $original_height, $new_width, $new_height) {
		$dst_img = ImageCreateTrueColor($new_width, $new_height);

		$x = imagecopyresampled($dst_img, $original_image_data, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

		return $dst_img;
	}

	// Borrar un archivo en servidor
	public function deleteFile($client) {
		try {
			$fileName = $client['filename'];
			unlink(CONSTANTS::PATH_EXPORT_WORD . '/' . $fileName);

			$resultPOST = [
				'status' => 'OK',
				'result' => true
			];
		} catch(Exception $e) {
			$resultPOST = [
				'status' => 'KO',
				'result' => false
			];
		}

		return $resultPOST;
	}

	// Borrar una carpeta en servidor
	public function deleteFolder($client) {
		try {
			$folderName = CONSTANTS::PATH_EXPORT_WORD . '/' . $client['folder'] . '/*';
			$files = glob($folderName);
			foreach($files as $file) {
				if(is_file($file)) {
					unlink($file);
				}
			}

			$resultPOST = [
				'status' => 'OK',
				'result' => true
			];
		} catch(Exception $e) {
			$resultPOST = [
				'status' => 'KO',
				'result' => false
			];
		}

		return $resultPOST;
	}

	// Añadir log
	public function setCMBPLOG($token, $typeEvent, $callerEvent, $text, $swlOrig, $systemEvent) {
		if(!isset($text)) {
			$text = '';
		}

		$url = CONSTANTS::SERVERAPI . 'setCMBPLOG';
		$params = [
			'token' => $token,
			'TypeEvent' => $typeEvent,
			'CallerEvent' => $callerEvent,
			'LogEvent' => $text,
			'SQLQuery' => $swlOrig,
			'systemEvent' => $systemEvent
		];
		$resultPOST = $this->sendCurlPOST($url, $params);

		if($resultPOST->status == 'OK') {
			return true;
		} else {
			return false;
		}
	}

	// Número de licencias libres
	public function getFreeLicences($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	public function OpenSSLDecrypt($value) {
		$res = openssl_decrypt($value, 'aes-256-cbc', '$$5oc1aLL4b5$$', 0 , '1234567890123456');
		if(!$res) return '';
		return $res;
	}

	// Actualización de fecha de blog
	public function setLastVersionControlled($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'version' => $client['version'],
			'compilacion' => $client['compilacion']
		];

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

		return $resultPOST;
	}

	// Crear directorio en servidor
	public function createDirectory($carpeta) {
		// SonarQube => No quitar, evita la perdida de permisos a la hora de crear o modificar archivos en servidor a través de los servicios
		
		// start - ds - change mode for security reasons - SonarQube
		// $oldmask = umask(0);
		$oldmask = umask(0027);
		// end - ds - change mode for security reasons - SonarQube		
		$createFile = mkdir($carpeta, 0777, true);		
		umask($oldmask);		

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

		return $response;
	}

	// Petición de RSC específico
	public function getRSC($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'rsc' => $client['rsc']
		];

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

		return $resultPOST;
	}

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

	// Actualizar misión
	public function updateMision($token, $params, $stampMision) {
		$url = CONSTANTS::SERVERAPI . 'updateMision';

		$params = [
			'token' => $token,
			'idmision' => $params['idmision'],
			'descripcion' => $params['descripcion'],
			'textomisionvalidacion' => $params['textovalidacion'],
			'textoiniciomision' => $params['textoiniciomision'],
			'textofinmision' => $params['textofinmision'],
			'textomisionok' => $params['textomisionok'],
			'textomisionko' => $params['textomisionko'],
			'tipomision' => $params['tipomision'],
			'desctipomision' => $params['desctipomision'],
			'fechahorainicio' => $params['fechahorainicio'],
			'fechahorainicioexec' => $params['fechahorainicioexec'],
			'fechahorafin' => $params['fechahorafin'],
			'fechahorafinexec' => $params['fechahorafinexec'],
			'importe' => $params['importe'],
			'encuesta' => $params['encuesta'],
			'idPlantillaReportes' => $params['idPlantillaReportes'],
			'currency' => $params['currency'],
			'country' => $params['country'],
			'order' => $params['order'],
			'importeinterno' => $params['importeinterno'],
			'finmisioncupo' => $params['finmisioncupo'],
			'textofinmisioncupo' => $params['textofinmisioncupo'],
			'currencyinterno' => $params['currencyinterno'],
			'needValidation' => $params['needValidation'],
			'cierreManual' => $params['manualClosing'],
			'textomisionkoAutoNoCumplimiento' => $params['textomisionkoAutoNoCumplimiento'],
			'usaComision' => $params['usaComision'],
			'importenocumplimiento' => $params['importenocumplimiento'],
			'currencynocumplimiento' => $params['currencynocumplimiento'],
			'misionInicial' => $params['misionInicial'],
			'misionInfinita' => $params['misionInfinita'],
			'idCliente' => $params['idCliente'],
			'tipoAnidada' => $params['tipoAnidada'],
			'estadoAnidada' => $stampMision,
			'requiereTracking' => $params['requiereTracking']
		];

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

		return $resultPOSTnestedMission;
	}

	// Petición de datos generales por país
	public function getMainDashboardByContry($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}
}