<?php
namespace FileRun;
Perms::checkAndExit("weblink");
Lang::setSection("Web Links");

$linkId = \S::R('linkId');
if (!$linkId) {
	jsonFeedback(false, 'Missing link ID!');
}
$linkInfo = WebLinks::get($linkId);
if (!$linkInfo || ($linkInfo['uid'] != $auth->currentUserInfo['id'])) {
	jsonFeedback(false, 'Invalid link!');
}

if (!empty($linkInfo['short_url'])) {
	jsonOutput([
		'success' => true,
		'url' => $linkInfo['short_url']
	]);
}

$longURL = $_POST['url'] ?? WebLinks::getURL(["id_rnd" => $linkInfo['id_rnd']]);

$isBitly = false;
if (isset($config['app']['weblinks']['custom_url_shortener'])) {
	$fetchOptions = [
		'url' => $config['app']['weblinks']['custom_url_shortener']
	];
	if (str_contains($fetchOptions['url'], '###')) {
		$fetchOptions['url'] = str_replace('###', urlencode($longURL), $fetchOptions['url']);
	} else {
		$fetchOptions['postVars'] = [
			'url' => $longURL,
			'URL' => $longURL,
			'format' => 'simple'
		];
	}
} else {
	if (!$settings->bitly_access_token) {
		jsonFeedback(false, 'A Bitly Access Token needs to be configured from the control panel.');
	}
	$fetchOptions = [
		'url' => 'https://api-ssl.bitly.com/v4/shorten',
		'headers' => ['Authorization' => 'Bearer '.$settings->bitly_access_token],
		'method' => 'POST',
		'json' => ['long_url' => $longURL]
	];
	$isBitly = true;
}
$output = Utils\HTTP::fetchFromURL($fetchOptions);


if (!$output) {
	jsonFeedback(false, 'Error: '.Utils\HTTP::getError());
}

if ($isBitly) {
	$response = json_decode($output, true);
	if (empty($response['link'])) {
		jsonFeedback(false, 'Error: ' . $output);
	}
	$shortURL = $response['link'];
} else {
	if (str_starts_with($output, 'http')) {
		$shortURL = $output;
	} else {
		jsonFeedback(false, 'Error: ' . $output);
	}
}

WebLinks::update(["short_url" => $shortURL], $linkInfo['id']);

jsonOutput([
	'success' => true,
	'url' => $shortURL
]);