<?php
/**
 * Define a usernotification.
 * @author Valentin CARRUESCO
 * @category Plugin
 * @license MIT
 */
class UserNotification extends Entity{
	public $id,$notification,$user,$read;
	protected $TABLE_NAME = 'user_notification';
	public $fields =
	array(
		'id' => 'key',
		'notification' => 'int',
		'user' => 'string',
		'read' => 'boolean'
	);
	public $joins = array(
		'notification' => 'Notification'
	);

	public static function byUser($myUser,$options = array()){

		require_once(__DIR__.SLASH.'Notification.class.php');

		$options = array_merge(array(
			'limit' => 100,
			'unread' => false,
			'types' => array()
		),$options);


		//Création des user_notification absentes pour les notification pinned
		foreach(Notification::staticQuery("SELECT n.id FROM {{table}} n LEFT JOIN `user_notification` un ON un.notification = n.id AND un.user=? WHERE n.pinned=? AND un.id IS NULL",array($myUser->login,1),true) as $pinneds){
			$userNotification = new UserNotification();
			$userNotification->notification = $pinneds->id;
			$userNotification->user = $myUser->login;
			$userNotification->read = 0;
			$userNotification->save();
		}

		//récuperation des user_notifications
		$query = 'SELECT *, un.id as id FROM {{table}} un LEFT JOIN '.Notification::tableName().' n ON un.notification=n.id
					WHERE un.user=? AND (n.start<? OR n.start IS NULL) AND (n.end>? OR n.end IS NULL) ';
		$data = array($myUser->login,time(),time());
		if($options['unread']===true){
			$query .= 'AND (un.read = ?)';
			$data[] = 0;
		}

		if(count($options['types'])!=0){
			$query .= ' and n.type IN ('.str_repeat('?,', count($options['types']) - 1) . '?'.')';
			$data = array_merge($data, $options['types']);
		}

		$query .= ' ORDER BY n.created DESC LIMIT '.$options['limit'];

		return UserNotification::staticQuery($query,$data);
	}

	public static function get_unreads_count($myUser,$key=null) {

		require_once(__DIR__.SLASH.'Notification.class.php');

		$query = 'SELECT COUNT(*) unread, n.type FROM {{table}} un INNER JOIN '.Notification::tableName().' n ON un.notification=n.id WHERE un.user=? AND (n.start<? OR n.start IS NULL) AND (n.end>? OR n.end IS NULL) AND (un.read = ?) GROUP BY n.type';

		$unreads = array();
		foreach (UserNotification::staticQuery($query, array($myUser->login,time(),time(),0)) as $unread)
			$unreads['detailled'][$unread['type']] = $unread['unread'];

		$unreads['total'] = isset($unreads['detailled']) ? array_sum($unreads['detailled']) : 0;
		$unreads['compact'] = $unreads['total'] > 5 ? '5+' : $unreads['total'];

		return isset($key) && isset($unreads[$key]) ? $unreads[$key] : $unreads;
	}
}
?>