<?php
namespace FileRun;

global $config;
use GuzzleHttp\Client;
use GuzzleHttp\Exception;

if (!$config) {exit();}

if ($this->isLimitedPreview() && !$this->getSetting('allow_without_download')) {
	$this->centeredThumb();
	return;
}

$writerURLDoc = 'https://writer.zoho.com/writer/officeapi/v1/document';
$writerURLPreview ='https://writer.zoho.com/v1/officeapi/document/preview';
$sheetURL = 'https://sheet.zoho.com/sheet/officeapi/v1/spreadsheet';
$showURL = 'https://show.zoho.com/show/officeapi/v1/presentation';

global $auth;
$version = $this->data['version'] ?: false;

$mode = 'view';
$saveURL = false;
if (!$this->isLimitedPreview() && Perms::check('upload')) {
	if ((!$this->data['shareInfo'] || ($this->data['shareInfo'] && $this->data['shareInfo']['perms_upload']))) {
		if ($this->data['weblink']) {
			$saveURL = $this->actionURL.'&method=saveRemoteChanges';
		} else {
			$weblinkInfo = WebLinks::createForService($this->data, 2, true);
			if (!$weblinkInfo) {
				self::outputError('Failed to setup weblink', 'html');
			}
			$saveURL = WebLinks::getSaveURL($weblinkInfo['id_rnd'], false, "zoho");
		}
		$mode = 'edit';
	}
}

$extension = \FM::getExtension($this->data['fileName']);
$isWriterViewMode = false;
if (in_array($extension, $this->writerExtensions)) {
	if ($mode == 'edit') {
		$url = $writerURLDoc;
	} else {
		$url = $writerURLPreview;
		$isWriterViewMode = true;
	}
	$serviceName = 'Writer';
} else {
	if (in_array($extension, $this->showExtensions)) {
		$url = $showURL;
		$serviceName = 'Show';
	} else {
		$url = $sheetURL;
		$serviceName = 'Sheet';
	}
}
$customAPIHostname = $this->getSetting('api_hostname');
if ($customAPIHostname && $customAPIHostname != 'zohoapis.com') {
	$url = str_replace('zoho.com', $customAPIHostname, $url);
}

$author = Users::formatFullName($auth->currentUserInfo);

$filePointer = $this->readFile([
	'returnFilePointer' => true
]);

$post = [
	['name' => 'apikey', 'contents' => $this->getSetting('APIKey')],
	['name' => 'document', 'contents' => $filePointer]
];

$metaFileId = MetaFiles::getId($this->data['fullPath']);
$zohoDocId = false;
$docIdMetaFieldId = false;
if ($metaFileId) {
	$d = MetaFields::getTable();
	$docIdMetaFieldId = $d->selectOneCol('id', [['`system`', '=', 1], ['name', '=', $d->q('zoho_collab')]]);
	$zohoDocId = MetaValues::get($metaFileId, $docIdMetaFieldId);
}
//if (!$zohoDocId) {$zohoDocId = uniqid(rand());}//newer zoho errors out on this

if (!$isWriterViewMode) {
	$documentInfo = ['document_name' => trim(\FM::stripExtension($this->data['fileName']))];
	if ($zohoDocId) {
		$documentInfo['document_id'] = $zohoDocId;
	}
	$post[] = [
		'name' => 'document_info',
		'contents' => json_encode($documentInfo)
	];
	$user_info = ['display_name' => preg_replace('/[^\00-\255]+/u', '_', $author)];
	if ($serviceName != 'Sheet') {
		$user_info['user_id'] = $auth->currentUserInfo['id'];
	}
	$post[] = [
		'name' => 'user_info',
		'contents' => json_encode($user_info)
	];
	if ($saveURL) {
		$post[] = [
			'name' => 'callback_settings',
			'contents' => json_encode([
				'save_format' => $extension,
				'save_url' => $saveURL
			])
		];
	}
}

$http = new Client();
try {
	$response = $http->request('POST', $url, [
		'headers' => ['User-Agent' => ''],
		'multipart' => $post
	]);
} catch (Exception\ConnectException $e) {
	jsonFeedback(false, 'Error uploading file: Network connection error: ' . $e->getMessage());
} catch (Exception\ClientException $e) {
	echo 'Error uploading file to Zoho server: '.$e->getResponse()->getStatusCode();
	echo '<br>';
	echo $e->getResponse()->getBody()->getContents();
	exit();
} catch (Exception\ServerException $e) {
	echo 'Error uploading file to Zoho server: '.$e->getResponse()->getStatusCode();
	echo '<br>';
	echo $e->getResponse()->getBody()->getContents();
	exit();
} catch (\RuntimeException $e) {
	echo 'Error: ' . $e->getMessage();
	exit();
}
$rs = $response->getBody()->getContents();
if (!$rs) {
	jsonFeedback(false, 'Error uploading file: empty server response!');
}
$rs = json_decode($rs, true);
if ($isWriterViewMode) {
	if ($rs['preview_url']) {
		header("Location: " . $rs['preview_url']);
		exit();
	}
} else {
	if ($rs['document_url']) {
		//save document id for collaboration
		if ($rs['document_id']) {
			if ($docIdMetaFieldId) {
				MetaValues::setByPath($this->data['fullPath'], $docIdMetaFieldId, $rs['document_id']);
			}
		}
		header("Location: " . $rs['document_url']);
		exit();
	}

	echo "<strong>Zoho:</strong>";
	echo "<div style=\"margin:5px;border:1px solid silver;padding:5px;overflow:auto;\"><pre>";
	if (false !== strpos($rs['warning'], "unable to import content")) {
		echo "Zoho.com service does not support this type of documents or was not able to access this web server.\r\n\r\n";
	}
	echo $response;
	echo "</pre></div>";
}