<?php
namespace FileRun;

use FileRun\Files\Actions\Upload\Utils;

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

$typeInfo = \FM::fileTypeInfo($this->data['fileName']);
if ($typeInfo['type'] == 'img') {
	$url = $this->actionURL.'&method=openInBrowser&noCache='.time();
} else {
	if (!Thumbs\Utils::extCanHaveThumb($typeInfo['extension'])) {
		exit('Cannot convert file type to image.');
	}
	$url = $config['url']['root'].'/t.php?width=4000&height=4000&p='.\S::forURL($this->data['relativePath']).'&noCache='.time();
}
if ($this->data['version']) {
	$url .= '&version='.\S::forURL($this->data['version']);
}

$chunkSize = Utils::getUploadChunkSize();

$originalExt = \FM::getExtension($this->data['fileName'], true);

if (in_array($typeInfo['extension'], ['png', 'svg', 'gif', 'bmp'])) {
	$saveExtension = $typeInfo['extension'] == 'png' ? $originalExt : 'png';
	$saveMimeType = 'image/png';
} else {
	$saveExtension = in_array($typeInfo['extension'], ['jpeg', 'jpg']) ? $originalExt : 'jpg';
	$saveMimeType = 'image/jpeg';
}

$folderPath = \FM::dirname($this->data['relativePath']);
$saveFileName = \FM::replaceExtension($this->data['fileName'], $saveExtension);
if ($this->data['relativePathInfo']['type'] == 'shared') {
	if ($this->data['shareInfo']['type'] == 'file') {
		$saveFileName = $this->data['relativePathInfo']['share_id'];
	}
}

$vars = [
	'cacheid' => UI\Utils::getStaticAssetCacheID(),
	'URLRoot' => $config['url']['root'],
	'originalFileName' => $this->data['fileName'],
	'saveFileName' => $saveFileName,
	'saveMimeType' => $saveMimeType,
	'imageURL' => $url,
	'windowId' => $_REQUEST['_popup_id'],
	'UploadChunkSize' => $chunkSize,
	'csrf_token' => self::getCSRFToken(),
	'devMode' => $config['dev']['mode']
];

$linkInfo = $this->data['weblink']['linkInfo'] ?? null;
if ($linkInfo) {
//	$vars['saveURL'] = '/?module=weblinks&section=public&page=upload';
//	$vars['uploadQuery'] = [
//		'id' => $linkInfo['id_rnd']
//	];
} else {
	$vars['saveURL'] = '/?module=fileman&section=do&page=up';
	$vars['uploadQuery'] = [
		'path' => $folderPath
	];
}

$page = [
	'styles' => [
		'basic', 'fa', 'ext',
		'cropper',
		$this->url.'/editor.css?cache='.$vars['cacheid']
	],
	'scripts' => [
		'ext',
		'ext/components/slider',
	    'flow/utils',
		'cropper',
		$this->url.'/app.js?cache='.$vars['cacheid'],
		$this->url.'/caman.full.min.js?cache='.$vars['cacheid']
	],
	'jsGlobals' => [
		'FR.vars' => $vars
	]
];

require $config['path']['includes'].'/ui/page/plugin.php';