<?php
namespace FileRun;
use FileRun\Utils\HTTP;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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

$rs = @file_get_contents("php://input");
if ($rs === false) {
	self::outputError(error_get_last()['message'], 'text');
}

if (!$rs) {
	self::outputError('Empty request.', 'text');
}
$data = json_decode($rs, false);

if ($data === NULL) {
	self::outputError('Bad request.', 'text');
}
$secret = $this->getSetting('serverSecret');

if ($secret) {
	$token = null;
	if (!empty($data->token)) {
		$token = $data->token;
	} else {
		$headers = getallheaders();
		if (!array_key_exists('Authorization', $headers)) {
			$header = $headers['Authorization'];
			if (str_starts_with($header, 'Bearer ')) {
				$token = substr($header, strlen("Bearer "));
			}
		}
	}
	if ($token) {
		try {
			$data = JWT::decode($token, new Key($secret, 'HS256'));
		} catch (\UnexpectedValueException $e) {
			self::outputError('Bad response. Could not decode token.', 'text');
		}
		if ($data === "") {
			self::outputError('Invalid JWT signature', 'text');
		}

	} else {
		self::outputError('Missing expected token.', 'text');
	}
}

if ($data->status != 2 && $data->status != 6) {
	echo json_encode(['error' => 0]);
	return false;
}
if (!$data->url) {
	self::outputError('No download URL provided.', 'text');
}
global $auth;
$tmpFilePath = $config['path']['temp'].'/onlyoffice_'.$auth->currentUserInfo['id'].'.'.time().'.tmp';

if (!HTTP::fetchFromURL([
	'url' => $data->url,
	'savePath' => $tmpFilePath
])) {
	$err = HTTP::getError();

	self::outputError($err ?? 'Empty contents, no error message', 'text');
}
if (!filesize($tmpFilePath)) {
	self::outputError('Empty contents.', 'text');
}
$d = $this->prepareWrite();
Files\Log::addByPath('debug', $d['fullPath'], $d);


$this->writeFile([
	'source' => 'move',
	'moveFullPath' => $tmpFilePath
]);
jsonOutput(['error' => 0]);