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

class UsuariosController {
	private $utilesController;

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

	// Todos los usuarios
	public function getAllUsers($client) {
		$country = '';
		if(isset($client['country'])) {
			$country = $client['country'];
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $country,
			'consejero' => $client['consejero'],
			'enabled' => $client['enabled'],
			'staff' => $client['staff'],
			'admin' => $client['admin']
		];

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

		return $resultPOST;
	}

	// Usuario por email
	public function getUserData($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email']
		];

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Petición de grupos de usuario
	public function getUserGroups($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'jid' => $client['jid']
		];

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

		return $resultPOST;
	}

	public function assignCPG($data) {
		$url = CONSTANTS::SERVERAPI . 'setUserCPGAssignment';
		$params = [
			'token' => $data['token'],
			'email' => $data['email'],
			'idCPG' => $data['idCPG']
		];

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

		return $resultPOST;
	}

	// Añadir usuario nuevo
	public function newUser($client) {
		$url = CONSTANTS::SERVERAPI . 'userExists';
		$params = [
			'token' => $client['token'],
			'email' => $client['user']['email']
		];

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

		if($resultPOST->status !== 'OK' && $resultPOST->result !== 'User exists') {
			if(!isset($resultPOST->status)) {
				$resultPOST['status'] = 'KO';
				$resultPOST['result'] = 'Service ERROR';
			}
			return $resultPOST;
		}

		$cpgdata = [
			'token' => $client['token'],
			'email' => $client['user']['email'],
			'idCPG' => $client['user']['idCPG']
		];

		if($resultPOST->result == 'User exists') {
			if($client['user']['idCPG'] && $client['user']['idCPG'] != 0) {
				$resultPOST = $this->assignCPG($cpgdata);
			}

			return $resultPOST;
		}

		$url = CONSTANTS::SERVERAPI . 'register';
		$params = [
			'token' => $client['token'],
			'email' => strtolower($client['user']['email']),
			'password' => $client['user']['password'],
			'name' => $client['user']['nameUser'],
			'usertype' => 3,
			'country' => $client['extendedInfo']['country']
		];

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

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

		// Enviar chat de bienvenida
		if($client['wellcomeChat'] == '1') {
			$url = CONSTANTS::SERVERAPI . 'sendWelcomeMessages_SaaS';
			$params = [
				'token' => $client['token'],
				'email' => strtolower($client['user']['email'])
			];
	
			$resultPOSTSaaS = $this->utilesController->sendCurlPOST($url, $params);

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

		// Notificación en log
		$type = 'Register user';
		$service = $client['userAdmin'];
		$event = 'New user: ' . strtolower($client['user']['email']);
		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');

		// Asignar el rol de usuario
		if(isset($client['user']['role']) && $client['user']['role'] != '') {
			$url = CONSTANTS::SERVERAPI . 'assignUserRole';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email'],
				'role' => $client['user']['role']
			];

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

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

		// Asignar el CPG
		if($client['user']['idCPG']) {
			$resultPOST2 = $this->assignCPG($cpgdata);

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

		// Comprobar el estado del usuario
		if($client['user']['enabled'] == '1') {
			// Activamos el usuario
			$url = CONSTANTS::SERVERAPI . 'enableUser';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email']
			];

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

			if($resultPOST2->status != 'OK') {
				return $resultPOST2;
			}
		} else if($client['user']['enabled'] == '0') {
			// Desactivamos el usuario
			$url = CONSTANTS::SERVERAPI . 'disableUser';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email']
			];

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

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

		// Comprobar si hay extended info
		if($client['extendedInfo']) {
			$url = CONSTANTS::SERVERAPI . 'setUserExtendedInfo';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email'],
				'username' => $client['extendedInfo']['userNombre'],
				'userapellidos' => $client['extendedInfo']['userApellidos'],
				'userapellidos2' => $client['extendedInfo']['userApellidos2'],
				'useridentificador' => $client['extendedInfo']['userIdentificador'],
				'useraccount' => $client['extendedInfo']['userAccount'],
				'consejero' => $client['extendedInfo']['consejero'],
				'numMisionesIncumplidas' => $client['extendedInfo']['numMisionesIncumplidas'],
				'staff' => $client['extendedInfo']['staff'],
				'country' => $client['extendedInfo']['country'],
				'lenguage' => $client['extendedInfo']['language'],
				'mailToNotify' => $client['extendedInfo']['mailToNotify'],
				'phoneToNotify' => $client['extendedInfo']['phoneToNotify'],
				'profile' => $client['extendedInfo']['profile'],
				'questionEstado' => $client['extendedInfo']['questionEstado'],
				'questionEdadFecha' => $client['extendedInfo']['questionEdadFecha'],
				'questionGenero' => $client['extendedInfo']['questionGenero'],
				'questionABI' => $client['extendedInfo']['questionABI'],
				'tryLogin' => '0'
			];

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

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

		// Añadir usuario a grupos nuevos
		if(count($client['user']['participants']) > 0) {
			// Obtener el jid del usuario
			$url = CONSTANTS::SERVERAPI . 'getUserJidByEmail';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email']
			];

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

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

			$jidUser = $resultPOST2->result;
			$participant = [$jidUser];
			foreach($client['user']['participants'] as $group) {
				$url = CONSTANTS::SERVERAPI . 'addToGroup';
				$params = [
					'token' => $client['token'],
					'groupId' => $group,
					'participants' => json_encode($participant)
				];

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

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

		// Comprobar si hay configuracion de bots
		if(isset($client['botConfig']['directLineSecret'])) {
			// Obtener el jid del usuario
			if(!isset($jidUser)) {
				$url = CONSTANTS::SERVERAPI . 'getUserJidByEmail';
				$params = [
					'token' => $client['token'],
					'email' => $client['user']['email']
				];

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

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

				$jidUser = $resultPOST2->result;
			}

			$url = CONSTANTS::SERVERAPI . 'setBotConfig';
			$params = [
				'token' => $client['token'],
				'idUserOrGroup' => $jidUser,
				'isGroup' => $client['botConfig']['isGroup'],
				'directLineSecret' => $client['botConfig']['directLineSecret'],
				'botNameId' => $client['botConfig']['botId'],
				'enabled' => $client['botConfig']['enabled'],
				'botUser' => $client['botConfig']['botUser'],
				'numVecesNoMatch' => $client['botConfig']['numVecesNoMatch'],
				'textNoMatch' => $client['botConfig']['textoNoMatch'],
				'userNotifNoMatch' => $client['botConfig']['userNotificarNoMatch'],
				'messageNotifNoMatch' => $client['botConfig']['messageNotifNoMatch'],
				'SaludoInicial' => $client['botConfig']['SaludoInicial']
			];

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

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

		// Comprobar si hay configuracion de asistente de voz
		if(isset($client['voiceAssistant']['dictionary']) && $client['voiceAssistant']['dictionary'] != '') {
			// Obtener el jid del usuario
			if(!isset($jidUser)) {
				$url = CONSTANTS::SERVERAPI . 'getUserJidByEmail';
				$params = [
					'token' => $client['token'],
					'email' => $client['user']['email']
				];

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

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

				$jidUser = $resultPOST2->result;
			}

			$url = CONSTANTS::SERVERAPI . 'setVoiceAssistantConfig';
			$params = [
				'token' => $client['token'],
				'idUserOrGroup' => $jidUser,
				'isGroup' => '0',
				'idDictionary' => $client['voiceAssistant']['dictionary'],
				'enabled' => $client['voiceAssistant']['enabled'],
				'numVecesNoMatch' => $client['voiceAssistant']['numVecesNoMatch'],
				'textoNoMatch' => $client['voiceAssistant']['textoNoMatch'],
				'userNotificarNoMatch' => $client['voiceAssistant']['userNotificarNoMatch'],
				'textoNotificarNoMatch' => $client['voiceAssistant']['textoNotificarNoMatch'],
				'texttouser' => $client['voiceAssistant']['texttouser'],
				'messageNoMatch' => ($client['voiceAssistant']['notificationType'] == 'user' ? '1' : '0'),
				'videocallNoMatch' => ($client['voiceAssistant']['notificationType'] == 'videocall' ? '1' : '0'),
				'emailNoMatch' => ($client['voiceAssistant']['notificationType'] == 'mail' ? '1' : '0'),
				'saludoInicial' => $client['voiceAssistant']['applyGreeting'],
				'textoSaludo' => $client['voiceAssistant']['textGreeting'],
				'country' => $client['voiceAssistant']['country'],
				'gender' => $client['voiceAssistant']['gender']
			];

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

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

		return $resultPOST;
	}

	// Cambiar contraseña
	public function changePass($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'password' => $client['password']
		];

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

		return $resultPOST;
	}

	// Detalle de pagos al usuario
	public function getDetallePagosByUser($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'user' => $client['user']
		];

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

		return $resultPOST;
	}

	// Editar usuario
	public function editUser($client) {
		// Comprobar si el usuario ha cambiado de estado
		if($client['user']['enabled'] != $client['userNew']['enabled']) {
			if($client['userNew']['enabled'] == '1') {
				// Comprobación de número de licencias disponibles
				$url = CONSTANTS::SERVERAPI . 'getFreeLicences';
				$params = [
					'token' => $client['token'],
					'country' => $client['country']
				];

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

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

				$freeLicences = $resultPOST->result;
				if($freeLicences < 1) {
					$response = [
						'status' => 'OK',
						'errorUsers' => 'overflow'
					];
					return $response;
				}

				// Activamos el usuario
				$url = CONSTANTS::SERVERAPI . 'enableUser';
				$params = [
					'token' => $client['token'],
					'email' => $client['user']['email'],
					'country' => $client['country']
				];

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

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

				// Notificación en log
				$type = 'Activate user';
				$service = $client['userAdmin'];
				$event = 'Activate user: ' . strtolower($client['user']['email']);
				$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');
			} else if($client['userNew']['enabled'] == '0') {
				// Desactivamos el usuario
				$url = CONSTANTS::SERVERAPI . 'disableUser';
				$params = [
					'token' => $client['token'],
					'email' => $client['user']['email']
				];

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

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

		// Comprobar si ha cambiado algun grupo
		if($client['userNew']['participants'] != $client['userNew']['participantsOld']) {
			// Comprobar grupos nuevos
			$newGroups = [];
			foreach($client['userNew']['participants'] as $member) {
				$search = in_array($member, $client['userNew']['participantsOld']);
				if(!$search) {
					array_push($newGroups, $member);
				}
			}

			// Añadir usuario a grupos nuevos
			if(count($newGroups) > 0) {
				$participant = [$client['user']['id']];
				foreach($newGroups as $group) {
					$url = CONSTANTS::SERVERAPI . 'addToGroup';
					$params = [
						'token' => $client['token'],
						'groupId' => $group,
						'participants' => json_encode($participant)
					];

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

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

			// Comprobar grupos eliminados
			$removeGroups = [];
			foreach($client['userNew']['participantsOld'] as $member) {
				$search = in_array($member, $client['userNew']['participants']);
				if(!$search) {
					array_push($removeGroups, $member);
				}
			}

			// Añadir usuario a grupos nuevos
			if(count($removeGroups) > 0) {
				$participant = [$client['user']['id']];
				foreach($removeGroups as $group) {
					$url = CONSTANTS::SERVERAPI . 'takeOutFromGroup';
					$params = [
						'token' => $client['token'],
						'groupId' => $group,
						'participants' => json_encode($participant)
					];

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

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

		// Comprobar si ha cambiado el nombre del usuario
		if($client['extendedInfo']['name'] != $client['userNew']['nameUser']) {
			$url = CONSTANTS::SERVERAPI . 'setUserName';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email'],
				'name' => $client['userNew']['nameUser']
			];

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

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

		// Comprobar si ha cambiado el rol de usuario
		if($client['user']['role'] != $client['userNew']['role']) {
			$url = CONSTANTS::SERVERAPI . 'deleteUserRole';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email']
			];

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

			if(isset($client['userNew']['role']) && $client['userNew']['role'] != '') {
				$url = CONSTANTS::SERVERAPI . 'assignUserRole';
				$params = [
					'token' => $client['token'],
					'email' => $client['user']['email'],
					'role' => $client['userNew']['role']
				];

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

				if($resultPOST->status != 'OK') {
					return $resultPOST;
				} else {
					//assignar los nuevos menús del rol
					$url = CONSTANTS::SERVERAPI . 'setUserCustomMenuRoleOptions';
					$params = [
						'token' => $client['token'],
						'email' => $client['user']['email'],
						'jid' => $client['user']['id']
					];

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

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

		// Comprobar si ha cambiado la extended info
		if($client['extendedInfo'] != $client['extendedInfoNew']) {
			$url = CONSTANTS::SERVERAPI . 'setUserExtendedInfo';
			$params = [
				'token' => $client['token'],
				'email' => $client['user']['email'],
				'username' => $client['extendedInfoNew']['userNombre'],
				'userapellidos' => $client['extendedInfoNew']['userApellidos'],
				'userapellidos2' => $client['extendedInfoNew']['userApellidos2'],
				'name' => $client['extendedInfoNew']['name'],
				'useridentificador' => $client['extendedInfoNew']['userIdentificador'],
				'useraccount' => $client['extendedInfoNew']['userAccount'],
				'consejero' => $client['extendedInfoNew']['consejero'],
				'numMisionesIncumplidas' => $client['extendedInfoNew']['numMisionesIncumplidas'],
				'staff' => $client['extendedInfoNew']['staff'],
				'country' => $client['extendedInfoNew']['country'],
				'lenguage' => $client['extendedInfoNew']['language'],
				'mailToNotify' => $client['extendedInfoNew']['mailToNotify'],
				'phoneToNotify' => $client['extendedInfoNew']['phoneToNotify'],
				'changedMail' => $client['extendedInfo']['validationEmail'] != $client['extendedInfoNew']['mailToNotify'] ? '1' : '0',
				'changedPhone' => $client['extendedInfo']['phoneToNotify'] != $client['extendedInfoNew']['phoneToNotify'] ? '1' : '0',
				'profile' => $client['extendedInfoNew']['profile'],
				'questionEstado' => $client['extendedInfoNew']['questionEstado'],
				'questionEdadFecha' => $client['extendedInfoNew']['questionEdadFecha'],
				'questionGenero' => $client['extendedInfoNew']['questionGenero'],
				'questionABI' => $client['extendedInfoNew']['questionABI'],
				'tryLogin' => $client['extendedInfoNew']['tryLogin']
			];

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

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

			// Comprobación de cambio de consejero a staff o viceversa
			if($client['extendedInfo']['consejero'] != $client['extendedInfoNew']['consejero']) {
				if($client['extendedInfoNew']['consejero'] == '1') {
					$event = 'El usuario ' . $client['user']['email'] . ' cambió de ser staff a consejero';
				} else if($client['extendedInfoNew']['staff'] == '1') {
					$event = 'El usuario ' . $client['user']['email'] . ' cambió de ser consejero a staff';
				}

				$this->utilesController->setCMBPLOG($client['token'], 'Modification of user information', 'setUserExtendedInfo', $client['userAdminMail'], $event, '1');
			}
		}

		// Comprobar si ha cambiado la configuracion de bots
		if($client['botConfigNew'] != $client['botConfig']) {
			$url = CONSTANTS::SERVERAPI . 'setBotConfig';
			$params = [
				'token' => $client['token'],
				'idUserOrGroup' => $client['botConfigNew']['idUserOrGroup'],
				'isGroup' => $client['botConfigNew']['isGroup'],
				'directLineSecret' => $client['botConfigNew']['directLineSecret'],
				'botNameId' => $client['botConfigNew']['botId'],
				'enabled' => $client['botConfigNew']['enabled'],
				'botUser' => $client['botConfigNew']['botUser'],
				'numVecesNoMatch' => $client['botConfigNew']['numVecesNoMatch'],
				'textNoMatch' => $client['botConfigNew']['textoNoMatch'],
				'userNotifNoMatch' => $client['botConfigNew']['userNotificarNoMatch'],
				'messageNotifNoMatch' => $client['botConfigNew']['messageNotifNoMatch'],
				'SaludoInicial' => $client['botConfigNew']['SaludoInicial']
			];

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

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

		// Comprobar si ha cambiado la configuracion de asistente de voz
		if($client['voiceAssistantNew'] != $client['voiceAssistant']) {
			$url = CONSTANTS::SERVERAPI . 'setVoiceAssistantConfig';
			$params = [
				'token' => $client['token'],
				'idUserOrGroup' => $client['voiceAssistantNew']['voiceAssisUser'],
				'isGroup' => '0',
				'idDictionary' => $client['voiceAssistantNew']['dictionary'],
				'enabled' => $client['voiceAssistantNew']['enabled'],
				'numVecesNoMatch' => $client['voiceAssistantNew']['numVecesNoMatch'],
				'textoNoMatch' => $client['voiceAssistantNew']['textoNoMatch'],
				'userNotificarNoMatch' => $client['voiceAssistantNew']['userNotificarNoMatch'],
				'textoNotificarNoMatch' => $client['voiceAssistantNew']['textoNotificarNoMatch'],
				'texttouser' => $client['voiceAssistantNew']['texttouser'],
				'messageNoMatch' => ($client['voiceAssistantNew']['notificationType'] == 'user' ? '1' : '0'),
				'videocallNoMatch' => ($client['voiceAssistantNew']['notificationType'] == 'videocall' ? '1' : '0'),
				'emailNoMatch' => ($client['voiceAssistantNew']['notificationType'] == 'mail' ? '1' : '0'),
				'saludoInicial' => $client['voiceAssistantNew']['applyGreeting'],
				'textoSaludo' => $client['voiceAssistantNew']['textGreeting'],
				'country' => $client['voiceAssistantNew']['country'],
				'gender' => $client['voiceAssistantNew']['gender']
			];

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

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

		$response['status'] = 'OK';

		return $response;
	}

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

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

		return $resultPOST;
	}

	// Derecho al olvido
	public function forgetUser($client) {
		// Comprobar el estado de olvido
		if($client['forget'] == '1') {
			$url = CONSTANTS::SERVERAPI . 'forgetUser';
			$params = [
				'token' => $client['token'],
				'email' => $client['email']
			];

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

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

			$type = 'forgetUser';
			$service = $client['userMail'];
			$event = $client['email'] . ' has been forgotten';

			$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');
		} else if($client['forget'] == '0') {
			$url = CONSTANTS::SERVERAPI . 'deleteForgetUser';
			$params = [
				'token' => $client['token'],
				'email' => $client['email']
			];

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

		return $resultPOST;
	}

	// Derecho al olvido
	public function disabledCPG($client) {
		$url = CONSTANTS::SERVERAPI . 'deleteUserCPGAssignment';
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'idCPG' => $client['idCPG']
		];

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

		return $resultPOST;
	}

	// Importar usuarios desde excel
	public function importUsers($client) {
		$response['errors'] = [];
		$response['status'] = 'OK';
		
		foreach($client['users'] as $user) {
			$email = strtolower($user['email']);

			$cpgdata = [
				'token' => $client['token'],
				'email' => $email,
				'idCPG' => $client['idCPG']
			];

			$url = CONSTANTS::SERVERAPI . 'register';
			$params = [
				'token' => $client['token'],
				'email' => $email,
				'password' => $user['password'],
				'name' => $user['nombre'],
				'country' => $user['pais'],
				'role' => $user['role'],
				'profile' => $user['perfil'],
				'usertype' => 3
			];

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

			// Comprobar si se ha podido guardar el usuario
			if($resultPOST->status != 'OK') {
				$error = $resultPOST->result;
				if (!isset($response['errors'][$error])) {
					$response['errors'][$error] = [];
				}
				array_push($response['errors'][$error], $user['email']);
				continue;
			} else {
				// Asignar CPG
				if($client['idCPG'] && $client['idCPG'] != 0) $resultPOST = $this->assignCPG($cpgdata);

				// Asignar rol
				if(isset($user['role'])) {
					$urlRole = CONSTANTS::SERVERAPI . 'assignUserRole';
					$params = [
						'token' => $client['token'],
						'email' => $email,
						'role' => $user['role']
					];

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

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

				if($user['consejero'] == 1) {
					$consejero = 1;
				} else {
					$consejero = 0;
				}

				$url = CONSTANTS::SERVERAPI . 'setUserExtendedInfo';
				$params = [
					'token' => $client['token'],
					'email' => $email,
					'username' => $user['nombre'],
					'userapellidos' => $user['apellido1'],
					'userapellidos2' => $user['apellido2'],
					'useridentificador' => '',
					'useraccount' => '',
					'consejero' => $consejero,
					'numMisionesIncumplidas' => '',
					'staff' => 1,
					// Añadido de paìs en minuscula
					'country' => strtolower($user['pais']),
					'lenguage' => $user['idioma'],
					'profile' => $user['perfil'],
					'tryLogin' => '0'
				];

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

		// Notificación en log
		$type = 'Mass registration of users';
		$service = $client['userAdmin'];
		$event = 'Mass registration of users';
		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');

		return $response;
	}

	// Pasar consejero 0 o 1
	// Activación masiva de usuarios enableUser
	public function activationUsers($client) {
		// Comprobación de número de licencias disponibles
		$url = CONSTANTS::SERVERAPI . 'getFreeLicences';
		$params = [
			'token' => $client['token']
		];

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

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

		$freeLicences = $resultPOST->result;
		$numberUsers = count($client['users']);
		if($numberUsers > $freeLicences) {
			$overflow = $numberUsers - $freeLicences;
			$response = [
				'status' => 'OK',
				'errorUsers' => 'overflow',
				'num' => $overflow
			];
			return $response;
		}

		$enableUsers = [];
		foreach($client['users'] as $user) {
			$email = strtolower($user['email']);

			if($user['consejero'] == 1) {
				$consejero = 1;
			} else {
				$consejero = 0;
			}

			$string = $email . '#' . $consejero . '#' . $user['pais'];

			array_push($enableUsers, $string);
		}

		if(count($enableUsers) > 0) {
			$url = CONSTANTS::SERVERAPI . 'enableMultipleUsers';
			$params = [
				'token' => $client['token'],
				'email' => json_encode($enableUsers)
			];

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

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

		// Notificación en log
		$type = 'Mass activation of users';
		$service = $client['userAdmin'];
		$event = 'Mass activation of users';
		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, '', '1');

		$response['status'] = 'OK';

		return $response;
	}

	// Desactivación masiva de usuarios
	public function deactivationUsers($client) {
		$disableUsers = [];
		foreach($client['users'] as $user) {
			$email = strtolower($user['email']);

			if($user['consejero'] == 1) {
				$consejero = 1;
			} else {
				$consejero = 0;
			}

			$string = $email . '#' . $consejero;

			array_push($disableUsers, $string);
		}

		if(count($disableUsers) > 0) {
			$url = CONSTANTS::SERVERAPI . 'disableMultipleUsers';
			$params = [
				'token' => $client['token'],
				'email' => json_encode($disableUsers)
			];

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

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

		$response['status'] = 'OK';

		return $response;
	}

	// Desasignar masiva de usuarios CPG
	public function dessasignCPG($client) {
		foreach($client['users'] as $user) {
			$email = strtolower($user['email']);

			// Desactivamos el usuario
			$url = CONSTANTS::SERVERAPI . 'disableUser';
			$params = [
				'token' => $client['token'],
				'email' => $email,
				'idCPG' => $client['idCPG']
			];

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

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

		$response['status'] = 'OK';

		return $response;
	}

	// Petición de respuestas de perfilación
	public function getPerfPosibleAnswers($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'email' => $client['email'],
			'type' => $client['type']
		];

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

		return $resultPOST;
	}

	/* TTT ESPECIAL 09/02/23 */
	// Comprobación de usuario para CPG
	/* public function userExists($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email']
		];

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

		return $resultPOST;
	} */
	/* TTT ESPECIAL 09/02/23 */

	// Posibles respuestas a una pregunta de encuesta
	public function getAllPosibleAnswersByQID($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'qid' => $client['qid'],
			'survey' => $client['survey'],
			'title' => $client['title'],
			'Pregunta' => $client['Pregunta']
		];

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

		return $resultPOST;
	}

	// Nueva segmentación
	public function setSegmentacion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'Descripcion' => $client['Descripcion'],
			'country' => $client['country'],
			'sid' => $client['sid'],
			'attributos' => json_encode($client['attributos']),
			'segmentos' => json_encode($client['segmentos'])
		];

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

		return $resultPOST;
	}

	// Eliminar segmentación
	public function deleteSegmentacion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['segmentations'] != '[]') {
			foreach($client['segmentations'] as $segmentation) {
				$params = [
					'token' => $client['token'],
					'idSegmentacion' => $segmentation['idSegmentacion'],
					'sid' => $segmentation['sid']
				];

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

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Editar segmentación
	public function updateSegmentacion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idSegmentacion' => $client['idSegmentacion'],
			'Descripcion' => $client['Descripcion'],
			'country' => $client['country'],
			'sid' => $client['sid'],
			'attributos' => json_encode($client['attributos']),
			'segmentos' => json_encode($client['segmentos'])
		];

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

		return $resultPOST;
	}

	// Ejecutar segmentación
	public function executeSegmentation($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idSegmentacion' => $client['idSegmentacion'],
			'sid' => $client['sid']
		];

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

		return $resultPOST;
	}

	// Desactivación y consejero = 0 para usuarios con datos incongruentes
	public function deactivateUnwelcomeCounselor($client) {
		// Marcar consejero a 0
		$url = CONSTANTS::SERVERAPI . 'setUserExtendedInfo';
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'username' => $client['username'],
			'userapellidos' => $client['userapellidos'],
			'userapellidos2' => $client['userapellidos2'],
			'name' => $client['name'],
			'useridentificador' => $client['useridentificador'],
			'useraccount' => $client['useraccount'],
			'consejero' => $client['consejero'],
			'numMisionesIncumplidas' => $client['numMisionesIncumplidas'],
			'staff' => $client['staff'],
			'country' => $client['country'],
			'lenguage' => $client['language'],
			'mailToNotify' => $client['mailToNotify'],
			'phoneToNotify' => $client['phoneToNotify'],
			'profile' => $client['profile'],
			'questionEstado' => $client['questionEstado'],
			'questionEdadFecha' => $client['questionEdadFecha'],
			'questionGenero' => $client['questionGenero'],
			'questionABI' => $client['questionABI'],
			'tryLogin' => $client['tryLogin']
		];

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

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

		// Desactivación del usuario
		$url = CONSTANTS::SERVERAPI . 'disableUser';
		$params = [
			'token' => $client['token'],
			'email' => $client['email']
		];

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

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

		// Log con evento
		$type = 'User deactivated due to data inconsistency';
		$service = $client['email'];
		$event = 'La ficha del usuario fue abierta por: ' . $client['adminEmail'];
		$rute = '';
		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');

		return $resultPOST;
	}

	// Crear segmentación programada
	public function setScheduledSegmentation($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'Activa' => $client['Activa'],
			'country' => $client['country'],
			'TiempoEntreEjecuciones' => $client['TiempoEntreEjecuciones'],
			'UnidadDeTiempo' => $client['UnidadDeTiempo']
		];

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

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

	// Editar segmentación programada
	public function updateScheduledSegmentation($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'Activa' => $client['Activa'],
			'country' => $client['country'],
			'TiempoEntreEjecuciones' => $client['TiempoEntreEjecuciones'],
			'UnidadDeTiempo' => $client['UnidadDeTiempo']
		];

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

		return $resultPOST;
	}
}