<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

config::set('users_at_page', 20);

class admin_users_list
{
	protected $page=1;
	public $pager=array();
	protected $filter=false;
	protected $orderby=0;
	protected $items_at_page;
	
	public function getUsers($page=1, $orderby=0, $filter=false, $items_at_page=false)
	{
		$this->page=$page;
		$this->filter=$filter;
		$this->orderby=$orderby;
		if (!$items_at_page) $this->items_at_page=config::get('users_at_page');
		else $this->items_at_page=$items_at_page;
		
		$this->_escapeFilter();
		$this->_setTotalUsers();
		$this->_setPager();
		
		$users=Db::i()->selectCol(
			"SELECT user_id
			FROM ?_users
			WHERE 1=1
			{AND (login LIKE ?}
			{OR email LIKE ?}
			{OR user_id=?)}
			ORDER BY ".$this->_getSort()." LIMIT ?d, ?d",
			($this->filter?'%'.$this->filter.'%':DBSIMPLE_SKIP),
			($this->filter?'%'.$this->filter.'%':DBSIMPLE_SKIP),
			($this->filter?$this->filter:DBSIMPLE_SKIP),
			$this->pager['sql_start'],
			$this->pager['sql_limit']
		);
		
		if ($users) {
			$users=User::i()->getUsersByIds($users);
			$this->_setGroups($users);
		}
		
		return $users;
	}
	
	protected function _setTotalUsers()
	{
		return $this->total=Db::i()->selectCell(
			"SELECT COUNT(user_id)
			FROM ?_users
			WHERE 1=1
			{AND (login LIKE ?}
			{OR email LIKE ?}
			{OR user_id=?)}",
			($this->filter?'%'.$this->filter.'%':DBSIMPLE_SKIP),
			($this->filter?'%'.$this->filter.'%':DBSIMPLE_SKIP),
			($this->filter?$this->filter:DBSIMPLE_SKIP)
		);
	}
	
	protected function _setPager()
	{
		$pg=Factory::create('Paginator', $this->total, $this->items_at_page, $this->page);
		$this->pager=$pg->getPages();
	}
	
	protected function _getSort()
	{
		$sort=array(
			0	=>	'user_id',
			1	=>	'user_id DESC',
			2	=>	'login',
			3	=>	'login DESC',
			4	=>	'u.group_id',
			5	=>	'u.group_id DESC',
			6	=>	'email',
			7	=>	'email DESC',
			8	=>	'`status`',
			9	=>	'`status` DESC'
		);
		if (array_key_exists($this->orderby, $sort)) return $sort[$this->orderby];
		return $sort[0];
	}
	
	protected function _escapeFilter()
	{
		$this->filter=addcslashes($this->filter, '_%');
	}
	
	protected function _setGroups($users)
	{
		$groups=Db::i()->selectCol("SELECT group_id AS ARRAY_KEY, group_name FROM ?_groups");
		foreach ($users as $id=>$user) {
			$users[$id]->group_name=$groups[$user->group_id];
		}
		return $users;
	}
}