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

class GruposController {
	private $utilesController;

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

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

		if($client['groups'] != '[]') {
			foreach($client['groups'] as $group) {
				$params = [
					'token' => $client['token'],
					'groupName' => $group['groupName'],
					'groupId' => $group['groupId']
				];

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

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

		return $resultPOST;
	}

	// Añadir grupo nuevo
	public function newGroup($client) {
		$response = [];
		$response['status'] = 'OK';

		// Creamos el grupo
		$url = CONSTANTS::SERVERAPI . 'createGroup';
		$params = [
			'token' => $client['token'],
			'groupAdmin' => $client['group']['groupAdmin'],
			'groupName' => $client['group']['groupName'],
			'participants' => json_encode($client['group']['participants']),
			'country' => $client['group']['country']
		];

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

		if($resultPOST->status == 'OK') {
			// Obtenemos el id del grupo que acabamos de crear
			$jid = $resultPOST->result;
			$url = CONSTANTS::SERVERAPI . 'getGroupJidByID';
			$params = [
				'token' => $client['token'],
				'groupId' => $jid
			];

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

			if($resultPOST->status == 'OK') {
				$idGroupComp = $resultPOST->result;
				// Notificar al grupo
				$url = CONSTANTS::SERVERAPI . 'postGroupSystemMessageWithPush';
				$params = [
					'token' => $client['token'],
					'message' => $client['group']['admin'] . ' ' . $client['creation'] . ' ' . $client['group']['groupName'],
					'to' => $idGroupComp,
					'from' => $client['group']['groupAdmin']
				];

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

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

				// Comprobamos si hay que añadir informacion de bots
				if($client['botConfig']['directLineSecret'] != '') {
					// Creamos la configuracion del bot para el grupo que acabamos de crear
					$url = CONSTANTS::SERVERAPI . 'setBotConfig';
					$params = [
						'token' => $client['token'],
						'idUserOrGroup' => $idGroupComp,
						'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']['textoNotificarNoMatch'],
						'SaludoInicial' => $client['botConfig']['SaludoInicial']
					];

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

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

		return $response;
	}

	// Usuarios pertenecientes a un grupo
	public function getAllUsersGroup($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'groupId' => $client['groupId']
		];

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

		return $resultPOST;
	}

	// Editar grupo
	public function editGroup($client) {
		$response['status'] = 'OK';

		// Identificador de grupo
		$url = CONSTANTS::SERVERAPI . 'getGroupJidByID';
		$params = [
			'token' => $client['token'],
			'groupId' => $client['groupId']
		];

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

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

		$groupJid = $resultPOST->result;

		$url = CONSTANTS::SERVERAPI . 'updateGroupCountry';
		$params = [
			'token' => $client['token'],
			'groupId' => $client['groupId'],
			'country' => $client['group']['country']
		];

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

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

		// Editar nombre
		if($client['isEditName'] == 1) {
			$url = CONSTANTS::SERVERAPI . 'renameGroup';
			$params = [
				'token' => $client['token'],
				'groupId' => $client['groupId'],
				'newName' => $client['group']['groupName']
			];

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

			if($resultPOST->status == 'OK') {
				// Notificar al grupo
				$url = CONSTANTS::SERVERAPI . 'postGroupSystemMessage';
				$params = [
					'token' => $client['token'],
					'message' => $client['nameChange'] . ' ' . $client['group']['groupName'],
					'to' => $groupJid,
					'from' => $client['group']['nameAdmin']
				];

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

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

		// Comprobar usuarios nuevos
		$addMembers = [];
		foreach($client['group']['participants'] as $member) {
			$search = in_array($member, $client['group']['participantsOld']);
			if(!$search) {
				array_push($addMembers, $member);
			}
		}

		if(count($addMembers) > 0) {
			$url = CONSTANTS::SERVERAPI . 'addToGroup';
			$params = [
				'token' => $client['token'],
				'groupId' => $client['groupId'],
				'participants' => json_encode($addMembers)
			];

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

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

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

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

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

		// Comprobar usuarios a eliminar
		$removeMembers = [];
		foreach($client['group']['participantsOld'] as $member) {
			$search = in_array($member, $client['group']['participants']);

			if(!$search) {
				array_push($removeMembers, $member);
			}
		}

		if(count($removeMembers) > 0) {
			$url = CONSTANTS::SERVERAPI . 'takeOutFromGroup';
			$params = [
				'token' => $client['token'],
				'groupId' => $client['groupId'],
				'participants' => json_encode($removeMembers)
			];

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

			if($resultPOST->status) {
				return $resultPOST;
			}
		}

		// Editar administrador
		if($client['isEditAdmin'] == 1) {
			$url = CONSTANTS::SERVERAPI . 'newAdminUserGroup';
			$params = [
				'token' => $client['token'],
				'groupId' => $client['groupId'],
				'jid' => $client['group']['idAdmin']
			];

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

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

		// Cambiar configuracion bots
		if($client['isEditBot'] == 1) {
			$url = CONSTANTS::SERVERAPI . 'setBotConfig';
			$params = [
				'token' => $client['token'],
				'idUserOrGroup' => $client['botConfig']['idUserOrGroup'],
				'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']
			];

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

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