<?php
/**
 * Define a planning event.
 * @author Julien NARBONI
 * @category Plugin
 * @license MIT
 */
class PlanningEvent extends Entity{
	public $id,$label,$type,$startDate,$endDate,$description,$street,$city,$zip,$planning,$notificationNumber,$notificationUnity,
		$notificationState,
		$resources = array(),
		$repeatType,
		$repeatDailyNumber,
		$repeatWeeklyDay,
		$repeatMonthlyNumber,
		$repeatMonthlyDay,
		$repeatYearlyNumber,
		$repeatYearlyMonth,
		$repeatUntil,
		$repeatOccurence,$group;
	protected $TABLE_NAME = 'planning_event';

	public $fields =
	array(
		'id' => 'key',
		'label' => 'string',
		'type' => array('type'=>'int','label'=>'Type', 'link'=>'plugin/planning/PlanningEventType.class.php'),
		'startDate' => 'date',
		'endDate' => 'date',
		'description' => 'longstring',
		'street' => 'string',
		'city' => 'string',
		'zip' => 'string',
		'planning' => array('type'=>'int','label'=>'Planning', 'link'=>'plugin/planning/Planning.class.php'),
		'group' => 'int',
		'notificationNumber' => 'int',
		'notificationState' => 'string',
		'notificationUnity' => 'string',
		'repeatType' => 'string',
		'repeatDailyNumber' => 'int',
		'repeatWeeklyDay' => 'string',
		'repeatMonthlyNumber' => 'int',
		'repeatMonthlyDay' => 'int',
		'repeatYearlyNumber' => 'int',
		'repeatYearlyMonth' => 'int',
		'repeatUntil' => 'string',
		'repeatOccurence' => 'int'
	);
	const NOTIFIED = 'notified';

	function __construct(){
		parent::__construct();
		//groupe unique de l'évent
		$this->group = time().'g'.mt_rand(0,1000);
		$this->notificationNumber = 0;
	}

	public static function getAll($user,$ranks,$plannings,$start = null,$end = null,$allowedPlannings = null){

		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');
		require_once(__DIR__.SLASH.'PlanningEventResource.class.php');

		if(!isset($start)) $start = strtotime('-1month');
		if(!isset($end)) $end = strtotime('+1month');

		$types = array();
		foreach(PlanningEventType::getAll() as $type){
			$types[$type->id] = $type;
		}



		$rankIds = array();
		foreach ($ranks as $rank) {
			if($rank->id==0) continue;
			$rankIds[] = $rank->id;
		}


		if(!isset($allowedPlannings)){
			$allowedPlannings = array();
			$sql = 'SELECT * FROM {{table}} p WHERE p.owner = ? OR p.id IN(SELECT s.planning FROM '.PlanningShare::tableName().' s WHERE (recipient = ? AND recipientEntity="user") ';

			if(count($rankIds)>0) $sql .= ' OR (recipient IN('.implode(',',$rankIds).') AND recipientEntity="rank" )';
			$sql .= ')';
			foreach(Planning::staticQuery($sql,array($user,$user)) as $row){
				$allowedPlannings[] = $row['id'];
			}
		}

		$originalPlannings = $plannings;
		foreach ($plannings as $key=>$id) {
			if(!in_array($id, $allowedPlannings)) unset($plannings[$key]);
		}

		//evite de planter le IN si aucun calendrier disponible
		if(empty($plannings)) $plannings[] = 0;

		$query = 'SELECT e.*,p.id AS '.Planning::tableName().'_join_id,p.color AS '.Planning::tableName().'_join_color,p.owner AS '.Planning::tableName().'_join_owner,p.default AS '.Planning::tableName().'_join_default FROM {{table}} e
				LEFT JOIN '.Planning::tableName().' p ON e.planning=p.id
				WHERE (
						(startDate BETWEEN ? AND ?)
						OR (endDate BETWEEN ? AND ?)
						OR (startDate<? && endDate>?)
						OR (repeatType != "" AND (repeatUntil = "" OR repeatUntil>startDate) )
					)
					AND planning IN('.implode(',',$plannings).')';

		$events = array();
		$eventIds  = array();
		foreach(self::staticQuery($query,array($start,$end,$start,$end,$start,$end),true,1) as $event){
			$event->type = isset($types[$event->type]) ? $types[$event->type] : new PlanningEventType();
			$event->planning = $event->join('planning');
			$eventIds[] = $event->id;
			$event->resources = array();
			$events[$event->id] = $event;
		}

		if(!empty($eventIds)){
			$resourceLabels = Dictionary::bySlug('planning_event_resource',true);
			foreach(PlanningEventResource::loadAll(array('event:IN'=>$eventIds)) as $resource){
				$row = $resource->toArray();
				$row['label'] = isset($resourceLabels[$row['resource']]) ? $resourceLabels[$row['resource']]->label  : '#'.$row['resource'];
				$events[$resource->event]->resources[] = $row;
			}
		}


		Plugin::callHook('planning_event_search',array(&$events,$originalPlannings,$start,$end));

		return $events;
	}

	public static function removeAll($user,$events){

		global $myUser;

		require_once(__DIR__.SLASH.'PlanningShare.class.php');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningEventResource.class.php');

		$events = self::staticQuery('SELECT e.*,p.id AS '.Planning::tableName().'_join_id,p.owner AS '.Planning::tableName().'_join_owner FROM {{table}} e LEFT JOIN '.Planning::tableName().' p ON p.id=e.planning  WHERE e.id IN ('.implode(',',$events).')',array(),true,1);
		$errors = array();
		foreach ($events as $event) {
			$planning = $event->join('planning');
			PlanningEventResource::delete(array('event'=>$event->id));
			if($planning->owner != $user && !$myUser->can('planning','configure')){
				if(PlanningShare::rowCount(array('planning'=>$planning->id,'edit'=>1,'recipient'=>$user))==0) {
					$errors[] = $event->id;
					continue;
				}
			}
			self::deleteById($event->id);
		}
		return $errors;
	}

	public function address(){
		if($this->street=='') return '';
		return $this->street.', '.$this->zip.' '.$this->city;
	}
}
?>