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

class AddOnsController {
	private $utilesController;

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

	// Carga de todos los AddOns
	public function getAllAddOns($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token']
		];

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

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

		return $response;
	}

	// Guardar AddOn nuevo
	public function setAddOn($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'addon_name' => $client['addon_name'],
			'addon_description' => $client['addon_description'],
			'country' => $client['country'],
			'addon_path' => $client['addon_path'],
			'addon_var' => $client['addon_var'],
			'addon_function' => $client['addon_function'],
			'addon_function_params' => $client['addon_function_params'],
			'addon_enabled' => $client['addon_enabled'],
			'gestiona_alert' => $client['gestiona_alert'],
			'addon_url' => $client['addon_url'],
			'addon_icon' => $client['addon_icon'],
			'enrolamiento' => $client['enrolamiento'],
			'fullScreen' => $client['fullScreen']
		];

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

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

		$idAddon = $resultPOST->id;

		// Añadir secciones
		foreach($client['secciones'] as $section) {
			$idSection = $section['idSection'];
			$description = $section['description'];
			if($idSection == '' || $description == '') {
				continue;
			}
			$section_icon = $section['section_icon'];

			// Nueva
			$url = CONSTANTS::SERVERAPI . 'setAddOnSection';
			$params = [
				'token' => $client['token'],
				'idAddon' => $idAddon,
				'idSection' => $idSection,
				'description' => $description,
				'section_icon' => $section_icon
			];

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

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

		// Añadir deeplinks
		$publicPath = $client['publicPath'] . 'addons/' . $client['id'];
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/addons/' . $client['id'];
		$index = 0;
		foreach($client['deeplinks'] as $deeplink) {
			$id = $deeplink['id'];
			$description = $deeplink['description'];
			if($id == '' || $description == '') {
				continue;
			}
			$file = isset($_FILES['file' . $index]) == true ? $_FILES['file' . $index] : '';
			$icon = $this->createFileIconDeepLink($folder, $file, $id);

			// Nuevo
			$url = CONSTANTS::SERVERAPI . 'setAddOnDeepLink';
			$params = [
				'token' => $client['token'],
				'idAddon' => $idAddon,
				'idDeepLink' => $id,
				'description' => $description,
				'iconDeepLink' => $icon,
				'publicPath' => $publicPath
			];

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

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

			$index = $index + 1;
		}

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

	// Actualizar AddOn
	public function updateAddOn($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'addon_name' => $client['addon_name'],
			'addon_description' => $client['addon_description'],
			'country' => $client['country'],
			'addon_path' => $client['addon_path'],
			'addon_var' => $client['addon_var'],
			'addon_function' => $client['addon_function'],
			'addon_function_params' => $client['addon_function_params'],
			'addon_enabled' => $client['addon_enabled'],
			'gestiona_alert' => $client['gestiona_alert'],
			'addon_url' => $client['addon_url'],
			'addon_icon' => $client['addon_icon'],
			'enrolamiento' => $client['enrolamiento'],
			'fullScreen' => $client['fullScreen']
		];

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

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

		// Nuevas y ediciones
		foreach($client['secciones'] as $section) {
			$idSection = $section['idSection'];
			$idSectionOld = $section['idSectionOld'];
			$description = $section['description'];
			if($idSection == '' || $description == '') {
				continue;
			}
			$section_icon = $section['section_icon'];

			$new = true;
			foreach($client['seccionesOld'] as $sectionOld) {
				if($idSectionOld == $sectionOld['idSection']) {
					$new = false;
					if($description != $sectionOld['description'] || $idSection != $idSectionOld || $section_icon != $sectionOld['section_icon']) {
						// Editar
						$url = CONSTANTS::SERVERAPI . 'updateAddOnSection';
						$params = [
							'token' => $client['token'],
							'idAddon' => $client['id'],
							'idSection' => $idSectionOld,
							'idSectionNew' => $idSection,
							'description' => $description,
							'section_icon' => $section_icon
						];

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

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

			if($new) {
				// Nueva
				$url = CONSTANTS::SERVERAPI . 'setAddOnSection';
				$params = [
					'token' => $client['token'],
					'idAddon' => $client['id'],
					'idSection' => $idSection,
					'description' => $description,
					'section_icon' => $section_icon
				];

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

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

		// Borrado
		foreach($client['seccionesOld'] as $sectionOld) {
			$idSectionOld = $sectionOld['idSection'];
			$clear = true;

			foreach($client['secciones'] as $section) {
				if($idSectionOld == $section['idSectionOld']) {
					$clear = false;
				}
			}

			if($clear) {
				$url = CONSTANTS::SERVERAPI . 'deleteAddOnSection';
				$params = [
					'token' => $client['token'],
					'idAddon' => $client['id'],
					'idSection' => $idSectionOld
				];

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

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

		// Deep Links Nuevas y ediciones
		$publicPath = $client['publicPath'] . 'addons/' . $client['id'];
		$folder = CONSTANTS::PATH_EXPORT_WORD . '/addons/' . $client['id'];
		$index = 0;
		foreach($client['deeplinks'] as $deeplink) {
			$id = $deeplink['id'];
			$idOld = $deeplink['idOld'];
			$description = $deeplink['description'];
			if($id == '' || $description == '') {
				continue;
			}
			$icon = $deeplink['icon'];
			$file = isset($_FILES['file' . $index]) == true ? $_FILES['file' . $index] : '';

			$new = true;
			foreach($client['deeplinksOld'] as $deeplinkOld) {
				if($idOld == $deeplinkOld['id']) {
					$new = false;
					if($description != $deeplinkOld['description'] || $id != $idOld || $icon != $deeplinkOld['icon']) {
						$this->deleteFileIconDeepLink($folder, $deeplinkOld['icon']);
						$icon = $this->createFileIconDeepLink($folder, $file, $id);
						// Editar
						$url = CONSTANTS::SERVERAPI . 'updateAddOnDeepLink';
						$params = [
							'token' => $client['token'],
							'idAddon' => $client['id'],
							'idDeepLink' => $idOld,
							'idDeepLinkNew' => $id,
							'description' => $description,
							'iconDeepLink' => $icon
						];

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

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

			if($new) {
				$icon = $this->createFileIconDeepLink($folder, $file, $id);

				// Nueva
				$url = CONSTANTS::SERVERAPI . 'setAddOnDeepLink';
				$params = [
					'token' => $client['token'],
					'idAddon' => $client['id'],
					'idDeepLink' => $id,
					'description' => $description,
					'iconDeepLink' => $icon,
					'publicPath' => $publicPath
				];

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

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

			$index = $index + 1;
		}

		// Deep Links Borrado
		foreach($client['deeplinksOld'] as $deeplinkOld) {
			$idOld = $deeplinkOld['id'];
			$clear = true;

			foreach($client['deeplinks'] as $deeplink) {
				if($idOld == $deeplink['idOld']) {
					$clear = false;
				}
			}

			if($clear) {
				$this->deleteFileIconDeepLink($folder, $deeplinkOld['icon']);

				$url = CONSTANTS::SERVERAPI . 'deleteAddOnDeepLink';
				$params = [
					'token' => $client['token'],
					'idAddon' => $client['id'],
					'idDeepLink' => $idOld
				];

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

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

		return $resultPOST;
	}

	// Petición de secciones de AddOn
	public function getAllAddOnsSection($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idAddon' => $client['idAddon']
		];

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

		return $resultPOST;
	}

	public function createFileIconDeepLink($folder, $file, $id) {
		// upload file to addons folder (addons/#)
		if($file != '' && $file != null) {
			$fecha = date_create();
			if(!file_exists($folder)) {
				$createFile = $this->utilesController->createDirectory($folder);

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

			$name = date_timestamp_get($fecha) . $id;
			$name = trim(strtolower($name));
			$name = str_replace(' ', '_', $name);
			$name = $name . '.jpg';

			// Reemplazar letras con acentos
			$icon = $this->utilesController->removeAccents($name);

			if(!move_uploaded_file($file['tmp_name'], $folder . '/' . $icon)) {
				return 'Error al subir la imagen';
			}
		} else {
			$icon = '';
		}

		return $icon;
	}

	public function deleteFileIconDeepLink($folder, $file) {
		unlink($folder . '/' . $file);
	}
}