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

if (!$users->userPerms->canManageMetadata()) {
	jsonFeedback(false, $locale->get("You are not allowed to manage the metadata settings.", "Admin: Metadata"));
}

if ($users->userPerms->isIndependentAdmin()) { //indep admins manage only their own created groups
	$filterCriteria = array("owner", "=", $auth->currentUserInfo['id']);
}

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("name", "LIKE", "'%".$str->fromHTML($_POST['search'])."%'");
}


$filetypes = $metadata->dt->select("*", $filterCriteria, $sort, $paging['perPage'], $paging['pageOffset'], true);
$foundRows = $db->GetOne("SELECT FOUND_ROWS()");
$paging['total'] = $foundRows;

$rows = array();
$countOwned = 0;
foreach ($filetypes as $key => $val) {
	if ($val['owner'] && $users->userPerms->isSuperUser()) {
		$ownerInfo = $users->getById(array("name"), $val['owner']);
		$countOwned++;
	} else {
		$ownerInfo = false;
	}
	$sets = $metadata->fieldsets->getForDocumentType($val['id']);
	$setsCount = is_array($sets) ? sizeof($sets) : 0;
	$rows[] = array(
		"id" => $val['id'],
		"name" => $val['name'],
		"owner" => $ownerInfo['name'],
		"sets" => $setsCount,
		"description" => $val['description']
	);
}

$returnedFields = array();
$returnedFields[] = array("header" => "ID", "name" => "id", "name" => "id", "width" => 30, "hidden" => true);
$returnedFields[] = array("header" => $locale->get("Name"), "name" => "name",  "width" => 150, "sortable" => true);
$returnedFields[] = array("header" => $locale->get("Field sets"), "name" => "sets",  "width" => 100);
if ($users->userPerms->isSuperUser() && $countOwned > 0) {
	$returnedFields[] = array("header" => $locale->get("Created by"), "name" => "owner", "width" => 140, "sortable" => true);
}
$returnedFields[] = array("header" => $locale->get("Description"), "name" => "description",  "width" => 150, "sortable" => true);


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


jsonOutput($rs);
?>