<?php
/**
 * ISO project
 * 
 * @author  Lukáš Havlíček
 * @version 1.0
 * 
 * Model for DB table messages.
 */
class Messages extends Zend_Db_Table_Abstract 
{
	protected $_name = 'iso_messages';
	protected $_primary = 'id_message';
	
	/**
     * Returns messages of specified user.
     *
     * @param	int $id_reciever User´s ID.
     * @param	bool $recieved Switch between recieved and sent messages.
     * 			If void, recieved messages are returned.
     * @param  	int $count Number of messages returned. If void, all messages are returned
     * @return 	Zend_Db_Table_Rowset
     */
	public function getMessages($id_reciever, $recieved = true, $count = 0)
	{	
		if (( (int) $id_reciever) <= 0) return null;
		
		$select = $this->select()->setIntegrityCheck(false)
					   ->from($this);
					   
		if ($recieved) {
			$select->join('iso_users', 'iso_users.id_user = iso_messages.id_sender');
			$select->where('id_reciever = ?', $id_reciever);
		} else {
			$select->join('iso_users', 'iso_users.id_user = iso_messages.id_reciever');
			$select->where('id_reciever = ?', $id_reciever);
		}
		
		$select->where('is_bin = 0');
		
		if (((int) $count) > 0) {
			$select->limit((int) $count);
		}
		
		$select->order(new Zend_Db_Expr('is_read ASC, datetime DESC'));
		
		return $this->fetchAll($select);
	}
}
?>