<?php
$locale->setSection("Admin: API");

if (!$users->userPerms->isSuperUser()) {
	jsonFeedback(false, "You are not allowed to access this page.");
}

if ($_GET['action'] == "add") {
	if ($config['misc']['demoMode']) {
		jsonFeedback(false, "Action unavailable in this demo version of the software!");
	} else {
		$clients = new FileRun\OAuth2\ClientManager;
		$data['name'] = trim(fromHTML($_POST['name']));
		$data['description'] = fromHTML($_POST['description']);
		$data['enabled'] = 1;
		$data['cid'] = fromHTML($_POST['cid']);
		$data['secret'] = fromHTML($_POST['secret']);
		$data['publisher'] = trim(fromHTML($_POST['publisher']));
		$data['website'] = trim(fromHTML($_POST['website']));
		$URIs = explode("\n", fromHTML($_POST['redirect_uris']));
		foreach($URIs as $k => $URI) {
			$URI = trim($URI);
			if (!$clients->isValidURI($URI)) {
				jsonFeedback(false, 'One of the provided URIs is not valid');
			}
			$URIs[$k] = $URI;
		}
		$rs = $clients->insert($data);
		if ($rs) {
			$clients->setURIs($URIs, $clients->lastInsertId);
			jsonFeedback(true, 'Oauth2 client successfully added');
		} else {
			jsonFeedback(false, "Failed to add client!");
		}
	}
}
$app['clientID'] = md5(rand());
$k = new \League\OAuth2\Server\Util\KeyAlgorithm\DefaultAlgorithm;
$app['clientSecret'] = $k->generate();

FileRun::displaySmartyPage();