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

class OperarController {
	private $utilesController;

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

	// Guardar, borrar o actualizar PopUps
	public function setPopups($client) {
		// Eliminar PopUps
		if($client['deletePopUps'] !== '[]') {
			for($i = 0; $i < count($client['deletePopUps']); $i++) {
				// Eliminar PopUp
				$url = CONSTANTS::SERVERAPI . 'deletePopup';
				$params = [
					'token' => $client['token'],
					'id' => $client['deletePopUps'][$i]
				];

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

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

				// Eliminar usuarios asignados a PopUp
				$url = CONSTANTS::SERVERAPI . 'deleteAllPopupsUserAssignment';
				$params = [
					'token' => $client['token'],
					'idPopUp' => $client['deletePopUps'][$i]
				];

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

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

		// Ruta de imágenes por defecto
		$idcpg = $client['idcpg'];
		$popUpsPath = CONSTANTS::PATH_EXPORT_WORD . '/pop_ups/';
		$popUpsCPGPath = CONSTANTS::PATH_EXPORT_WORD . '/pop_ups/' . $idcpg . '/';
		$popUpsImagesPath = CONSTANTS::PATH_EXPORT_WORD . '/pop_ups/'.$idcpg . '/images/';

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

		$imgPrincipal = $popUpsWebPath . 'pop_ups.png';

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

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

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

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

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

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

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

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

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

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

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

		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;
			$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 pop_ups
					$rutaArchivo = $popUpsImagesPath . 'image_' . $i . '.' . $type_Array[1];
					if(!move_uploaded_file($_FILES[$key]['tmp_name'], $rutaArchivo)) {
						$response['status'] = 'KO';
						return $response;
					} else {
						if($client['sectionsArray'][$i]['id'] == '') {
							// Nuevo PopUps
							$url = CONSTANTS::SERVERAPI . 'setPopups';
							$params = [
								'token' => $client['token'],
								'prioridad' => $client['sectionsArray'][$i]['prioridad'],
								'nombre' => $client['sectionsArray'][$i]['nombre'],
								'descripcion' => $client['sectionsArray'][$i]['descripcion'],
								'imagen' => $popUpsWebPath . $idcpg . '/images/image_' . $i . '.' . $type_Array[1],
								'titulo' => $client['sectionsArray'][$i]['title'],
								'texto' => $client['sectionsArray'][$i]['description'],
								'texto_boton' => $client['sectionsArray'][$i]['texto_boton'],
								'idAddon' => $client['sectionsArray'][$i]['idAddon'],
								'deeplink' => $client['sectionsArray'][$i]['deeplink'],
								'timeshow' => $client['sectionsArray'][$i]['timeshow'],
								'enabled' => $client['sectionsArray'][$i]['enabled']
							];

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

							if($resultPOST->status != 'OK') {
								return $resultPOST;
							}
						} else {
							// Editar PopUps
							$url = CONSTANTS::SERVERAPI . 'updatePopups';
							$params = [
								'token' => $client['token'],
								'id' => $client['sectionsArray'][$i]['id'],
								'prioridad' => $client['sectionsArray'][$i]['prioridad'],
								'nombre' => $client['sectionsArray'][$i]['nombre'],
								'descripcion' => $client['sectionsArray'][$i]['descripcion'],
								'imagen' => $popUpsWebPath . $idcpg . '/images/image_' . $i . '.' . $type_Array[1],
								'titulo' => $client['sectionsArray'][$i]['title'],
								'texto' => $client['sectionsArray'][$i]['description'],
								'texto_boton' => $client['sectionsArray'][$i]['texto_boton'],
								'idAddon' => $client['sectionsArray'][$i]['idAddon'],
								'deeplink' => $client['sectionsArray'][$i]['deeplink'],
								'timeshow' => $client['sectionsArray'][$i]['timeshow'],
								'enabled' => $client['sectionsArray'][$i]['enabled']
							];

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

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

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

		return $resultPOST;
	}

	// Usuarios asignados a un PopUp
	public function getAllPopupsUserAssignment($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idPopUp' => $client['idPopUp']
		];

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

		return $resultPOST;
	}

	// Asignar usuarios a un PopUp
	public function setPopupsUserAssignment($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idPopUp' => $client['idPopUp'],
			'idUser' => $client['idUser']
		];

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

		return $resultPOST;
	}
}