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

class CPGController {
	private $utilesController;

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

	// Crear nuevo CPG
	public function setCPG($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'],
			'colorMenu1' => $client['colorMenu1'],
			'colorFuenteMenu1' => $client['colorFuenteMenu1'],
			'colorMenu2' => $client['colorMenu2'],
			'colorFuenteMenu2' => $client['colorFuenteMenu2'],
			'colorMenu3' => $client['colorMenu3'],
			'colorFuenteMenu3' => $client['colorFuenteMenu3'],
			'logoPrimario' => '',
			'logoSecundario' => '',
			'favicon' => '',
			'logoWalletApp' => '',
			'logoWelcomeApp' => ''
		];

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

		$codeError = '';
		if(isset($resultPOST->codeError)) {
			$codeError = $resultPOST->codeError;
		}

		// ID de nuevo CPG
		$idCPG = $resultPOST->idCPG;

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

		// Ruta de CPG para Multi tenant
		$idTenant = $client['idTenant'];
		$CPGPath = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/cpg/' . $idCPG;

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

			if($createFile['status'] == 'KO') {
				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)), $CPGPath . '/' . $new_name);
					} else {
						move_uploaded_file($file['tmp_name'], $CPGPath . '/' . $new_name);
					}
				} else {
					// imagen por defecto
					$origin = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/' . $new_name;
					$destiny = $CPGPath . '/' . $new_name;

					copy($origin, $destiny);
				}
			}
		} else {
			foreach($files as $key => $name) {
				// imagen por defecto
				$origin = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/' . $name;
				$destiny = $CPGPath . '/' . $name;

				copy($origin, $destiny);
			}
		}

		// Imágenes de CPG 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 = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/' . $name;
			$destiny = $CPGPath . '/' . $name;

			copy($origin, $destiny);
		}

		// Editar el CPG con las nuevas rutas de las imágenes
		$url = CONSTANTS::SERVERAPI . 'updateCPG';
		$params = [
			'token' => $client['token'],
			'idCPG' => $idCPG,
			'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'],
			'colorMenu1' => $client['colorMenu1'],
			'colorFuenteMenu1' => $client['colorFuenteMenu1'],
			'colorMenu2' => $client['colorMenu2'],
			'colorFuenteMenu2' => $client['colorFuenteMenu2'],
			'colorMenu3' => $client['colorMenu3'],
			'colorFuenteMenu3' => $client['colorFuenteMenu3'],
			'logoPrimario' => $client['urlLogos'] . $idCPG . '/logo.png',
			'logoSecundario' => $client['urlLogos'] . $idCPG . '/logo_home.png',
			'favicon' => $client['urlLogos'] . $idCPG . '/favicon.ico',
			'logoWalletApp' => $client['urlLogos'] . $idCPG . '/wallet_card.png',
			'logoWelcomeApp' => $client['urlLogos'] . $idCPG . '/logo_welcome.png'
		];

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

		// Código de error en la creación del CPG
		$resultPOST->codeError = $codeError;

		return $resultPOST;
	}

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

		if($client['cpgs'] != '[]') {
			foreach($client['cpgs'] as $cpg) {
				$params = [
					'token' => $client['token'],
					'idCPG' => $cpg['id']
				];

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

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

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Actualizar CPG
	public function updateCPG($client) {
		if($client['changes'] === true) {
			$url = CONSTANTS::SERVERAPI . $client['action'];
			$params = [
				'token' => $client['token'],
				'idCPG' => $client['idCPG'],
				'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'],
				'colorMenu1' => $client['colorMenu1'],
				'colorFuenteMenu1' => $client['colorFuenteMenu1'],
				'colorMenu2' => $client['colorMenu2'],
				'colorFuenteMenu2' => $client['colorFuenteMenu2'],
				'colorMenu3' => $client['colorMenu3'],
				'colorFuenteMenu3' => $client['colorFuenteMenu3'],
				'logoPrimario' => $client['urlLogos'] . $client['idCPG'] . '/logo.png',
				'logoSecundario' => $client['urlLogos'] . $client['idCPG'] . '/logo_home.png',
				'favicon' => $client['urlLogos'] . $client['idCPG'] . '/favicon.ico',
				'logoWalletApp' => $client['urlLogos'] . $client['idCPG'] . '/wallet_card.png',
				'logoWelcomeApp' => $client['urlLogos'] . $client['idCPG'] . '/logo_welcome.png'
			];

			$resultPOST = $this->utilesController->sendCurlPOST($url, $params);
		} 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 CPG
		$idTenant = $client['idTenant'];
		$CPGPath = CONSTANTS::PATH_EXPORT_WORD . '/tenants/' . $idTenant . '/cpg/' . $client['idCPG'];

		if(!file_exists($CPGPath)) {
			$createFile = $this->utilesController->createDirectory($CPGPath);

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

		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)), $CPGPath . '/' . $new_name);
					} else {
						move_uploaded_file($file['tmp_name'], $CPGPath . '/' . $new_name);
					}
				}
			}
		}

		return $resultPOST;
	}

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

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

		return $resultPOST;
	}

	// Petición de detalle de licencias usadas
	public function getSocialLabsLicencesDetailByCPG($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idCPG' => $client['idCPG']
		];

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

		return $resultPOST;
	}
}