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

class TenantController {
	private $utilesController;

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

	// Crear nuevo tenant
	public function setTenant($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'country' => $client['country'],
			'lenguage' => $client['lenguage'],
			'razonSocial' => $client['razonSocial'],
			'nombreComercial' => $client['nombreComercial'],
			'identFiscal' => $client['identFiscal'],
			'direccion' => $client['direccion'],
			'poblacion' => $client['poblacion'],
			'provincia' => $client['provincia'],
			'cp' => $client['cp'],
			'telefono' => $client['telefono'],
			'web' => $client['web'],
			'email' => $client['email'],
			'numLicencias' => $client['numLicencias'],
			'activo' => $client['activo'],
			'colorPrimario' => $client['colorPrimario'],
			'colorSecundario' => $client['colorSecundario'],
			'logoPrimario' => '',
			'logoSecundario' => '',
			'favicon' => '',
			'logoWalletApp' => '',
			'logoWelcomeApp' => ''
		];

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

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

		// ID de nuevo tenant
		$idTenant = $resultPOST->idTenant;

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

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

		// Carpeta de tenant
		if(!file_exists($tenantPath)) {
			$createFile = $this->utilesController->createDirectory($tenantPath);

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

		if($resultPOST->status == 'OK' && 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);
					}
				} else {
					// imagen por defecto
					$origin = $client['urlLogos'] . '0/' . $new_name;
					$destiny = $tenantPath . '/' . $new_name;

					copy($origin, $destiny);
				}
			}
		} else {
			foreach($files as $key => $name) {
				// imagen por defecto
				$origin = $client['urlLogos'] . '0/' . $name;
				$destiny = $tenantPath . '/' . $name;

				copy($origin, $destiny);
			}
		}

		// Imágenes de tenant para reportes sacadas del tenant 0
		$filesReports = [
			'plantilla' => 'plantilla.PNG',
			'plantilla_portada' => 'plantilla_portada.PNG',
			'logo' => 'logo_rep.PNG'
		];
		foreach($filesReports as $key => $name) {
			// imagen por defecto
			$origin = $client['urlLogos'] . '0/' . $name;
			$destiny = $tenantPath . '/' . $name;

			copy($origin, $destiny);
		}

		// Editar el tenant con las nuevas rutas de las imágenes
		$url = CONSTANTS::SERVERAPI . 'updateTenant';
		$params = [
			'token' => $client['token'],
			'idTenant' => $idTenant,
			'country' => $client['country'],
			'lenguage' => $client['lenguage'],
			'razonSocial' => $client['razonSocial'],
			'nombreComercial' => $client['nombreComercial'],
			'identFiscal' => $client['identFiscal'],
			'direccion' => $client['direccion'],
			'poblacion' => $client['poblacion'],
			'provincia' => $client['provincia'],
			'cp' => $client['cp'],
			'telefono' => $client['telefono'],
			'web' => $client['web'],
			'email' => $client['email'],
			'numLicencias' => $client['numLicencias'],
			'activo' => $client['activo'],
			'colorPrimario' => $client['colorPrimario'],
			'colorSecundario' => $client['colorSecundario'],
			'logoPrimario' => $client['urlLogos'] . $idTenant. '/logo.png',
			'logoSecundario' => $client['urlLogos'] . $idTenant . '/logo_home.png',
			'favicon' => $client['urlLogos'] . $idTenant . '/favicon.ico',
			'logoWalletApp' => $client['urlLogos'] . $idTenant . '/wallet_card.png',
			'logoWelcomeApp' => $client['urlLogos'] . $idTenant . '/logo_welcome.png'
		];

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

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

	// Petición de tenant por id
	public function getTenantById($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idTenant' => $client['idTenant']
		];

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

		return $resultPOST;
	}

	// Actualizar tenant
	public function updateTenant($client) {
		if($client['changes'] === true) {
			$url = CONSTANTS::SERVERAPI . $client['action'];
			$params = [
				'token' => $client['token'],
				'idTenant' => $client['idTenant'],
				'country' => $client['country'],
				'lenguage' => $client['lenguage'],
				'razonSocial' => $client['razonSocial'],
				'nombreComercial' => $client['nombreComercial'],
				'identFiscal' => $client['identFiscal'],
				'direccion' => $client['direccion'],
				'poblacion' => $client['poblacion'],
				'provincia' => $client['provincia'],
				'cp' => $client['cp'],
				'telefono' => $client['telefono'],
				'web' => $client['web'],
				'email' => $client['email'],
				'numLicencias' => $client['numLicencias'],
				'activo' => $client['activo'],
				'colorPrimario' => $client['colorPrimario'],
				'colorSecundario' => $client['colorSecundario'],
				'logoPrimario' => $client['urlLogos'] . $client['idTenant'] . '/logo.png',
				'logoSecundario' => $client['urlLogos'] . $client['idTenant'] . '/logo_home.png',
				'favicon' => $client['urlLogos'] . $client['idTenant'] . '/favicon.ico',
				'logoWalletApp' => $client['urlLogos'] . $client['idTenant'] . '/wallet_card.png',
				'logoWelcomeApp' => $client['urlLogos'] . $client['idTenant'] . '/logo_welcome.png'
			];

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

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

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

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

		if(($resultPOST->status == 'OK' || $resultPOST['status'] == 'OK') && 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;
	}

	// Guardado de licencias del tenant
	public function setSocialLabsLicencesByTenant($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'tenants' => json_encode($client['tenants'])
		];

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

		return $resultPOST;
	}
}