<?php
require_once(dirname(__FILE__) . '/../customConfig/Constants.php');

class Service {
	private $token;
	private $controller;

	function __construct() {
		$this->token = 'HtDFjQYeyfFb9e27n9URgFw27b9en9URg11Fw664ey11664ey11WJ9P27aGLOKmFh';
		$this->controller = new Controller;
	}

	public function startTest() {
		$directory = dirname(__FILE__) . '/running.txt';
		$errorFile = dirname(__FILE__) . '/runningError.txt';
		$exists = file_exists($directory);

		if(!$exists) {
			try {
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio, no hay archivo running.txt');
				// Crear fichero
				$startDate = date('Y-m-d H:i:s');
				file_put_contents($directory, $startDate);
				// Ejecutar notificaciones
				$response = $this->startService();
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Termina la llamada a startService');

				// Control de errores
				$responseDecode = json_decode($response);
				$responseDecode->missions = json_decode($responseDecode->missions);
				$date = date('Y-m-d H:i:s');

				if($responseDecode->schedule_payments != 'OK') {
					// Escribir devolución en archivo de errores - Schedule Payments
					file_put_contents($errorFile, $date . ' Schedule Payments: ' . $responseDecode->schedule_payments . "\n\r", FILE_APPEND);
				}

				if($responseDecode->programs != 'OK') {
					// Escribir devolución en archivo de errores - Programadas
					file_put_contents($errorFile, $date . ' Programadas: ' . $responseDecode->programs . "\n\r", FILE_APPEND);
				}

				if($responseDecode->missions->endMission != 'OK') {
					// Escribir devolución en archivo de errores - Fin de misión
					file_put_contents($errorFile, $date . ' Fin de misión: ' . $responseDecode->missions->endMission . "\n\r", FILE_APPEND);
				}

				$exists = file_exists($directory);
				if($exists) {
					$deleteCheck = false;
					while(!$deleteCheck) {
						$deleteCheck = unlink($directory);
					}
				}
			} catch(Exception $e) {
				//Gestión de excepciones
				$exceptionString =	' EXCEPTION OCURRED: ' . $e->getMessage() . "\r\n" .
									'	-Exception Code: ' . $e->getCode() . "\r\n" .
									'	-Exception Line: ' . $e->getLine() . "\r\n" .
									'	-Exception Trace: ' . "\r\n" . $e->getTraceAsString() . "\r\n";
				//escribir la excepción en el errorfile
				file_put_contents($errorFile, $date . $exceptionString . '---------------------------------' . "\r\n", FILE_APPEND);
				//lanzar un log en el server para registrarlo
				$this->controller ->setCMBPLOG($this->token, 'SERVICE_EXCEPTION', 'service exception', $exceptionString, '');
			}
		}
	}

