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

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;

class ItemsController {
	private $utilesController;

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

	// Crear nuevo item
	public function setItems($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'fichaGS1Completa' => $client['fichaGS1Completa'],
			'pendienteRevision' => $client['pendienteRevision'],
			'barcode' => $client['barcode'],
			'nombre' => $client['nombre'],
			'descripcion' => $client['descripcion'],
			'categoria' => $client['categoria'],
			'subcategoria' => $client['subcategoria'],
			'segmento' => $client['segmento'],
			'subsegmento' => $client['subsegmento'],
			'ocasiones' => $client['ocasiones'],
			'fabricante' => $client['fabricante'],
			'marca' => $client['marca'],
			'submarca' => $client['submarca'],
			'sabor' => $client['sabor'],
			'empaque' => $client['empaque'],
			'contenido' => $client['contenido'],
			'unidadMedida' => $client['unidadMedida'],
			'rangoContenido' => $client['rangoContenido'],
			'imgFolder' => ''
		];

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

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

		// ID del item creado
		$idItem = $resultPOST->id;

		// Tiendas con el articulo
		$url = CONSTANTS::SERVERAPI . 'setItemComercios';
		$params = [
			'token' => $client['token'],
			'item' => $idItem,
			'comercios' => $client['stores'] == '[]' ? $client['stores'] : json_encode($client['stores'])
		];

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

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

		// Ruta de imágenes de item
		$itemPath = CONSTANTS::PATH_EXPORT_WORD . '/items/' . $idItem;

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

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

		// Imágenes
		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;

			$count = 0;
			foreach($_FILES as $key => $value) {
				if($_FILES[$key]['size'] <= $maxSize) {
					$type = $_FILES[$key]['type'];
					$type_Array = explode('/', $type);
					$timeStamp = str_replace('.', '', microtime(true));

					$keepIn = $itemPath . '/' . $idItem . '_' . $timeStamp . '.' . $type_Array[1];
					if($client['acceptItemImages'][$count]['main'] == '_main_') {
						// Si es la imagen principal añadir '_main_' al nombre
						$keepIn = $itemPath . '/' . $idItem . '_' . $timeStamp . '_main_.' . $type_Array[1];
					}

					// Mover imagen a carpeta de artículo
					if(!move_uploaded_file($_FILES[$key]['tmp_name'], $keepIn)) {
						$resultPOST->status = 'KO';
						$resultPOST->result = 'File not copied';
						return $resultPOST;
					}
				} else {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file is too large: ' . $_FILES[$key]['name'];
					return $resultPOST;
				}
				$count++;
			}

			$url = CONSTANTS::SERVERAPI . 'updateItems';
			$params = [
				'token' => $client['token'],
				'idItem' => $idItem,
				'fichaGS1Completa' => $client['fichaGS1Completa'],
				'pendienteRevision' => $client['pendienteRevision'],
				'barcode' => $client['barcode'],
				'nombre' => $client['nombre'],
				'descripcion' => $client['descripcion'],
				'categoria' => $client['categoria'],
				'subcategoria' => $client['subcategoria'],
				'segmento' => $client['segmento'],
				'subsegmento' => $client['subsegmento'],
				'ocasiones' => $client['ocasiones'],
				'fabricante' => $client['fabricante'],
				'marca' => $client['marca'],
				'submarca' => $client['submarca'],
				'sabor' => $client['sabor'],
				'empaque' => $client['empaque'],
				'contenido' => $client['contenido'],
				'unidadMedida' => $client['unidadMedida'],
				'rangoContenido' => $client['rangoContenido'],
				'imgFolder' => $itemPath
			];

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

