<?php
require_once 'app/class-alert.php';
require_once 'app/class-user-manager.php';
require_once 'app/class-session.php';
require_once 'app/class-user.php';

/**
 * Alert Manager
 * 
 * Performs Alert operations
 * @author tm - Advantis Solutions
 * @version 1.0.1
 * @package Backend\Alerts 
 */
class AlertManager {
	
	/**
	 * Setnew alert in DB for specific role of a specific organization.
	 * All users of this role and organisation will see alert.
	 * Userid is optional, if set only the specific user will see this alert.
	 *
	 * @param int $alerttypeid        	
	 * @param int $roleid        	
	 * @param int $organisationid        	
	 * @param string $contextid        	
	 * @param string $contextdescription        	
	 * @param int $userid        	
	 * @return Alert $obj
	 */
	static public function new_alert($alerttypeid, $roleid, $organisationid, $contextid, $contextdescription, $userid = null) {
		$alert = new Alert ();
		
		$alert->setNew ( $alerttypeid, $roleid, $organisationid, $contextid, $contextdescription, $userid );
		
		$em = new EntityManager ( $alert::BASEENTITY );
		
		$alert = $em->create ( $alert );
		
		return $alert;
	}
	
	/**
	 * gets session user alerts
	 *
	 * @param bool $t
	 *        	true if live alerts and false if archived
	 * @return array of alerts
	 */
	function get_user_alerts($t = true) {
		$list = null;
		
		if ($t) {
			$filter = " != ";
		} else {
			$filter = " = ";
		}
		
		$user = Session::get_user ();
		$role = Session::get_activerole ();
		
		$em = new EntityManager ( Alert::LISTVIEW );
		
		$list = $em->load ( 'alert_organisationid=? and alert_roleid=? and ( alert_userid is null or alert_userid= ? ) and alert_statuscodeid ' . $filter . '? order by alert_creationdate desc', array (
				$user->organisationid,
				$role->roleid,
				$user->id,
				__ALERT_STATUS_ARCHIVED 
		) );
		
		return $list;
	}
	
	
	
	/**
	 * Gets session user alerts stored as history
	 *
	 * @return array of alerts
	 */
	function get_user_history_alerts() {
		return $this->get_user_alerts ( false );
	}
	
	/**
	 * Gets session user live alerts
	 *
	 * @return array of alerts
	 */
	function get_user_live_alerts() {
		return $this->get_user_alerts ();
	}
	
	/**
	 * Gets number of alerts available to session user
	 *
	 * @return int
	 */
	function user_show_alerts() {
		return count ( $this->get_user_live_alerts () );
	}
}

?>