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

class ReportsImages {
	private $utilesController;

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

	public function getImages($token, $idSurvey, $user, $filename) {
		try {
			$ctrl = new Controller();
			$url = CONSTANTS::SERVERAPI . 'getAnalyticsMuestraToExport';
			$params = [
				'token' => $token,
				'numPreguntasPerfilacionEnAnalyticMostreo' => 0,
				'survey' => $idSurvey

			];

			$resultPOST = $ctrl->sendCurlPOST($url, $params);
			$surveys = [];
			foreach($resultPOST->questions as $questions) {
				if($questions->type == '|') {
					array_push($surveys, $questions->id);
				}
			}

			if(count($surveys) > 0) {
				$images = [];
				foreach($surveys as $survey) {
					$images[$survey] = [];
					foreach($resultPOST->result as $result) {
						if(isset($result->$survey)) {
							$image = json_decode($result->$survey);
							if(isset($image[0])) {
								$data = [
									'name' => $image[0]->filename,
									'ext' => $image[0]->ext
								];
								array_push($images[$survey], $data);
							}
						}
					}
				}
			};

			$date = date_create();
			foreach($images as $key => $value) {
				foreach($value as $image) {
					$serverUrl = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/' . date_timestamp_get($date) . $image['name'] . '.' . $image['ext'];
					$url = CONSTANTS::SERVERSURVEYSINTERNAL . 'upload/surveys/' . $idSurvey . '/files/' . $image['name'];

					$filepath = $serverUrl;
					$carpeta = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/';
					if(!file_exists($carpeta)) {
						$createFile = $this->utilesController->createDirectory($carpeta);

						if($createFile['status'] == 'KO') {
							return 'The folder has not been created';
						}
					}

					file_put_contents($filepath, file_get_contents($url));

					// Carpeta donde guardar los elementos a comprimir
					$folder = CONSTANTS::PATH_EXPORT_WORD . '/' . $user . '/';
					if(!file_exists($folder)) { // Si no existe, se crea
						$createFile = $this->utilesController->createDirectory($folder);

						if($createFile['status'] == 'KO') {
							return 'The folder has not been created';
						}
					}

					// Objeto ZIP
					$zip = new ZipArchive();
					$zip->open($folder . $filename, ZipArchive::CREATE);
					$zip->addFile($serverUrl, 'multimedia/' . $key . '/' . $image['name'] . '.' . $image['ext']);
				}
			}
		} catch(Exception $e) {
			return false;
		}

		return true;
	}
}