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

class AjustesController {
	private $utilesController;

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

	// WELCOME TOUR
	public function setWelcomeTour($client) {
		// Ruta de imágenes por defecto
		$welcomeTourPath = CONSTANTS::PATH_EXPORT_WORD . '/welcometour/';
		$welcomeTourImagesPath = CONSTANTS::PATH_EXPORT_WORD . '/welcometour/images/';

		// Ruta web stcm.const.downloads + 'welcometour/'
		$welcomeTourWebPath = $client['path'];

		$imgPrincipal = $welcomeTourWebPath . 'welcometour.png';

		// Al guardar los valores se borra el contenido anterior, ya que las imagenes pueden haber cambiado (contenido y orden)
		if(!file_exists($welcomeTourPath)) {
			$createFile = $this->utilesController->createDirectory($welcomeTourPath);

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

			$createFile = $this->utilesController->createDirectory($welcomeTourImagesPath);

			if($createFile['status'] == 'KO') {
				return $createFile;
			}
		} else {
			if(!file_exists($welcomeTourImagesPath)) {
				$createFile = $this->utilesController->createDirectory($welcomeTourImagesPath);

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

			$folderName = $welcomeTourImagesPath . '/*';
			$files = glob($folderName);
			foreach($files as $file) {
				if(is_file($file)) {
					unlink($file);
				}
			}
		}

		// Ordenación de array
		foreach ($client['sectionsArray'] as $key => $value) {
			$aux[$key] = $value['order'];
		}
		array_multisort($aux, SORT_ASC, $client['sectionsArray']);

		if(isset($_FILES) && count($_FILES) > 0) {
			$url = CONSTANTS::SERVERAPI . 'getCMBPConfig';
			$params = [
				'token' => $client['token']
			];

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

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

			$maxSize = $resultPOST->result[0]->upload_max_filesize_bytes;
			$data = '[';
			$i = 0;

			foreach($_FILES as $key => $value) {
				if($_FILES[$key]['size'] <= $maxSize) {
					$type = $_FILES[$key]['type'];
					$type_Array = explode('/', $type);

					// Mover imagen a carpeta de welcometour
					$rutaArchivo = $welcomeTourImagesPath . '/' . 'image_' . $client['sectionsArray'][$i]['order'] . '.' . $type_Array[1];
					if(!move_uploaded_file($_FILES[$key]['tmp_name'], $rutaArchivo)) {
						$response['status'] = 'KO';
						return $response;
					} else {
						$data .= '"' . $client['sectionsArray'][$i]['order'] . '#image_' . $client['sectionsArray'][$i]['order'] . '.' . $type_Array[1] . '#' . $client['sectionsArray'][$i]['title'] . '#' . $client['sectionsArray'][$i]['description'] . '#' . $welcomeTourWebPath . 'images' . '",';
					}

					$i++;
				} else {
					// imagen por defecto
					$origin = $imgPrincipal;
					$destiny = $welcomeTourPath . '/welcometour.png';
					copy($origin, $destiny);
				}
			}
		}

		$data = substr($data, 0, -1);

		$data .= ']';

		// Actualizar rutas de imágenes
		$url = CONSTANTS::SERVERAPI . 'setWelcomeTour';
		$params = [
			'token' => $client['token'],
			'data' => $data
		];

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

		return $resultPOST;
	}

	// Crear dominio
	public function newDomain($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'domain' => $client['domain']
		];

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

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

	// Actualizar dominio
	public function updateDomain($client) {
		$url = CONSTANTS::SERVERAPI . 'deleteDomain';
		$params = [
			'token' => $client['token'],
			'domain' => $client['domain']
		];

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

		if($resultPOST->status == 'OK') {
			$url = CONSTANTS::SERVERAPI . 'newDomain';
			$params = [
				'token' => $client['token'],
				'domain' => $client['newDomain']
			];

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

			return $resultPOST;
		} else {
			return $resultPOST;
		}
	}

	// BOTS
	// Crear bot
	public function setBot($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'botNameId' => $client['botName'],
			'directLineSecret' => $client['directLine'],
			'pais' => $client['pais']
		];

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

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

	// Actualizar bot
	public function updateBot($client) {
		$url = CONSTANTS::SERVERAPI . 'deleteBot';
		$params = [
			'token' => $client['token'],
			'botNameId' => $client['botName']
		];

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

		if($resultPOST->status == 'OK') {
			$url = CONSTANTS::SERVERAPI . 'setBot';
			$params = [
				'token' => $client['token'],
				'botNameId' => $client['botNameNew'],
				'directLineSecret' => $client['directLine'],
				'pais' => $client['pais']
			];

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

			return $resultPOST;
		} else {
			return $resultPOST;
		}
	}

	// DEFINICIÓN CATALOGACIÓN ASESORES
	// Crear catalogación de asesores
	public function saveNewCatalogM($client) {
		$url = CONSTANTS::SERVERAPI . 'setCatalogacionM';
		$params = [
			'token' => $client['token'],
			'rangoDesde' => $client['catalog']['rangoDesde'],
			'rangoHasta' => $client['catalog']['rangoHasta'],
			'catalogacion' => $client['catalog']['catalogacion']
		];

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

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

		return $response;
	}

	// Actualizar catalogación de asesores
	public function setCatalogacionM($client) {
		$url = CONSTANTS::SERVERAPI . 'deleteCatalogacionesM';
		$params = [
			'token' => $client['token']
		];

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

		if($resultPOST->status == 'OK') {
			$url = CONSTANTS::SERVERAPI . $client['action'];
			foreach($client['catalogs'] as $catalog) {
				$params = [
					'token' => $client['token'],
					'rangoDesde' => $catalog['rangoDesde'],
					'rangoHasta' => $catalog['rangoHasta'],
					'catalogacion' => $catalog['catalogacion']
				];

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

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

			$response['status'] = 'OK';
			return $response;
		} else {
			$response['status'] = 'KO';
			return $response;
		}
	}

	// SECCIÓN PERFILACIÓN
	// Nueva perfilación por género
	public function setPerfGenero($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'genero' => $client['genero'],
			'licencias' => $client['licencias'],
			'porcentaje' => $client['porcentaje'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI']
		];

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

		return $resultPOST;
	}

	// Nueva perfilación por estado
	public function setPerfEstados($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'estado' => $client['estado'],
			'licencias' => $client['licencias'],
			'porcentaje' => $client['porcentaje'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI'],
			'regionABIAux' => $client['regionABIAux'],
			'ciudad' => $client['ciudad']
		];

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

		return $resultPOST;
	}

	// Nueva perfilación por edad
	public function setPerfEdad($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'edad' => $client['edad'],
			'licencias' => $client['licencias'],
			'porcentaje' => $client['porcentaje'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI'],
			'min' => $client['min'],
			'max' => $client['max']
		];

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

		return $resultPOST;
	}

	// Nueva perfilación por PerfSec
	public function setPerfSec($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'licencias' => $client['licencias'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'sec' => $client['sec'],
			'min' => $client['min'],
			'max' => $client['max']
		];

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

		return $resultPOST;
	}

	// Nueva perfilación por PerfRegion
	public function setPerfRegion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'licencias' => $client['licencias'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI']
		];

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

		return $resultPOST;
	}

	// Nueva integración
	public function setLicenciasDiscriminantes($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'pais' => $client['pais'],
			'cumple' => $client['cumple'],
			'nocumple' => $client['nocumple']
		];

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

		return $resultPOST;
	}