		return $resultPOST;
	}

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

		if($client['items'] != '[]') {
			foreach($client['items'] as $item) {
				$params = [
					'token' => $client['token'],
					'idItem' => $item['idItem']
				];

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

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

		return $resultPOST;
	}

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

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

		// Imágenes de items
		$itemPath = $resultPOST->result[0]->imgFolder;
		$files = scandir($itemPath);

		$resultPOST->result[0]->imgFolder = [];
		if($files) {
			for($i = 0; $i < count($files); $i++) {
				if($files[$i] == '.' || $files[$i] == '..' || $files[$i] == 'delete') {
					continue;
				}

				array_push($resultPOST->result[0]->imgFolder, $files[$i]);
			}
		}

		return $resultPOST;
	}

	// Actualizar item
	public function updateItems($client) {
		$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;

		// Ruta de imágenes de item
		$itemPath = CONSTANTS::PATH_EXPORT_WORD . '/items/' . $client['idItem'];

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

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

		for($i = 0; $i < count($client['acceptItemImages']); $i++) {
			if($client['acceptItemImages'][$i]['status'] == 'new') {
				// Imagen nueva
				if($_FILES['img' . $i]['size'] <= $maxSize) {
					$type = $_FILES['img' . $i]['type'];
					$type_Array = explode('/', $type);
					$timeStamp = str_replace('.', '', microtime(true));

					// Mover imagen a carpeta de artículo
					$keepIn = $itemPath . '/' . $client['idItem'] . '_' . $timeStamp . '.' . $type_Array[1];
					if($client['acceptItemImages'][$i]['main'] == '_main_') {
						// Si es la imagen principal añadir '_main_' al nombre
						$keepIn = $itemPath . '/' . $client['idItem'] . '_' . $timeStamp . '_main_.' . $type_Array[1];
					}

					if(!move_uploaded_file($_FILES['img' . $i]['tmp_name'], $keepIn)) {
						$resultPOST->status = 'KO';
						$resultPOST->result = 'File not copied';
						return $resultPOST;
					}
				} else {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file is too large: ' . $_FILES['img' . $i]['name'];
					return $resultPOST;
				}
			} else if($client['acceptItemImages'][$i]['status'] == 'delete') {
				// Ruta de imágenes borradas
				$deleteItemPath = CONSTANTS::PATH_EXPORT_WORD . '/items/' . $client['idItem'] . '/delete';

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

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

				$fileName = end(explode('/', $client['acceptItemImages'][$i]['imgPath']));
				rename($itemPath . '/' . $fileName, $deleteItemPath . '/' . $fileName);
			} else if(strrpos($client['acceptItemImages'][$i]['imgPath'], '_main_') !== false && $client['acceptItemImages'][$i]['main'] == '0') {
				// Antigua imagen principal
				$fileName = end(explode('/', $client['acceptItemImages'][$i]['imgPath']));
				rename($itemPath . '/' . $fileName, $itemPath . '/' . str_replace('_main_', '', $fileName));
			} else if(strrpos($client['acceptItemImages'][$i]['imgPath'], '_main_') === false && $client['acceptItemImages'][$i]['main'] == '_main_') {
				// Nueva imagen principal
				$fileNameOld = end(explode('/', $client['acceptItemImages'][$i]['imgPath']));
				$fileNameArray = explode('.', $fileNameOld);
				$theLast = array_pop($fileNameArray);
				$filenameNew = implode('.', $fileNameArray) . '_main_.' . $theLast;

				rename($itemPath . '/' . $fileNameOld, $itemPath . '/' . $filenameNew);
			}
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'idItem' => $client['idItem'],
			'fichaGS1Completa' => $client['fichaGS1Completa'],
			'pendienteRevision' => $client['pendienteRevision'],
			'barcode' => $client['barcode'],
			'nombre' => $client['nombre'],
			'descripcion' => $client['descripcion'],
			'categoria' => $client['categoria'],
			'subcategoria' => $client['subcategoria'],
			'segmento' => $client['segmento'],
			'subsegmento' => $client['subsegmento'],
			'ocasiones' => $client['ocasiones'],
			'fabricante' => $client['fabricante'],
			'marca' => $client['marca'],
			'submarca' => $client['submarca'],
			'sabor' => $client['sabor'],
			'empaque' => $client['empaque'],
			'contenido' => $client['contenido'],
			'unidadMedida' => $client['unidadMedida'],
			'rangoContenido' => $client['rangoContenido'],
			'imgFolder' => $itemPath
		];

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

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

		// Tiendas con el articulo
		$url = CONSTANTS::SERVERAPI . 'setItemComercios';
		$params = [
			'token' => $client['token'],
			'item' => $client['idItem'],
			'comercios' => $client['stores'] == '[]' ? $client['stores'] : json_encode($client['stores'])
		];

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

		return $resultPOST;
	}

	// Subida de archivo de items descargados
	public function sendExcelDataToServerItems($client) {
		$response = [
			'status' => 'OK',
			'result' => 'Success'
		];

		try {
			// Excel
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$cabeceras = $client['dataExcelHead'];

			$col = 1;
			foreach($cabeceras as $field) {
				$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
				$col++;
			}

			// Datos
			$row = 2;
			$allData = $client['dataExcelBody'];
			foreach($allData as $data) {
				$col = 1;
				foreach($data as $value) {
					$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
					$col++;
				}
				$row++;
			}

			// Estilos encabezados
			$letra = $spreadsheet->getActiveSheet()->getHighestColumn();
			$spreadsheet->getActiveSheet()->getStyle('A1:' . $letra . '1')->applyFromArray(
				[
					'fill' => [
						'type' => Fill::FILL_SOLID,
						'color' => [
							'rgb' => 'E5E4E2'
						]
					],
					'font' => [
						'bold' => false
					]
				]
			);

			// Autoajustar celdas
			$column = 'A';
			while($column != $letra) {
				$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
				$column++;
			}

			$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

			$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/items/exportar/' . $client['userMail'];

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

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

			$filename = $client['stampName'] . '.xlsx';

			$writer = new Xlsx($spreadsheet);
			$writer->save($carpeta . '/' . $filename);

			$type = 'Exported Items';
			$service = $client['userMail'];
			$event = 'Se generó y descargó un archivo de catálogo de productos. Id del archivo: ' . $client['stampName'];
			$rute = '/items/exportar/' . $client['userMail'] . '/' . $filename;

			$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');
		} catch(Exception $e) {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
		}

		return $response;
	}

	// Modificar registros a través de archivo
	public function updateNewItemsFromFile($client) {
		$response = array("status"=>"OK", "result"=>[]);
		$type = 'UpdateNewItemsFromFile';
		$service = $client['userMail'];
		$event = 'Se modificaron los registros del Catálogo a través de un archivo excel.';
		$rute = '';

		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');

		$itemsResponse = array(
			"setItems" => array("OK" => 0, "KO" => 0),
			"setItemComercios" => array("OK" => 0, "KO" => 0)
		);

		foreach($client['itemsArray'] as $item) {
			if($item['idItem'] != '' && isset($item['barcode']) && $item['barcode'] != '') {
				// Editar
				$url = CONSTANTS::SERVERAPI . 'updateItems';
				$params = [
					'token' => $client['token'],
					'idItem' => $item['idItem'],
					'fichaGS1Completa' => $item['fichaGS1Completa'],
					'pendienteRevision' => $item['pendienteRevision'],
					'barcode' => $item['barcode'],
					'nombre' => $item['nombre'],
					'descripcion' => $item['descripcion'],
					'categoria' => $item['categoria'],
					'subcategoria' => $item['subcategoria'],
					'segmento' => $item['segmento'],
					'subsegmento' => $item['subsegmento'],
					'ocasiones' => $item['ocasiones'],
					'fabricante' => $item['fabricante'],
					'marca' => $item['marca'],
					'submarca' => $item['submarca'],
					'sabor' => $item['sabor'],
					'empaque' => $item['empaque'],
					'contenido' => $item['contenido'],
					'unidadMedida' => $item['unidadMedida'],
					'rangoContenido' => $item['rangoContenido'],
					'imgFolder' => $item['imgFolder']
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK') {
					++$itemsResponse["setItems"]["KO"];
				} else {
					++$itemsResponse["setItems"]["OK"];
				}

				// Tiendas con el articulo
				$comercios = [];
				if(!empty($item['comercios'])) {
					$comercios = explode(",", $item['comercios']);
					$comercios = array_filter($comercios, 'strlen');
					$comercios = array_map('intval', $comercios);
				}
				$comercios = json_encode($comercios);

				// Tiendas con el articulo
				$url = CONSTANTS::SERVERAPI . 'setItemComercios';
				$params = [
					'token' => $client['token'],
					'item' => $item['idItem'],
					'comercios' => $comercios
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK') {
					++$itemsResponse["setItemComercios"]["KO"];
				} else {
					++$itemsResponse["setItemComercios"]["OK"];
				}
			} else if(isset($item['barcode']) && $item['barcode'] != '') {
				// Crear
				$url = CONSTANTS::SERVERAPI . 'setItems';
				$params = [
					'token' => $client['token'],
					'fichaGS1Completa' => $item['fichaGS1Completa'],
					'pendienteRevision' => $item['pendienteRevision'],
					'barcode' => $item['barcode'],
					'nombre' => $item['nombre'],
					'descripcion' => $item['descripcion'],
					'categoria' => $item['categoria'],
					'subcategoria' => $item['subcategoria'],
					'segmento' => $item['segmento'],
					'subsegmento' => $item['subsegmento'],
					'ocasiones' => $item['ocasiones'],
					'fabricante' => $item['fabricante'],
					'marca' => $item['marca'],
					'submarca' => $item['submarca'],
					'sabor' => $item['sabor'],
					'empaque' => $item['empaque'],
					'contenido' => $item['contenido'],
					'unidadMedida' => $item['unidadMedida'],
					'rangoContenido' => $item['rangoContenido'],
					'imgFolder' => ''
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK') {
					++$itemsResponse["setItems"]["KO"];
				} else {
					++$itemsResponse["setItems"]["OK"];
				}

				// Tiendas con el articulo
				$comercios = [];
				if(!empty($item['comercios'])) {
					$comercios = explode(",", $item['comercios']);
					$comercios = array_filter($comercios, 'strlen');
					$comercios = array_map('intval', $comercios);
				}
				$comercios = json_encode($comercios);

				$url = CONSTANTS::SERVERAPI . 'setItemComercios';
				$params = [
					'token' => $client['token'],
					'item' => $resultPOST->id,
					'comercios' => $comercios
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK') {
					++$itemsResponse["setItemComercios"]["KO"];
				} else {
					++$itemsResponse["setItemComercios"]["OK"];
				}
			}
		}

		$response["result"] = $itemsResponse;

		return $response;
	}

	// Crear nuevo tipo de tienda
	public function setComercioType($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'descripcion' => $client['descripcion']
		];

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

		return $resultPOST;
	}

	// Eliminar tipo de tienda
	public function deleteComercioType($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];

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

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

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

		return $resultPOST;
	}

	// Actualizar tipo de tienda
	public function updateComercioType($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'descripcion' => $client['descripcion']
		];

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

		return $resultPOST;
	}

	// Crear nueva tienda
	public function setComercios($client) {
		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'nombre' => $client['nombre'],
			'direccion' => $client['direccion'],
			'idComercioType' => $client['idComercioType'],
			'telefono' => $client['telefono'],
			'email' => $client['email'],
			'personaContacto' => $client['personaContacto'],
			'horarioApertura' => $client['horarioApertura'],
			'horarioCierre' => $client['horarioCierre'],
			'numCajas' => $client['numCajas'],
			'numRefrigeradores' => $client['numRefrigeradores'],
			'latitude' => $client['latitude'],
			'longitude' => $client['longitude'],
			'altitude' => $client['altitude'],
			'accuracy' => $client['accuracy'],
			'abiertaPublico' => $client['abiertaPublico'],
			'ventanilla' => $client['ventanilla'],
			'apertura24H' => $client['apertura24H'],
			'fotosFolder' => ''
		];

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

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

		// ID de la tienda creada
		$idStore = $resultPOST->id;

		// Articulos en tienda
		$url = CONSTANTS::SERVERAPI . 'setComercioItems';
		$params = [
			'token' => $client['token'],
			'id' => $idStore,
			'items' => $client['items'] == '[]' ? $client['items'] : json_encode($client['items'])
		];

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

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

		// Ruta de imágenes de tienda
		$storePath = CONSTANTS::PATH_EXPORT_WORD . '/stores/' . $idStore;

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

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

		// Imágenes
		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;

			$count = 0;
			foreach($_FILES as $key => $value) {
				if($_FILES[$key]['size'] <= $maxSize) {
					$type = $_FILES[$key]['type'];
					$type_Array = explode('/', $type);
					$timeStamp = str_replace('.', '', microtime(true));

					$keepIn = $storePath . '/' . $idStore . '_' . $timeStamp . '.' . $type_Array[1];
					if($client['acceptStoreImages'][$count]['main'] == '_main_') {
						// Si es la imagen principal añadir '_main_' al nombre
						$keepIn = $storePath . '/' . $idStore . '_' . $timeStamp . '_main_.' . $type_Array[1];
					}

					// Mover imagen a carpeta de tienda
					if(!move_uploaded_file($_FILES[$key]['tmp_name'], $keepIn)) {
						$resultPOST->status = 'KO';
						$resultPOST->result = 'File not copied';
						return $resultPOST;
					}
				} else {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file is too large: ' . $_FILES[$key]['name'];
					return $resultPOST;
				}
				$count++;
			}

			$url = CONSTANTS::SERVERAPI . 'updateComercios';
			$params = [
				'token' => $client['token'],
				'id' => $idStore,
				'nombre' => $client['nombre'],
				'direccion' => $client['direccion'],
				'idComercioType' => $client['idComercioType'],
				'telefono' => $client['telefono'],
				'email' => $client['email'],
				'personaContacto' => $client['personaContacto'],
				'horarioApertura' => $client['horarioApertura'],
				'horarioCierre' => $client['horarioCierre'],
				'numCajas' => $client['numCajas'],
				'numRefrigeradores' => $client['numRefrigeradores'],
				'latitude' => $client['latitude'],
				'longitude' => $client['longitude'],
				'altitude' => $client['altitude'],
				'accuracy' => $client['accuracy'],
				'abiertaPublico' => $client['abiertaPublico'],
				'ventanilla' => $client['ventanilla'],
				'apertura24H' => $client['apertura24H'],
				'fotosFolder' => $storePath
			];

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

		return $resultPOST;
	}

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

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

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

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

		return $resultPOST;
	}

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

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

		// Imágenes de tiendas
		$storePath = $resultPOST->result[0]->fotosFolder;
		$files = scandir($storePath);

		$resultPOST->result[0]->fotosFolder = [];
		if($files) {
			for($i = 0; $i < count($files); $i++) {
				if($files[$i] == '.' || $files[$i] == '..' || $files[$i] == 'delete') {
					continue;
				}

				array_push($resultPOST->result[0]->fotosFolder, $files[$i]);
			}
		}

		return $resultPOST;
	}

	// Actualizar tienda
	public function updateComercios($client) {
		$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;

		// Ruta de imágenes de tienda
		$storePath = CONSTANTS::PATH_EXPORT_WORD . '/stores/' . $client['id'];

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

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

		for($i = 0; $i < count($client['acceptStoreImages']); $i++) {
			if($client['acceptStoreImages'][$i]['status'] == 'new') {
				// Imagen nueva
				if($_FILES['img' . $i]['size'] <= $maxSize) {
					$type = $_FILES['img' . $i]['type'];
					$type_Array = explode('/', $type);
					$timeStamp = str_replace('.', '', microtime(true));

					// Mover imagen a carpeta de artículo
					$keepIn = $storePath . '/' . $client['id'] . '_' . $timeStamp . '.' . $type_Array[1];
					if($client['acceptStoreImages'][$i]['main'] == '_main_') {
						// Si es la imagen principal añadir '_main_' al nombre
						$keepIn = $storePath . '/' . $client['id'] . '_' . $timeStamp . '_main_.' . $type_Array[1];
					}

					if(!move_uploaded_file($_FILES['img' . $i]['tmp_name'], $keepIn)) {
						$resultPOST->status = 'KO';
						$resultPOST->result = 'File not copied';
						return $resultPOST;
					}
				} else {
					$resultPOST->status = 'KO';
					$resultPOST->result = 'The file is too large: ' . $_FILES['img' . $i]['name'];
					return $resultPOST;
				}
			} else if($client['acceptStoreImages'][$i]['status'] == 'delete') {
				// Ruta de imágenes borradas
				$deleteStorePath = CONSTANTS::PATH_EXPORT_WORD . '/stores/' . $client['id'] . '/delete';

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

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

				$fileName = end(explode('/', $client['acceptStoreImages'][$i]['imgPath']));
				rename($storePath . '/' . $fileName, $deleteStorePath . '/' . $fileName);
			} else if(strrpos($client['acceptStoreImages'][$i]['imgPath'], '_main_') !== false && $client['acceptStoreImages'][$i]['main'] == '0') {
				// Antigua imagen principal
				$fileName = end(explode('/', $client['acceptStoreImages'][$i]['imgPath']));
				rename($storePath . '/' . $fileName, $storePath . '/' . str_replace('_main_', '', $fileName));
			} else if(strrpos($client['acceptStoreImages'][$i]['imgPath'], '_main_') === false && $client['acceptStoreImages'][$i]['main'] == '_main_') {
				// Nueva imagen principal
				$fileNameOld = end(explode('/', $client['acceptStoreImages'][$i]['imgPath']));
				$fileNameArray = explode('.', $fileNameOld);
				$theLast = array_pop($fileNameArray);
				$filenameNew = implode('.', $fileNameArray) . '_main_.' . $theLast;

				rename($storePath . '/' . $fileNameOld, $storePath . '/' . $filenameNew);
			}
		}

		$url = CONSTANTS::SERVERAPI . $client['action'];
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'nombre' => $client['nombre'],
			'direccion' => $client['direccion'],
			'idComercioType' => $client['idComercioType'],
			'telefono' => $client['telefono'],
			'email' => $client['email'],
			'personaContacto' => $client['personaContacto'],
			'horarioApertura' => $client['horarioApertura'],
			'horarioCierre' => $client['horarioCierre'],
			'numCajas' => $client['numCajas'],
			'numRefrigeradores' => $client['numRefrigeradores'],
			'latitude' => $client['latitude'],
			'longitude' => $client['longitude'],
			'altitude' => $client['altitude'],
			'accuracy' => $client['accuracy'],
			'abiertaPublico' => $client['abiertaPublico'],
			'ventanilla' => $client['ventanilla'],
			'apertura24H' => $client['apertura24H'],
			'fotosFolder' => $storePath
		];

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

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

		// Articulos en tienda
		$url = CONSTANTS::SERVERAPI . 'setComercioItems';
		$params = [
			'token' => $client['token'],
			'id' => $client['id'],
			'items' => $client['items'] == '[]' ? $client['items'] : json_encode($client['items'])
		];

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

		return $resultPOST;
	}

	// Subida de archivo de stores descargados
	public function sendExcelDataToServerStores($client) {
		$response = [
			'status' => 'OK',
			'result' => 'Success'
		];

		try {
			// Excel
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$cabeceras = $client['dataExcelHead'];

			$col = 1;
			foreach($cabeceras as $field) {
				$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
				$col++;
			}

			// Datos
			$row = 2;
			$allData = $client['dataExcelBody'];
			foreach($allData as $data) {
				$col = 1;
				foreach($data as $value) {
					$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
					$col++;
				}
				$row++;
			}

			// Estilos encabezados
			$letra = $spreadsheet->getActiveSheet()->getHighestColumn();
			$spreadsheet->getActiveSheet()->getStyle('A1:' . $letra . '1')->applyFromArray(
				[
					'fill' => [
						'type' => Fill::FILL_SOLID,
						'color' => [
							'rgb' => 'E5E4E2'
						]
					],
					'font' => [
						'bold' => false
					]
				]
			);

			// Autoajustar celdas
			$column = 'A';
			while($column != $letra) {
				$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
				$column++;
			}

			$spreadsheet->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);

			$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/stores/exportar/' . $client['userMail'];

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

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

			$filename = $client['stampName'] . '.xlsx';

			$writer = new Xlsx($spreadsheet);
			$writer->save($carpeta . '/' . $filename);

			$type = 'Exported Stores';
			$service = $client['userMail'];
			$event = 'Se generó y descargó un archivo de tiendas. Id del archivo: ' . $client['stampName'];
			$rute = '/stores/exportar/' . $client['userMail'] . '/' . $filename;

			$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');
		} catch(Exception $e) {
			$response['status'] = 'KO';
			$response['result'] = 'Error';
		}

		return $response;
	}

	// Modificar registros a través de archivo
	public function updateNewStoresFromFile($client) {
		$type = 'updateNewStoresFromFile';
		$service = $client['userMail'];
		$event = 'Se modificaron los registros de tiendas a través de un archivo excel.';
		$rute = '';

		$this->utilesController->setCMBPLOG($client['token'], $type, $service, $event, $rute, '1');

		foreach($client['itemsArray'] as $store) {
			if($store['id'] != '') {
				// Editar
				$url = CONSTANTS::SERVERAPI . 'updateComercios';
				$params = [
					'token' => $client['token'],
					'id' => $store['id'],
					'nombre' => $store['nombre'],
					'direccion' => $store['direccion'],
					'idComercioType' => $store['idComercioType'],
					'telefono' => $store['telefono'],
					'email' => $store['email'],
					'personaContacto' => $store['personaContacto'],
					'horarioApertura' => $store['horarioApertura'],
					'horarioCierre' => $store['horarioCierre'],
					'numCajas' => $store['numCajas'],
					'numRefrigeradores' => $store['numRefrigeradores'],
					'latitude' => $store['latitude'],
					'longitude' => $store['longitude'],
					'altitude' => $store['altitude'],
					'accuracy' => $store['accuracy'],
					'abiertaPublico' => $store['abiertaPublico'],
					'ventanilla' => $store['ventanilla'],
					'apertura24H' => $store['apertura24H'],
					'fotosFolder' => $store['fotosFolder'],
				];

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

				// Registro de errores
				if($resultPOST->status != 'OK') {
					return $resultPOST;
				}
			} else {
				// Crear
				$url = CONSTANTS::SERVERAPI . 'setComercios';
				$params = [
					'token' => $client['token'],
					'nombre' => $store['nombre'],
					'direccion' => $store['direccion'],
					'idComercioType' => $store['idComercioType'],
					'telefono' => $store['telefono'],
					'email' => $store['email'],
					'personaContacto' => $store['personaContacto'],
					'horarioApertura' => $store['horarioApertura'],
					'horarioCierre' => $store['horarioCierre'],
					'numCajas' => $store['numCajas'],
					'numRefrigeradores' => $store['numRefrigeradores'],
					'latitude' => $store['latitude'],
					'longitude' => $store['longitude'],
					'altitude' => $store['altitude'],
					'accuracy' => $store['accuracy'],
					'abiertaPublico' => $store['abiertaPublico'],
					'ventanilla' => $store['ventanilla'],
					'apertura24H' => $store['apertura24H'],
					'fotosFolder' => ''
				];

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

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

		return $resultPOST;
	}
}