<?php
require_once(dirname(__FILE__).'/../../../lib/api/class.group.php');
require_once(dirname(__FILE__).'/class.adminview.php');

class AKB_GROUPXML extends AdminView
{

	/**
		* GetGroups
		* Get the list of groups
		*
		* @param string $MsgDesc A message to display
		* @param int $MsgStatus the status of the message being displayed
		*
		* @return void
		*/
	function GetGroups()
	{
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('group', 'edit')
		&& !$_SESSION['user']->verify('group', 'delete')) {
			$errors = array(
			0 => array(
			"code" => 'XMLNoPermission',
			"message" => GetLang('XMLNoPermission')
			)
			);
			XmlShowError(GetLang('XMLGetGroupsFailed'), $errors);
			return false;
		}
		$idsString = '';
		$ids = array();
		
		if (isset($GLOBALS['xmlRequest']->groups) && isset($GLOBALS['xmlRequest']->groups->id)) {
			for($i=0; isset($GLOBALS['xmlRequest']->groups->id[$i]); $i++) {
				$ids[] = strval($GLOBALS['xmlRequest']->groups->id[$i]);
			}
		}
		if (is_array($ids) && sizeof($ids)) {
			$idsString = " AND groupid in ('".implode("','", $ids)."') ";
		}

		$query =
		"
		select gg.groupid, gg.name, gg.contactable, (
		SELECT  COUNT(m.groupid) as numberofusers
					FROM (".$GLOBALS['tablePrefix']."members m
					RIGHT JOIN ".$GLOBALS['tablePrefix']."groups g ON g.groupid = m.groupid)
		            WHERE g.groupid = gg.groupid
		            GROUP BY g.groupid, g.name
		) as numberofusers
		"
		." FROM ".$GLOBALS['tablePrefix']."groups gg "
		." WHERE 1=1 "
		. $idsString
		;

		if (!$result = $GLOBALS['AKB_DB']->Query($query)) {
			return false;
		}
		$groups = array();

		while($row = $GLOBALS['AKB_DB']->Fetch($result)) {
			array_push($groups, $row);
		}
		$xmlResponseArray['TotalGroups'] = sizeof($groups);
		foreach ($groups as $eachGroup) {
			$tmpGroups = array();
			foreach ($eachGroup as $k=>$v) {
				$tmpGroups[$k] = $v;
			}
			$xmlResponseArray['GroupDetails'][] = array(
			'group' => $tmpGroups
			);

		}
		XmlShowResponse(sprintf(GetLang('XMLQueryGroupsOK'), $xmlResponseArray['TotalGroups']), $xmlResponseArray);
		return true;
	}
}
?>