	// Eliminar perfilación por género
	public function deletePerfGenero($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['profiles'] != '[]') {
			foreach($client['profiles'] as $profiling) {
				$params = [
					'token' => $client['token'],
					'genero' => $profiling['genero'],
					'pais' => $profiling['pais'],
					'region' => $profiling['region']
				];

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

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

		return $resultPOST;
	}

	// Eliminar perfilación por estado
	public function deletePerfEstados($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['profiles'] != '[]') {
			foreach($client['profiles'] as $profiling) {
				$params = [
					'token' => $client['token'],
					'estado' => $profiling['estado'],
					'pais' => $profiling['pais'],
					'region' => $profiling['region'],
					'ciudad' => $profiling['ciudad']
				];

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

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

		return $resultPOST;
	}

	// Eliminar perfilación por edad
	public function deletePerfEdad($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['profiles'] != '[]') {
			foreach($client['profiles'] as $profiling) {
				$params = [
					'token' => $client['token'],
					'edad' => $profiling['edad'],
					'pais' => $profiling['pais'],
					'region' => $profiling['region']
				];

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

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

		return $resultPOST;
	}

	// Eliminar perfilación por PerfSec
	public function deletePerfSec($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['profiles'] != '[]') {
			foreach($client['profiles'] as $profiling) {
				$params = [
					'token' => $client['token'],
					'sec' => $profiling['sec'],
					'pais' => $profiling['pais'],
					'region' => $profiling['region']
				];

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

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

		return $resultPOST;
	}

	// Eliminar perfilación por PerfRegion
	public function deletePerfRegion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

		if($client['profiles'] != '[]') {
			foreach($client['profiles'] as $profiling) {
				$params = [
					'token' => $client['token'],
					'regionABI' => $profiling['regionABI'],
					'pais' => $profiling['pais'],
					'region' => $profiling['region']
				];

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

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

		return $resultPOST;
	}

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

		if($client['profiles'] != '[]') {
			foreach($client['profiles'] as $profiling) {
				$params = [
					'token' => $client['token'],
					'pais' => $profiling['pais']
				];

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

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

		return $resultPOST;
	}

	// Editar perfilación por género
	public function editPerfGenero($client) {
		$url = CONSTANTS::SERVERAPI . 'deletePerfGenero';
		$params = [
			'token' => $client['token'],
			'genero' => $client['generoOld'],
			'pais' => $client['paisOld'],
			'region' => $client['regionOld']
		];

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

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

		$url = CONSTANTS::SERVERAPI . 'setPerfGenero';
		$params = [
			'token' => $client['token'],
			'genero' => $client['genero'],
			'licencias' => $client['licencias'],
			'porcentaje' => $client['porcentaje'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI']
		];

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

		return $resultPOST;
	}

	// Editar perfilación por estado
	public function editPerfEstados($client) {
		$url = CONSTANTS::SERVERAPI . 'deletePerfEstados';
		$params = [
			'token' => $client['token'],
			'estado' => $client['estadoOld'],
			'pais' => $client['paisOld'],
			'region' => $client['regionOld'],
			'ciudad' => $client['ciudadOld']
		];

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

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

		$url = CONSTANTS::SERVERAPI . 'setPerfEstados';
		$params = [
			'token' => $client['token'],
			'estado' => $client['estado'],
			'licencias' => $client['licencias'],
			'porcentaje' => $client['porcentaje'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI'],
			'regionABIAux' => $client['regionABIAux'],
			'ciudad' => $client['ciudad']
		];

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

		return $resultPOST;
	}

	// Editar perfilación por edad
	public function editPerfEdad($client) {
		$url = CONSTANTS::SERVERAPI . 'deletePerfEdad';
		$params = [
			'token' => $client['token'],
			'edad' => $client['edadOld'],
			'pais' => $client['paisOld'],
			'region' => $client['regionOld']
		];

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

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

		$url = CONSTANTS::SERVERAPI . 'setPerfEdad';
		$params = [
			'token' => $client['token'],
			'edad' => $client['edad'],
			'licencias' => $client['licencias'],
			'porcentaje' => $client['porcentaje'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI'],
			'min' => $client['min'],
			'max' => $client['max']
		];

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

		return $resultPOST;
	}

	// Editar perfilación por PerfSec
	public function editPerfSec($client) {
		$url = CONSTANTS::SERVERAPI . 'deletePerfSec';
		$params = [
			'token' => $client['token'],
			'sec' => $client['secOld'],
			'pais' => $client['paisOld'],
			'region' => $client['regionOld']
		];

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

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

		$url = CONSTANTS::SERVERAPI . 'setPerfSec';
		$params = [
			'token' => $client['token'],
			'licencias' => $client['licencias'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'sec' => $client['sec'],
			'min' => $client['min'],
			'max' => $client['max']
		];

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

		return $resultPOST;
	}

	// Editar perfilación por PerfRegion
	public function editPerfRegion($client) {
		$url = CONSTANTS::SERVERAPI . 'deletePerfRegion';
		$params = [
			'token' => $client['token'],
			'regionABI' => $client['regionABIOld'],
			'pais' => $client['paisOld'],
			'region' => $client['regionOld']
		];

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

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

		$url = CONSTANTS::SERVERAPI . 'setPerfRegion';
		$params = [
			'token' => $client['token'],
			'licencias' => $client['licencias'],
			'pais' => $client['pais'],
			'region' => $client['region'],
			'regionABI' => $client['regionABI']
		];

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

		return $resultPOST;
	}

	// Editar integración
	public function editLicenciasDiscriminantes($client) {
		$url = CONSTANTS::SERVERAPI . 'deleteLicenciasDiscriminantes';
		$params = [
			'token' => $client['token'],
			'pais' => $client['paisOld']
		];

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

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

		$url = CONSTANTS::SERVERAPI . 'setLicenciasDiscriminantes';
		$params = [
			'token' => $client['token'],
			'pais' => $client['pais'],
			'cumple' => $client['cumple'],
			'nocumple' => $client['nocumple']
		];

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

		return $resultPOST;
	}

	// FORMULARIO DE REGISTRO
	// Cambiar la configuración de registro
	public function setRegisterConfiguration($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'email' => $client['email'],
			'firstname' => $client['firstname'],
			'lastname' => $client['lastname'],
			'secondlastname' => $client['secondlastname'],
			'country' => $client['country'],
			'countrydefault' => $client['countrydefault'],
			'language' => $client['language'],
			'languagedefault' => $client['languagedefault'],
			'role' => $client['role'],
			'roledefault' => $client['roledefault'],
			'acceptterms' => $client['acceptterms'],
			'codevalidationtimeminutes' => $client['codevalidationtimeminutes'],
			'rscValidation' => $client['rscValidation'],
			'terms' => json_encode($client['terms']),
			'validateBySMS' => $client['validateBySMS'],
			'validateByEmail' => $client['validateByEmail']
		];

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

		return $resultPOST;
	}

	// PAÍSES
	// Petición de plantillas de pagos según país
	public function getTemplatePagosByCountry($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'pais' => $client['pais']
		];

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

		return $resultPOST;
	}

	// Petición de tipos de identificación según país
	public function getPaisesTipoIdentificacion($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'pais' => $client['pais']
		];

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

		return $resultPOST;
	}

	// Petición de tipos de cuentas según país
	public function getPaisesTipoCuentas($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'pais' => $client['pais']
		];

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

		return $resultPOST;
	}

	// Petición de bancos según país
	public function getPaisesBancos($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'pais' => $client['pais']
		];

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

		return $resultPOST;
	}

	// Petición de textos de bienvenida según país
	public function getWelcomeChatsById($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['pais']
		];

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Actualización de parámetros de países
	public function updatePaises($client) {
        //TODO: REFACTOR EVERYTHING TO ONE API SERVICE
		// General
		$country = $client['country'];

		$url = CONSTANTS::SERVERAPI . 'updatePaisesByID';
		$params = [
			'token' => $client['token'],
			'id' => $country['isocode'],
			'descripcion' => $country['descripcion'],
			'value' => $country['enabled'],
			'default' => $country['default'],
			'zone' => $country['zone'],
			'currency' => $country['currency'],
			'currency_symbol' => $country['currency_symbol'],
			'rscRegisterNoLicenses' => $country['rscRegisterNoLicenses'],
			'rscWelcomePage' => $country['rscWelcomePage'],
			'rscCongratsMessage' => $country['rscCongratsMessage'],
			'rscFailMessage' => $country['rscFailMessage'],
			'rscMyReferralsPage' => $country['rscMyReferralsPage'],
			'rscClabeText' => $country['rscClabeText'],
			'rscClabeLabel' => $country['rscClabeLabel'],
			'rscClabePlaceholder' => $country['rscClabePlaceholder'],
			'rscClabeInvalid' => $country['rscClabeInvalid'],
			'rscClabeExists' => $country['rscClabeExists'],
			'rscClabeAdded' => $country['rscClabeAdded'],
			'rscClabeSecure' => $country['rscClabeSecure'],
			'rscClabeEdit' => $country['rscClabeEdit'],
			'rscWelcomeMsg' => $country['rscWelcomeMsg'],
			'location' => $client['location'],
			'equivalencePoints' => $client['equivalencePoints'],
			'sp_perfilacion' => $client['sp_perfilacion'],
			'formatoFecha' => $client['formatoFecha'],
			'poblacion' => $client['poblacion']
		];

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

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

		// Campos de pago
		$paymentFields = $client['paymentFields'];

		$url = CONSTANTS::SERVERAPI . 'setTemplatePagosByCountry';
		$params = [
			'token' => $client['token'],
			'pais' => $paymentFields['pais'],
			'tipoIdentificacion' => $paymentFields['tipoIdentificacion'],
			'identificacion' => $paymentFields['identificacion'],
			'banco' => $paymentFields['banco'],
			'tipoCuenta' => $paymentFields['tipoCuenta'],
			'telefono' => $paymentFields['telefono'],
			'ciudad' => $paymentFields['ciudad'],
			'direccion' => $paymentFields['direccion']
		];

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

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

		// Tipo de identificación
		$identificationArray = $client['identificationArray'];

		$url = CONSTANTS::SERVERAPI . 'deleteAllPaisesTipoIdentificacion';
		$params = [
			'token' => $client['token'],
			'pais' => $paymentFields['pais']
		];

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

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

		foreach ($identificationArray as $identification) {
			if($identification['rsc'] == '') {
				continue;
			}

			$url = CONSTANTS::SERVERAPI . 'setPaisesTipoIdentificacion';
			$params = [
				'token' => $client['token'],
				'pais' => $paymentFields['pais'],
				'description' => $identification['rsc'],
				'id' => $identification['code']
			];

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

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

		// Tipo de cuenta
		$accountArray = $client['accountArray'];

		$url = CONSTANTS::SERVERAPI . 'deleteAllPaisesTipoCuentas';
		$params = [
			'token' => $client['token'],
			'pais' => $paymentFields['pais']
		];

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

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

		foreach ($accountArray as $account) {
			if($account['rsc'] == '') {
				continue;
			}

			$url = CONSTANTS::SERVERAPI . 'setPaisesTipoCuentas';
			$params = [
				'token' => $client['token'],
				'pais' => $paymentFields['pais'],
				'description' => $account['rsc'],
				'id' => $account['code']
			];

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

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

		// Bancos
		$banksArray = $client['banksArray'];

		$url = CONSTANTS::SERVERAPI . 'deleteAllPaisesBancos';
		$params = [
			'token' => $client['token'],
			'pais' => $paymentFields['pais']
		];

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

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

		foreach($banksArray as $banks) {
			if($banks['code'] == '' && $banks['description'] == '') {
				continue;
			}

			$url = CONSTANTS::SERVERAPI . 'setPaisesBancos';
			$params = [
				'token' => $client['token'],
				'pais' => $paymentFields['pais'],
				'id' => $banks['code'],
				'description' => $banks['description']
			];

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

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

		// Chats de bienvenida
		if($client['chatsChange'] === true) {
			$chatsArray = $client['chatsArray'];

			if($client['chatsNew'] === 'false') {
				$url = CONSTANTS::SERVERAPI . 'deleteAllWelcomeChatsByCountry';
				$params = [
					'token' => $client['token'],
					'country' => $client['country']['isocode']
				];

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

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

			foreach($chatsArray as $chats) {
				if($chats['user'] === '' || $chats['type'] === '') {
					continue;
				}

				switch($chats['type']) {
					// Mensaje
					case '0':
						$RSCANotficar = $chats['message'];
						$TipoArchivoANotificar = '';
						$ArchivoANotificar = '';
						$pathArchivoANotificar = '';
						$EncuestaANotificar = '';
						$MisionANotificar = '';
						break;
					// Mensaje con adjunto
					case '1':
						if($client['chatsAttached'] !== true) {
							$name = $chats['attached'];
							$path = $chats['attachedPath'];
						} else {
							if(isset($_FILES)) {
								foreach($_FILES as $file) {
									if($file['name'] == $chats['attached']) {
										$resultPOST = (object)['status' => '', 'result' => ''];

										$fileNotif = $file;
										$fecha = date_create();
										$jidClear = str_replace('@', '_', $chats['user']);
										$archivo = CONSTANTS::PATH_EXPORT_WORD . '/notificaciones/chatswelcome/' . $client['country']['isocode'] . '/' . $jidClear;
										if(!file_exists($archivo)) {
											$createFile = $this->utilesController->createDirectory($archivo);

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

										// Comprobación de nombre original
										$strangerCharts = ['?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', '\'', '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+'];
										for($i = 0; $i < count($strangerCharts); $i++) {
											if(strpos($fileNotif['name'], $strangerCharts[$i]) !== false) {
												$resultPOST->status = 'KO';
												$resultPOST->result = 'The file name is not correct';
												return $resultPOST;
											}
										}

										// Lista de extensiones permitidas
										$safeList = ['avi', 'gif', 'jpg', 'jpeg', 'mpeg', 'pdf', 'wav', 'weba', 'webm', 'png', 'mp3', 'mov', 'mp4', 'bmp'];
										$nameArray = explode('.', $fileNotif['name']);
										$lastPosition = count($nameArray) - 1;
										$extension = $nameArray[$lastPosition];
										$extension = strtolower($extension);
										if(!in_array($extension, $safeList)) {
											$resultPOST->status = 'KO';
											$resultPOST->result = 'The extension name is not correct';
											return $resultPOST;
										}

										$name = date_timestamp_get($fecha) . $fileNotif['name'];
										$name = trim(strtolower($name));
										$name = str_replace(' ', '_', $name);

										// Reemplazar letras con acentos
										$name = $this->utilesController->removeAccents($name);
										$path = $archivo . '/' . $name;

										if(!move_uploaded_file($fileNotif['tmp_name'], $archivo . '/' . $name)) {
											return 'Error uploading image';
										}
										break;
									} else {
										$name = $chats['attached'];
										$path = $chats['attachedPath'];
									}
								}
							}
						}

						$RSCANotficar = $chats['message'];
						$TipoArchivoANotificar = $chats['typeAttached'];
						$ArchivoANotificar = $name;
						$pathArchivoANotificar = $path;
						$EncuestaANotificar = '';
						$MisionANotificar = '';
						break;
					// Encuesta
					case '2':
						$RSCANotficar = $chats['message'];
						$TipoArchivoANotificar = '';
						$ArchivoANotificar = '';
						$pathArchivoANotificar = '';
						$EncuestaANotificar = $chats['survey'];
						$MisionANotificar = '';
						break;
					// Misión
					case '3':
						$RSCANotficar = '';
						$TipoArchivoANotificar = '';
						$ArchivoANotificar = '';
						$pathArchivoANotificar = '';
						$EncuestaANotificar = '';
						$MisionANotificar = $chats['mission'];
						break;
				}

				$url = CONSTANTS::SERVERAPI . 'setWelcomeChats';
				$params = [
					'token' => $client['token'],
					'country' => $client['country']['isocode'],
					'jid' => $chats['user'],
					'MotivoNotificacion' => $chats['type'],
					'RSCANotficar' => $RSCANotficar,
					'TipoArchivoANotificar' => $TipoArchivoANotificar,
					'ArchivoANotificar' => $ArchivoANotificar,
					'PathArchivoANotificar' => $pathArchivoANotificar,
					'EncuestaANotificar' => $EncuestaANotificar,
					'MisionANotificar' => $MisionANotificar
				];

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

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

		// Ponderaciones
		if($client['weightings'] !== 'null') {
			$url = CONSTANTS::SERVERAPI . 'setPonderacionesByCountry';
			$params = [
				'token' => $client['token'],
				'country' => $client['country']['isocode'],
				'ponderations' => json_encode($client['weightings'])
			];

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

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

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

	// IDIOMAS
	// Actualización de parámetros de idiomas
	public function updateIdiomas($client) {
		$url = CONSTANTS::SERVERAPI . 'updateIdiomasByID';
		foreach($client['idiomas'] as $language) {
			$params = [
				'token' => $client['token'],
				'id' => $language['isocode'],
				'value' => $language['enabled'],
				'default' => $language['default']
			];

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

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

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

	// PERFILES
	// Creación de perfil
	public function setProfile($client) {
		$url = CONSTANTS::SERVERAPI . 'setProfile';
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'value' => $client['value'],
			'description' => $client['description'],
			'default' => $client['default']
		];

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

		return $resultPOST;
	}

	// Eliminar perfil
	public function deleteProfile($client) {
		$url = CONSTANTS::SERVERAPI . 'deleteProfilesByID';

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

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

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

		return $resultPOST;
	}

	// Actualizar perfil
	public function updateProfile($client) {
		$url = CONSTANTS::SERVERAPI . 'updateProfilesByID';
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'value' => $client['value'],
			'description' => $client['description'],
			'default' => $client['default']
		];

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

		return $resultPOST;
	}

	// Nueva exclusión wordcloud
	public function setWordsExcludedCloud($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'values' => json_encode($client['values'])
		];

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

		return $resultPOST;
	}

	// Borrar exclusión wordcloud por ID
	public function deleteWordExcludedCloudByID($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

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

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

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

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

	// Update exclusión wordcloud por ID
	public function updateWordExcludedCloudByID($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'word' => $client['word']
		];

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

		return $resultPOST;
	}
}