<?

class lc_pm_list
{
	public $pager=array();
	protected $user_id;
	public $box_id=0; //0-входящие, 1 - исходящие
	
	function __construct($page=1, $box_id=0)
	{
		$this->user_id=User::i()->id;
		$this->page=$page;
		$this->box_id=$box_id;
	}
	
	function getList()
	{
		if ($this->box_id)
			return $this->_getOutbox();
		else
			return $this->_getInbox();
	}

	protected function _getInbox()
	{
		$this->total=Db::i()->selectCell("SELECT COUNT(mess_id)
									FROM ?_lc_pm m
									WHERE receiver_id=? AND m.status IN (?a)", $this->user_id, lc_pm::$in_statuses);
		
		$this->_setPager();
		
		if ($this->total)
		{
			//отправителя ставим через LEFT JOIN, так как для системного сообщения будет задан несуществующий id
			$messages=Db::i()->select("SELECT mess_id, us.login as sender, rs.login as receiver, unread, putdate, subj, m.sender_id
									FROM ?_lc_pm m
									LEFT JOIN ?_users us ON m.sender_id=us.user_id
									JOIN ?_users rs ON m.receiver_id=rs.user_id
									WHERE receiver_id=? AND m.status IN (?a) ORDER BY mess_id DESC LIMIT ?d, ?d", $this->user_id, lc_pm::$in_statuses, $this->pager['sql_start'], $this->pager['sql_limit']);
		}
		return $messages;
	}
	
	
	
	protected function _getOutbox()
	{
		$this->total=Db::i()->selectCell("SELECT COUNT(mess_id)
									FROM ?_lc_pm m
									WHERE sender_id=? AND m.status IN (?a)", $this->user_id, lc_pm::$out_statuses);
	
		$this->_setPager();
		
		if ($this->total)
		{
			$messages=Db::i()->select("SELECT mess_id, us.login as sender, rs.login as receiver, subj, putdate, m.receiver_id
									FROM ?_lc_pm m
									JOIN ?_users us ON m.sender_id=us.user_id
									JOIN ?_users rs ON m.receiver_id=rs.user_id
									WHERE sender_id=? AND m.status IN (?a) ORDER BY mess_id DESC LIMIT ?d, ?d", $this->user_id, lc_pm::$out_statuses, $this->pager['sql_start'], $this->pager['sql_limit']);
		}
		return $messages;
	}
	
	private function _setPager()
	{
		$pg=new Paginator($this->total, $this->items_at_page, $this->page);
		$this->pager=$pg->getPages();
	}
}