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

class ProyectosController {
	private $utilesController;
	private $misionesController;
	private $notificacionesController;
	private $rotacionesController;

	function __construct() {
		$this->utilesController = new UtilesController();
		$this->misionesController = new MisionesController();
		$this->notificacionesController = new NotificacionesController();
		$this->rotacionesController = new RotacionesController();
	}

	public function requestProject($client, $idProject = null) {
		if($idProject === null) {
			$id = $client['id'] ?? '';
		} else {
			$id = $idProject;
		}

		$url = CONSTANTS::SERVERAPI . 'getCMBPProjects';
		$params = [
			'token' => $client['token'],
			'id' => $id
		];

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

		return $resultPOST;
	}

	// Petición de objetivos de encuestas de perfilación
	public function getTargetsSurvey($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey']
		];

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

		return $resultPOST;
	}

	// Petición de valores de pregunta de encuesta de perfilación
	public function getTargetsSurveyByQID($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'qid' => $client['qid']
		];

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

		return $resultPOST;
	}

	// Creación de proyecto
	public function insertCMBPProjects($client) {
		$date = new DateTime();
		$id = $date->format('YnjHisv');
		$projectFiles = [];

		// Subida de archivos si los hay
		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;

			// Ruta del documento
			$documentPathDir = CONSTANTS::PATH_EXPORT_WORD . '/projects/' . $id;

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

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

			$control = 0;
			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);

				// Lista de extensiones permitidas
				$safeList = ['avi', 'gif', 'jpg', 'jpeg', 'mpeg', 'pdf', 'wav', 'weba', 'webm', 'png', 'mp3', 'mov', 'mp4', 'bmp', 'xlsx', 'csv', 'pptx', 'docx'];
				$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;
				}

				$fileData = $documentPathDir . '#' . $newname . '#' . $_FILES[$key]['size'] . '#' . $client['filesToUploadInfo'][$control]['descripcion'];
				array_push($projectFiles, $fileData);
				$control++;
			}
		}

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

		if((isset($client['producto_proyecto']) && $client['producto_proyecto'] == '1') || (isset($client['proyectoSBS']) && $client['proyectoSBS'] == '1')) {
			$params = [
				'token' => $client['token'],
				'id' => $id,
				'country' => $client['country'],
				'NombreProyecto' => $client['NombreProyecto'],
				'LiderProyecto' => $client['LiderProyecto'],
				'Resultados' => $client['Resultados'],
				'ChatGrupal' => $client['ChatGrupal'],
				'FechaProyecto' => $client['FechaProyecto'],
				'LiderProyectoEmail' => $client['LiderProyectoEmail'],
				'ListaDistribucion' => $client['ListaDistribucion'],
				'notificarInclusion' => $client['notificarInclusion'],
				'applicantName' => $client['applicantName'],
				'brandsInvolved' => $client['brandsInvolved'],
				'projectDescription' => $client['projectDescription'],
				'background' => $client['background'],
				'businessObjective' => $client['businessObjective'],
				'investigationObjective' => $client['investigationObjective'],
				'actionStandard' => $client['actionStandard'],
				'favorableResults' => $client['favorableResults'],
				'notFavorableResults' => $client['notFavorableResults'],
				'admin' => $client['admin'],
				'projectFiles' => json_encode($projectFiles),
				'cpgList' => $client['cpgList'],
				'proyectoReparticion' => '0',
				'targetTotalPanel' => '0'
			];
		} else {
			$params = [
				'token' => $client['token'],
				'id' => $id,
				'country' => $client['country'],
				'sidPerfilacion' => (implode(',', $client['sidPerfilacion']) === NULL ? '' : implode(',', $client['sidPerfilacion'])),
				'NombreProyecto' => $client['NombreProyecto'],
				'LiderProyecto' => $client['LiderProyecto'],
				'ClienteInterno' => $client['ClienteInterno'],
				'ObjetivoProyecto' => $client['ObjetivoProyecto'],
				'DecisionATomar' => $client['DecisionATomar'],
				'Resultados' => $client['Resultados'],
				'ChatIndividual' => $client['ChatIndividual'],
				'ChatGrupal' => $client['ChatGrupal'],
				'VideoIndividual' => $client['VideoIndividual'],
				'VideoGrupal' => $client['VideoGrupal'],
				'FechaProyecto' => $client['FechaProyecto'],
				'LiderProyectoEmail' => $client['LiderProyectoEmail'],
				'ListaDistribucion' => $client['ListaDistribucion'],
				'IdPerfilacion' => (implode(',', $client['IdPerfilacionDesc']) === NULL ? '' : implode(',', $client['IdPerfilacionDesc'])),
				'IdPerfilacionDesc' => (implode(',', $client['IdPerfilacionDesc']) === NULL ? '' : implode(',', $client['IdPerfilacionDesc'])),
				'notificarInclusion' => $client['notificarInclusion'],
				'sidRelations' => $client['sidRelations'],
				'inclusivo' => $client['inclusivo'],
				'useSegmentation' => $client['useSegmentation'],
				'sidRelationsSegmentation' => (implode(',', $client['sidRelationsSegmentation']) === NULL ? '' : implode(',', $client['sidRelationsSegmentation'])),
				'IdSegmentacion' => (implode(',', $client['IdSegmentacion']) === NULL ? '' : implode(',', $client['IdSegmentacion'])),
				'IdSegmentacionDesc' => (implode(',', $client['IdSegmentacionDesc']) === NULL ? '' : implode(',', $client['IdSegmentacionDesc'])),
				'applicantName' => $client['applicantName'],
				'brandsInvolved' => $client['brandsInvolved'],
				'projectDescription' => $client['projectDescription'],
				'background' => $client['background'],
				'businessObjective' => $client['businessObjective'],
				'investigationObjective' => $client['investigationObjective'],
				'actionStandard' => $client['actionStandard'],
				'favorableResults' => $client['favorableResults'],
				'notFavorableResults' => $client['notFavorableResults'],
				'admin' => $client['admin'],
				'projectFiles' => json_encode($projectFiles),
				'cpgList' => $client['cpgList'],
				'proyectoReparticion' => $client['proyectoReparticion'],
				'targetTotalPanel' => $client['targetTotalPanel']
			];
		}

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

		if($resultPOST->status == 'OK') {
			// Creado a partir de producto
			if(isset($client['producto_proyecto']) && $client['producto_proyecto'] == '1') {
				$resultPOST->result = $id;
				return $resultPOST;
			} else if($client['useSegmentation'] == '0' && $client['targetTotalPanel'] == '0') {
				// Encuestas
				$resultPOST = $this->SaveCMBPProjectsTargets($client, $id, false);
				if($resultPOST->status == 'OK') {
					$resultPOST->result = $id;
					return $resultPOST;
				} else {
					return $resultPOST;
				}
			} else if($client['useSegmentation'] == '1' && $client['targetTotalPanel'] == '0') {
				// Segmentaciones
				$resultPOST = $this->setCMBPProjectsTargetsSegmentation($client, $id, false);
				if($resultPOST->status == 'OK') {
					$resultPOST->result = $id;
					return $resultPOST;
				} else {
					return $resultPOST;
				}
			} else if($client['targetTotalPanel'] == '1') {
				// Todos los usuarios
				$resultPOST->result = $id;
				return $resultPOST;
			}
		} else {
			return $resultPOST;
		}
	}

	// Guardar objetivos de proyecto para encuestas
	public function SaveCMBPProjectsTargets($client, $id, $update) {
		$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsTargets';

		foreach($client['targetsSurvey'] as $targetsSurvey) {
			$k = 0;
			$launch = 100;
			// $projectsTargetsArray: ["order#columname#value#valuecode"]
			$size = count($targetsSurvey);
			$projectsTargetsArray = '[';
			for($i = 0; $i < $size; $i++) {
				if($targetsSurvey[$i]['type'] == 'T') {
					//
				} else if($targetsSurvey[$i]['type'] != 'K') {
					$value = implode(',', $targetsSurvey[$i]['value']);
					$code = implode(',', $targetsSurvey[$i]['code']);
					$string = $k . '#' . $targetsSurvey[$i]['columnName'] . '#' . strval($value) . '#' . strval($code);
					$projectsTargetsArray .= '"' . $string . '",';
					$k++;
				} else {
					$sizeK = count($targetsSurvey[$i]['valuesSQ']);
					for($j = 0; $j < $sizeK; $j++) {
						$columnNameKArray = explode('|', $targetsSurvey[$i]['valuesSQ'][$j]);
						$columnNameK = $columnNameKArray[0];
						$value = implode(',', $targetsSurvey[$i]['value'][$columnNameK]);
						$code = implode(',', $targetsSurvey[$i]['code'][$columnNameK]);
						$string = $k . '#' . $columnNameK . '#' . $value . '#' . $code;
						$projectsTargetsArray .= '"' . $string . '",';
						$k++;
					}
				}

				// Envío cada 100
				if($k >= $launch) {
					$projectsTargetsArray = substr($projectsTargetsArray, 0, -1);
					$projectsTargetsArray .= ']';

					$params = [
						'token' => $client['token'],
						'id' => $id,
						'projectsTargetsArray' => $projectsTargetsArray
					];

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

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

					$projectsTargetsArray = '[';
					$launch += 100;
				}
			}

			if($projectsTargetsArray != '[') {
				$projectsTargetsArray = substr($projectsTargetsArray, 0, -1);
			}
			$projectsTargetsArray .= ']';

			if($projectsTargetsArray != '[]') {
				$params = [
					'token' => $client['token'],
					'id' => $id,
					'projectsTargetsArray' => $projectsTargetsArray
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}
			} else if(!$update && $k < 100) {
				$resultPOST = [
					'status' => 'OK',
					'result' => $id
				];
			}
		}

		if($update) {
			// Eliminar misiones de proyecto
			$resultPOST = $this->deleteCMBPProjectsMisiones($client, $id);
		}

		return $resultPOST;
	}

	// Guardar objetivos de proyecto para segmentaciones
	public function setCMBPProjectsTargetsSegmentation($client, $id, $update) {
		$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsTargetsSegmentation';
		// $projectsTargetsArray: ["order#idSegmentation#nameSegmentation#nameSegment#enabled"]
		$params = [
			'token' => $client['token'],
			'id' => $id,
			'projectsTargetsArray' => json_encode($client['segSegmentations'])
		];

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

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

		if($update) {
			// Eliminar misiones de proyecto
			$resultPOST = $this->deleteCMBPProjectsMisiones($client, $id);
		}

		return $resultPOST;
	}

	// Eliminar misiones de proyecto
	public function deleteCMBPProjectsMisiones($client, $id) {
		$url = CONSTANTS::SERVERAPI . 'deleteCMBPProjectsMisiones';
		$params = [
			'token' => $client['token'],
			'id' => $id
		];

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

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

		// Guardar misiones de proyecto
		$resultPOST = $this->SaveCMBPProjectsMisiones($client, $id);
		return $resultPOST;
	}

	// Guardar misiones de proyecto
	public function SaveCMBPProjectsMisiones($client, $id) {
		if($client['projectMissions'] != '[]') {
			$size = count($client['projectMissions']);
			for($i = 0; $i < $size; $i++) {
				$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisiones';
				$params = [
					'token' => $client['token'],
					'id' => $id,
					'mision' => $client['projectMissions'][$i]['idmision'],
					'missionStamp' => $client['projectMissions'][$i]['stampMision'],
					'Descripcion' => $client['projectMissions'][$i]['descripcion'],
					'fechahorainicio' => $client['projectMissions'][$i]['fechahorainicio'],
					'fechahorafin' => $client['projectMissions'][$i]['fechahorafin'],
					'importe' => $client['projectMissions'][$i]['importe'],
					'inicionotificado' => $client['projectMissions'][$i]['inicionotificado'],
					'finnotificado' => $client['projectMissions'][$i]['finnotificado']
				];

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

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

			return $resultPOST;
		} else {
			$resultPOST = [
				'status' => 'OK',
				'result' => 'Projects Misions added'
			];
			return $resultPOST;
		}
	}

	// Validación para la creación de proyecto
	public function spAddFieldsPerf($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

	// Petición de misiones de proyecto
	public function getCMBPProjectsMisiones($client, $token, $idProyect) {
		if(isset($token)) {
			$url = CONSTANTS::SERVERAPI . 'getCMBPProjectsMisiones';
		} else {
			$url = CONSTANTS::SERVERAPI . $client['action'];
			$token = $client['token'];
			$idProyect = $client['id'];
		}

		$params = [
			'token' => $token,
			'id' => $idProyect
		];

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Petición de participantes de proyecto con comprobación de ejecución
	public function getCMBPProjectsParticipantesValidacion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'sid' => $client['sid'],
			'mision' => $client['mision'],
			'fechahorainicio' => $client['fechahorainicio'],
			'fechahorafin' => $client['fechahorafin']
		];

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

		return $resultPOST;
	}

	// Petición de valores/códigos previos de encuesta de perfilación/proyecto
	public function getCMBPProjectsTargets($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'sidPerfilacion' => $client['sidPerfilacion']
		];

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

		return $resultPOST;
	}

	// Petición de segmentos previos de segmentaciones
	public function getCMBPProjectsTargetsSegmentation($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'sidRelationsSegmentation' => $client['sidRelationsSegmentation']
		];

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

		return $resultPOST;
	}

	// Expulsión de participante
	public function deleteCMBPProjectsParticipantes($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$participant = '["' . $client['participants'] . '"]';
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'participants' => $participant,
			'motivoExclusion' => $client['motivoExclusion']
		];

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

		// Notificación de expulsión
		if($resultPOST->status == 'OK') {
			$dataMsg = [
				'message' => $client['message'],
				'from' => $client['from'],
				'emailsToSend' => $participant,
				'idlist' => ''
			];

			$resultPOST = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);
		}

		return $resultPOST;
	}

	// Edición de proyecto
	public function updateCMBPProjects($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if((isset($client['producto_proyecto']) && $client['producto_proyecto'] == '1') || (isset($client['proyectoSBS']) && $client['proyectoSBS'] == '1')) {
			$params = [
				'token' => $client['token'],
				'id' => $client['id'],
				'country' => $client['country'],
				'NombreProyecto' => $client['NombreProyecto'],
				'LiderProyecto' => $client['LiderProyecto'],
				'Resultados' => $client['Resultados'],
				'ChatGrupal' => $client['ChatGrupal'],
				'FechaProyecto' => $client['FechaProyecto'],
				'LiderProyectoEmail' => $client['LiderProyectoEmail'],
				'ListaDistribucion' => $client['ListaDistribucion'],
				'notificarInclusion' => $client['notificarInclusion'],
				'applicantName' => $client['applicantName'],
				'brandsInvolved' => $client['brandsInvolved'],
				'projectDescription' => $client['projectDescription'],
				'background' => $client['background'],
				'businessObjective' => $client['businessObjective'],
				'investigationObjective' => $client['investigationObjective'],
				'actionStandard' => $client['actionStandard'],
				'favorableResults' => $client['favorableResults'],
				'notFavorableResults' => $client['notFavorableResults'],
				'admin' => $client['admin'],
				'cpgList' => $client['cpgList'],
				'targetTotalPanel' => '0'
			];
		} else {
			$params = [
				'token' => $client['token'],
				'id' => $client['id'],
				'country' => $client['country'],
				'sidPerfilacion' => (implode(',', $client['sidPerfilacion']) === NULL ? '' : implode(',', $client['sidPerfilacion'])),
				'NombreProyecto' => $client['NombreProyecto'],
				'LiderProyecto' => $client['LiderProyecto'],
				'ClienteInterno' => $client['ClienteInterno'],
				'ObjetivoProyecto' => $client['ObjetivoProyecto'],
				'DecisionATomar' => $client['DecisionATomar'],
				'Resultados' => $client['Resultados'],
				'ChatIndividual' => $client['ChatIndividual'],
				'ChatGrupal' => $client['ChatGrupal'],
				'VideoIndividual' => $client['VideoIndividual'],
				'VideoGrupal' => $client['VideoGrupal'],
				'FechaProyecto' => $client['FechaProyecto'],
				'LiderProyectoEmail' => $client['LiderProyectoEmail'],
				'ListaDistribucion' => $client['ListaDistribucion'],
				'IdPerfilacion' => (implode(',', $client['IdPerfilacionDesc']) === NULL ? '' : implode(',', $client['IdPerfilacionDesc'])),
				'IdPerfilacionDesc' => (implode(',', $client['IdPerfilacionDesc']) === NULL ? '' : implode(',', $client['IdPerfilacionDesc'])),
				'notificarInclusion' => $client['notificarInclusion'],
				'sidRelations' => $client['sidRelations'],
				'inclusivo' => $client['inclusivo'],
				'useSegmentation' => $client['useSegmentation'],
				'sidRelationsSegmentation' => (implode(',', $client['sidRelationsSegmentation']) === NULL ? '' : implode(',', $client['sidRelationsSegmentation'])),
				'IdSegmentacion' => (implode(',', $client['IdSegmentacion']) === NULL ? '' : implode(',', $client['IdSegmentacion'])),
				'IdSegmentacionDesc' => (implode(',', $client['IdSegmentacionDesc']) === NULL ? '' : implode(',', $client['IdSegmentacionDesc'])),
				'applicantName' => $client['applicantName'],
				'brandsInvolved' => $client['brandsInvolved'],
				'projectDescription' => $client['projectDescription'],
				'background' => $client['background'],
				'businessObjective' => $client['businessObjective'],
				'investigationObjective' => $client['investigationObjective'],
				'actionStandard' => $client['actionStandard'],
				'favorableResults' => $client['favorableResults'],
				'notFavorableResults' => $client['notFavorableResults'],
				'cpgList' => $client['cpgList'],
				'targetTotalPanel' => $client['targetTotalPanel']
			];
		}

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

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

		if($resultPOST->status == 'OK') {
			// Editado a partir de producto
			if((isset($client['producto_proyecto']) && $client['producto_proyecto'] == '1') || (isset($client['proyectoSBS']) && $client['proyectoSBS'] == '1')) {
				return $resultPOST;
			} else {
				// Revisar asignación de cupo para misiones / proyecto
				if($client['modifiedQuota'] !== 'false' && $client['quotaElementsArrayMissions'] !== '[]') {
					$project = $client['id'];
					$quotaElementsArrayMissions = $client['quotaElementsArrayMissions'];

					// Iteración por misiones
					$sizeA = count($quotaElementsArrayMissions);
					for($i = 0; $i < $sizeA; $i++) {
						$stampMision = $quotaElementsArrayMissions[$i][0]['stampMision'];
						$survey = $quotaElementsArrayMissions[$i][0]['surveys'];
						$quotaElement = '[';

						// Iteración por segmentos
						$sizeB = count($quotaElementsArrayMissions[$i]);
						for($j = 0; $j < $sizeB; $j++) {
							// Si el segmento no tiene valor asignado, se continua la iteración
							if($quotaElementsArrayMissions[$i][$j]['value'] == '0') {
								continue;
							}

							// ID de segmento
							$segment = $quotaElementsArrayMissions[$i][$j]['idSegmento'];
							$segmentValue = $quotaElementsArrayMissions[$i][$j]['value'];
							$genderArray = [];
							$ageArray = [];
							$nseArray = [];
							$regionArray = [];
							$maxLength = 0;

							// Primer hijo 'género'
							$gender = $quotaElementsArrayMissions[$i][$j]['childs'][0]['childs'];
							$sizeGender = count($gender);
							for($g = 0; $g < $sizeGender; $g++) {
								if($gender[$g]['value'] == '0') {
									continue;
								} else {
									$array = [
										'name' => $gender[$g]['name'],
										'value' => $gender[$g]['value']
									];
									array_push($genderArray, $array);
								}
							}
							if(count($genderArray) > $maxLength) {
								$maxLength = count($genderArray);
							}

							// Segundo hijo 'edad'
							$age = $quotaElementsArrayMissions[$i][$j]['childs'][1]['childs'];
							$sizeAge = count($age);
							for($g = 0; $g < $sizeAge; $g++) {
								if($age[$g]['value'] == '0') {
									continue;
								} else {
									$array = [
										'name' => $age[$g]['name'],
										'value' => $age[$g]['value']
									];
									array_push($ageArray, $array);
								}
							}
							if(count($ageArray) > $maxLength) {
								$maxLength = count($ageArray);
							}

							// Tercer hijo 'NSE'
							$nse = $quotaElementsArrayMissions[$i][$j]['childs'][2]['childs'];
							$sizeNse = count($nse);
							for($g = 0; $g < $sizeNse; $g++) {
								if($nse[$g]['value'] == '0') {
									continue;
								} else {
									$array = [
										'name' => $nse[$g]['name'],
										'value' => $nse[$g]['value']
									];
									array_push($nseArray, $array);
								}
							}
							if(count($nseArray) > $maxLength) {
								$maxLength = count($nseArray);
							}

							// Cuarto hijo 'región'
							$region = $quotaElementsArrayMissions[$i][$j]['childs'][3]['childs'];
							$sizeRegion = count($region);
							for($g = 0; $g < $sizeRegion; $g++) {
								if($region[$g]['value'] == '0') {
									continue;
								} else {
									$array = [
										'name' => $region[$g]['name'],
										'value' => $region[$g]['value']
									];
									array_push($regionArray, $array);
								}
							}
							if(count($regionArray) > $maxLength) {
								$maxLength = count($regionArray);
							}

							$genderSize = count($genderArray);
							$ageSize = count($ageArray);
							$nseSize = count($nseArray);
							$regionSize = count($regionArray);

							// Revisión de valores de género
							if($genderSize > 0) {
								for($g = 0; $g < $genderSize; $g++) {
									$quotaGender = '"' . $segment . '#' . $segmentValue . '#' . $genderArray[$g]['name'] . '#' . $genderArray[$g]['value'] . '#';

									// Revisión de valores de edad
									if($ageSize > 0) {
										for($a = 0; $a < $ageSize; $a++) {
											$quotaAge = $quotaGender . $ageArray[$a]['name'] . '#' . $ageArray[$a]['value'] . '#';

											// Revisión de valiores de NSE
											if($nseSize > 0) {
												for($n = 0; $n < $nseSize; $n++) {
													$quotaNse = $quotaAge . $nseArray[$n]['name'] . '#' . $nseArray[$n]['value'] . '#';

													// Revisión de valores de región
													if($regionSize > 0) {
														for($r = 0; $r < $regionSize; $r++) {
															$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
														}
													} else {
														$quotaElement .= $quotaNse . '##",';
													}
												}
											} else {
												$quotaNse = $quotaAge . '##';

												// Revisión de valores de región
												if($regionSize > 0) {
													for($r = 0; $r < $regionSize; $r++) {
														$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
													}
												} else {
													$quotaElement .= $quotaNse . '##",';
												}
											}
										}
									} else {
										$quotaAge = $quotaGender . '##';

										// Revisión de valores de NSE
										if($nseSize > 0) {
											for($n = 0; $n < $nseSize; $n++) {
												$quotaNse = $quotaAge . $nseArray[$n]['name'] . '#' . $nseArray[$n]['value'] . '#';

												// Revisión de valores de región
												if($regionSize > 0) {
													for($r = 0; $r < $regionSize; $r++) {
														$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
													}
												} else {
													$quotaElement .= $quotaNse . '##",';
												}
											}
										} else {
											$quotaNse = $quotaAge . '##';

											// Revisión de valores de región
											if($regionSize > 0) {
												for($r = 0; $r < $regionSize; $r++) {
													$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
												}
											} else {
												$quotaElement .= $quotaNse . '##",';
											}
										}
									}
								}
							} else {
								$quotaGender = '"' . $segment . '#' . $segmentValue . '###';

								// Revisión de valores de edad
								if($ageSize > 0) {
									for($a = 0; $a < $ageSize; $a++) {
										$quotaAge = $quotaGender . $ageArray[$a]['name'] . '#' . $ageArray[$a]['value'] . '#';

										// Revisión de valores de NSE
										if($nseSize > 0) {
											for($n = 0; $n < $nseSize; $n++) {
												$quotaNse = $quotaAge . $nseArray[$n]['name'] . '#' . $nseArray[$n]['value'] . '#';

												// Revisión de valores de región
												if($regionSize > 0) {
													for($r = 0; $r < $regionSize; $r++) {
														$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
													}
												} else {
													$quotaElement .= $quotaNse . '##",';
												}
											}
										} else {
											$quotaNse = $quotaAge . '##';

											// Revisión de valores de región
											if($regionSize > 0) {
												for($r = 0; $r < $regionSize; $r++) {
													$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
												}
											} else {
												$quotaElement .= $quotaNse . '##",';
											}
										}
									}
								} else {
									$quotaAge = $quotaGender . '##';

									// Revisión de valores de NSE
									if($nseSize > 0) {
										for($n = 0; $n < $nseSize; $n++) {
											$quotaNse = $quotaAge . $nseArray[$n]['name'] . '#' . $nseArray[$n]['value'] . '#';

											// Revisión de valores de región
											if($regionSize > 0) {
												for($r = 0; $r < $regionSize; $r++) {
													$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
												}
											} else {
												$quotaElement .= $quotaNse . '##",';
											}
										}
									} else {
										$quotaNse = $quotaAge . '##';

										// Revisión de valores de región
										if($regionSize > 0) {
											for($r = 0; $r < $regionSize; $r++) {
												$quotaElement .= $quotaNse . $regionArray[$r]['name'] . '#' . $regionArray[$r]['value'] . '#",';
											}
										} else {
											$quotaElement .= $quotaNse . '##",';
										}
									}
								}
							}
						}

						$quotaElement = substr($quotaElement, 0, -1);
						$quotaElement .= ']';

						$urlQuota = CONSTANTS::SERVERAPI . 'setDesgloseCuposMision';
						$paramsQuota = [
							'token' => $client['token'],
							'project' => $project,
							'stampMision' => $stampMision,
							'survey' => $survey,
							'valuesDesglose' => $quotaElement
						];

						$resultPOSTQuota = $this->utilesController->sendCurlPOST($urlQuota, $paramsQuota);

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

				// Eliminar objetivos de proyecto
				// Encuestas
				$resultPOSTdelSur = $this->deleteCMBPProjectsTargets($client, $client['id']);
				// Segmentaciones
				$resultPOSTdelSeg = $this->deleteCMBPProjectsTargetsSegmentation($client, $client['id']);

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

	// Eliminar objetivos de proyecto para encuestas
	public function deleteCMBPProjectsTargets($client, $id) {
		$url = CONSTANTS::SERVERAPI . 'deleteCMBPProjectsTargets';
		$params = [
			'token' => $client['token'],
			'id' => $id
		];

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

		if($resultPOST->status != 'OK') {
			return $resultPOST;
		} else {
			// Guardar objetivos de proyecto
			if($client['useSegmentation'] == '0') {
				$resultPOST = $this->SaveCMBPProjectsTargets($client, $id, true);
			}
		}

		return $resultPOST;
	}

	// Eliminar objetivos de proyecto para segmentaciones
	public function deleteCMBPProjectsTargetsSegmentation($client, $id) {
		$url = CONSTANTS::SERVERAPI . 'deleteCMBPProjectsTargetsSegmentation';
		$params = [
			'token' => $client['token'],
			'id' => $id
		];

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

		if($resultPOST->status != 'OK') {
			return $resultPOST;
		} else {
			// Guardar objetivos de proyecto
			if($client['useSegmentation'] == '1') {
				$resultPOST = $this->setCMBPProjectsTargetsSegmentation($client, $id, true);
			}
		}

		return $resultPOST;
	}

	// Petición de grabación de video llamadas de proyecto
	public function getFilesRecordedByProject($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idProject' => $client['idProject']
		];

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

		return $resultPOST;
	}

	// Petición de respuestas/participantes de encuesta filtrados
	public function getAnswersSurveyByQuery($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$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);

		return $resultPOST;
	}

	// Petición de respuestas/participantes de segmentación filtrados
	public function getAnswersSurveyByQuerySegmentation($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'segmentation' => $client['segmentation'],
			'whereQuery' => $client['whereQuery'],
			'maxRows' => $client['maxRows'],
			'inclusivo' => $client['inclusivo'],
			'values' => $client['values'],
			'cpgList' => $client['cpgList']
		];

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

		return $resultPOST;
	}

	// Ejecución de metodologías en resultados
	public function executeMethodologiesOnResults($client) {
		// String de participantes
		$participantsString = '[';

		$participantsCount = count($client['participants']);
		for($i = 0; $i < $participantsCount; $i++) {
			$participantsString .= '"' . $client['participants'][$i][0] . '",';
		}
		$participantsString = substr($participantsString, 0, -1);
		$participantsString .= ']';

		// Guardado de participantes de proyecto
		$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsParticipantes';
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'participants' => $participantsString
		];

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

		// Si se han guardado bien los participantes
		if($resultPOST->status == 'OK') {
			$resultPOST = [
				'status' => 'OK'
			];

			if($client['values'] !== '[]') {
				// asignación de rotaciones
				$resultPOST = $this->rotacionesController->setUserRotacion($client);
				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}
			}

			// Si el proyecto tiene Lista de difusión
			if($client['diffusionList'] == 1) {
				// Si la Lista de difusión no tiene ID
				$IDListDistribution = $client['ListaDistribucionID'];
				if($client['ListaDistribucionID'] == '') {
					// Creación de lista de difusión nueva con el ID del proyecto
					$resultPOST = $this->createDistributionListProject($client, $participantsString, $client['id']);

					// Si se crea la Lista de difusión
					if($resultPOST->status == 'OK') {
						// Recogida de la Lista de difusión creada
						$url = CONSTANTS::SERVERAPI . 'getDistributionListByIdProject';
						$params = [
							'token' => $client['token'],
							'idProject' => $client['id']
						];

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

						// Se se recibe la Lista de difusión
						if($resultPOST->status == 'OK') {
							$arrayObjects = $resultPOST->result;
							$size = count($arrayObjects);
							// Por cada elemento de la Lista de difusión
							for($i = 0; $i < $size; $i++) {
								$iIDListaDistribucionProyecto = $arrayObjects[$i]->id;
								$IDListDistribution = $iIDListaDistribucionProyecto;
								// Si el elemento tiene un ID de Lista de difusión
								if($iIDListaDistribucionProyecto != '') {
									// Actualización del ID del elemento de la Lista de difusión
									$url = CONSTANTS::SERVERAPI . 'updateCMBPProjectsListaDistribucionID';
									$params = [
										'token' => $client['token'],
										'id' => $client['id'],
										'ListaDistribucionID' => $iIDListaDistribucionProyecto
									];

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

									// Si el elemento ha sido actualizado
									if($resultPOST->status == 'OK') {
										// Si no se trata de un chat individual
										if($client['individualChat'] == 0) {
											$resultPOST = $this->getCMBPProjectsMisionesNotificaciones($client['token'], 'Alta1A1', $client['id']);

											if($resultPOST->status == 'OK') {
												$arrayNotified = $resultPOST->result;
												$Notified = [];
												$sizeNoti = count($arrayNotified);
												for($j = 0; $j < $sizeNoti; $j++) {
													array_push($Notified, $arrayNotified[$j]->idUser);
												}

												$paramsNotified = '[';
												$sizePart = count($client['participants']);
												for($l = 0; $l < $sizePart; $l++) {
													if(!in_array($client['participants'][$l][0], $Notified)) {
														$paramsNotified .= '"' . $client['participants'][$l][0] . '",';
													}
												}
												$paramsNotified = substr($paramsNotified, 0, -1);
												$paramsNotified .= ']';

												if($paramsNotified != ']') {
													$message = $client['greeting'] . ' ' . $client['description'];
													$dataMsg = [
														'message' => $message,
														'from' => $client['admin'],
														'emailsToSend' => $paramsNotified,
														'idlist' => ''
													];

													// Envío de notificación si está activada la opción
													if($client['notificarInclusion'] == '1') {
														$resultPOST = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);
													}

													$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisionesNotificaciones';
													$params = [
														'token' => $client['token'],
														'project' => $client['id'],
														'idmision' => 'Alta1A1',
														'users' => $paramsNotified
													];

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

													if($resultPOST->status != 'OK') {
														return $resultPOST;
													} else {
														break;
													}
												}
											} else {
												return $resultPOST;
											}
										}
									} else {
										return $resultPOST;
									}
								}
							}
						} else {
							return $resultPOST;
						}
					} else {
						return $resultPOST;
					}
				} else {
					// Saludo para nuevo miembro
					$resultPOST = $this->getCMBPProjectsMisionesNotificaciones($client['token'], 'Alta1A1', $client['id']);

					if($resultPOST->status == 'OK') {
						// Participantes que ya han recibido el saludo
						$arrayNotified = $resultPOST->result;
						$Notified = [];
						$sizeNoti = count($arrayNotified);
						for($j = 0; $j < $sizeNoti; $j++) {
							array_push($Notified, $arrayNotified[$j]->idUser);
						}

						// Array de participantes que no han recibido el saludo
						$emailsNotified = '[';
						$paramsNotified = '[';
						$sizePart = count($client['participants']);
						for($l = 0; $l < $sizePart; $l++) {
							if(!in_array($client['participants'][$l][0], $Notified)) {
								$paramsNotified .= '"' . $client['participants'][$l][0] . '",';
								$emailsNotified .= '"' . $client['participants'][$l][1] . '",';
							}
						}
						$paramsNotified = substr($paramsNotified, 0, -1);
						$paramsNotified .= ']';
						$emailsNotified = substr($emailsNotified, 0, -1);
						$emailsNotified .= ']';
						if($paramsNotified != ']') {
							$message = $client['greeting'] . ' ' . $client['description'];
							$dataMsg = [
								'message' => $message,
								'from' => $client['admin'],
								'emailsToSend' => $paramsNotified,
								'idlist' => '',
								'idProject' => $client['id']
							];

							// Envío de notificación si está activada la opción
							if($client['notificarInclusion'] == '1') {
								$resultPOST = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);
							}

							// Registro de usuarios que han sido saludados
							$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisionesNotificaciones';
							$params = [
								'token' => $client['token'],
								'project' => $client['id'],
								'idmision' => 'Alta1A1',
								'users' => $paramsNotified
							];

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

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

							// Misiones de proyecto
							$resultPOST = $this->getCMBPProjectsMisiones($client, $client['token'], $client['id']);

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

							if(count($resultPOST->result) > 0) {
								// Búsqueda de misiones en proceso
								date_default_timezone_set(date_default_timezone_get());
								$now = strtotime(date('d-m-Y H:i:00', time()));
								$activeMissions = [];

								$size = count($resultPOST->result);
								for($i = 0; $i < $size; $i++) {
									$start = str_replace('/', '-', $resultPOST->result[$i]->fechahorainicio);
									$startTime = strtotime($start);
									$end = str_replace('/', '-', $resultPOST->result[$i]->fechahorafin);
									$endTime = strtotime($end);

									if($now > $startTime && $now < $endTime) {
										array_push($activeMissions, $resultPOST->result[$i]->idmision);
									}
								}

								// Busqueda de datos de misión si hay misiones en proceso
								if(count($activeMissions) > 0) {
									$resultPOST = $this->misionesController->getAllMisiones($client, $client['token']);

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

									$size = count($resultPOST->result);
									for($i = 0; $i < $size; $i++) {
										if(in_array($resultPOST->result[$i]->idmision, $activeMissions)) {
											$activeMission = $resultPOST->result[$i];

											$dataMsg = [
												'token' => $client['token'],
												'from' => $client['admin'],
												'emailsToSend' => $paramsNotified,
												'message' => $activeMission->textoiniciomision,
												'idlist' => '',
												'silent' => ($activeMission->isSurvey == '1' ? '1' : '0'),
												'misionStamp' => $activeMission->stampMision,
												'idProject' => $client['id'],
												'initMision' => '1',
												'finMision' => '0',
												'isMision' => '0',
												'cumplidaMision' => '0',
												'noCumplidaMision' => '0',
												'cupoMision' => '0',
												'validationMision' => '0'
											];
											if($activeMission->isPassiveTracking != '1') {
												$url = CONSTANTS::SERVERAPI . 'postMessageMultiple';

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

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

											// setCMBPProjectsMisionesNotificaciones
											$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisionesNotificaciones';
											$textIDMision = $activeMission->idmision . ';#;init';
											$params = [
												'token' => $client['token'],
												'project' => $client['id'],
												'idmision' => $textIDMision,
												'users' => $paramsNotified
											];

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

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

											// postSurvey
											if($activeMission->isSurvey == '1') {
												$url = CONSTANTS::SERVERAPI . 'postSurvey';
												$params = [
													'token' => $client['token'],
													'from' => $client['admin'],
													'emailsToSend' => $paramsNotified,
													'message' => $activeMission->sid,
													'idlist' => '',
													'misionStamp' => $activeMission->stampMision,
													'idProject' => $client['id'],
													'isMision' => '1'
												];

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

												if($resultPOST->status != 'OK') {
													return $resultPOST;
												}
											}
											// post question if passivetracking
											if($activeMission->isPassiveTracking == '1') {
												// postquestion
												$var = explode('@', $client['admin']);
												$username = $var[0];
												$data = [
													'from' => $client['admin'],
													'emailsToSend' => $paramsNotified,
													'message' => $activeMission->textoiniciomision,
													'idlist' => ''
												];
												$questionResult =$this->notificacionesController->PostQuestionMultiple($client, $data, $client['token']);
												if($questionResult->status != 'OK') {
													return $questionResult;
												}
											}
										}
									}
								}
							}
						}
					} else {
						return $resultPOST;
					}

					// Añadir usuarios a la Lista de difusión
					$url = CONSTANTS::SERVERAPI . 'addUserToDistributionList';
					$params = [
						'token' => $client['token'],
						'idlist' => $client['ListaDistribucionID'],
						'destinatarios' => $participantsString
					];

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

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

			// Misiones de proyecto
			$resultPOST = $this->getCMBPProjectsMisiones($client, $client['token'], $client['id']);

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

			// Comprobación de misiones con recordatorio
			foreach($resultPOST->result as $missionRec) {
				$url = CONSTANTS::SERVERAPI . 'getMisionRemember';
				$params = [
					'token' => $client['token'],
					'stampMision' => $missionRec->stampMision
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				} else if(count($resultPOST->result) > 0) {
					// Si la msión tiene recordatorios se actualizan las notificaciones
					$url = CONSTANTS::SERVERAPI . 'updatemissionRememberNotification';
					$params = [
						'token' => $client['token'],
						'id' => $missionRec->stampMision,
						'idProject' => $missionRec->idProject,
						'ListaANotificar' => $IDListDistribution
					];

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

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

			if($client['groupChat'] == 1) {
				if($client['ChatGrupalID'] == '') {
					// AltaGrupo
					$resultPOST = $this->getCMBPProjectsMisionesNotificaciones($client['token'], 'AltaGrupo', $client['id']);

					if($resultPOST->status == 'OK') {
						$arrayGroup = $resultPOST->result;
						$Group = [];
						$sizeGroup = count($arrayGroup);
						for($j = 0; $j < $sizeGroup; $j++) {
							array_push($Group, $arrayGroup[$j]->idUser);
						}

						$paramsGroup = '[';
						$sizePart = count($client['participants']);
						for($l = 0; $l < $sizePart; $l++) {
							if(!in_array($client['participants'][$l][0], $Group)) {
								$paramsGroup .= '"' . $client['participants'][$l][0] . '",';
							}
						}
						$paramsGroup = substr($paramsGroup, 0, -1);
						$paramsGroup .= ']';

						// Creación de nuevo grupo
						$url = CONSTANTS::SERVERAPI . 'createGroup';
						$params = [
							'token' => $client['token'],
							'groupAdmin' => $client['admin'],
							'groupName' => $client['description'],
							'participants' => $paramsGroup,
							'country' => $client['country']
						];

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

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

							$url = CONSTANTS::SERVERAPI . 'getGroupJidByID';
							$params = [
								'token' => $client['token'],
								'groupId' => $sGrupoANotificar
							];

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

							if($resultPOST->status == 'OK') {
								$GroupTo = $resultPOST->result;
								if($GroupTo != '') {
									$url = CONSTANTS::SERVERAPI . 'updateCMBPProjectsChatGrupalID';
									$params = [
										'token' => $client['token'],
										'id' => $client['id'],
										'ChatGrupalID' => $iIDGrupoProyecto
									];

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

									if($resultPOST->status == 'OK') {
										$url = CONSTANTS::SERVERAPI . 'postGroupMessage';
										$message = $client['greetingGroupChat'] . ' ' . $client['description'];
										$params = [
											'token' => $client['token'],
											'message' => $message,
											'to' => $GroupTo,
											'from' => $client['admin']
										];

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

										if($resultPOSTX->status == 'OK') {
											$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisionesNotificaciones';
											$params = [
												'token' => $client['token'],
												'project' => $client['id'],
												'idmision' => 'AltaGrupo',
												'users' => $paramsGroup
											];

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

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

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

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

					// ¿Se han añadido nuevos miembros?
					if($paramsNotified != ']') {
						// JID de grupo a través de su ID
						$url = CONSTANTS::SERVERAPI . 'getGroupJidByID';
						$params = [
							'token' => $client['token'],
							'groupId' => $client['ChatGrupalID']
						];

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

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

						$groupJid = $resultPOST->result;

						// Notificar de nuevos miembros
						$url = CONSTANTS::SERVERAPI . 'postGroupSystemMessage';
						$params = [
							'token' => $client['token'],
							'message' => $client['greetingNewsGroupChat'],
							'to' => $groupJid,
							'from' => $client['admin']
						];

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

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

			if($client['individualChat'] == 1 && $client['notificarInclusion'] == 1) {
				// Alta1A1
				$resultPOST = $this->getCMBPProjectsMisionesNotificaciones($client['token'], 'Alta1A1', $client['id']);

				if($resultPOST->status == 'OK') {
					$arrayNotified = $resultPOST->result;
					$Notified = [];
					$sizeNoti = count($arrayNotified);
					for($j = 0; $j < $sizeNoti; $j++) {
						array_push($Notified, $arrayNotified[$j]->idUser);
					}

					$paramsNotified = '[';
					$sizePart = count($client['participants']);
					for($l = 0; $l < $sizePart; $l++) {
						if(!in_array($client['participants'][$l][0], $Notified)) {
							$paramsNotified .= '"' . $client['participants'][$l][0] . '",';
						}
					}
					$paramsNotified = substr($paramsNotified, 0, -1);
					$paramsNotified .= ']';

					if($paramsNotified != ']') {
						$message = $client['greeting'] . ' ' . $client['description'];
						$dataMsg = [
							'message' => $message,
							'from' => $client['admin'],
							'emailsToSend' => $paramsNotified,
							'idlist' => ''
						];

						// Envío de notificación si está activada la opción
						if($client['notificarInclusion'] == '1') {
							$resultPOST = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);
						}

						$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisionesNotificaciones';
						$params = [
							'token' => $client['token'],
							'project' => $client['id'],
							'idmision' => 'Alta1A1',
							'users' => $paramsNotified
						];

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

						if($resultPOST->status != 'OK') {
							return $resultPOST;
						}
					}
				} else {
					return $resultPOST;
				}
			}
			return $resultPOST;
		} else {
			if($client['missionsCount'] > 0) {
				// Iniciar servicio de misiones (IniciamosServiciosMisiones)
				$url = CONSTANTS::SERVERAPI . 'getCMBPMisionesInicioTimer';
				$params = [
					'token' => $client['token']
				];

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

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

					$sizeOMS = count($objectMissionStart);
					for($i = 0; $i < $sizeOMS; $i++) {
						$sIdMision = $objectMissionStart[$i]->idmision;
						$sUserQueNotifica = $objectMissionStart[$i]->LiderProyectoJID;
						$sidProject = $objectMissionStart[$i]->idProject;
						$fechahorainicioexec = $objectMissionStart[$i]->fechahorainicioexec;
						$fechahorafinexec = $objectMissionStart[$i]->fechahorafinexec;
						$textomisionok = $objectMissionStart[$i]->textomisionok;
						$textomisionko = $objectMissionStart[$i]->textomisionko;
						$importe = $objectMissionStart[$i]->importe;
						$sEncuestaId = $objectMissionStart[$i]->EncuestaId;
						$sEncuesta = $objectMissionStart[$i]->encuesta;
						$sTipoMision = $objectMissionStart[$i]->tipomision;
						$sListaDistrb = $objectMissionStart[$i]->ListaDistribucionID;
						$sTexto = $objectMissionStart[$i]->textoiniciomision;
						$misionStamp = $objectMissionStart[$i]->stampMision;
					}

					// Participantes
					$url = CONSTANTS::SERVERAPI . 'getCMBPMisionesParticipantes';
					$params = [
						'token' => $client['token'],
						'mision' => $sIdMision,
						'idProject' => $sidProject
					];

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

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

						// Notificaciones
						$url = CONSTANTS::SERVERAPI . 'getCMBPProjectsMisionesNotificaciones';
						$params = [
							'token' => $client['token'],
							'project' => $sidProject,
							'idmision' => $sIdMision . ';#;init'
						];

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

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

							$notified = [];
							$sizeOMN = count($objectMissionNotifications);
							for($i = 0; $i < $sizeOMN; $i++) {
								array_push($notified, $objectMissionNotifications[$i]->idUser);
							}

							$idUserString = '[';
							$sizeParticipants = count($objectMissionParticipants);
							for($l = 0; $l < $sizeParticipants; $l++) {
								if(!in_array($objectMissionParticipants[$l]->idUser, $notified)) {
									$idUserString .= '"' . $objectMissionParticipants[$l]->idUser . '",';
								}
							}
							$idUserString = substr($sizeParticipants, 0, -1);
							$idUserString .= ']';

							if($sizeParticipants != ']' && $sTexto != '') {
								$dataMsg = [
									'message' => $sTexto,
									'from' => $sUserQueNotifica,
									'emailsToSend' => $idUserString,
									'idlist' => $sListaDistrb
								];

								// Envío de notificación si está activada la opción
								if($client['notificarInclusion'] == '1') {
									$resultPOST = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);
								}

								if($resultPOST->status == 'OK') {
									$url = CONSTANTS::SERVERAPI . 'setCMBPProjectsMisionesNotificaciones';
									$params = [
										'token' => $client['token'],
										'project' => $sidProject,
										'idmision' => $sIdMision . ';#;init',
										'users' => $idUserString
									];

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

									if($resultPOST->status == 'OK') {
										if($sEncuesta == 1 && $sEncuestaId != '') {
											$url = CONSTANTS::SERVERAPI . 'postSurvey';
											$params = [
												'token' => $client['token'],
												'from' => $sUserQueNotifica,
												'emailsToSend' => $idUserString,
												'message' => $sEncuestaId,
												'idlist' => '',
												'misionStamp' => $misionStamp
											];

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

											if($resultPOST->status == 'OK') {
												// ActualizaMisionProjectInicioFinNotioficado
												$url = CONSTANTS::SERVERAPI . 'updateMisionInicioNotificado';
												$params = [
													'token' => $client['token'],
													'idProject' => $sidProject,
													'mision' => $sIdMision,
													'Value' => 1
												];

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

												if($resultPOST->status == 'OK') {
													if($sTipoMision == 'Referidos') {
														$url = CONSTANTS::SERVERAPI . 'enableReferrals';
														$params = [
															'token' => $client['token']
														];

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

														if($resultPOST->status != 'OK') {
															return $resultPOST;
														}
													}
												} else {
													return $resultPOST;
												}
											} else {
												return $resultPOST;
											}
										}
									} else {
										return $resultPOST;
									}
								}
							} else {
								$url = CONSTANTS::SERVERAPI . 'updateMisionInicioNotificado';
								$params = [
									'token' => $client['token'],
									'idProject' => $sidProject,
									'mision' => $sIdMision,
									'Value' => 1
								];

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

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

	// Creación de Lista de Difusión de proyecto
	public function createDistributionListProject($client, $participantsString, $idProject) {
		$url = CONSTANTS::SERVERAPI . 'createDistributionList';
		$params = [
			'token' => $client['token'],
			'admin' => $client['admin'],
			'activa' => '1',
			'idProject' => $idProject,
			'description' => $client['description'],
			'destinatarios' => $participantsString,
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// Envío de notificación de proyecto
	public function getCMBPProjectsMisionesNotificaciones($token, $idMission, $idProject) {
		$url = CONSTANTS::SERVERAPI . 'getCMBPProjectsMisionesNotificaciones';
		$params = [
			'token' => $token,
			'idmision' => $idMission,
			'project' => $idProject
		];

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

		return $resultPOST;
	}

	// Envío de aviso de videollamada
	public function sendRequest($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$idcallArray = explode('#', $client['idcall']);
		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'bid' => $client['bid'],
			'type' => $client['type'],
			'idcall' => $idcallArray[1]
		];

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

		return $resultPOST;
	}

	// Envío de aviso de videollamada
	public function sendIncomingCall($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$idcallArray = explode('#', $client['idcall']);

		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'bid' => $client['bid'],
			'type' => $client['type'],
			'idcall' => $idcallArray[1]
		];

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

		return $resultPOST;
	}

	// Eliminar usuario de video llamada
	public function moderatorOutUserCall($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$idcallArray = explode('#', $client['idcall']);

		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'idcall' => $idcallArray[1]
		];

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

		return $resultPOST;
	}

	// Usuarios en videollamada
	public function usersInCall($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$idcallArray = explode('#', $client['idcall']);
		$params = [
			'token' => $client['token'],
			'idcall' => $idcallArray[1]
		];

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

		return $resultPOST;
	}

	// Fin de videollamada
	public function moderatorLeaveCall($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$idcallArray = explode('#', $client['idcall']);
		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'type' => $client['type'],
			'idcall' => $idcallArray[1]
		];

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

		return $resultPOST;
	}

	// Registro de videollamada
	public function registerCall($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$idcallArray = explode('#', $client['idcall']);
		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'bid' => $client['bid'],
			'type' => $client['type'],
			'idcall' => $idcallArray[1],
			'stamp' => $client['stamp']
		];

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

		return $resultPOST;
	}

	// Validar misión
	public function validateMission($client) {
		$url = CONSTANTS::SERVERAPI . 'addValueToWallet';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey'],
			'users' => $client['idUser'],
			'importe' => $client['importe'],
			'mision' => $client['mision'],
			'currency' => $client['currency'],
			'stampMision' => $client['stampMission']
		];

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

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

		// Servicio de guardado de validación (aceptado)
		$urlVal = CONSTANTS::SERVERAPI . 'setMisionValidation';
		$paramsVal = [
			'token' => $client['token'],
			'idmision' => $client['mision'],
			'users' => $client['idUser'],
			'estado' => 1,
			'motivo' => '',
			'project' => $client['project']
		];

		$resultPOSTVal = $this->utilesController->sendCurlPOST($urlVal, $paramsVal);

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

		$dataMsg = [
			'message' => $client['textMision'],
			'to' => $client['idUser'],
			'from' => $client['from']
		];

		$result = $this->notificacionesController->PostMessageToUser($client, $dataMsg, $client['token']);

		return $result;
	}

	// Validar misión múltiple
	public function validateMissionMultiple($client) {
		$size = count($client['idUser']);
		for($i = 0; $i < $size; $i++) {
			$url = CONSTANTS::SERVERAPI . 'addValueToWallet';
			$params = [
				'token' => $client['token'],
				'survey' => $client['survey'],
				'users' => $client['idUser'][$i],
				'importe' => $client['importe'],
				'mision' => $client['mision'],
				'currency' => $client['currency'],
				'stampMision' => $client['stampMission']
			];

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

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

		// Servicio de guardado de validación (aceptado)
		$users = json_encode($client['idUser']);
		$urlVal = CONSTANTS::SERVERAPI . 'setMisionValidationMultiple';
		$paramsVal = [
			'token' => $client['token'],
			'idmision' => $client['mision'],
			'users' => $users,
			'estado' => 1,
			'motivo' => '',
			'project' => $client['project']
		];

		$resultPOSTVal = $this->utilesController->sendCurlPOST($urlVal, $paramsVal);

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

		$dataMsg = [
			'message' => $client['textMision'],
			'emailsToSend' => $users,
			'from' => $client['from'],
			'idlist' => ''
		];

		$result = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);

		return $result;
	}

	// Rechazar misión
	public function refuseMission($client) {
		// Servicio de guardado de validación (rechazado)
		$urlVal = CONSTANTS::SERVERAPI . 'setMisionValidation';
		$paramsVal = [
			'token' => $client['token'],
			'idmision' => $client['mision'],
			'users' => $client['idUser'],
			'estado' => 0,
			'motivo' => $client['motivos'],
			'project' => $client['project']
		];

		$resultPOSTVal = $this->utilesController->sendCurlPOST($urlVal, $paramsVal);

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

		$msg = $client['textMision'] . "\n" . $client['motivos'];
		$dataMsg = [
			'message' => $msg,
			'to' => $client['idUser'],
			'from' => $client['from']
		];

		$result = $this->notificacionesController->PostMessageToUser($client, $dataMsg, $client['token']);

		// Notificación en log
		$type = 'Refuse payment';
		$service = $client['userAdmin'];
		$event = 'Se rechazó el pago a ' . $client['idUser'] . ' de la misión ' . $client['mision'];

		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');

		return $result;
	}

	// Rechazar misión múltiple
	public function setMisionValidationMultiple($client) {
		// Servicio de guardado de validación (rechazado)
		$users = json_encode($client['idUser']);
		$urlVal = CONSTANTS::SERVERAPI . 'setMisionValidationMultiple';
		$paramsVal = [
			'token' => $client['token'],
			'idmision' => $client['mision'],
			'users' => $users,
			'estado' => 0,
			'motivo' => $client['motivos'],
			'project' => $client['project']
		];

		$resultPOSTVal = $this->utilesController->sendCurlPOST($urlVal, $paramsVal);

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

		$msg = $client['textMision'] . "\n" . $client['motivos'];

		$dataMsg = [
			'message' => $msg,
			'emailsToSend' => $users,
			'from' => $client['from'],
			'idlist' => ''
		];

		$result = $this->utilesController->postMessageMultiple($client, $dataMsg, $client['token']);

		// Notificación en log
		$type = 'Refuse payment';
		$service = $client['userAdmin'];
		$event = 'Se rechazó el pago a ' . implode(',', $client['idUser']) . ' de la misión ' . $client['mision'];

		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');

		return $result;
	}

	// Misiones validación encuesta
	public function getSurveyByUser($client) {
		// Petición de todas las preguntas de la encuesta
		$url = CONSTANTS::SERVERAPI . 'getQuestionsSurvey';
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey']
		];

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

		if($resultPOST->status == 'OK') {
			$questions = $resultPOST->result;
			$questionsFiltered = [];

			foreach($questions as $quest) {
				$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestra';
				$params = [
					'token' => $client['token'],
					'survey' => $client['survey'],
					'pregunta' => $quest->columnName,
					'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPreguntasPerfilacionEnAnalyticMostreo'],
					'continuingMission' => $client['continuingMission']
				];

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

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

				$answers = [];
				foreach($resultQuest->result->resultado as $answer) {
					// userToken (e-mail)
					if($client['userToken'] == $answer->userEmail) {
						array_push($answers, $answer);
					}
				}

				$obj = [
					'question' => $quest->question,
					'type' => $quest->type,
					'answer' => $answers
				];
				array_push($questionsFiltered, $obj);
			}

			$result = [
				'status' => 'OK',
				'result' => $questionsFiltered
			];
			return $result;
		} else {
			return $resultPOST;
		}
	}

	// Misiones validación pedido
	public function getOrdersByUser($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'startDate' => $client['startDate'],
			'endDate' => $client['endDate'],
			'username' => $client['username']
		];

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

		return $resultPOST;
	}

	// Misiones comprobación de validación
	public function isMisionValidated($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idmision' => $client['idmision'],
			'users' => $client['users']
		];

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

		return $resultPOST;
	}

	// Modificación de motivos de expulsión
	public function deleteAllMotivosExpulsionProject($client) {
		// Borra la lista de motivos
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

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

		if($resultPOST->status == 'OK') {
			// Guarda la nueva lista de motivos
			$url = CONSTANTS::SERVERAPI . 'setMotivosExpulsionProject';
			$params = [
				'token' => $client['token'],
				'motivos' => json_encode($client['motivos'])
			];

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

		return $resultPOST;
	}

	// Guardado de video externo
	public function setFileRecordedExternal($client) {
		// Archivo a subir
		if(isset($_FILES['fileRecorded'])) {
			$fileRecorded = $_FILES['fileRecorded'];

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

			if($fileRecorded['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($fileRecorded['name'], $strangerCharts[$i]) !== false) {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file name is not correct';
					return $resultPOST;
				}
			}

			$newname = str_replace('-', '_', $fileRecorded['name']);
			$newname = str_replace(' ', '_', $newname);

			// Lista de extensiones permitidas
			$safeList = ['avi', 'mpeg', 'webm', 'mov', 'mp4'];
			$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;
			}

			$urlPathCod = $resultPOST->result[0]->videoCallsRecordingPath;
			$urlPathDeCod = $this->utilesController->OpenSSLDecrypt($urlPathCod);
			$date = new DateTime();

			$videocallFolder = $urlPathDeCod . '/' . $date->format('Y') . '/' . $date->format('m') . '/' . $date->format('d');

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

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

			// Mover archivo a carpeta
			$idCallPath = str_replace('CODE#', '', $client['idcall']);
			if(!move_uploaded_file($fileRecorded['tmp_name'], $videocallFolder . '/' . $idCallPath . '_' . $newname)) {
				$resultPOST->status = 'KO';
				$resultPOST->result = 'The file could not be saved';
				return $resultPOST;
			}
		} else {
			$resultPOST = [
				'status' => 'KO',
				'There is no file to upload'
			];
			return $resultPOST;
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'jid' => $client['jid'],
			'dateArmed' => $date->format('d/m/Y H:i:s'),
			'folderRecorded' => '/' . $date->format('Y') . '/' . $date->format('m') . '/' . $date->format('d'),
			'fileRecorded' => $idCallPath . '_' . $newname,
			'idProject' => $client['idProject'],
			'stamp' => $client['stamp'],
			'idcall' => $client['idcall']
		];

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

		return $resultPOST;
	}

	// Petición de imágenes de encuesta con validación
	public function getSurveysFilesByQuestion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'qid' => $client['qid'],
			'mision' => $client['mision']
		];

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

		return $resultPOST;
	}

	// Comprobación de imágenes repetidas de encuesta con validación
	public function getCompareFilesBySurveys($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'survey' => $client['survey']
		];

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

		return $resultPOST;
	}

	// Analizar imagen
	public function analizaFoto($client) {
		$size = count($client['urlImage']);
		for($i = 0; $i < $size; $i++) {
			$url = CONSTANTS::SERVERAPI . $client['action'];
			$params = [
				'token' => $client['token'],
				'urlImage' => $client['urlImage'][$i],
				'lenguage' => $client['lenguage']
			];

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

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

		return $resultPOST;
	}

	// Analizar imagen con OCR
	public function procesaOCRFotosFolder($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'sid' => $client['sid'],
			'lenguage' => $client['lenguage'],
			'stampMision' => $client['stampMision'],
			'idProject' => $client['idProject']
		];

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

		return $resultPOST;
	}

	// Información de la imagen analizada
	public function getFotoAnalizedData($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'urlImage' => $client['urlImage']
		];

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

		return $resultPOST;
	}

	// Información de la imagen analizada con OCR
	public function getImageDataOCRProcessed($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'fileName' => $client['fileName']
		];

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

		return $resultPOST;
	}

	// Corrección de datos OCR
	public function setImageDataOCRSimilarities($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'fileName' => $client['fileName'],
			'idCapture' => $client['idCapture'],
			'data' => json_encode($client['data'])
		];

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

		return $resultPOST;
	}

	// Sacar audio de video
	public function convertMP4ToWAV($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'fileNameUpload' => $client['fileNameUpload'],
			'recordedFilePath' => $client['recordedFilePath'],
			'idCall' => $client['idCall']
		];

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

		return $resultPOST;
	}

	// Transcribir audio
	public function saveTranscriptionInfo($client) {
		// Borrado de la transcripción anterior si fuera necesario
		if($client['reTranscription'] == '1') {
			$url = CONSTANTS::SERVERAPI . 'deleteTranscriptionFileByProject';
			$params = [
				'token' => $client['token'],
				'idProject' => $client['idProject'],
				'idcall' => $client['idCall']
			];

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

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

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

		$size = count($client['textTranscription']);
		$control = 499;
		$textArrayToSend = [];
		for($i = 0; $i < $size; $i++) {
			array_push($textArrayToSend, $client['textTranscription'][$i]);
			if($i == $control) {
				$params = [
					'token' => $client['token'],
					'idProject' => $client['idProject'],
					'idCall' => $client['idCall'],
					'textTranscription' => json_encode($textArrayToSend)
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				} else {
					$control += 500;
					$textArrayToSend = [];
				}
			}
		}

		if(count($textArrayToSend) > 0) {
			$params = [
				'token' => $client['token'],
				'idProject' => $client['idProject'],
				'idCall' => $client['idCall'],
				'textTranscription' => json_encode($textArrayToSend)
			];

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

		return $resultPOST;
	}

	// Petición de transcripción por proyecto e idCall
	public function getFilesTranscriptionByProject($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idProject' => $client['idProject'],
			'idcall' => $client['idcall']
		];

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

		return $resultPOST;
	}

	// Añadir documento a proyecto
	public function insertCMBPProjectsFile($client) {
		$projectFiles = [];

		// Subida de archivos si los hay
		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;

			// Ruta del documento
			$documentPathDir = CONSTANTS::PATH_EXPORT_WORD . '/projects/' . $client['id'];

			// 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);

				// Lista de extensiones permitidas
				$safeList = ['avi', 'gif', 'jpg', 'jpeg', 'mpeg', 'pdf', 'wav', 'weba', 'webm', 'png', 'mp3', 'mov', 'mp4', 'bmp', 'xlsx', 'csv', 'pptx', 'docx'];
				$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;
				}

				// Añadir descripción al final
				$fileData = $documentPathDir . '#' . $newname . '#' . $_FILES[$key]['size'] . '#' . $client['fileToUploadDesc'];
				array_push($projectFiles, $fileData);
			}
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'admin' => $client['admin'],
			'projectFiles' => json_encode($projectFiles)
		];

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Eliminar documentos de proyecto
	public function deleteCMBPProjectsFileById($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'projectFiles' => $client['projectFiles']
		];

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

		$fileName = $client['filename'];
		unlink(CONSTANTS::PATH_EXPORT_WORD . '/projects/' . $client['id'] . '/' . $fileName);

		return $resultPOST;
	}

	// Editar descripción de documento de proyecto
	public function updateCMBPProjectsFilesDesc($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'admin' => $client['admin'],
			'id' => $client['id'],
			'Descripcion' => $client['descripcion']
		];

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

		return $resultPOST;
	}

	// Lista de asesores notificados
	public function getCMBPProjectsMisionesUsersNotif($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'missionStamp' => $client['missionStamp']
		];

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

		return $resultPOST;
	}

	// Petición de asignación de cupo por proyecto / misión
	public function getDesgloseCuposMision($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'project' => $client['project'],
			'stampMision' => $client['stampMision']
		];

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

		return $resultPOST;
	}
	
	// Petición de asignación de cupo por proyecto / misión
	public function getMissionQuotaBreakdown($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idProject' => $client['project'],
			'missionStamp' => $client['stampMision'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// Posibles respuestas para las 4 preguntas de perfilación
	public function getAnalyticsMuestraToExportHeaders($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country']
		];

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

		return $resultPOST;
	}

	// Asignacion de porcentaje a misiones de un proyecto
	public function setCMBPProjectsMisionesCuotaReparto($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		for($i = 0; $i < count($client['missions']); $i++) {
			$params = [
				'token' => $client['token'],
				'missionStamp' => $client['missions'][$i]['missionStamp'],
				'cuotaReparto' => $client['missions'][$i]['cuotaReparto']
			];

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

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

		return $resultPOST;
	}

	// Reparto de asesores en misiónes de proyecto
	public function setRepartoPartProjByMissions($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idProject' => $client['idProject']
		];

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

		return $resultPOST;
	}

	// Asesores asignados a mision de proyecto con repartición
	public function getRepartoPartProjByMissions($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idProject' => $client['idProject'],
			'missionStamp' => $client['missionStamp']
		];

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

		return $resultPOST;
	}

	// Asignar a usuario comercios y articulos
	public function setUserComerciosItems($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'idProject' => $client['idProject'],
			'stampMision' => $client['stampMision'],
			'values' => $client['values'] == '[]' ? $client['values'] : json_encode($client['values'])
		];

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

		return $resultPOST;
	}

	// Comercios y articulos asignados a usuario
	public function getUserComerciosItems($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'idProject' => $client['idProject'],
			'stampMision' => $client['stampMision']
		];

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

		return $resultPOST;
	}

	// Servicio de petición de datos de evidencias a validar
	public function servicioParaValidacionDeEvidencias($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			/* ¿Qué parámetros se necesitarán? */
		];

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

		return $resultPOST;
	}
}