<?php
namespace FileRun;
use FileRun\UI;
use FileRun\Utils\Translation;
use Firebase\JWT\JWT;

global $settings, $config;
if (!$config) {exit();}

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

$saveURL = false;
$extension = \FM::getExtension($this->data['fileName']);
$version = $this->data['version'] ?: false;

$isEditable = !$_GET['preview_plugin'] &&
			in_array($extension, $this->canEditTypes) &&
			!$this->isLimitedPreview() &&
			Perms::check('upload') &&
			(!$this->data['shareInfo'] || ($this->data['shareInfo'] && $this->data['shareInfo']['perms_upload']));


if ($this->data['weblink']) {
	$url = $this->data['weblink']['download_url'];
	$isEditable = $isEditable && WebLinks::verifyAllowEditing($this->data['weblink']['linkInfo']);
	if ($isEditable) {
		$saveURL = $this->actionURL . '&method=saveRemoteChanges';
	}
} else {
	$weblinkInfo = WebLinks::createForService($this->data, null, $isEditable);
	if (!$weblinkInfo) {
		self::outputError('Failed to setup weblink', 'html');
	}
	$url = WebLinks::getURL([
		'id_rnd' => $weblinkInfo['id_rnd'],
		'download' => 1,
		'version' => $version
	]);
	if ($isEditable) {
		$saveURL = WebLinks::getSaveURL($weblinkInfo['id_rnd'], false, "onlyoffice");
	}
}

$mode = $saveURL ? 'edit' : 'view';

//these changed in version 6.1 (https://api.onlyoffice.com/editors/changelog#61)
if (in_array($extension, $this->ext['text'])) {
	$docType = 'word';
} else if (in_array($extension, $this->ext['spreadsheet'])) {
	$docType = 'cell';
} else {
	$docType = 'slide';
}

global $auth;
$owner = Users::formatFullName($auth->currentUserInfo);
if ($this->data['weblink']) {
	$authorFirstName = 'Guest';
	$authorLastName = 'via '.$owner;
	$author = $authorFirstName.' '.$authorLastName;
} else {
	$authorFirstName = $auth->currentUserInfo['name'];
	$authorLastName = $auth->currentUserInfo['name2'];
	$author = $owner;
}

$fileModifTime = filemtime($this->data['fullPath']);

$pid = Paths::getId($this->data['fullPath'], true);
$documentKey = substr(implode('-',
	[$pid, $version, $fileModifTime]
), 0, 20);
$isMobile = $_REQUEST['mobile'] ?? false;

$opts = [
	'documentType' => $docType,
	"type" => ($isMobile ? 'mobile' : 'desktop'),
	"document" => [
		"fileType" => $extension,
		"key" => $documentKey,
		"title" => $this->data['fileName'],
		"url" => $url,
		"info" => [
			"author" => $author,
			"owner" => $author
		],
		"permissions" => [
			'chat' => (bool) $this->getSetting('oo_chat'),
            "comment" => true,
            "commentGroups" => [
                "edit" => [],
                "remove" => [],
                "view" => ""
            ],
            "copy" => true,
            "deleteCommentAuthorOnly" => false,
            "download" => false,
            "edit" => true,
            "editCommentAuthorOnly" => false,
            "fillForms" => true,
            "modifyContentControl" => true,
            "modifyFilter" => true,
            "print" => true,
            "review" => true,
            "reviewGroups" => []
        ]
	],
	"editorConfig" => [
		"mode" => $mode,
		"lang" => Translation\ShortCode::get(Lang::getCurrent()),
		"user" => [
			"id" => (string) $auth->currentUserInfo['id'],
			"name" => $author,
			"firstname" => $authorFirstName,
			"lastname" => $authorLastName
		],
		"customization" => [
			"autosave" => (bool) $this->getSetting('oo_autosave'),
			'about' => false,
			'comments' => (bool) $this->getSetting('oo_comments'),
			//'chat' => (bool) $this->getSetting('oo_chat'), //deprecated in v7.1
			'feedback' => false,
			'goback' => false,
			'compactHeader' => (bool) $this->getSetting('oo_compactHeader'),
			'uiTheme' => UI\Theme::isDark() ? 'default-dark' : 'default-light',
			'hideRightMenu' => true,
			'toolbarNoTabs' => true,
			'zoom' => $isMobile ? 100 : $this->getSetting('oo_zoom'),
			'logo' => ['url' => null]
		]
	],
	"events" => [
		'onError' => 'function (event) {
		 	console.log(event);
			if (event && docEditor) {
				docEditor.showMessage(event.data);
			}
		}'
	],
	"height" => "100%",
	"width" => "100%"
];

if ($this->isLimitedPreview()) {
	$opts['document']['permissions'] = array_replace($opts['document']['permissions'], [
		"edit" => false,
		"download" => false,
		"review" => false,
		'copy' => false,
		"fillForms" => false,
		"print" => false,
		"comment" => false,
		"editCommentsAuthorOnly" => true,
        "deleteCommentsAuthorOnly" => true
	]);
}

if ($mode == 'view') {
	$opts['type'] = 'embedded';
	$opts['editorConfig']['embedded'] = ['toolbarDocked' => 'bottom'];
} else {
	$opts['editorConfig']['customization']['forcesave'] = true;
}

if ($saveURL) {
	$opts['editorConfig']['callbackUrl'] = $saveURL;
}
$secret = $this->getSetting('serverSecret');
if ($secret != '') {
    $opts['token'] = JWT::encode($opts, $secret, 'HS256');
}

$page = [
	'noJSTrans' => true,
	'scripts' => [
		$this->url.'/app.js?v='.$settings->currentVersion,
		gluePath(self::getSetting('serverURL'), '/web-apps/apps/api/documents/api.js')
	],
	'jsGlobals' => [
		'var Settings' => $opts,
		'var DocumentServerURL' => self::getSetting('serverURL')
	]
];
require $config['path']['includes'].'/ui/page/plugin.php';

$this->logAction();