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

class ConfiguracionController {
	private $utilesController;

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

	// Peticion de políticas
	public function getPoliciesByID($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => CONSTANTS::POLITICS
		];

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

		return $resultPOST;
	}

	// Guardar políticas
	public function setPolicies($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$archivo = fopen(CONSTANTS::PATH_EXPORT_WORD . '/' . CONSTANTS::POLITICS, 'w') or die('Error creating file!');
		$txt = $client['file'];
		fwrite($archivo, $txt);
		fclose($archivo);

		$file = new CURLFile(CONSTANTS::PATH_EXPORT_WORD . '/' . CONSTANTS::POLITICS, 'file/html', CONSTANTS::POLITICS);

		$params = [
			'token' => $client['token'],
			'file' => $file
		];

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

		return $resultPOST;
	}

	// Configuracion general
	public function getCMBPConfig($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

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

		// Registro de errores
		if($resultPOST->status == 'OK') {
			$resultPOST->result[0]->cdp_endpoint_KEY = $this->utilesController->OpenSSLDecrypt($resultPOST->result[0]->cdp_endpoint_KEY);
		}

		return $resultPOST;
	}

	// Actualizar configuración general
	public function setCMBPConfig($client) {
		$url = CONSTANTS::SERVERAPI . 'getCMBPConfig';
		$params = [
			'token' => $client['token']
		];

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

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

		$maxSize = $resultPOST->result[0]->upload_max_filesize_bytes;
		$tipoPerfilacionOld = $resultPOST->result[0]->TipoPerfilacion;

		$colors = '[';
		$i = 0;
		foreach($client['colores'] as $color) {
			$colors .= '"' . $color . '"';
			if($i < (count($client['colores']) - 1)) {
				$colors .= ',';
			}
			$i++;
		}
		$colors .= ']';

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'APIUserPassword' => '',
			'SMTPServer' => $client['SMTPServer'],
			'SMTPUser' => $client['SMTPUser'],
			'SMTPUserPassword' => $client['SMTPUserPassword'],
			'SMTPSSL' => $client['SMTPSSL'],
			'SMTPNombreMail' => $client['SMTPNombreMail'],
			'SMTPPort' => $client['SMTPPort'],
			'LOGRowsLoad' => $client['LOGRowsLoad'],
			'SYSNotifUser' => $client['SYSNotifUser'],
			'SYSNotifUserName' => $client['SYSNotifUserName'],
			'SYSMisionsUser' => $client['SYSMisionsUser'],
			'SYSMisionsUserName' => $client['SYSMisionsUserName'],
			'FormatoFechaServer' => $client['FormatoFechaServer'],
			'FormatoHoraServer' => $client['FormatoHoraServer'],
			'URLEncuestas' => $client['URLEncuestas'],
			'URLQnA' => $client['URLQnA'],
			'URLWordCloud' => $client['URLWordCloud'],
			'RGBInicio' => $client['RGBInicio'],
			'RGBFin' => $client['RGBFin'],
			'numPreguntasPerfilacionEnAnalyticMostreo' => $client['numPreguntasPerfilacionEnAnalyticMostreo'],
			'URLWordCloudSurvey' => $client['URLWordCloudSurvey'],
			'URLPoliticasPrivacidad' => $client['URLPoliticas'],
			'URLVideoCalls' => $client['URLVideoCalls'],
			'URLMarket' => $client['URLMarket'],
			'FontAnalytics' => $client['FontAnalytics'],
			'SizeFontAnalytics' => $client['SizeFontAnalytics'],
			'UsarColorDegradado' => $client['UsarColorDegradado'],
			'colores' => $colors,
			'minutesToDelete' => $client['minutesToDelete'],
			'minutesToEdit' => $client['minutesToEdit'],
			'defaultRoleUser' => $client['defaultRoleUser'],
			'TipoPerfilacion' => $client['TipoPerfilacion'],
			'SurveyPerfilacionDefault' => $client['SurveyPerfilacionDefault'],
			'QuestionGenero' => $client['QuestionGenero'],
			'QuestionEstado' => $client['QuestionEstado'],
			'QuestionEdad' => $client['QuestionEdad'],
			'splitCharacter' => $client['splitCharacter'],
			'colorprincipal' => $client['colorprincipal'],
			'colorsecundario' => $client['colorsecundario'],
			'mailingImageVisible' => $client['mailingImageVisible'],
			'mailingImagePosition' => $client['mailingImagePosition'],
			'xmpp_domain' => $client['xmpp_domain'],
			'secondsTracking' => $client['secondsTracking'],
			'numWordSentenceWordCloud' => $client['numWordSentenceWordCloud'],
			'URLAndroid' => $client['URLAndroid'],
			'URLiOS' => $client['URLiOS'],
			'minutesBlockTry' => $client['minutesBlockTry'],
			'numErrorLogin' => $client['numErrorLogin'],
			'minutesResetErrorLogin' => $client['minutesResetErrorLogin'],
			'sp_perfilacion_default' => $client['sp_perfilacion_default'],
			'azureCognitiveLenguajeKEY' => $client['azureCognitiveLenguajeKEY'],
			'azureCognitiveLenguajeRegion' => $client['azureCognitiveLenguajeRegion'],
			'azureCognitiveVisualHost' => $client['azureCognitiveVisualHost'],
			'azureCognitiveVisualKEY' => $client['azureCognitiveVisualKEY'],
			'azureCognitiveTextHost' => $client['azureCognitiveTextHost'],
			'azureCognitiveTextKEY' => $client['azureCognitiveTextKEY'],
			'azureCognitiveTranslatorKEY' => $client['azureCognitiveTranslatorKEY'],
			'azureCognitiveTranslatorHost' => $client['azureCognitiveTranslatorHost'],
			'azureCognitiveTranslatorRegion' => $client['azureCognitiveTranslatorRegion'],
			'googleMapsAPIKey' => $client['googleMapsAPIKey'],
			'twilioSSID' => $client['twilioSSID'],
			'twilioToken' => $client['twilioToken']
		];

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

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

		// Cambio de teléfonos para Twilio
		if($client['twilioValuesChange'] == '1') {
			$url = CONSTANTS::SERVERAPI . 'setTwilioCountriesTelphone';

			$twilioValues = '[';
			$size = count($client['twilioValues']);
			for($j = 0; $j < $size; $j++) {
				if($twilioValues != '[') {
					$twilioValues .= ',';
				}

				$twilioValues .= '"' . $client['twilioValues'][$j]['isocode'] . '#' . $client['twilioValues'][$j]['telefono'] . '"';
			}

			$twilioValues .= ']';

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

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

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

		// Si cambia el tipo de perfilación
		if($tipoPerfilacionOld != $client['TipoPerfilacion']) {
			// Notificación en log
			$type = 'Profiling type changed';
			$service = $client['userMail'];
			$event = 'Se ha cambiado el tipo de perfilación de tipo ' . $tipoPerfilacionOld . ' a tipo ' . $client['TipoPerfilacion'];

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

		if($client['TipoPerfilacion'] == 3 && $client['countries'] != '') {
			// Países / Perfilación
			$result = $this->setSurveyCountry($client['token'], $client['countries']);

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

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

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

			if($file['size'] <= $maxSize) {
				$type = $file['type'];
				$type_Array = explode('/', $type);
				$tempName = 'tempName.' . $type_Array[1];

				$repPath = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $client['idTenant'];

				move_uploaded_file($file['tmp_name'], $repPath . '/' . $tempName);

				// Modifiacion imagen 
				$original_path = $repPath . '/' . $tempName;

				$original_image_data = $this->utilesController->createImageFromSource($original_path, $type);

				$original_width = getimagesize($original_path)[0];
				$original_height = getimagesize($original_path)[1];

				if($key == 'logo') {
					$new_width = 139;
				} else {
					$new_width = 1270;
				}

				$new_height = $original_height * $new_width / $original_width;

				$hdpi = $this->utilesController->resizeImage($original_image_data, $original_width, $original_height, $new_width, $new_height);

				imagepng($hdpi, $repPath . '/' . $new_name);
				unlink($original_path);
			}
		}

		// Herramientas
		$url = CONSTANTS::SERVERAPI . 'execSocialTools';

		// Cambio de colores
		if($client['colorprincipal'] != $client['colorPriOld'] || $client['colorsecundario'] != $client['colorSecOld']) {
			$params = [
				'token' => $client['token'],
				'tool' => 5,
				'color' => $client['colorsecundario'],
				'oldColor' => $client['colorprincipal']
			];

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

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

		// Tenant
		if($client['tenantChanges'] === true) {
			$url = CONSTANTS::SERVERAPI . 'updateTenantLookAndFeel';
			$params = [
				'token' => $client['token'],
				'idTenant' => $client['idTenant'],
				'colorPrimario' => $client['tenantColorPrimario'],
				'colorSecundario' => $client['tenantColorSecundario'],
				'colorMenu1' => $client['colorMenu1'],
				'colorFuenteMenu1' => $client['colorFuenteMenu1'],
				'colorMenu2' => $client['colorMenu2'],
				'colorFuenteMenu2' => $client['colorFuenteMenu2'],
				'colorMenu3' => $client['colorMenu3'],
				'colorFuenteMenu3' => $client['colorFuenteMenu3']
			];

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

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

			// Imágenes de tenant
			$files = [
				'logoPrimario' => 'logo.png',
				'logoSecundario' => 'logo_home.png',
				'favicon' => 'favicon.ico',
				'logoEmail' => 'logo_email.png',
				'logoWalletApp' => 'wallet_card.png',
				'logoWelcomeApp' => 'logo_welcome.png',
				'logoIcon' => 'logo_icon.png',
				'logoLogin' => 'logo_login.png'
			];

			// Ruta de tenant
			$tenantPath = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $client['idTenant'];

			if(isset($_FILES)) {
				// Recibir imagenes
				foreach($files as $key => $new_name) {
					if(isset($_FILES[$key])) {
						$file = $_FILES[$key];
						$type = $file['type'];
						$type_Array = explode('/', $type);

						if($key != 'favicon' && $type_Array[1] != 'png') {
							// Cambio de imagen a .png
							$nameTemp = $file['tmp_name'];
							imagepng(imagecreatefromstring(file_get_contents($nameTemp)), $tenantPath . '/' . $new_name);
						} else {
							move_uploaded_file($file['tmp_name'], $tenantPath . '/' . $new_name);
						}
					}
				}
			}
		}

		return $resultPOST;
	}

	// Guardar relación
	public function setSurveyCountry($token, $countries) {
		$resultPOST = (object)[
			'status' => 'OK',
			'result' => 'OK'
		];

		foreach($countries as $data) {
			if(isset($data['survey'])) {
				$url = CONSTANTS::SERVERAPI . 'dropSurveyCountry';
				$params = [
					'token' => $token,
					'country' => $data['isocode']
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK' && $resultPOST->result != 'This country has not got survey assigned.') {
					return $resultPOST;
				}

				$url = CONSTANTS::SERVERAPI . 'setSurveyCountry';
				$params = [
					'token' => $token,
					'survey' => $data['survey'],
					'country' => $data['isocode'],
					'QuestionEstado' => $data['QuestionEstado'],
					'QuestionEdad' => $data['QuestionEdad'],
					'QuestionGenero' => $data['QuestionGenero'],
					'QuestionNSE' => $data['QuestionNSE']
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK' && $resultPOST->result != 'Survey not exists.') {
					return $resultPOST;
				}
			}
		}

		return $resultPOST;
	}

	// FUNCIONALIDADES APP
	// Actualizar funcionalidades
	public function setSystemConfig($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'config' => json_encode($client['config'])
		];

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

		return $resultPOST;
	}

	// LOGS
	// Petición de logs
	public function getCMBPLOG($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'rowsFilter' => $client['rowsFilter']
		];

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

		return $resultPOST;
	}

	// RSC
	// Importar RSC
	public function importRSC($client) {
		// Borrado de registros anteriores
		$url = CONSTANTS::SERVERAPI . 'deleteAllRSC';
		$params = [
			'token' => $client['token']
		];

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

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

		// Importacion en un servicio
		$rscArray = [];
		foreach($client['newRSC'] as $rsc) {
			array_push($rscArray, $rsc['rsc'] . '|' . $rsc['esp'] . '|' . $rsc['mex'] . '|' . $rsc['eng'] . '|' . $rsc['idn'] . '|' . $rsc['app'] . '|' . $rsc['country']);
		}

		$url = CONSTANTS::SERVERAPI . 'setAllRSC';
		$params = [
			'token' => $client['token'],
			'rsc' => json_encode($rscArray)
		];

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

		return $resultPOST;
	}

	// Sincronizar RSC
	public function synchronizeRSC($client) {
		// Petición de último RSC dela plataforma
		$url = CONSTANTS::SERVERAPI . 'getAllRSCSystem';
		$params = [
			'token' => $client['token']
		];

		$resultPOST = $this->utilesController->sendCurlPOST($url, $params);
		if($resultPOST->status != 'OK') {
			return $resultPOST;
		}

		$allRSCClient = $resultPOST->result;

		// Petición de RSC a partir del último número
		$url = CONSTANTS::SERVERSOCIAL . 'getAllRSCStandar';
		//TODO: REFACTOR THIS SUPER BAD PRACTICE
        // It is using a hardcoded token instead of authenticating making the whole API Vulnerable
        //$domain = CONSTANTS::SERVERDOMAIN;
        $domain = 'sociallabs.biz';
		$params = [
			'token' => $domain,
			'idTenant' => $client['idTenant']
		];

		$resultPOST = $this->utilesController->sendCurlPOST($url, $params);
		if($resultPOST->status != 'OK') {
			return $resultPOST;
		}

		$allRSCOrigin = $resultPOST->result;

		function compare_objects($obj_a, $obj_b) {
			return $obj_a->idRSC - $obj_b->idRSC;
		}

		$diff = array_udiff($allRSCOrigin, $allRSCClient, 'compare_objects');

		//No hay nuevos RSC
		if(count($diff) == 0) {
			$resultPOST = [
				'status' => 'OK',
				'result' => 'No RSC defined'
			];

			return $resultPOST;
		}

		// Añadir los nuevos RSC
		$rscArray = [];
		foreach($diff as $rsc) {
			$search = ['&lt;', '&gt;'];
			$replace = ['<', '>'];

			$esp = str_replace($search, $replace, $rsc->ESP);
			$mex = str_replace($search, $replace, $rsc->MEX);
			$eng = str_replace($search, $replace, $rsc->ENG);
			$idn = str_replace($search, $replace, $rsc->IDN);
			$bra = str_replace($search, $replace, $rsc->BRA);

			array_push($rscArray, $rsc->idRSC . '|' . $esp . '|' . $mex . '|' . $eng . '|' . $idn . '|' . $bra . '|' . $rsc->app . '|' . $rsc->country);
		}

		$url = CONSTANTS::SERVERAPI . 'setAllRSC';
		$params = [
			'token' => $client['token'],
			'rsc' => json_encode($rscArray)
		];

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

		return $resultPOST;
	}

	// Nuevo RSC
	public function setRSC($client) {
		$url = CONSTANTS::SERVERAPI . 'getAllRSCByLenguage';
		$params = [
			'token' => $client['token'],
			'lenguage' => 'ESP'
		];

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

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

		$rsc = $resultPOST->total + 1;

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

		foreach($client as $key => $value) {
			if($key != 'action' && $key != 'token') {
				$params[$key] = $value;
			}
		}

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

		return $resultPOST;
	}

	// Editar RSC
	public function updateRSC($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

		foreach($client as $key => $value) {
			if($key != 'action' && $key != 'token') {
				$params[$key] = $value;
			}
		}

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

		return $resultPOST;
	}
}