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

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

if ($_REQUEST['limit']) {
	$paging['perPage'] = $str->fromHTML($_REQUEST['limit']);
} else {
	$paging['perPage'] = 20;
}
if ($_REQUEST['start']) {
	$paging['pageOffset'] = $str->fromHTML($_REQUEST['start']);
} else {
	$paging['pageOffset'] = 0;
}
if ($_REQUEST['sort']) {
	$paging['sort'] = $str->fromHTML($_REQUEST['sort']);
	$paging['sort_dir'] = $str->fromHTML($_REQUEST['dir']);
	$sort = array($paging['sort']  => $paging['sort_dir']);
} else {
	$sort = array("name" => "ASC");
}

if ($_POST['search']) {
	$filterCriteria[] = array(
		array("name", "LIKE", "'%".$str->fromHTML($_POST['search'])."%'", "AND"),
		array("description", "LIKE", "'%".$str->fromHTML($_POST['search'])."%'", "OR")
	);
}

$clients = new FileRun\OAuth2\ClientManager;
$list = $clients->select("*", $filterCriteria, $sort, $paging['perPage'], $paging['pageOffset'], true);
$foundRows = $db->GetOne("SELECT FOUND_ROWS()");
$paging['total'] = $foundRows;

$rows = array();
$countOwned = 0;
foreach ($list as $key => $record) {
	if ($record['owner'] && $users->userPerms->isSuperUser()) {
		$ownerInfo = $users->getById(array("name"), $record['owner']);
		$countOwned++;
	} else {
		$ownerInfo = false;
	}
	$usersInGroup = $groups->selectUsersByGrup($record['id']);
	$rows[] = array(
		"id" => $record['id'],
		"cid" => $record['cid'],
		"owner" => $ownerInfo['name'],
		"name" => $record['name'],
		"publisher" => $record['publisher'],
		"description" => $record['description']
	);
}

$returnedFields = array();
$returnedFields[] = array("header" => "ID", "name" => "id", "width" => 30, "hidden" => true);
$returnedFields[] = array("header" => $locale->get("Name"), "name" => "name",  "width" => 150, "sortable" => true);
$returnedFields[] = array("header" => $locale->get("Publisher"), "name" => "publisher",  "width" => 150, "sortable" => true);
$returnedFields[] = array("header" => $locale->get("Client ID"), "name" => "cid", "width" => 150);
$returnedFields[] = array("header" => $locale->get("Description"), "name" => "description", "width" => 200, "sortable" => true);

$rs = array(
	"metaData" => array(
		"fields" => $returnedFields,
		"root" => "rows",
		"totalProperty" => "totalCount"
	),
	"totalCount" => $paging['total'],
	"rows" => $rows,
	"success" => true
);


jsonOutput($rs);