	public function startService() {
		try {
			$controlErrors = [
				'programs' => '',
				'missions' => ''
			];

			// Llamar a las notificaciones schedule_payments
			$schedule_payments = $this->schedule_payments();
			$controlErrors['schedule_payments'] = $schedule_payments;
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Termina la llamada a schedule payments');

			// Llamar a las notificaciones programadas
			$programs = $this->programs();
			$controlErrors['programs'] = $programs;
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Termina la llamada a programs');

			// Llamar a las misiones programadas
			$missions = $this->missions();
			$controlErrors['missions'] = $missions;
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Termina la llamada a missions');

			return json_encode($controlErrors);
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPNotificationsServiceCiclicasTimer($unitTime, $timeEjecution) {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPNotificationsServiceCiclicasTimer';
			$params = [
				'token' => $this->token,
				'TiempoEntreEjecuciones' => $timeEjecution,
				'UnidadDeTiempo' => $unitTime
			];

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

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPNotificationsServiceSchedulePaymentsTimer($unitTime, $timeEjecution) {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPNotificationsServiceSchedulePaymentsTimer';
			$params = [
				'token' => $this->token,
				'TiempoEntreEjecuciones' => $timeEjecution,
				'UnidadDeTiempo' => $unitTime
			];

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

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPNotificationsServiceProgramadasTimer() {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPNotificationsServiceProgramadasTimer';
			$params = [
				'token' => $this->token
			];

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

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPMisionesInicioTimer() {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPMisionesInicioTimer';
			$params = [
				'token' => $this->token
			];

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

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getCMBPMisionesInicioTimer', $resultPOST->status, '');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Fin de getCMBPMisionesInicioTimer');

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPMisionesFinCupo() {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPMisionesFinCupo';
			$params = [
				'token' => $this->token
			];

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

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getCMBPMisionesFinCupo', $resultPOST->status, '');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Fin de getCMBPMisionesFinCupo');

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPMisionesFinTimer() {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPMisionesFinTimer';
			$params = [
				'token' => $this->token
			];

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

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getCMBPMisionesFinTimer', $resultPOST->status, '');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Fin de getCMBPMisionesFinTimer');

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	// Si es misión de encuesta solo al inicio
	// 'silent' => '1',
	public function postMessageMultiple($token, $message, $usuarioQueNotifica, $destinatarios, $listaANotificar, $silent = '', $misionStamp = '', $idProject = '', $initMision = '0', $finMision = '0', $cumplidaMision = '0', $noCumplidaMision = '0', $cupoMision = '0', $validationMision = '0') {
		try {
			$url = CONSTANTS::SERVERAPI . 'postMessageMultiple';
			if($listaANotificar != '') {
				$emailsToSend = '';
			} else {
				$emailsToSend = json_encode($destinatarios);
			}

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'from: ' . $usuarioQueNotifica);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'emailsToSend: ' . $emailsToSend);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'message: ' . $message);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idlist: ' . $listaANotificar);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'silent: ' . $silent);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'misionStamp: ' . $misionStamp);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idProject: ' . $idProject);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'initMision: ' . $initMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'finMision: ' . $finMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'isMision: 0');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'cumplidaMision: ' . $cumplidaMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'noCumplidaMision: ' . $noCumplidaMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'cupoMision: ' . $cupoMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'validationMision: ' . $validationMision); */

			$params = [
				'token' => $token,
				'from' => $usuarioQueNotifica,
				'emailsToSend' => $emailsToSend,
				'message' => $message,
				'idlist' => $listaANotificar,
				'silent' => $silent,
				'misionStamp' => $misionStamp,
				'idProject' => $idProject,
				'initMision' => $initMision,
				'finMision' => $finMision,
				'isMision' => '0',
				'cumplidaMision' => $cumplidaMision,
				'noCumplidaMision' => $noCumplidaMision,
				'cupoMision' => $cupoMision,
				'validationMision' => $validationMision
			];

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

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'resultPOST->status: ' . $resultPOST->status);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'resultPOST->result: ' . $resultPOST->result);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'from: ' . $usuarioQueNotifica);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'emailsToSend: ' . $emailsToSend);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'message: ' . $message);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idlist: ' . $listaANotificar);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'silent: ' . $silent);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'misionStamp: ' . $misionStamp);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idProject: ' . $idProject);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'initMision: ' . $initMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'finMision: ' . $finMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'cumplidaMision: ' . $cumplidaMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'noCumplidaMision: ' . $noCumplidaMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'cupoMision: ' . $cupoMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'validationMision: ' . $validationMision); */

			if($resultPOST->status == 'OK') {
				return true;
			} else {
				return false;
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function addValueToWallet($token, $encuestaID, $idUsers, $importe, $idMision, $stampMission, $currency) {
		try {
			$url = CONSTANTS::SERVERAPI . 'addValueToWallet';
			$params = [
				'token' => $token,
				'survey' => $encuestaID,
				'users' => $idUsers,
				'importe' => $importe,
				'mision' => $idMision,
				'currency' => $currency,
				'stampMision' => $stampMission
			];

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

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'resultPOST->status: ' . $resultPOST->status);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'resultPOST->result: ' . $resultPOST->result);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'survey: ' . $encuestaID);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'users: ' . $idUsers);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'importe: ' . $importe);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'mision: ' . $idMision); */

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'addValueToWallet', $resultPOST->status, '');

			if($resultPOST->status == 'OK') {
				return true;
			} else {
				return false;
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function addProjectsMisionesParticipantes($token, $idMision, $idUsers, $idProject, $estado) {
		try {
			$url = CONSTANTS::SERVERAPI . 'addProjectsMisionesParticipantes';
			$params = [
				'token' => $token,
				'idmision' => $idMision,
				'users' => json_encode($idUsers),
				'project' => $idProject,
				'estado' => $estado
			];

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

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, '/////addProjectsMisionesParticipantes/////');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'token: ' . $token);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idmision: ' . $idMision);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'users: ' . json_encode($idUsers));
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'project: ' . $idProject);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'estado: ' . $estado);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'status: ' . $resultPOST->status);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'result: ' . $resultPOST->result);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, '/////'); */

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'addProjectsMisionesParticipantes', $resultPOST->status, '');

			if($resultPOST->status == 'OK') {
				return true;
			} else {
				return false;
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getCMBPMisionesCumplimientos($token, $sIdUser, $sFfechahorainicioexec, $sFfechahorafinexec) {
		try {
			$url = CONSTANTS::SERVERAPI . 'getCMBPMisionesCumplimientos';
			$params = [
				'token' => $token,
				'user' => $sIdUser,
				'fechahorainicio' => $sFfechahorainicioexec,
				'fechahorafin' => $sFfechahorafinexec
			];

			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getCMBPMisionesCumplimientos - inicio');

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'user ' . $sIdUser);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'fechahorainicio ' . $sFfechahorainicioexec);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'fechahorafin ' . $sFfechahorafinexec); */

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

			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getCMBPMisionesCumplimientos - resultado: ' . $resultPOST->status);

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getCMBPMisionesCumplimientos', $resultPOST->status, '');

			return $resultPOST;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function updateMissionProjectStartEndNotify($idProject, $idMision, $Inicio, $fechahorainicioexec, $fechahorafinexec, $textomisionok, $textomisionko, $importe, $UserQueNotifica, $TipoMision, $idTenant, $idCPG, $needValidation, $stampMission, $currency) {
		try {
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Función updateMissionProjectStartEndNotify - Inicio: ' . $Inicio);
			if($Inicio) {
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Llamada a updateMisionInicioNotificado');
				$result = $this->controller->updateMisionInicioNotificado($this->token, $idProject, $idMision, 1, $idTenant, $idCPG);
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'updateMisionInicioNotificado: ' . $result);
				if($result) {
					if($TipoMision == 'Referidos') {
						$result2 = $this->controller->enableReferrals($this->token);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'enableReferrals: ' . $result2->status);
						if($result2->status == 'OK') {
							return true;
						} else {
							return false;
						}
					} else {
						return true;
					}
				} else {
					return false;
				}
			} else {
				$result = $this->controller->updateMisionFinNotificado($this->token, $idProject, $idMision, 1, $idTenant, $idCPG);
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'updateMisionFinNotificado: ' . $result);
				if($result) {
					$res = false;
					if($TipoMision == 'Referidos') {
						$result2 = $this->controller->disableReferrals($this->token);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'disableReferrals: ' . $result2->status);
						if($result2->status == 'OK') {
							$res = true;
						}
					} else {
						$res = true;
					}

					if($res) {
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio de CheckCumplimientosMision');
						$result = $this->CheckCumplimientosMision($this->token, $idProject, $idMision, $fechahorainicioexec, $fechahorafinexec, $textomisionok, $textomisionko, $importe, $UserQueNotifica, $needValidation, $stampMission, $currency);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'CheckCumplimientosMision: ' . $result);
						return $result;
					} else {
						return $res;
					}
				} else {
					return false;
				}
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function CheckCumplimientosMision($token, $idProject, $idMision, $fechahorainicioexec, $fechahorafinexec, $textomisionok, $textomisionko, $importe, $UserQueNotifica, $needValidation, $stampMission, $currency) {
		try {
			$res = $this->controller->getCMBPMisionesParticipantes($this->token, $idMision, $idProject);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getCMBPMisionesParticipantes: ' . $res->status);
			if($res->status == 'OK' && count($res->result) > 0) {
				$bResult = false;
				$sParamsOK = [];
				$sParamsKO = [];
				foreach($res->result as $mission) {
					// Si la misión es de encuesta
					if($mission->survey != '') {
						if($mission->estadoMision == '1' && $needValidation != '1') {
							array_push($sParamsOK, $mission->idUser);
						} else if($needValidation != '1') {
							array_push($sParamsKO, $mission->idUser);
						}
						$encuestaID = $mission->survey;
					} else {
						$idUser = $mission->idUser;
						$data = [
							'token' => $this->token,
							'idmision' => $idMision
						];

						$res2 = $this->controller->getMisionesObjetivos($data, '1');
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getMisionesObjetivos: ' . $res2->status . ' Num: ' . count($res2->result));

						if($res2->status == 'OK' && count($res2->result) > 0) {
							$allResults = true;

							foreach($res2->result as $objective) {
								$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Bucle: ' . $objective->objetivo);
								$objetivo = $objective->objetivo;
								$numVecesObjetivo = $objective->numveces;
								$periodoParaCumplirObjetivo = $objective->periodo;
								$encuestaID = $objective->encuesta;
								$orderamount = $objective->orderamount;
								$orderamountporcfinanciated = $objective->orderamountporcfinanciated;
								$orderproductunit = $objective->orderproductunit;
								$orderproductnumitems = $objective->orderproductnumitems;
								$orderproductitem = $objective->orderproductitem;
								$ordernumtimes = $objective->ordernumtimes;
								$orderproductamount = $objective->orderproductamount;

								$result = $this->ObjetivoCumplido(
									$idUser,
									$objetivo,
									$numVecesObjetivo,
									$periodoParaCumplirObjetivo,
									$fechahorainicioexec,
									$fechahorafinexec,
									$encuestaID,
									$orderamount,
									$orderamountporcfinanciated,
									$orderproductunit,
									$orderproductnumitems,
									$orderproductitem,
									$ordernumtimes,
									$orderproductamount,
									$idProject,
									$idMision
								);
								$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObjetivoCumplido: ' . $result);

								if(!$result) {
									$allResults = false;
									break;
								}
							}

							if($allResults) {
								array_push($sParamsOK, $idUser);
							} else {
								array_push($sParamsKO, $idUser);
							}
						} else {
							$bResult = false;
						}
					}
				}

				$iNumUsersOK = count($sParamsOK);
				$iNumUsersKO = count($sParamsKO);

				if($iNumUsersOK > 0) {
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'NumUsersOK: ' . count($sParamsOK));
					$sTextoOK = str_replace('%1', $importe, $textomisionok);

					if($encuestaID == '') {
						/*
							Envío de notificación de OK cuando no es encuesta
							Parámetros a partir de $sParamsOK
							$listaANotificar = '',
							$silent = '',
							$misionStamp = '',
							$idProject = '',
							$initMision = '0',
							$finMision = '0',
							$cumplidaMision = '1',
							$noCumplidaMision = '0',
							$cupoMision = '0',
							$validationMision = '0'
						*/
						$resMsg = $this->postMessageMultiple($this->token, $sTextoOK, $UserQueNotifica, $sParamsOK, '', '', '', '', '0', '0', '1', '0', '0', '0');
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'postMessageMultiple: ' . $resMsg);

						if($resMsg) {
							$bResult = true;
						} else {
							$bResult = false;
						}
					} else {
						$bResult = true;
					}

					if($bResult) {
						// Mirar si requiere validacion
						if($encuestaID == '') {
							$usersOK = implode(',', $sParamsOK);
							$resWall = $this->addValueToWallet($this->token, $encuestaID, $usersOK, $importe, $idMision, $stampMission, $currency);
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'addValueToWallet: ' . $resWall);
						} else {
							$resWall = true;
						}

						if($resWall) {
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio de addProjectsMisionesParticipantes OK');

							$res1 = $this->addProjectsMisionesParticipantes($this->token, $idMision, $sParamsOK, $idProject, 'OK');

							/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idMision: ' . $idMision);
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sParamsOK: ' . json_encode($sParamsOK));
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idProject: ' . $idProject); */
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'addProjectsMisionesParticipantes OK: ' . $res1);

							if($res1) {
								$bResult = true;
							} else {
								$bResult = false;
							}
						} else {
							$bResult = true;
						}
					} else {
						$bResult = false;
					}
				} else {
					$bResult = true;
				}

				if($iNumUsersKO > 0) {
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'NumUsersKO: ' . count($sParamsKO));
					$sTextoKO = str_replace('%1', $importe, $textomisionko);
					/*
						Envío de notificación de KO
						Parámetros a partir de $sParamsKO
						$listaANotificar = '',
						$silent = '',
						$misionStamp = '',
						$idProject = '',
						$initMision = '0',
						$finMision = '0',
						$cumplidaMision = '0',
						$noCumplidaMision = '1',
						$cupoMision = '0',
						$validationMision = '0'
					*/
					$res1 = $this->postMessageMultiple($this->token, $sTextoKO, $UserQueNotifica, $sParamsKO, '', '', '', '', '0', '0', '0', '1', '0', '0');
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'postMessageMultiple: ' . $res1);
					if($res1) {
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio de addProjectsMisionesParticipantes KO');
						/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'token: ' . $this->token);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idMision: ' . $idMision);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sParamsKO: ' . json_encode($sParamsKO));
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idProject: ' . $idProject); */

						$res2 = $this->addProjectsMisionesParticipantes($this->token, $idMision, $sParamsKO, $idProject, 'KO');

						/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idMision: ' . $idMision);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sParamsKO: ' . json_encode($sParamsKO));
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idProject: ' . $idProject); */
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'addProjectsMisionesParticipantes KO: ' . ($res2 == false ? 'FALSE' : $res2));

						if($res2) {
							$bResult = true;
						} else {
							$bResult = false;
						}
					} else {
						$bResult = false;
					}
				} else {
					$bResult = true;
				}
			} else {
				$bResult = false;
			}

			return $bResult;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function ObjetivoCumplido($idUser, $objetivo, $numVecesObjetivo, $periodoParaCumplirObjetivo, $fechahorainicioexec, $fechahorafinexec, $encuestaID, $orderamount, $orderamountporcfinanciated, $orderproductunit, $orderproductnumitems, $orderproductitem, $ordernumtimes, $orderproductamount, $idProject, $idMision) {
		try {
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObjetivoCumplido - Periodo: ' . $periodoParaCumplirObjetivo);

			$format = 'd/m/Y H:i:s';
			$datetime1 = DateTime::createFromFormat($format, $fechahorainicioexec);
			$datetime2 = DateTime::createFromFormat($format, $fechahorafinexec);
			$contador = date_diff($datetime1, $datetime2);

			switch($periodoParaCumplirObjetivo) {
				case 'dia':
					$diasAGestionar = $contador->d;

					for($i = 0; $i < $diasAGestionar; $i++) {
						$fechahorafinexec = date_add($datetime1, date_interval_create_from_date_string('1 days'));
						$params = [
							'sIdUser' => $idUser,
							'fechahorainicioexec' => $fechahorainicioexec,
							'fechahorafinexec' => $fechahorafinexec,
							'inumMensajesAGrupo' => 0,
							'inumFotosAGrupo' => 0,
							'inumVideosAGrupo' => 0,
							'inumMensajesIndividual' => 0,
							'inumFotosIndividual' => 0,
							'inumVideosIndividual' => 0,
							'inumVideoCallsTotales' => 0,
							'inumVideoCallsGrupales' => 0,
							'inumVideoCallsIndividuales' => 0,
							'inumActivityPhotos' => 0,
							'inumEscaneoCompras' => 0,
							'inumFotoCompras' => 0,
							'inumEscaneoConsumos' => 0,
							'inumFotoConsumos' => 0,
							'inumVideoCompras' => 0,
							'inumVideoConsumos' => 0,
							'inumReferrals' => 0
						];

						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio de ObtenemosObjetivoEntreFechas');
						$res = $this->ObtenemosObjetivoEntreFechas($params);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObtenemosObjetivoEntreFechas: ' . $res->status);

						$format = 'd/m/Y';
						$startDate = DateTime::createFromFormat($format, $fechahorainicioexec);
						$endDate = DateTime::createFromFormat($format, (string)$fechahorafinexec);

						if($res->status == 'OK') {
							$params = [
								'sObjetivo' => $objetivo,
								'iNumVecesObjetivo' => $numVecesObjetivo,
								'inumMensajesAGrupo' => $res->result[0]->numMensajesAGrupo,
								'inumFotosAGrupo' => 0,
								'inumVideosAGrupo' => 0,
								'inumMensajesIndividual' => $res->result[0]->numMensajesIndividual,
								'inumFotosIndividual' => 0,
								'inumVideosIndividual' => 0,
								'inumVideoCallsTotales' => $res->result[0]->numVideoCallsTotales,
								'inumVideoCallsGrupales' => $res->result[0]->numVideoCallsGrupales,
								'inumVideoCallsIndividuales' => $res->result[0]->numVideoCallsIndividuales,
								'inumActivityPhotos' => 0,
								'inumEscaneoCompras' => 0,
								'inumFotoCompras' => 0,
								'inumEscaneoConsumos' => 0,
								'inumFotoConsumos' => 0,
								'sEncuestaID' => $encuestaID,
								'sIdUser' => $idUser,
								'inumVideoCompras' => 0,
								'inumVideoConsumos' => 0,
								'inumReferrals' => 0,
								'startDate' => $startDate,
								'endDate' => $endDate,
								'numVideoCallsTotalesDesglose' => $res->result[0]->numVideoCallsTotalesDesglose,
								'idProject' => $idProject,
								'idMision' => $idMision
							];

							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio de ValidamosObjetivoCumplido');
							$bRes = $this->ValidamosObjetivoCumplido($params);
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ValidamosObjetivoCumplido: ' . $bRes);

							if(!$bRes) {
								break;
							}
						} else {
							$bRes = false;
						}
					}
					return $bRes;
				break;

				case 'hora':
					$horasAGestionar = $contador->h;

					for($i = 0; $i < $horasAGestionar; $i++) {
						$fechahorafinexec = date_add($datetime1, date_interval_create_from_date_string('1 hour'));
						$params = [
							'sIdUser' => $idUser,
							'fechahorainicioexec' => $fechahorainicioexec,
							'fechahorafinexec' => $fechahorafinexec,
							'inumMensajesAGrupo' => 0,
							'inumFotosAGrupo' => 0,
							'inumVideosAGrupo' => 0,
							'inumMensajesIndividual' => 0,
							'inumFotosIndividual' => 0,
							'inumVideosIndividual' => 0,
							'inumVideoCallsTotales' => 0,
							'inumVideoCallsGrupales' => 0,
							'inumVideoCallsIndividuales' => 0,
							'inumActivityPhotos' => 0,
							'inumEscaneoCompras' => 0,
							'inumFotoCompras' => 0,
							'inumEscaneoConsumos' => 0,
							'inumFotoConsumos' => 0,
							'inumVideoCompras' => 0,
							'inumVideoConsumos' => 0,
							'inumReferrals' => 0
						];

						$res = $this->ObtenemosObjetivoEntreFechas($params);

						if($res->status == 'OK') {
							$format = 'd/m/Y';
							$startDate = DateTime::createFromFormat($format, $fechahorainicioexec);
							$endDate = DateTime::createFromFormat($format, (string)$fechahorafinexec);

							$params = [
								'sObjetivo' => $objetivo,
								'iNumVecesObjetivo' => $numVecesObjetivo,
								'inumMensajesAGrupo' => $res->result[0]->numMensajesAGrupo,
								'inumFotosAGrupo' => 0,
								'inumVideosAGrupo' => 0,
								'inumMensajesIndividual' => $res->result[0]->numMensajesIndividual,
								'inumFotosIndividual' => 0,
								'inumVideosIndividual' => 0,
								'inumVideoCallsTotales' => $res->result[0]->numVideoCallsTotales,
								'inumVideoCallsGrupales' => $res->result[0]->numVideoCallsGrupales,
								'inumVideoCallsIndividuales' => $res->result[0]->numVideoCallsIndividuales,
								'inumActivityPhotos' => 0,
								'inumEscaneoCompras' => 0,
								'inumFotoCompras' => 0,
								'inumEscaneoConsumos' => 0,
								'inumFotoConsumos' => 0,
								'sEncuestaID' => $encuestaID,
								'sIdUser' => $idUser,
								'inumVideoCompras' => 0,
								'inumVideoConsumos' => 0,
								'inumReferrals' => 0,
								'startDate' => $startDate,
								'endDate' => $endDate,
								'numVideoCallsTotalesDesglose' => $res->result[0]->numVideoCallsTotalesDesglose,
								'idProject' => $idProject,
								'idMision' => $idMision
							];

							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Inicio de ValidamosObjetivoCumplido');
							$bRes = $this->ValidamosObjetivoCumplido($params);
							$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ValidamosObjetivoCumplido: ' . $bRes);

							if(!$bRes) {
								break;
							}
						} else {
							$bRes = false;
						}
					}
					return $bRes;
				break;

				default:
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObjetivoCumplido - default');
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sIdUser ' . $idUser);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'fechahorainicioexec ' . $fechahorainicioexec);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'fechahorafinexec ' . $fechahorafinexec);

					$params = [
						'sIdUser' => $idUser,
						'fechahorainicioexec' => $fechahorainicioexec,
						'fechahorafinexec' => $fechahorafinexec,
						'inumMensajesAGrupo' => 0,
						'inumFotosAGrupo' => 0,
						'inumVideosAGrupo' => 0,
						'inumMensajesIndividual' => 0,
						'inumFotosIndividual' => 0,
						'inumVideosIndividual' => 0,
						'inumVideoCallsTotales' => 0,
						'inumVideoCallsGrupales' => 0,
						'inumVideoCallsIndividuales' => 0,
						'inumActivityPhotos' => 0,
						'inumEscaneoCompras' => 0,
						'inumFotoCompras' => 0,
						'inumEscaneoConsumos' => 0,
						'inumFotoConsumos' => 0,
						'inumVideoCompras' => 0,
						'inumVideoConsumos' => 0,
						'inumReferrals' => 0
					];

					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObtenemosObjetivoEntreFechas - inicio');
					$res = $this->ObtenemosObjetivoEntreFechas($params);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObtenemosObjetivoEntreFechas resultado: ' . $res->status);

					$format = 'd/m/Y';
					$startDate = DateTime::createFromFormat($format, $fechahorainicioexec);
					$endDate = DateTime::createFromFormat($format, $fechahorafinexec);

					if($res->status == 'OK') {
						$params = [
							'sObjetivo' => $objetivo,
							'iNumVecesObjetivo' => $numVecesObjetivo,
							'inumMensajesAGrupo' => $res->result[0]->numMensajesAGrupo,
							'inumFotosAGrupo' => 0,
							'inumVideosAGrupo' => 0,
							'inumMensajesIndividual' => $res->result[0]->numMensajesIndividual,
							'inumFotosIndividual' => 0,
							'inumVideosIndividual' => 0,
							'inumVideoCallsTotales' => $res->result[0]->numVideoCallsTotales,
							'inumVideoCallsGrupales' => $res->result[0]->numVideoCallsGrupales,
							'inumVideoCallsIndividuales' => $res->result[0]->numVideoCallsIndividuales,
							'inumActivityPhotos' => 0,
							'inumEscaneoCompras' => 0,
							'inumFotoCompras' => 0,
							'inumEscaneoConsumos' => 0,
							'inumFotoConsumos' => 0,
							'sEncuestaID' => $encuestaID,
							'sIdUser' => $idUser,
							'inumVideoCompras' => 0,
							'inumVideoConsumos' => 0,
							'inumReferrals' => 0,
							'orderamount' => $orderamount,
							'orderamountporcfinanciated' => $orderamountporcfinanciated,
							'orderproductunit' => $orderproductunit,
							'orderproductnumitems' => $orderproductnumitems,
							'orderproductitem' => $orderproductitem,
							'horaIni' => $fechahorainicioexec,
							'horaFin' => $fechahorafinexec,
							'startDate' => $fechahorainicioexec,
							'endDate' => $fechahorafinexec,
							'ordernumtimes' => $ordernumtimes,
							'orderproductamount' => $orderproductamount,
							'numVideoCallsTotalesDesglose' => $res->result[0]->numVideoCallsTotalesDesglose,
							'idProject' => $idProject,
							'idMision' => $idMision
						];

						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ValidamosObjetivoCumplido - inicio');
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sObjetivo ' . $objetivo);
						$ValidamosObjetivoCumplido = $this->ValidamosObjetivoCumplido($params);
						$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ValidamosObjetivoCumplido resultado: ' . $ValidamosObjetivoCumplido);

						return $ValidamosObjetivoCumplido;
					} else {
						return false;
					}
				break;
			}

			return false;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function ObtenemosObjetivoEntreFechas($params) {
		try {
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'ObtenemosObjetivoEntreFechas - Entra en la función');
			$format = 'd/m/Y H:i:s';

			$date = DateTime::createFromFormat($format, $params['fechahorainicioexec']);
			$sFfechahorainicioexec = $date->format('Y-m-d H:i');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sFfechahorainicioexec - ' . $sFfechahorainicioexec);

			$date = DateTime::createFromFormat($format, $params['fechahorafinexec']);
			$sFfechahorafinexec = $date->format('Y-m-d H:i');
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sFfechahorafinexec - ' . $sFfechahorafinexec);

			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getCMBPMisionesCumplimientos - inicio');
			$res = $this->getCMBPMisionesCumplimientos($this->token, $params['sIdUser'], $sFfechahorainicioexec, $sFfechahorafinexec);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getCMBPMisionesCumplimientos resultado: ' . $res->status);

			return $res;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function ValidamosObjetivoCumplido($params) {
		try {
			switch($params['sObjetivo']) {
				case 'Referidos':
					if($params['inumReferrals'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoProductoCompra':
					if($params['inumVideoCompras'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoProductoConsumo':
					if($params['inumVideoConsumos'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'ConversacionChatUnitario':
					if($params['inumMensajesIndividual'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'ConversacionChatGrupal':
					if($params['inumMensajesAGrupo'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'EscaneoProductoCompra':
					if($params['inumEscaneoCompras'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'EscaneoProductoConsumo':
					if($params['inumEscaneoConsumos'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'FotoActividad':
					if($params['inumActivityPhotos'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'FotoChatGrupal':
					if($params['inumFotosAGrupo'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'FotoChatUnitario':
					if($params['inumFotosIndividual'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'FotoProductoCompra':
					if($params['inumFotoCompras'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'FotoProductoConsumo':
					if($params['inumFotoConsumos'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoCallGrupal':
					$projectControl = false;
					foreach($params['numVideoCallsTotalesDesglose'] as $projectVal) {
						if($projectVal->idProject == $params['idProject']) {
							$projectControl = true;
						}
					}

					if(($params['inumVideoCallsGrupales'] >= $params['iNumVecesObjetivo']) && $projectControl) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoCallUnitaria':
					$projectControl = false;
					foreach($params['numVideoCallsTotalesDesglose'] as $projectVal) {
						if($projectVal->idProject == $params['idProject']) {
							$projectControl = true;
						}
					}

					/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'projectControl - ' . $projectControl);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'idProject - ' . $params['idProject']);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'inumVideoCallsIndividuales - ' . $params['inumVideoCallsIndividuales']); */

					if(($params['inumVideoCallsIndividuales'] >= $params['iNumVecesObjetivo']) && $projectControl) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoCall':
					if($params['inumVideoCallsTotales'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoChatGrupal':
					if($params['inumVideosAGrupo'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'VideoChatUnitario':
					if($params['inumVideosIndividual'] >= $params['iNumVecesObjetivo']) {
						return true;
					} else {
						return false;
					}
				break;

				case 'Encuesta':
					/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getSurveyExecutedByUser - inicio');
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sEncuestaID' . $params['sEncuestaID']);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'sIdUser ' . $params['sIdUser']); */

					$surveyVal = $this->getSurveyExecutedByUser(
						$this->token,
						$params['sEncuestaID'],
						$params['sIdUser'],
						$params['idMision']
					);

					if($surveyVal == false) {
						return false;
					} else {
						return true;
					}
				break;

				case 'Pedido (Importe)':
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountOrderedByUser - inicio');

					$amountPurchased = $this->getAmountOrderedByUser(
						$this->token,
						$params['sIdUser'],
						$params['orderamount'],
						$params['orderamountporcfinanciated'],
						$params['startDate'],
						$params['endDate']
					);

					if($amountPurchased == false) {
						return false;
					} else {
						return true;
					}
				break;

				case 'Pedido (Producto)':
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductPurchasedByUser - inicio');

					$productPurchased = $this->getProductPurchasedByUser(
						$this->token,
						$params['sIdUser'],
						$params['orderproductitem'],
						$params['orderproductnumitems'],
						$params['startDate'],
						$params['endDate']
					);

					if($productPurchased == false) {
						return false;
					} else {
						return true;
					}
				break;

				case 'Pedido (Artículo/Importe)':
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser - inicio');

					$productPurchased = $this->getProductsAmountFromOrdersByUser(
						$this->token,
						$params['sIdUser'],
						$params['orderproductitem'],
						$params['orderproductamount'],
						$params['startDate'],
						$params['endDate']
					);

					if($productPurchased == false) {
						return false;
					} else {
						return true;
					}
				break;

				case 'Pedido (Num. Pedidos)':
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser - inicio');

					$productPurchased = $this->getOrderTimesFromOrdersByUser(
						$this->token,
						$params['sIdUser'],
						$params['ordernumtimes'],
						$params['orderamountporcfinanciated'],
						$params['startDate'],
						$params['endDate']
					);

					if($productPurchased == false) {
						return false;
					} else {
						return true;
					}
				break;

				case 'PassiveTracking':
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getPassiveTrackingDoneByUser - inicio');

					$passiveTracking = $this->getPassiveTrackingDoneByUser(
						$this->token,
						$params['sIdUser'],
						$params['horaIni'],
						$params['horaFin']
					);

					if($passiveTracking == false) {
						return false;
					} else {
						return true;
					}
				break;

				default:
					// ADVERTENCIA: El tipo de objetivo analizado no es de la apliación.
					return false;
				break;
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getSurveyExecutedByUser($token, $encuestaID, $idUser, $idMision) {
		try {
			$url = CONSTANTS::SERVERAPI . 'getSurveyExecutedByUser';
			$params = [
				'token' => $token,
				'survey' => $encuestaID,
				'user' => $idUser,
				'mision' => $idMision
			];

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

			if($resultPOST->status == 'OK' && $resultPOST->result > 0) {
				return true;
			} else {
				return false;
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getProductPurchasedByUser($token, $idUser, $productCode, $productNum, $startDate, $endDate) {
		try {
			// We obtain the products from the user
			$url = CONSTANTS::SERVERAPI . 'getProductsFromOrdersByUser';
			$var = explode('@', $idUser);
			$username = $var[0];

			$format = 'd/m/Y H:i:s';
			$dateStart = DateTime::createFromFormat($format, $startDate);
			$dateStartFinal = $dateStart->format('Y-m-d H:i');
			$dateEnd = DateTime::createFromFormat($format, $endDate);
			$dateEndFinal = $dateEnd->format('Y-m-d H:i');

			$params = [
				'token' => $token,
				'username' => $username,
				'startDate' => $dateStartFinal,
				'endDate' => $dateEndFinal
			];

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

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser username: ' . $username);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser startDate: ' . $startDate);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser endDate: ' . $endDate); */

			if($resultPOST->status == 'OK' && count($resultPOST->result) > 0) {
				$item = null;
				foreach($resultPOST->result as $product) {
					/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser productCode: ' . $productCode);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser product_code: ' . $product->product_code); */

					if($productCode == $product->product_code) {
						$item = $product;
						break;
					}
				}

				/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser productNum: ' . $productNum);
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsFromOrdersByUser total_product_quantity: ' . $item->total_product_quantity); */

				if($item == null) {
					// We haven't found the product
					return false;
				} else if($item->total_product_quantity < $productNum) {
					// The quantity bought is less than the objective defiened quantity
					return false;
				}

				return true;
			} else {
				return false;
			}

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getProductsFromOrdersByUser', $resultPOST->status, '');
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getProductsAmountFromOrdersByUser($token, $idUser, $productCode, $orderproductamount, $startDate, $endDate) {
		try {
			// We obtain the products from the user
			$url = CONSTANTS::SERVERAPI . 'getProductsAmountFromOrdersByUser';
			$var = explode('@', $idUser);
			$username = $var[0];

			$format = 'd/m/Y H:i:s';
			$dateStart = DateTime::createFromFormat($format, $startDate);
			$dateStartFinal = $dateStart->format('Y-m-d H:i');
			$dateEnd = DateTime::createFromFormat($format, $endDate);
			$dateEndFinal = $dateEnd->format('Y-m-d H:i');

			$params = [
				'token' => $token,
				'username' => $username,
				'startDate' => $dateStartFinal,
				'endDate' => $dateEndFinal
			];

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

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser username: ' . $username);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser startDate: ' . $startDate);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser endDate: ' . $endDate); */

			if($resultPOST->status == 'OK' && count($resultPOST->result) > 0) {
				$item = null;
				foreach($resultPOST->result as $product) {
					/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser productCode: ' . $productCode);
					$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser product_code: ' . $product->product_code); */

					if($productCode == $product->product_code) {
						$item = $product;
						break;
					}
				}

				/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser productAmount: ' . $orderproductamount);
				$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getProductsAmountFromOrdersByUser totalAmount: ' . $item->totalAmount); */

				if($item == null) {
					// We haven't found the product
					return false;
				} else if($item->totalAmount < $orderproductamount) {
					// Para un gasto menor que el marcado en la misión
					return false;
				}

				return true;
			} else {
				return false;
			}

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getProductsAmountFromOrdersByUser', $resultPOST->status, '');
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getPassiveTrackingDoneByUser($token, $idUser, $startDate, $endDate) {
		try {
			// We obtain the products from the user
			$format = 'd/m/Y H:i:s';
			$startDateFormated = DateTime::createFromFormat($format, $startDate);
			$endDateFormated = DateTime::createFromFormat($format, $endDate);
			$SstartDateFormated = $startDateFormated->format('Y/m/d H:i:s');
			$SendDateFormated = $endDateFormated->format('Y/m/d H:i:s');

			$url = CONSTANTS::SERVERAPI . 'getPassiveTrackingDataByUser';
			$var = explode('@', $idUser);
			$username = $var[0];
			$params = [
				'token' => $token,
				'username' => $username,
				'startDate' => $SstartDateFormated,
				'endDate' => $SendDateFormated
			];

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

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

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getPassiveTrackingDataByUser', $resultPOST->status, '');
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getAmountOrderedByUser($token, $idUser, $totalAmount, $percentCredit, $startDate, $endDate) {
		try {
			// We obtain the amount from the user
			$url = CONSTANTS::SERVERAPI . 'getAmountFromOrdersByUser';
			$var = explode('@', $idUser);
			$username = $var[0];

			$format = 'd/m/Y H:i:s';
			$dateStart = DateTime::createFromFormat($format, $startDate);
			$dateStartFinal = $dateStart->format('Y-m-d H:i');
			$dateEnd = DateTime::createFromFormat($format, $endDate);
			$dateEndFinal = $dateEnd->format('Y-m-d H:i');

			$params = [
				'token' => $token,
				'username' => $username,
				'startDate' => $dateStartFinal,
				'endDate' => $dateEndFinal
			];

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser username: ' . $username);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser startDate: ' . $startDate);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser endDate: ' . $endDate);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser totalAmount: ' . $totalAmount);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser total_amount: ' . $resultPOST->result[0]->total_amount);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser percentCredit: ' . $percentCredit);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getAmountFromOrdersByUser percent_credit: ' . $resultPOST->result[0]->percent_credit); */

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

			if($resultPOST->status == 'OK' && count($resultPOST->result) > 0) {
				if($resultPOST->result[0]->total_amount < $totalAmount || $resultPOST->result[0]->percent_credit < $percentCredit) {
					// The user hasn't spent what the objective said
					return false;
				} else {
					// The quantity bought is less than the objective defiened quantity
					return true;
				}
			} else {
				return false;
			}

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getAmountFromOrdersByUser', $resultPOST->status, '');
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function getOrderTimesFromOrdersByUser($token, $idUser, $ordernumtimes, $percentCredit, $startDate, $endDate) {
		try {
			// We obtain the amount from the user
			$url = CONSTANTS::SERVERAPI . 'getOrderTimesFromOrdersByUser';
			$var = explode('@', $idUser);
			$username = $var[0];

			$format = 'd/m/Y H:i:s';
			$dateStart = DateTime::createFromFormat($format, $startDate);
			$dateStartFinal = $dateStart->format('Y-m-d H:i');
			$dateEnd = DateTime::createFromFormat($format, $endDate);
			$dateEndFinal = $dateEnd->format('Y-m-d H:i');

			$params = [
				'token' => $token,
				'username' => $username,
				'startDate' => $dateStartFinal,
				'endDate' => $dateEndFinal
			];

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

			/* $this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser username: ' . $username);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser startDate: ' . $startDate);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser endDate: ' . $endDate);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser ordernumtimes: ' . $ordernumtimes);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser total_orders: ' . $resultPOST->result[0]->total_orders);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser percentCredit: ' . $percentCredit);
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'getOrderTimesFromOrdersByUser percent_credit: ' . $resultPOST->result[0]->percent_credit); */

			if($resultPOST->status == 'OK' && count($resultPOST->result) > 0) {
				if($resultPOST->result[0]->total_orders < $ordernumtimes || $resultPOST->result[0]->percent_credit < $percentCredit) {
					// The user hasn't spent what the objective said
					return false;
				} else {
					// The quantity bought is less than the objective defiened quantity
					return true;
				}
			} else {
				return false;
			}

			// LOG
			$this->controller->setCMBPLOG($this->token, 'SERVICE', 'getOrderTimesFromOrdersByUser', $resultPOST->status, '');
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function schedule_payments() {
		try {
			$returnSchedulePayments = 'OK';
			$schedule_payments = $this->controller->getCMBPNotificationsServiceSchedulePayments($this->token);

			if($schedule_payments->status == 'OK' && count($schedule_payments->result) > 0) {
				foreach($schedule_payments->result as $result) {
					$unitTime = $result->UnidadDeTiempo;
					$timeEjecution = $result->TiempoEntreEjecuciones;

					// Obtengo los id de las notificaciones a ejecutar
					$notifications = $this->getCMBPNotificationsServiceSchedulePaymentsTimer($unitTime, $timeEjecution);

					if($notifications->status == 'OK' && count($notifications->result) > 0) {
						foreach($notifications->result as $notification) {
							// Comprobación de ciclo
							if(isset($notification->UltimaEjecucion) && $notification->UltimaEjecucion != '') {
								date_default_timezone_set(date_default_timezone_get());
								$dateNow = strtotime(date('d-m-Y H:i:00', time()));
								$dateLastNotIni = $notification->UltimaEjecucion;

								// Dividir en fecha y hora
								$dateLastNotArray = explode(' ', $dateLastNotIni);

								// Fecha
								$dateArray = explode('-', $dateLastNotArray[0]);
								$dateLast = $dateArray[2] . '-' . $dateArray[1] . '-' . $dateArray[0];

								// Dividir en hora, minutos y segundos
								$dateLastNotTimeArray = explode(':', $dateLastNotArray[1]);

								// Crear la fecha/hora de la última ejecución pasando los segundos a 00
								$dateLastNot = $dateLast . ' ' . $dateLastNotTimeArray[0] . ':' . $dateLastNotTimeArray[1] . ':00';

								$period = $notification->TiempoEntreEjecuciones;
								$interval = $notification->UnidadDeTiempo;
								$tInter = '';

								switch($interval) {
									case 'minutos':
										$tInter = ' minute';
										break;
									case 'horas':
										$tInter = ' hour';
										break;
									case 'días':
										$tInter = ' days';
										break;
								}

								$dateInterval = strtotime('+' . $period . $tInter, strtotime($dateLastNot));

								// TTT Problemas con el timezone 'America/Mexico_City' ya que PHP no está actualizado a la anulación del cambio de horario
								/* if(date_default_timezone_get() == "America/Mexico_City") {
									$dateNow -= 3600;
								} */

								if($dateNow < $dateInterval) {
									continue;
								}
							}
							// Ejecuto las notificaciones mediante su id
							$executeNot = $this->controller->executeNofiticationSchedulePayments($notification->id, $this->token);

							if($executeNot->status == 'KO') {
								$returnSchedulePayments = 'executeNofiticationSchedulePayments KO';
							}
						}
					} else if($notifications->status == 'KO') {
						$returnSchedulePayments = 'getCMBPNotificationsServiceSchedulePaymentsTimer KO';
					}
				}
			} else if($schedule_payments->status == 'KO') {
				$returnSchedulePayments = 'getCMBPNotificationsServiceSchedulePayments KO';
			}
			return $returnSchedulePayments;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function programs() {
		try {
			$returnPrograms = 'OK';

			//Comprobar si hay alguna notificacion programada que ejecutar
			$programs = $this->getCMBPNotificationsServiceProgramadasTimer();
			if($programs->status == 'OK' && count($programs->result) > 0) {
				foreach($programs->result as $result) {
					// El servicio 'getCMBPNotificationsServiceProgramadasTimer' devolverá los mensajes que ya deben ser enviados

					$date = new DateTime();

					// Obtengo los id de las notificaciones a ejecutar
					$execute = $this->controller->executeNofitication($result->id, $this->token, '1');

					if($execute->status == 'OK') {
						$update = $this->controller->updateCMBPNotificationsExecution($result->id, $date->format('d/m/Y H:i:s'), '', '', $this->token, $result->idTenant, $result->idCPG);

						if($update->status == 'KO') {
							$returnPrograms = 'updateCMBPNotificationsExecution KO';
						}
					} else if($execute->status == 'KO') {
						$returnPrograms = 'executeNofitication KO';
					}
				}
			} else if($programs->status == 'KO') {
				$returnPrograms = 'getCMBPNotificationsServiceProgramadasTimer KO';
			}

			return $returnPrograms;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function missions() {
		try {
			$returnMissions = [
				'endMission' => 'OK'
			];

			// Fin mision
			$endMission = $this->missionEndService(false);
			$returnMissions['endMission'] = $endMission;
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Termina la llamada a missionEndService de fin');

			return json_encode($returnMissions);
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	// Duplicated just for reference
	public function missionStartService($start = true) {
		// Migration is complete
	}

	public function missionEndService($start) {
		
		$res = $this->updateMissionProjectStartEndNotify(
				$missionCupo->idProject,
				$missionCupo->idmision,
				$start,
				$missionCupo->fechahorainicioexec,
				$missionCupo->fechahorafinexec,
				$missionCupo->textomisionok,
				$missionCupo->textomisionko,
				$missionCupo->importe,
				$missionCupo->LiderProyectoJID,
				$missionCupo->tipomision,
				$missionCupo->idTenant,
				$missionCupo->idCPG,
				$missionCupo->needValidation,
				$missionCupo->stampMision,
				$missionCupo->currency
			);
														

			// Comprobación de fin
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Llamada a getCMBPMisionesFinTimer');
			$missions = $this->getCMBPMisionesFinTimer();
			$this->LogToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE, 'Resultado de getCMBPMisionesFinTimer: ' . $missions->status);

			if($missions->status == 'KO') {
				$returnMissionsService = 'getCMBPMisionesFinTimer KO';
			}
			}


			return $returnMissionsService;
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function LogToFile($file, $message) {
		try {
			$nombre_archivo = $file;
			$nombre_archivo = CONSTANTS::REGISTER_LOGS_SERVICE_PATH . $file;

			if(CONSTANTS::REGISTER_LOGS_SERVICE) {
				if($archivo = fopen($nombre_archivo, 'a')) {
					fwrite($archivo, date('Y-m-d H:i:s') . "\t|| " . $message . " \n");
					fclose($archivo);
				}
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}

	public function ErrorToFile($file, $message) {
		try {
			$nombre_archivo = $file;
			$nombre_archivo = CONSTANTS::REGISTER_LOGS_SERVICE_PATH . $file;

			if($archivo = fopen($nombre_archivo, 'a')) {
				fwrite($archivo, date('Y-m-d H:i:s') . "\t|| " . $message . " \n");
				fclose($archivo);
			}
		} catch(Exception $e) {
			$error = __FUNCTION__ . ': Excepción capturada: ' . $e->getMessage();
			$this->ErrorToFile(CONSTANTS::REGISTER_LOGS_SERVICE_FILE_ERROR, $error);
			return $error;
		}
	}
}