<?php
namespace FileRun;

use GuzzleHttp\Client;

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

$ext = \FM::getExtension($this->data['fullPath']);
$url = $this->urlBase.'/formats/'.\S::forURL($ext);
$http = new Client();
try {
	$response = $http->request('GET', $url, [
		'auth' => [self::getSetting('APIKey'), '']
	]);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
	self::outputError('Network connection error: '.$e->getMessage(), 'html');
} catch (\GuzzleHttp\Exception\ClientException $e) {
	if ($e->getResponse()->getStatusCode() == 404) {
		self::outputError("Zamzar doesn't seem to provide any conversion option for the ".mb_strtoupper($ext)." file type.", 'html');
	} else {
		self::outputError('Error: '.$e->getResponse()->getStatusCode(), 'html');
	}
} catch (\GuzzleHttp\Exception\ServerException $e) {
	self::outputError('Server error: '.$e->getResponse()->getStatusCode(), 'html');
} catch (\RuntimeException $e) {
	self::outputError('Error: '.$e->getMessage(), 'html');
}
$rs = $response->getBody()->getContents();
if (!$rs) {
	self::outputError('Error getting conversion formats: empty Zamzar server response!', 'html');
}
$rs = json_decode($rs, true);
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title><?php echo \S::safeHTML(\S::forHTML($this->data['fileName']));?></title>
	<?php UI\CSS::insertLink();?>
	<link rel="stylesheet" href="<?php echo $this->url;?>/style.css?v=<?php echo $settings->currentVersion;?>" />
	<?php UI\JS::insertScripts(['ext']);?>
	<script src="<?php echo $this->url;?>/app.js?v=<?php echo $settings->currentVersion;?>"></script>
	<script src="?module=fileman&section=utils&page=translation.js&sec=<?php echo \S::forURL("Custom Actions: Zamzar")?>&lang=<?php echo \S::forURL(Lang::getCurrent())?>"></script>
	<script>
		var URLRoot = '<?php echo \S::safeJS($config['url']['root'])?>';
		var path = '<?php echo \S::safeJS($this->data['relativePath'])?>';
		var windowId = '<?php echo \S::safeJS($_REQUEST['_popup_id'])?>';
		var csrf = '<?php echo \S::safeJS(self::getCSRFToken())?>';
	</script>
</head>

<body>
<div id="selectFormat">
	<div style="clear:both;margin:10px;">
		<?php
		if (sizeof($rs['targets']) > 0){
			echo self::t('Convert "%1" to:', [\S::safeHTML($this->data['fileName'])]);
		} else {
			echo self::t('No conversion option found for the "%1" file type.', [strtoupper(\S::safeHTML($ext))]);
		}
		?>
	</div>
	<div style="max-width:600px">
		<div class="x-clear"></div>
	<?php
	foreach ($rs['targets'] as $format) {
		?>
		<div class="format extLabel ext_<?php echo \S::safeHTML(strtolower($format['output_format']));?>" data-format="<?php echo \S::safeHTML($format['name']);?>">
			<?php echo \S::safeHTML(strtoupper($format['name']));?>
		</div>
	<?php
	}
	?>
		<div class="x-clear" style="height:30px;"></div>
	</div>
</div>
</body>
</html>