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

class AnalyticsController {
	private $utilesController;
	private $generateTableExcel;

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

	// ASESORES
	public function getAnalyticsConsejeros($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// Excel de asesores
	public function getAnalyticsConsejerosToExport($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'cabecerasExcel' => $client['cabeceras'],
			'parametrosExcel' => $client['parametros'],
			'pathExcel' => CONSTANTS::PATH_EXPORT_WORD,
			// Para uso en localhost
			//'pathExcel' => '/var/www/html/sociallabs/public/stcm_backend_web/API/Downloads',
			'nameExcel' => $client['nameExcel']
		];

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

		return $resultPOST;
	}

	// ASESORES - Nuevo
	public function getAnalyticsConsejerosInfo($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'type' => $client['type'],
			'version' => $client['version']
		];

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

		return $resultPOST;
	}

	// ASESORES - Nuevo
	public function getAnalyticsConsejerosAppVersion($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsConsejeros';
		$countries = explode(',', $client['country']);
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		$countriesResp = $resultPOST->result->country;

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

		// Datos generales versiones app
		$response['appVersionGeneral'] = [];
		$response['appVersionGeneral']['data'] = [];
		$response['appVersionGeneral']['labels'] = [];
		$appVersion = [];
        $clientCountries = $client['countries'] ?? '';

		foreach($resultPOST->result->desgloseAdminPanel as $admin) {
			// Control países seleccionados
			if(in_array($admin->countryISO, $countries) || $clientCountries) {
				array_push($appVersion, $admin->appVersion);
			}
		}

		foreach($resultPOST->result->desgloseConsejerosActivos as $consejero) {
			// Control países seleccionados
			if(in_array($consejero, $countries) || $clientCountries == '') {
				array_push($appVersion, $consejero->appVersion);
			}
		}

		$response['appVersionGeneral']['total'] = count($appVersion);

		$appVersion = array_count_values($appVersion);

		// Ordenación datos
		foreach($appVersion as $appObj) {
			array_push($response['appVersionGeneral']['data'], $appObj);
		}

		foreach(array_keys($appVersion) as $appObj) {
			array_push($response['appVersionGeneral']['labels'], $appObj);
		}
		array_multisort($response['appVersionGeneral']['data'], SORT_DESC, $response['appVersionGeneral']['labels']);

		// Datos por país
		if($clientCountries == '') {
			$countries = $countriesResp;
		}
		if(count($countries) > 1) {
			foreach($countries as $idCountry) {
				$response[$idCountry] = [];
				$response[$idCountry]['data'] = [];
				$response[$idCountry]['labels'] = [];
				$appVersion = [];

				foreach($resultPOST->result->desgloseAdminPanel as $admin) {
					// Control países seleccionados
					if($admin->countryISO == $idCountry) {
						array_push($appVersion, $admin->appVersion);
					}
				}

				foreach($resultPOST->result->desgloseConsejerosActivos as $consejeros) {
					// Control países seleccionados
					if($consejeros->countryISO == $idCountry) {
						array_push($appVersion, $consejeros->appVersion);
					}
				}

				$response[$idCountry]['total'] = count($appVersion);

				$appVersion = array_count_values($appVersion);

				// Ordenación datos
				foreach($appVersion as $appObj) {
					array_push($response[$idCountry]['data'], $appObj);
				}

				foreach(array_keys($appVersion) as $appObj) {
					array_push($response[$idCountry]['labels'], $appObj);
				}
				array_multisort($response[$idCountry]['data'], SORT_DESC, $response[$idCountry]['labels']);
			}
		}

		$response['country'] = $countries;
		$response['status'] = 'OK';
		return $response;
	}

	// Comprobación de perfilación de usuario
	public function getIfUserPerfila($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email']
		];

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

		return $resultPOST;
	}

	// Envío de e-mail con numero de solicitud de licencias de asesores
	public function sendEmailLicences($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'numlicencias' => $client['numlicencias']
		];

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

		return $resultPOST;
	}

	// CUMPLIMIENTO
	public function getAnalyticsMisiones($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'project' => $client['project'],
			'mision' => $client['mision']
		];

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

		return $resultPOST;
	}

	// Petición de Lista de Difusión OK/KO
	public function getDistributionList($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'NombreProyecto' => $client['NombreProyecto'],
			'LiderProyecto' => $client['LiderProyecto']
		];

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

		return $resultPOST;
	}

	// Creación de Lista de Difusión OK/KO
	public function createDistributionList($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$destinatarios = explode(',', $client['destinatarios']);
		$destinatariosArray = '[';
		$destinatariosCount = count($destinatarios);
		for($i = 0; $i < $destinatariosCount; $i++) {
			$destinatariosArray .= '"' . $destinatarios[$i] . '",';
		}
		$destinatariosArray = substr($destinatariosArray, 0, -1);
		$destinatariosArray .= ']';
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'admin' => $client['admin'],
			'activa' => $client['activa'],
			'description' => $client['description'],
			'destinatarios' => $destinatariosArray,
			'idProject' => $client['idProject'],
			'idMision' => $client['idMision'],
			'aux01' => $client['aux01']
		];

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

		return $resultPOST;
	}

	// Actualización de Lista de Difusión OK/KO
	public function updateDistributionList($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$destinatarios = explode(',', $client['destinatarios']);
		$destinatariosArray = '[';
		$destinatariosCount = count($destinatarios);
		for($i = 0; $i < $destinatariosCount; $i++) {
			$destinatariosArray .= '"' . $destinatarios[$i] . '",';
		}
		$destinatariosArray = substr($destinatariosArray, 0, -1);
		$destinatariosArray .= ']';
		$params = [
			'token' => $client['token'],
			'idlist' => $client['idList'],
			'admin' => $client['admin'],
			'activa' => $client['activa'],
			'description' => $client['description'],
			'destinatarios' => $destinatariosArray,
			'idProject' => $client['idProject'],
			'idMision' => $client['idMision'],
			'aux01' => $client['aux01']
		];

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

		return $resultPOST;
	}

	// Petición de datos proyecto / misión en el momento
	public function getSnapAcualMisionCumplimiento($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'project' => $client['project'],
			'idmision' => $client['idmision']
		];

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

		return $resultPOST;
	}

	// MUESTREO
	// Petición de preguntas
	public function getQuestionsSurvey($client) {
		$filter = '';
		if($client['filter'] == '1') {
			$filter = '1';
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'filter' => $filter
		];

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

		return $resultPOST;
	}

	// Petición de gráficas
	public function getAnalyticsMuestra($client) {
		$response['status'] = 'KO';
		$url = CONSTANTS::SERVERAPI . $client['action'];
		if($client['isPerf'] == 1) {
			$response['perf'] = true;
		} else {
			$response['perf'] = false;
		}
		// Añadido para Gráfica de NSE
		$numPerf = $client['param4'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'pregunta' => $client['question'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['param4'],
			'preguntaSQ' => $client['preguntaSQ'],
			'continuingMission' => $client['continuingMission']
		];

		if($client['continuingMission'] == '1') {
			$params['startDate'] = $client['startDate'];
			$params['endDate'] = $client['endDate'];
		}

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

		if($resultPOST->status === 'OK') {
			$data = $resultPOST->result->resultado;

			// Si el array de result->resultado esta vacío return $resultPOST;
			if(count($data) == 0) {
				return $resultPOST;
			}

			$isTypeM = false;
			if($data[0]->tipoPregunta == 'B') {
				$type = 'B';
				$labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
			} else if($data[0]->tipoPregunta == 'A') {
				$type = 'A';
				$labels = ['1', '2', '3', '4', '5'];
			} else {
				$url = CONSTANTS::SERVERAPI . 'getAllPosibleAnswersByQID';
				$qidArray = explode('X', $client['question']);
				$qid = array_pop($qidArray);
				if(strpos($qid, 'S')) {
					$qidArray = explode('SQ', $qid);
					$qid = $qidArray[0];
				}
				$params = [
					'token' => $client['token'],
					'qid' => $qid,
					'survey' => $client['survey'],
					'title' => $client['title'],
					'Pregunta' => $client['question']
				];

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

				$type = $resultPOST2->type;
				if($resultPOST2->status === 'OK') {
					$labels = [];
					switch($type) {
						case '|':
						case '!':
						case '7':
						case 'C':
						case 'F':
						case 'G':
						case 'L':
						case 'Y':
						case 'J':
							foreach($resultPOST2->result as $value) {
								array_push($labels, $value->answer);
							}
						break;

						case ':':
						case 'M':
							$isTypeM = true;
							foreach($resultPOST2->result as $value) {
								array_push($labels, $value->question);
							}
						break;

						case '2':
							foreach($resultPOST2->result as $value) {
								array_push($labels, $value->edad);
							}
						break;

						case 'T':
						case 'S':
							$labels = [];
						break;

						case '5':
							$labels = ['1', '2', '3', '4', '5'];
						break;

						case '3':
							$labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
						break;

						case 'Q':
							$labels = [];
						break;

						default:
							foreach($resultPOST2->result as $value) {
								array_push($labels, $value->answer);
							}
						break;
					}
				} else {
					return $resultPOST2;
				}
			}
		} else {
			return $resultPOST;
		}

		$analyticGraph = new AnalyticGraph();
		if($response['perf']) {
			$response['status'] = 'OK';
			$response['result']['resultado'] = $analyticGraph->dataFormatOptionsPerf($data, $labels, $isTypeM);
		} else {
			$response['result']['resultado'] = $analyticGraph->dataFormatOptions($data, $labels, $isTypeM, $type, $numPerf);
			$response['status'] = 'OK';
		}

		return $response;
	}

	// Petición de gráficas para muestreo dinámico
	public function getAnalyticsMuestraDinamic($client) {
		$response['status'] = 'OK';
		$response['result'] = [];

		if($client['isPerf'] == '1') {
			$response['perf'] = true;
		} else {
			$response['perf'] = false;
		}

		$size = count($client['questions']);
		for($i = 0; $i < $size; $i++) {
			$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestra';
			$params = [
				'token' => $client['token'],
				'survey' => $client['survey'],
				'pregunta' => $client['questions'][$i],
				'numPreguntasPerfilacionEnAnalyticMostreo' => $client['param4'],
				'preguntaSQ' => '',
				'continuingMission' => $client['continuingMission']
			];

			if($client['continuingMission'] == '1') {
				$params['startDate'] = $client['startDate'];
				$params['endDate'] = $client['endDate'];
			}

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

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

			$data = $resultPOST->result->resultado;

			// Si el array de result->resultado esta vacío return $resultPOST;
			if(count($data) == 0) {
				return $resultPOST;
			}

			$isTypeM = false;
			if($data[0]->tipoPregunta == 'B') {
				$type = 'B';
				$labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
			} else if($data[0]->tipoPregunta == 'A') {
				$type = 'A';
				$labels = ['1', '2', '3', '4', '5'];
			} else {
				$url = CONSTANTS::SERVERAPI . 'getAllPosibleAnswersByQID';
				$qidArray = explode('X', $client['questions'][$i]);
				$qid = array_pop($qidArray);
				if(strpos($qid, 'S')) {
					$qidArray = explode('SQ', $qid);
					$qid = $qidArray[0];
				}
				$params = [
					'token' => $client['token'],
					'qid' => $qid,
					'survey' => $client['survey'],
					'title' => $client['titles'][$i],
					'Pregunta' => $client['questions'][$i]
				];

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

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

				$type = $resultPOST2->type;
				$isTypeM = false;
				$labels = [];
				switch($type) {
					case 'M':
						$isTypeM = true;
						foreach($resultPOST2->result as $value) {
							array_push($labels, $value->question);
						}
					break;

					case '5':
						$labels = ['1', '2', '3', '4', '5'];
					break;

					case '3':
						$labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
					break;

					default:
						foreach($resultPOST2->result as $value) {
							array_push($labels, $value->answer);
						}
					break;
				}
			}

			$analyticGraph = new AnalyticGraph();
			
			// if($response['perf']) {
			// 	$result = $analyticGraph->dataFormatOptionsPerf($data, $labels, $isTypeM);
			// } else {
			// 	$result = $analyticGraph->dataFormatOptions($data, $labels, $isTypeM, $type, $client['param4']);
			// }
			
			$result = $analyticGraph->dataFormatOptions($data, $labels, $isTypeM, $type, $client['param4']);
			array_push($response['result'], $result);
		}

		return $response;
	}

	// Petición de gráficas para muestreo dinámico filtrado
	public function getAnswersSurveyByQueryDinamic($client) {
		$response['status'] = 'OK';
		$response['result'] = [];

		$url = CONSTANTS::SERVERAPI . 'getAnswersSurveyByQuery';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'whereQuery' => $client['whereQuery'],
			'maxRows' => $client['maxRows'],
			'havingQuery' => $client['havingQuery'],
			'havingQueryColumnID' => $client['havingQueryColumnID'],
			'inclusivo' => $client['inclusivo'],
			'cpgList' => $client['cpgList']
		];

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

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

		$filteredUsers = [];
		$sizeFU = count($resultPOST->result);
		for($i = 0; $i < $sizeFU; $i++) {
			array_push($filteredUsers, $resultPOST->result[$i]->token);
		}

		if($client['isPerf'] == '1') {
			$response['perf'] = true;
		} else {
			$response['perf'] = false;
		}

		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestra';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'pregunta' => $client['questions'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['param4'],
			'preguntaSQ' => '',
			'continuingMission' => $client['continuingMission']
		];

		if($client['continuingMission'] == '1') {
			$params['startDate'] = $client['startDate'];
			$params['endDate'] = $client['endDate'];
		}

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

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

		$data = [];
		$sizeAM = count($resultPOST->result->resultado);
		for($i = 0; $i < $sizeAM; $i++) {
			if(in_array($resultPOST->result->resultado[$i]->userEmail, $filteredUsers)) {
				// Control por género
				if(count($client['profilingParameters']['selectedGender']) > 0 && !in_array($resultPOST->result->resultado[$i]->perf003, $client['profilingParameters']['selectedGender'])) {
					continue;
				}

				// Control por rango de edad
				if(count($client['profilingParameters']['selectedAgeRange']) > 0 && !in_array($resultPOST->result->resultado[$i]->perf002Range, $client['profilingParameters']['selectedAgeRange'])) {
					continue;
				}

				// Control por estado
				if(count($client['profilingParameters']['selectedStates']) > 0 && !in_array($resultPOST->result->resultado[$i]->perf001, $client['profilingParameters']['selectedStates'])) {
					continue;
				}

				// Control por NSE
				if(count($client['profilingParameters']['selectedNse']) > 0 && !in_array($resultPOST->result->resultado[$i]->perf004, $client['profilingParameters']['selectedNse'])) {
					continue;
				}

				array_push($data, $resultPOST->result->resultado[$i]);
			}
		}

		// Si el array de result->resultado esta vacío return $response;
		if(count($data) == 0) {
			return $response;
		}

		$isTypeM = false;
		if($data[0]->tipoPregunta == 'B') {
			$type = 'B';
			$labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
		} else if($data[0]->tipoPregunta == 'A') {
			$type = 'A';
			$labels = ['1', '2', '3', '4', '5'];
		} else {
			$url = CONSTANTS::SERVERAPI . 'getAllPosibleAnswersByQID';
			$qidArray = explode('X', $client['questions']);
			$qid = array_pop($qidArray);
			if(strpos($qid, 'S')) {
				$qidArray = explode('SQ', $qid);
				$qid = $qidArray[0];
			}
			$params = [
				'token' => $client['token'],
				'qid' => $qid,
				'survey' => $client['survey'],
				'title' => $client['titles'],
				'Pregunta' => $client['questions']
			];

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

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

			$type = $resultPOST2->type;
			$isTypeM = false;
			$labels = [];
			switch($type) {
				case 'M':
					$isTypeM = true;
					foreach($resultPOST2->result as $value) {
						array_push($labels, $value->question);
					}
				break;

				case '5':
					$labels = ['1', '2', '3', '4', '5'];
				break;

				case '3':
					$labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
				break;

				default:
					foreach($resultPOST2->result as $value) {
						array_push($labels, $value->answer);
					}
				break;
			}
		}

		$analyticGraph = new AnalyticGraph();
		if($response['perf']) {
			$result = $analyticGraph->dataFormatOptionsPerf($data, $labels, $isTypeM);
			array_push($response['result'], $result);
		} else {
			$result = $analyticGraph->dataFormatOptions($data, $labels, $isTypeM, $type, $client['param4']);
			array_push($response['result'], $result);
		}

		return $response;
	}

	// Petición de opciones para preguntas tipo ':'
	public function getOptionsFor2PointsTypeQuetsion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'parent_qid' => $client['parent_qid']
		];

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

		return $resultPOST;
	}

	// MUESTREO DETALLADO
	public function getAnalyticsMuestraToExportByPerfQuestion($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfQuestion';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'country' => $client['country'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPreguntasPerfilacionEnAnalyticMostreo'],
			'hideopenquestions' => $client['hideopenquestions']
		];

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

		return $resultPOST;
	}

	// Petición de todas las tablas de las preguntas
	public function getAnalyticsMuestraToExportByPerf($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerf';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'country' => $client['country'],
			'pregunta' => $client['pregunta'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPreguntasPerfilacionEnAnalyticMostreo'],
			'onlyOKUsers' => $client['onlyOKUsers']
		];

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

		return $resultPOST;
	}

	// MUESTREO DETALLADO MAZ
	public function getAnalyticsMuestraToExportByPerfQuestionMAZ($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfQuestionMAZ';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// Petición de todas las tablas de las preguntas
	public function getAnalyticsMuestraToExportByPerfQuestionComaparativo($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfQuestionComaparativo';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'country' => $client['country'],
			'pregunta' => $client['pregunta']
		];

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

		return $resultPOST;
	}

	// Petición de todas las tablas de las preguntas
	public function getAnalyticsMuestraToExportByPerfComparativo($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfComparativo';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'country' => $client['country'],
			'pregunta' => $client['pregunta']
		];

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

		return $resultPOST;
	}

	// Petición de todas las tablas de las preguntas
	public function getAnalyticsMuestraToExportByPerfMAZ($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfMAZ';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'country' => $client['country'],
			'pregunta' => $client['pregunta']
		];

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

		return $resultPOST;
	}

	// MUESTREO DETALLADO MAZ SEGMENTO
	public function getAnalyticsMuestraToExportByPerfQuestionMAZSegmento($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfQuestionMAZSegmento';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'segmento' => json_encode($client['segmento'])
		];

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

		return $resultPOST;
	}

	// Petición de todas las tablas de las preguntas
	public function getAnalyticsMuestraToExportByPerfMAZSegmento($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExportByPerfMAZSegmento';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'segmento' => json_encode($client['segmento']),
			'pregunta' => $client['pregunta']
		];

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

		return $resultPOST;
	}

	// Comprobación de la integridad de las encuestas
	public function getIfSurveysAreEquals($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey']
		];

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

		return $resultPOST;
	}

	// Comprobación de la integridad de las preguntas
	public function getIfQuestionsAreEquals($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'questions' => $client['questions']
		];

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

		return $resultPOST;
	}

	// Resultado respuestas de encuesta y preguntas para calcular diferencias significativas
	public function getAnalyticsDiferenciasSignificativas($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'pregunta' => $client['pregunta']
		];

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

		return $resultPOST;
	}

	// MUESTREO COMPARATIVO
	// Petición de gráficas para comparativa
	public function getAnalyticsMuestraComparativa($client) {
		$resp = [
			'status' => 'OK',
			'result' => []
		];
		$url = CONSTANTS::SERVERAPI . $client['action'];

		$surveys = '[';
		$surveyCount = count($client['surveys']);
		for($i = 0; $i < $surveyCount; $i++) {
			$surveys .= $client['surveys'][$i] . ',';
		}
		$surveys = substr($surveys, 0, -1);
		$surveys .= ']';

		$params = [
			'token' => $client['token'],
			'surveys' => $surveys,
			'pregunta' => $client['question'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['param4']
		];

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

		if($resultPOST->status === 'OK') {
			$url = CONSTANTS::SERVERAPI . 'getAllPosibleAnswersByQID';

			$qidArray = explode('X', $client['columnName']);
			$qid = array_pop($qidArray);

			$params = [
				'token' => $client['token'],
				'qid' => $qid,
				'survey' => $client['surveys'][$surveyCount - 1],
				'title' => $client['question'],
				'Pregunta' => $client['columnName']
			];

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

			$isTypeM = false;
			if($resultPOST2->status === 'OK') {
				$labels = [];
				switch($resultPOST2->type) {
					case '!':
					case 'F':
					case 'G':
					case 'L':
					case 'Y':
						foreach($resultPOST2->result as $value) {
							array_push($labels, $value->answer);
						}
					break;

					case 'M':
						$isTypeM = true;
						foreach($resultPOST2->result as $value) {
							array_push($labels, $value->question);
						}
					break;

					case '2':
						foreach($resultPOST2->result as $value) {
							array_push($labels, $value->edad);
						}
					break;

					case 'T':
					case 'S':
					case 'Q':
						$labels = [];
					break;

					case '5':
						$array = $resultPOST2->result;
						array_multisort($array);
						foreach($array as $value) {
							array_push($labels, $value->answer);
						}
					break;

					default:
						foreach($resultPOST2->result as $value) {
							array_push($labels, $value->answer);
						}
					break;
				}
			} else {
				return $resultPOST2;
			}

			foreach ($resultPOST->result as $value) {
				$data = $value;

				if(count($data) == 0) {
					array_push($resp['result'], false);
				} else {
					$analyticGraph = new AnalyticGraph();
					array_push($resp['result'], $analyticGraph->dataFormatOptions($data, $labels, $isTypeM, $resultPOST2->type, $client['param4']));
				}
			}
			$resultPOST->result = $resp;
		} else {
			return $resultPOST;
		}
		return $resultPOST;
	}

	// CONVERSACIONES
	// Petición de Conversaciones
	public function getAnalyticsConversacion($client) {
		if($client['type'] === 'readValidate' && isset($client['idgroup'])) {
			// Nombre de grupo por id
			$url = CONSTANTS::SERVERAPI . 'getGroupJidByID';
			$params = [
				'token' => $client['token'],
				'groupId' => $client['idgroup']
			];

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

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

			$client['idgroup'] = $resultPOST->result;
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'bid' => $client['bid'],
			'idgrupo' => $client['idgroup'],
			'fechaInicio' => $client['fechaInicio'],
			'fechaFin' => $client['fechaFin'],
			'idlista' => $client['idlista']
		];

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

		if($client['type'] === 'read' || $client['type'] === 'readValidate') {
			return $resultPOST;
		} else {
			if($resultPOST->status === 'OK') {
				$user = $client['user'];
				$group = false;
				if($client['idgroup'] != '') {
					$group = true;
				}
				$result = $this->getAllAttachedConversation($resultPOST->result, $user, $group);
				$resultPOST->result = $result;
				return $resultPOST;
			} else {
				return $resultPOST;
			}
		}
	}

	// Petición de todos los adjuntos de una Conversación
	public function getAllAttachedConversation($result, $user, $group) {
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/';
		if(!file_exists($folder)) {
			$createFile = $this->utilesController->createDirectory($folder);

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

		$zip = new ZipArchive();
		$zip->open($folder . 'attachment.zip', ZipArchive::CREATE);
		$zip->addEmptyDir('attachment');

		$size = count($result);
		for($i = 0; $i < $size; $i++) {
			if($result[$i]->attachmentName != '') {
				// Nombre de emisor
				$name = str_replace(' ', '_', $result[$i]->nameUser);
				$surname = str_replace(' ', '_', $result[$i]->userApellidos);
				$surname2 = str_replace(' ', '_', $result[$i]->userApellidos2);
				$folderName = $name;
				if($surname != '') {
					$folderName .= '_' . $surname;
				}
				if($surname2 != '') {
					$folderName .= '_' . $surname2;
				}
				if($folderName == '') {
					$folderName = 'issuing';
				}
				// Emisor
				$issuing = explode('@', $result[$i]->jid);
				$issuingR = $issuing[0];
				// ZIP
				$zip->addEmptyDir('attachment/' . $folderName);
				$fileType = explode('/', $result[$i]->attachmentType);
				$type = $fileType[0];
				switch($type) {
					case 'image':
						$url = CONSTANTS::ATTACHMENTS . 'imagenes/';
						break;
					case 'video':
						$url = CONSTANTS::ATTACHMENTS . 'video/';
						break;
					case 'audio':
						$url = CONSTANTS::ATTACHMENTS . 'audio/';
						break;
					case 'application':
						$url = CONSTANTS::ATTACHMENTS . 'docs/';
						break;
				}
				$dateTime = explode(' ', $result[$i]->stampServer);
				$year = substr($dateTime[0], 0, 4);
				$month = substr($dateTime[0], 5, 2);
				$day = substr($dateTime[0], 8, 2);

				// Receptor
				$receiving = explode('@', $result[$i]->bid);
				$receivingUser = $receiving[0];

				// En caso de grupo
				if($group) {
					$issuingR = $receivingUser;
				}

				// URL
				$url .= $year . '/' . $month . '/' . $day . '/' . $issuingR . '/';

				// Nombre del archivo
				$attachmentName = trim($result[$i]->attachmentName, '"');
				if($result[$i]->attachmentType == 'video/quicktime') {
					$fileLastDot = strrpos($attachmentName, '.');
					$attachmentName = substr($attachmentName, 0, $fileLastDot);
					$attachmentName .= '.mp4';
				}

				$url .= $result[$i]->stamp . $receivingUser . $attachmentName;
				file_put_contents($folder . $attachmentName, file_get_contents($url));
				$zip->addFile($folder . $attachmentName, 'attachment/' . $folderName . '/' . $attachmentName);
			}
		}
		$zip->close();
		return $user . '/attachment.zip';
	}

	// Petición de adjunto de Conversaciones
	public function getAttachedConversation($client) {
		$url = $client['url'];
		$file = $client['file'];
		$user = $client['user'];
		$date = date_create();
		$serverUrl = '/' . $user . '/' . date_timestamp_get($date) . $file;

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

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

		file_put_contents($filepath, file_get_contents($url));
		$response['file'] = $serverUrl;

		return $response;
	}

	// INVERSIÓN
	// Petición de Inversión
	public function getAnalyticsInversion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'project' => $client['project'],
			'rangoDesde' => $client['rangoDesde'],
			'rangoHasta' => $client['rangoHasta']
		];

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

		return $resultPOST;
	}

	// CATALOGACIÓN ASESORES
	// Petición de catalogación de consejeros
	public function getCatalogacionesConsejeros($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// LICENCIAS
	public function getStatusLicencesDetail($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'control' => $client['control']
		];

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

		return $resultPOST;
	}

	// PERFILACIÓN SIN FINALIZAR
	// Petición de Lista de consejeros sin perfilación
	public function getAnalyticsConsejerosNoFinPerf($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// CDP
	// Petición de Lista de CDP - Usuarios
	public function getDataIntegrationCDP($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

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

		if($client['noLimited'] == '1') {
			// Exportar a excel
			$dataRows = $resultPOST->dataintegration_cdp;
			if(count($dataRows) != '0') {
				$cabeceras = '';
				if($client['gdpr'] == '0') {
					$cabeceras .= 'abi_first_name';
					$cabeceras .= ',abi_last_name';
					$cabeceras .= ',abi_last_name2,';
				}
				$cabeceras .= 'zone';
				$cabeceras .= ',country';
				$cabeceras .= ',abi_brand';
				$cabeceras .= ',abi_email';
				$cabeceras .= ',abi_dateofbirth';
				$cabeceras .= ',abi_gender';
				$cabeceras .= ',abi_phone';
				$cabeceras .= ',abi_address';
				$cabeceras .= ',abi_number';
				$cabeceras .= ',abi_complement';
				$cabeceras .= ',abi_zipcode';
				$cabeceras .= ',abi_neighborhood';
				$cabeceras .= ',abi_city';
				$cabeceras .= ',abi_country';
				$cabeceras .= ',abi_marketingactivation';
				$cabeceras .= ',abi_tcpp';
				$cabeceras .= ',creationDate';
				$cabeceras .= ',abi_consent_date';
				$cabeceras .= ',abi_campaign';

				$date = date_create();
				$stamp = date_timestamp_get($date);
				$timeStamp = $stamp * 1000;

				$generateTableExcel = new GenerateTableExcel();
				$filename = $generateTableExcel->printExcelFromResultOrdered($dataRows, $cabeceras, $timeStamp, true); // $dataraw == true
				if($filename == 'The folder has not been created') {
					$resultPOST = [
						'status' => 'KO',
						'result' => 'The folder has not been created'
					];
				} else {
					$filename = str_replace(CONSTANTS::PATH_EXPORT_WORD . '/', '', $filename);
					$resultPOST = [
						'status' => 'OK',
						'result' => $filename
					];
				}
			} else {
				$resultPOST = ['result' => 'OK'];
				return $resultPOST;
			}
		}

		return $resultPOST;
	}

	// Petición de Lista de CDP - Encuestas
	public function getAnalyticsMuestraToExport_CDP($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPreguntasPerfilacionEnAnalyticMostreo'],
			'survey' => $client['survey']
		];

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

		if($client['noLimited'] == '1') {
			// Exportar a excel
			$dataRows = $resultPOST->result;
			if(count($dataRows) != '0') {
				$cabeceras = '';
				if($client['gdpr'] == '0') {
					$cabeceras .= 'abi_first_name';
					$cabeceras .= ',abi_last_name,';
				}
				$cabeceras .= 'abi_dateofbirth';
				$cabeceras .= ',abi_email';
				$cabeceras .= ',abi_phone';
				$cabeceras .= ',abi_gender';
				$cabeceras .= ',abi_question';
				$cabeceras .= ',abi_response';

				$date = date_create();
				$stamp = date_timestamp_get($date);
				$timeStamp = $stamp * 1000;

				$generateTableExcel = new GenerateTableExcel();

				$filename = $generateTableExcel->printExcelFromResultOrderedNew($dataRows, $cabeceras, $timeStamp);
				if($filename == 'The folder has not been created') {
					$resultPOST = [
						'status' => 'KO',
						'result' => $filename
					];
				} else {
					$filename = str_replace(CONSTANTS::PATH_EXPORT_WORD . '/', '', $filename);
					$resultPOST = [
						'status' => 'OK',
						'result' => $filename
					];
				}
			} else {
				$resultPOST = ['result' => 'OK'];
				return $resultPOST;
			}
		}

		return $resultPOST;
	}

	// Ejecutar y actualizar CDP - Encuestas
	public function sendCDPData($client) {
		$resultPOST = [
			'status' => 'OK',
			'result' => 'OK'
		];

		foreach($client['dataSurvey'] as $dataSurvey) {
			if($dataSurvey['abi_sended_on'] == '') {
				// URL
				$url = $client['abi_country_endpoint'];

				// Datos
				$datos = [
					'abi_dateofbirth' => $dataSurvey['abi_dateofbirth'],
					'abi_email' => $dataSurvey['abi_email'],
					'abi_phone' => $dataSurvey['abi_phone'],
					'abi_first_name' => $dataSurvey['abi_first_name'],
					'abi_last_name' => $dataSurvey['abi_last_name'],
					'abi_gender' => $dataSurvey['abi_gender'],
					'abi_survey_id' => $client['abi_survey_id'],
					'abi_survey_title' => $client['abi_survey_title'],
					'abi_question' => $dataSurvey['abi_question'],
					'abi_response' => $dataSurvey['abi_response'],
					'abi_earned_points' => $client['abi_earned_points'],
					'abi_program_name' => $client['abi_program_name']
				];

				// Crear opciones de la petición HTTP
				$opciones = [
					'http' => [
						'header' => "Content-type: application/json\r\n" . 'X-TD-Write-Key: ' . $client['cdp_endpoint_KEY'] . "\r\n",
						'method' => 'POST',
						'content' => json_encode($datos)
					],
				];

				// Preparar petición
				$contexto = stream_context_create($opciones);

				// Hacerla
				$resultado = file_get_contents($url, false, $contexto);
				if($resultado === false) {
					$resultPOST = $this->utilesController->setCMBPLOG($client['token'], 'ENDPOINT', 'sendCDPData', $dataSurvey['abi_email'], '', '1');
					return $resultPOST;
				}

				// Registro
				$url = CONSTANTS::SERVERAPI . 'setCDPPostLog';
				$params = [
					'token' => $client['token'],
					'email' => $dataSurvey['abi_email'],
					'sid' => $client['abi_survey_id'],
					'qid' => $dataSurvey['abi_question_id']
				];

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

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

		return $resultPOST;
	}

	// Ejecutar y actualizar CDP - Usuarios
	public function sendCDPDataUsers($client) {
		$resultPOST = [
			'status' => 'OK',
			'result' => 'OK'
		];

		foreach($client['dataUsers'] as $dataUsers) {
			if($dataUsers['abi_sended_on'] == '') {
				// URL
				$url = $dataUsers['abi_country_endpoint'];

				// Datos
				$datos = [
					'abi_email' => $dataUsers['abi_email'],
					'abi_phone' => $dataUsers['abi_phone'],
					'abi_first_name' => $dataUsers['abi_first_name'],
					'abi_last_name' => $dataUsers['abi_last_name'],
					'abi_gender' => $dataUsers['abi_gender'],
					'abi_zone' => $dataUsers['abi_zone'],
					'abi_country' => $dataUsers['abi_country'],
					'abi_state' => $dataUsers['abi_state'],
					'abi_city' => $dataUsers['abi_city'],
					'abi_brand' => $dataUsers['abi_brand'],
					'abi_form' => $dataUsers['abi_form'],
					'abi_campaign' => $dataUsers['abi_campaign'],
					'td_client_id' => $dataUsers['td_client_id'],
					'td_url' => $dataUsers['td_url'],
					'td_host' => $dataUsers['td_host'],
					'td_import_method' => $dataUsers['td_import_method'],
					'abi_tcpp' => $dataUsers['abi_tcpp'],
					'purpose_name' => $dataUsers['purpose_name']
				];

				// Crear opciones de la petición HTTP
				$opciones = [
					'http' => [
						'header' => "Content-type: application/json\r\n" . 'X-TD-Write-Key: ' . $client['cdp_endpoint_KEY'] . "\r\n",
						'method' => 'POST',
						'content' => json_encode($datos)
					],
				];

				// Preparar petición
				$contexto = stream_context_create($opciones);

				// Hacerla
				$resultado = file_get_contents($url, false, $contexto);

				if($resultado === false) {
					$resultPOST = $this->utilesController->setCMBPLOG($client['token'], 'ENDPOINT', 'sendCDPDataUsers', $dataUsers['abi_email'], '', '1');
					return $resultPOST;
				}

				// Registro
				$url = CONSTANTS::SERVERAPI . 'setCDPPostUserLog';
				$params = [
					'token' => $client['token'],
					'email' => $dataUsers['abi_email']
				];

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

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

		return $resultPOST;
	}

	// CUBOS DINÁMICOS
	// Petición de todos las tablas por esquema
	public function getAllSchemaTables($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'schema' => $client['schema']
		];

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

		return $resultPOST;
	}

	// Petición de todos los campos de tabla por esquema
	public function getAllSchemaTablesFields($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'schema' => $client['schema'],
			'table_name' => $client['table_name']
		];

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

		return $resultPOST;
	}

	// Crear cubo
	public function setBI($client, $intern) {
		if($intern === false) {
			$url = CONSTANTS::SERVERAPI . $client['action'];
		} else {
			$url = CONSTANTS::SERVERAPI . 'setBI';
		}

		if($client['table_name'] != '[]') {
			$table_name = json_encode($client['table_name']);
		} else {
			$table_name = $client['table_name'];
		}

		if($client['field_name'] != '[]') {
			$field_name = json_encode($client['field_name']);
		} else {
			$field_name = $client['field_name'];
		}

		if($client['bi_relations'] != '[]') {
			$bi_relations = json_encode($client['bi_relations']);
		} else {
			$bi_relations = $client['bi_relations'];
		}

		if($client['bi_filters'] != '[]') {
			$bi_filters = json_encode($client['bi_filters']);
		} else {
			$bi_filters = $client['bi_filters'];
		}

		$params = [
			'token' => $client['token'],
			'name' => $client['name'],
			'description' => $client['description'],
			'country' => $client['country'],
			'sp_initial' => $client['sp_initial'],
			'table_name' => $table_name,
			'field_name' => $field_name,
			'bi_relations' => $bi_relations,
			'bi_filters' => $bi_filters,
			'limitRows' => $client['limitRows']
		];

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

		return $resultPOST;
	}

	// Eliminar cubo
	public function deleteBI($client, $intern) {
		if($intern === false) {
			$url = CONSTANTS::SERVERAPI . $client['action'];

			if($client['cubes'] != '[]') {
				foreach($client['cubes'] as $cube) {
					$params = [
						'token' => $client['token'],
						'id' => $cube['id']
					];

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

					if($resultPOST->status != 'OK') {
						return $resultPOST;
					}
				}
			} else {
				$resultPOST = ['status' => 'OK'];
			}
		} else {
			$url = CONSTANTS::SERVERAPI . 'deleteBI';
			$params = [
				'token' => $client['token'],
				'id' => $client['id']
			];

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Definir filtros
	public function setBIFiltros($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$valueArray = [];
		foreach($client['values'] as $value) {
			$val = $value['table_name'] . '#' . $value['field_name'] . '#' . $value['value'] . '#' . $value['order'];
			array_push($valueArray, $val);
		}

		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'value' => json_encode($valueArray)
		];

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

		return $resultPOST;
	}

	// Consultar store procedure
	public function getBI_SP_Execution($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id']
		];

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

		return $resultPOST;
	}

	// Ejecutar cubo por id
	public function getBIExecution($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id']
		];

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

		if($client['toExport'] == 'true' && $resultPOST->status == 'OK') {
			$filename = $this->generateTableExcel->printExcel($resultPOST->result, $client['cabeceras'], $client['parametros'], $client['nameExcel']);

			if(!$filename) {
				$resultPOST = [
					'status' => 'KO',
					'result' => 'Excel error'
				];
			} else {
				$resultPOST = [
					'status' => 'OK',
					'result' => $filename
				];
			}

			return $resultPOST;
		} else {
			return $resultPOST;
		}
	}

	// PASSIVE TRACKING
	// Petición de passive tracking
	public function getAnalyticsPassiveTrackingExport($client) {
		$url = CONSTANTS::SERVERAPI . $client['actionExport'];
		$params = [
			'token' => $client['token'],
			'fechaInicio' => $client['fechaInicio'],
			'fechaFin' => $client['fechaFin'],
			'country' => $client['country']
		];

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

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

		if($client['toExport'] == 'true') {
			$filename = $this->generateTableExcel->printExcelPassiveTracking($resultPOST->result, $client['cabeceras'], $client['parametros'], $client['nameExcel'], $client['bExcel'], $client['bPPT'], $client['graphs'], $client['idTenant']);

			if(!$filename) {
				$resultPOST = [
					'status' => 'KO',
					'result' => 'Excel error'
				];
			} else {
				$resultPOST = [
					'status' => 'OK',
					'result' => $filename
				];
			}

			return $resultPOST;
		} else {
			return $resultPOST;
		}
	}

	public function getAnalyticsPassiveTracking($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		if($client['toExport'] == 'true') $url = CONSTANTS::SERVERAPI . $client['actionExport'];
		$params = [
			'token' => $client['token'],
			'fechaInicio' => $client['fechaInicio'],
			'fechaFin' => $client['fechaFin'],
			'country' => $client['country']
		];

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

		$response['age'] = [];
		$response['age']['datasets'] = [];
		$response['age']['datasets']['data'] = [];
		$response['age']['datasets']['background'] = '#6c4675';
		$response['age']['labels'] = [];

		$response['gender'] = [];
		$response['gender']['datasets'] = [];
		$response['gender']['datasets']['data'] = [];
		$response['gender']['datasets']['background'] = ['#FF0000', '#0000FF'];
		$response['gender']['labels'] = [];

		$response['states'] = [];
		$response['states']['datasets'] = [];
		$response['states']['datasets']['data'] = [];
		$response['states']['datasets']['background'] = '#6c4675';
		$response['states']['labels'] = [];

		$response['nse'] = [];
		$response['nse']['datasets'] = [];
		$response['nse']['datasets']['data'] = [];
		$response['nse']['datasets']['background'] = '#6c4675';
		$response['nse']['labels'] = [];

		$ageArray = [];
		$genderArray = [];
		$statesArray = [];
		$nseArray = [];
		$estados = [];

		foreach($resultPOST->result as $userData) {
			array_push($ageArray, $userData->questionEdad);
			array_push($genderArray, $userData->questionGenero);
			array_push($statesArray, $userData->questionEstado);
			array_push($nseArray, $userData->questionABI);

			$country = $userData -> questionPais;
			$estado = $userData -> questionEstado;
			array_push($estados, [$country, $estado]);
		}

		$ageArray = array_count_values($ageArray);
		$genderArray = array_count_values($genderArray);
		$statesArray = array_count_values($statesArray);
		$nseArray = array_count_values($nseArray);

		// Edad
		foreach($ageArray as $appObj) {
			array_push($response['age']['datasets']['data'], $appObj);
		}

		foreach(array_keys($ageArray) as $appObj) {
			array_push($response['age']['labels'], $appObj);
		}
		array_multisort($response['age']['datasets']['data'], SORT_DESC, $response['age']['labels']);

		// Género
		foreach($genderArray as $appObj) {
			array_push($response['gender']['datasets']['data'], $appObj);
		}

		foreach(array_keys($genderArray) as $appObj) {
			array_push($response['gender']['labels'], $appObj);
		}
		array_multisort($response['gender']['datasets']['data'], SORT_DESC, $response['gender']['labels']);

		// Estados
		foreach($statesArray as $appObj) {
			array_push($response['states']['datasets']['data'], $appObj);
		}

		foreach(array_keys($statesArray) as $appObj) {
			array_push($response['states']['labels'], $appObj);
		}
		array_multisort($response['states']['datasets']['data'], SORT_DESC, $response['states']['labels']);

		// NSE
		foreach($nseArray as $appObj) {
			array_push($response['nse']['datasets']['data'], $appObj);
		}

		foreach(array_keys($nseArray) as $appObj) {
			array_push($response['nse']['labels'], $appObj);
		}
		array_multisort($response['nse']['datasets']['data'], SORT_DESC, $response['nse']['labels']);

		// Edad
		$total = array_sum($response['age']['datasets']['data']);
		for($i=0; $i < count($response['age']['datasets']['data']); $i++) {
			$response['age']['datasets']['data'][$i] = number_format(($response['age']['datasets']['data'][$i] * 100) / $total, 1);
		}

		// Género
		$total = array_sum($response['gender']['datasets']['data']);
		for($i=0; $i < count($response['gender']['datasets']['data']); $i++) {
			$response['gender']['datasets']['data'][$i] = number_format(($response['gender']['datasets']['data'][$i] * 100) / $total, 1);
		}

		// Estados
		$total = array_sum($response['states']['datasets']['data']);
		for($i=0; $i < count($response['states']['datasets']['data']); $i++) {
			$response['states']['datasets']['data'][$i] = number_format(($response['states']['datasets']['data'][$i] * 100) / $total, 1);
		}

		// NSE
		$total = array_sum($response['nse']['datasets']['data']);
		for($i=0; $i < count($response['nse']['datasets']['data']); $i++) {
			$response['nse']['datasets']['data'][$i] = number_format(($response['nse']['datasets']['data'][$i] * 100) / $total, 1);
		}

		// FORMATOS
		$response['age']['type'] = 'bar';
		$response['gender']['type'] = 'pie';
		$response['states']['type'] = 'bar';
		$response['nse']['type'] = 'pie';
		$response['mapData'] = $estados;

		// OPCIONES
		$optionsPie = '{
			"layout": {
				"padding": {
					"top": -26
				}
			},
			"responsive": true,
			"maintainAspectRatio": false,
			"legend": {
				"position": "right",
				"onClick": false
			},
			"title": {
				"display": false,
				"text": "",
				"fontSize": 16
			}
		}';

		$optionsBar = '{
			"layout": {
				"padding": {
					"top": -26
				}
			},
			"responsive": true,
			"maintainAspectRatio": false,
			"legend": {
				"display": false,
				"onClick": false
			},
			"scales": {
				"xAxes": [{
					"ticks": {
						"display": true,
						"autoSkip": false
					}
				}],
				"yAxes": [{
					"display": false,
					"ticks": {
						"fontSize": 14,
						"beginAtZero": true
					}
				}]
			},
			"title": {
				"display": false,
				"text": "",
				"fontSize": 16
			}
		}';

		$response['age']['options'] = $optionsBar;
		$response['gender']['options'] = $optionsPie;
		$response['states']['options'] = $optionsBar;
		$response['nse']['options'] = $optionsPie;

		$resultPOST->graphs = $response;

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

		if($client['toExport'] == 'true') {
			$filename = $this->generateTableExcel->printExcelPassiveTracking($resultPOST->result, $client['cabeceras'], $client['parametros'], $client['nameExcel'], $client['bExcel'], $client['bPPT'], $client['graphs'], $client['idTenant']);

			if(!$filename) {
				$resultPOST = [
					'status' => 'KO',
					'result' => 'Excel error'
				];
			} else {
				$resultPOST = [
					'status' => 'OK',
					'result' => $filename
				];
			}

			return $resultPOST;
		} else {
			return $resultPOST;
		}
	}

	public function getAnalyticsPassiveTrackingDetails($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'fechaInicio' => $client['fechaInicio'],
			'fechaFin' => $client['fechaFin'],
			'country' => $client['country'],
			'email' => $client['email'],
			'type' => $client['type']
		];

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

		return $resultPOST;
	}

	// Gráficas Muestreo en Analytic Passive Tracking
	public function getPassiveTrackingGraphs($client) {
		$url = CONSTANTS::SERVERAPI . 'getAnalyticsPassiveTrackingGraphs';
		$params = [
			'token' => $client['token'],
			'fechaInicio' => $client['fechaInicio'],
			'fechaFin' => $client['fechaFin'],
			'country' => $client['country']
		];

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

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

		$result = $resultPOST->result;

		$response['apps'] = [];
		$response['apps']['datasets'] = [];
		$response['apps']['datasets']['data'] = [];
		$response['apps']['datasets']['background'] = '#6c4675';
		$response['apps']['labels'] = [];

		$response['devices'] = [];
		$response['devices']['datasets'] = [];
		$response['devices']['datasets']['data'] = [];
		$response['devices']['datasets']['background'] = '#6c4675';
		$response['devices']['labels'] = [];

		$response['network'] = [];
		$response['network']['datasets'] = [];
		$response['network']['datasets']['data'] = [];
		$response['network']['datasets']['background'] = '#6c4675';
		$response['network']['labels'] = [];

		$appsArray = [];
		$devicesArray = [];
		$networkArray = [];

		foreach($result as $userData) {
			foreach($userData->apps as $apps) {
				array_push($appsArray, $apps->appName);
			}
			foreach($userData->network as $network) {
				array_push($networkArray, $network->type);
			}
			// No contar el mismo dispositivo varias veces
			$devicesArrayAux = [];
			foreach($userData->device as $device) {
				array_push($devicesArrayAux, $device->manufacturer);
			}
			$devicesArrayAux = array_unique($devicesArrayAux);
			$devicesArray = array_merge($devicesArray, $devicesArrayAux);
		}

		$appsArray = array_count_values($appsArray);
		$devicesArray = array_count_values($devicesArray);
		$networkArray = array_count_values($networkArray);

		foreach($appsArray as $key => $value) {
			array_push($response['apps']['datasets']['data'], $value);
			array_push($response['apps']['labels'], $key);
		}
		array_multisort($response['apps']['datasets']['data'], SORT_DESC, $response['apps']['labels']);

		$response['apps']['datasets']['data'] = array_slice($response['apps']['datasets']['data'], 0, 10);
		$response['apps']['labels'] = array_slice($response['apps']['labels'], 0, 10);

		// Dispositivos
		foreach($devicesArray as $appObj) {
			array_push($response['devices']['datasets']['data'], $appObj);
		}

		foreach(array_keys($devicesArray) as $appObj) {
			array_push($response['devices']['labels'], $appObj);
		}
		array_multisort($response['devices']['datasets']['data'], SORT_DESC, $response['devices']['labels']);

		// Redes
		foreach($networkArray as $appObj) {
			array_push($response['network']['datasets']['data'], $appObj);
		}

		foreach(array_keys($networkArray) as $appObj) {
			array_push($response['network']['labels'], $appObj);
		}
		array_multisort($response['network']['datasets']['data'], SORT_DESC, $response['network']['labels']);

		// Pasar a porcentaje
		// Dispositivos
		$total = array_sum($response['devices']['datasets']['data']);
		for($i=0; $i < count($response['devices']['datasets']['data']); $i++) {
			$response['devices']['datasets']['data'][$i] = number_format(($response['devices']['datasets']['data'][$i] * 100) / $total, 1);
		}

		// Network
		$total = array_sum($response['network']['datasets']['data']);
		for($i=0; $i < count($response['network']['datasets']['data']); $i++) {
			$response['network']['datasets']['data'][$i] = number_format(($response['network']['datasets']['data'][$i] * 100) / $total, 1);
		}

		// FORMATOS
		$response['apps']['type'] = 'bar';
		$response['devices']['type'] = 'bar';
		$response['network']['type'] = 'pie';

		// OPCIONES
		$optionsPie = '{
			"layout": {
				"padding": {
					"top": -26
				}
			},
			"responsive": true,
			"maintainAspectRatio": false,
			"legend": {
				"position": "right",
				"onClick": false
			},
			"title": {
				"display": false,
				"text": "",
				"fontSize": 16
			}
		}';

		$optionsBar = '{
			"layout": {
				"padding": {
					"top": -26
				}
			},
			"responsive": true,
			"maintainAspectRatio": false,
			"legend": {
				"display": false,
				"onClick": false
			},
			"scales": {
				"xAxes": [{
					"ticks": {
						"display": true,
						"autoSkip": false
					}
				}],
				"yAxes": [{
					"display": false,
					"ticks": {
						"fontSize": 14,
						"beginAtZero": true
					}
				}]
			},
			"title": {
				"display": false,
				"text": "",
				"fontSize": 16
			}
		}';

		$response['apps']['options'] = $optionsBar;
		$response['devices']['options'] = $optionsBar;
		$response['network']['options'] = $optionsPie;
		$response['status'] = 'OK';

		return $response;
	}

	// STORES
	// Petición de información de stores
	public function getAppInfoStore($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'locale' => $client['locale'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// KPI SURVEYS
	// Petición de KPI surveys
	public function getAnalyticsKPIS($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'stampMision' => $client['stampMision'],
			'survey' => $client['survey'],
			'red_herringControl' => $client['red_herringControl'],
			'red_herringControlValue' => $client['red_herringControlValue'],
			'speedingMarginPercent' => $client['speedingMarginPercent'],
			'numFlatliningControl' => $client['numFlatliningControl']
		];

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

		return $resultPOST;
	}

	// Devuelve los tiempos de respuesta de las preguntas de una encuesta
	public function getSurveyQuestionTimings($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idSurvey' => $client['idSurvey'],
			'questions' => json_encode($client['questions']),
			'users' => json_encode($client['users']),
		];

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

		return $resultPOST;
	}

	// Devuelve los tiempos de respuesta de los usuarios de una encuesta
	public function getSurveyUserTimings($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idSurvey' => $client['idSurvey'],
			'questions' => json_encode($client['questions']),
			'users' => json_encode($client['users']),
		];

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

		return $resultPOST;
	}

	// PLANTILLAS REPORTES
	// Eliminar plantilla/s para reportes
	public function deletePlantillaReportes($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['plantillas'] != '[]') {
			foreach($client['plantillas'] as $plantilla) {
				$params = [
					'token' => $client['token'],
					'id' => $plantilla['id']
				];

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

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

				// Borrado de carpeta con las imágenes
				$folderName = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/' . $plantilla['id'] . '/*';
				$files = glob($folderName);
				foreach($files as $file) {
					if(is_file($file)) {
						unlink($file);
					}
				}
				rmdir(CONSTANTS::PATH_EXPORT_WORD . '/report_templates/' . $plantilla['id']);
			}
		} else {
			$resultPOST = ['status' => 'OK'];
		}

		return $resultPOST;
	}

	// Crear plantilla para reportes
	public function setPlantillaReportes($client) {
		// Datos de tamaño máximo de archivo
		$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;

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'nombre' => $client['nombre'],
			'descripcion' => $client['descripcion'],
			'tipoFuente' => $client['tipoFuente'],
			'tamanoFuente' => $client['tamanoFuente'],
			'rangoColores' => $client['rangoColores'],
			'colorInicio' => $client['colorInicio'],
			'colorFinal' => $client['colorFinal'],
			'coloresComponenRango' => $client['coloresComponenRango'],
			'plantilla' => $client['plantillaURL'],
			'plantillaPortada' => $client['plantillaPortadaURL'],
			'logo' => $client['logoURL'],
			'colorTituloPortada' => $client['colorTituloPortada'],
			'colorTitulo' => $client['colorTitulo'],
			'answersOrder' => $client['answersOrder'],
			// Valores de tipo de gráfica
			'type3' => $client['type3'],
			'type4' => $client['type4'],
			'type5' => $client['type5'],
			'typeINTERROGANTE' => $client['typeINTERROGANTE'],
			'typeL' => $client['typeL'],
			'typeO' => $client['typeO'],
			'typeY' => $client['typeY'],
			'typeM' => $client['typeM'],
			'idCPG' => $client['idCPG']
		];

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

		$idPlantilla = $resultPOST->idPlantilla;

		// Creación de carpeta
		$folderSave = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/' . $idPlantilla . '/';

		if(!file_exists($folderSave)) {
			$createFile = $this->utilesController->createDirectory($folderSave);

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

				return $response;
			}
		}

		// Recibir imagenes
		$files = [
			'plantilla' => 'plantilla.PNG',
			'plantillaPortada' => 'plantilla_portada.PNG',
			'logo' => 'logo_rep.PNG'
		];

		foreach($files as $key => $new_name) {
			$file = $_FILES[$key];

			if($file === NULL || $file['size'] > $maxSize) {
				// imagen por defecto
				$origin = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/' . $new_name;
				$destiny = $folderSave . $new_name;

				copy($origin, $destiny);
			} else {
				move_uploaded_file($file['tmp_name'], $folderSave . '/' . $new_name);
			}
		}

		// Actualización de la plantilla de reporte con la dirección de las imágenes definitiva
		$url = CONSTANTS::SERVERAPI . 'updatePlantillaReportes';
		$params = [
			'token' => $client['token'],
			'id' => $idPlantilla,
			'nombre' => $client['nombre'],
			'descripcion' => $client['descripcion'],
			'tipoFuente' => $client['tipoFuente'],
			'tamanoFuente' => $client['tamanoFuente'],
			'rangoColores' => $client['rangoColores'],
			'colorInicio' => $client['colorInicio'],
			'colorFinal' => $client['colorFinal'],
			'coloresComponenRango' => $client['coloresComponenRango'],
			'plantilla' => 'report_templates/' . $idPlantilla . '/plantilla.PNG',
			'plantillaPortada' => 'report_templates/' . $idPlantilla . '/plantilla_portada.PNG',
			'logo' => 'report_templates/' . $idPlantilla . '/logo_rep.PNG',
			'colorTituloPortada' => $client['colorTituloPortada'],
			'colorTitulo' => $client['colorTitulo'],
			'answersOrder' => $client['answersOrder'],
			// Valores de tipo de gráfica
			'type3' => $client['type3'],
			'type4' => $client['type4'],
			'type5' => $client['type5'],
			'typeINTERROGANTE' => $client['typeINTERROGANTE'],
			'typeL' => $client['typeL'],
			'typeO' => $client['typeO'],
			'typeY' => $client['typeY'],
			'typeM' => $client['typeM']
		];

		if ($client['idCPG'] != null) $params['idCPG'] = $client['idCPG'];

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

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Editar plantilla para reportes
	public function updatePlantillaReportes($client) {
		// Datos de tamaño máximo de archivo
		$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;

		// Carpeta de plantilla
		$folderSave = CONSTANTS::PATH_EXPORT_WORD . '/report_templates/' . $client['id'] . '/';

		// Recibir imagenes
		$files = [
			'plantilla' => 'plantilla.PNG',
			'plantillaPortada' => 'plantilla_portada.PNG',
			'logo' => 'logo_rep.PNG'
		];

		foreach($files as $key => $new_name) {
			$file = $_FILES[$key];

			if($file === NULL || $file['size'] > $maxSize) {
				continue;
			} else {
				move_uploaded_file($file['tmp_name'], $folderSave . '/' . $new_name);
			}
		}

		// Actualización de la plantilla de reporte
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'nombre' => $client['nombre'],
			'descripcion' => $client['descripcion'],
			'tipoFuente' => $client['tipoFuente'],
			'tamanoFuente' => $client['tamanoFuente'],
			'rangoColores' => $client['rangoColores'],
			'colorInicio' => $client['colorInicio'],
			'colorFinal' => $client['colorFinal'],
			'coloresComponenRango' => $client['coloresComponenRango'],
			'plantilla' => 'report_templates/' . $client['id'] . '/plantilla.PNG',
			'plantillaPortada' => 'report_templates/' . $client['id'] . '/plantilla_portada.PNG',
			'logo' => 'report_templates/' . $client['id'] . '/logo_rep.PNG',
			'colorTituloPortada' => $client['colorTituloPortada'],
			'colorTitulo' => $client['colorTitulo'],
			'answersOrder' => $client['answersOrder'],
			// Valores de tipo de gráfica
			'type3' => $client['type3'],
			'type4' => $client['type4'],
			'type5' => $client['type5'],
			'typeINTERROGANTE' => $client['typeINTERROGANTE'],
			'typeL' => $client['typeL'],
			'typeO' => $client['typeO'],
			'typeY' => $client['typeY'],
			'typeM' => $client['typeM']
		];

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

		return $resultPOST;
	}

	// Marcar plantilla por defecto
	public function setPlantillaReportesDefault($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id']
		];

		if ($client['idCPG'] != null) $params['idCPG'] = $client['idCPG'];

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

		return $resultPOST;
	}

	// Upload custom font
	public function setReportCustomFont($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;

		$url = CONSTANTS::SERVERAPI . $client['action'];

		if ($_FILES['file']['size'] <= $maxSize) {
			// Creación de carpeta de usuario
			$filepath = CONSTANTS::PATH_EXPORT_WORD . '/customfonts/';
			if (!file_exists($filepath)) {
				$createFile = $this->utilesController->createDirectory($filepath);

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

			// Mover imagen a carpeta de usuario
			if (!move_uploaded_file($_FILES['file']['tmp_name'], $filepath . '/' . $_FILES['file']['name'])) {
				$response['status'] = 'KO';
				return $response;
			}
		}
		else {
			$response['status'] = 'KO';
			$response['result'] = 'File size is bigger than system file max size';
			return $response;
		}

		//call to WS to add custom font to tables
		$url = CONSTANTS::SERVERAPI . 'setTemplateReportCustomFont';
		$params = [
			'token' => $client['token'],
			'fontName' => explode('.', $_FILES['file']['name'])[0],
			'fontFile' => $_FILES['file']['name']
		];

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

	// get custom font list
	public function getTemplateReportCustomFont($client)
	{
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

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

		return $resultPOST;
	}
}