<?php

	/** PLANNING **/

	//Récuperation d'une liste de planning
	Action::register('planning_search',function(&$response){

		global $myUser,$_,$myFirm,$conf;
		User::check_access('planning','read');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');

		$rankIds = array();

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

		$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 .= ')';

		$plannings = Planning::staticQuery($sql,array($myUser->login,$myUser->login),true);
		$selectedPlannings = json_decode($myUser->preference('planning_selected_calendars'),true);

		$selectedPlannings = !is_array($selectedPlannings) ?  array() : $selectedPlannings;
		$selectedPlannings = array_filter($selectedPlannings);

		if(count($plannings)==0){
			$item = Planning::provide();
			$item->label = 'Général';
			$item->color = '#17a2b8';
			$item->owner = $myUser->login;
			$item->type = 'local';
			$item->default = true;
			$item->slug = slugify($item->label);
			$item->save();
			$plannings[] = $item;
		}

		Plugin::callHook('planning_planning_search',array(&$plannings,&$selectedPlannings));

		usort($plannings, function($a,$b){
			global $myUser;
			if($a->owner == $myUser->login) return -1;
			return 1;
		});



		foreach($plannings as $planning){
			$row = $planning->toArray();
			if(in_array($planning->id, $selectedPlannings) || ($planning->default && count($selectedPlannings) ==0 ) )
				$row['selected'] = true;
			if((int)$conf->get('planning_show_default')!==1 && $planning->default) continue;
			$row['editable'] = $planning->owner != $myUser->login ? false : true;
			$row['shared'] = $row['owner'] != $myUser->login;
			$row['ownerName'] = User::byLogin($row['owner'])->fullName();

			$response['rows'][] = $row;
		}

	});



	Action::register('planning_edit',function(&$response){
		global $myUser,$_;
		User::check_access('planning','edit');
		require_once(__DIR__.SLASH.'planning.modal.php');
		exit();
	});

	//Ajout ou modification d'élément planning
	Action::register('planning_save',function(&$response){

		global $myUser,$_;
		User::check_access('planning','edit');
		require_once(__DIR__.SLASH.'Planning.class.php');
		$item = Planning::provide();

		if($item->id!=0 && $item->owner != $myUser->login && !$myUser->superadmin) throw new Exception("Seul le propriétaire de ce planning peut le modifier");

		$item->label = $_['planning-label'];
		$item->color = $_['planning-color'];
		$item->owner = $myUser->login;
		$item->type = 'local';
		$item->save();

	});

	//Suppression d'élement planning
	Action::register('planning_delete',function(&$response){

		global $myUser,$_;
		User::check_access('planning','delete');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningEvent.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');
		$planning = Planning::provide();
		if(!$planning) throw new Exception("Planning inexistant");
		if($planning->default) throw new Exception("Vous ne pouvez pas supprimer le planning par défaut");
		if($planning->owner != $myUser->login && !$myUser->superadmin) throw new Exception("Vous ne pouvez pas supprimer un planning dont vous n'êtes pas le propriétaire");
		Planning::deleteById($planning->id);
		PlanningEvent::delete(array('planning'=>$planning->id));
		PlanningShare::delete(array('planning'=>$planning->id));


	});


	Action::register('planning_widget_load',function(&$response){
		global $myUser;
		User::check_access('planning','read');
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();

		$widget->title = 'Mes 10 prochains rendez vous';

		ob_start();
		require_once(__DIR__.SLASH.'widget.php');
		$widget->content = ob_get_clean();


		echo json_encode($widget);
		exit();
	});

	/** PLANNINGEVENT **/

	//Récuperation d'une liste de planningevent
	Action::register('planning_event_search',function(&$response){

		global $myUser,$_,$myFirm,$conf;
		User::check_access('planning','read');

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

		if(!isset($_['plannings'])) return;
		$_['plannings'] = explode(',',$_['plannings']);
		$plannings = $_['plannings'];
		$start = strtotime($_['start']);
		$end = strtotime($_['end']);
		$events =  array();



		foreach(array_merge(get_not_workable($start),get_not_workable($end)) as $time){
				if($time < $start || $time > $end) continue;
				$events[] = array(
					'start' 			=> date('Y-m-d\TH:i:s',$time),
					'end' 				=> date('Y-m-d\T23:59:59',$time),
					'backgroundColor'	=> '#cecece',
					'display'			=> 'background'
				);
				$events[] = array(
					'start' 			=> date('Y-m-d',$time),
					'end' 				=> date('Y-m-d',$time),
					'backgroundColor'	=> '#cecece',
					'allDay' => true,
					'display'			=> 'background'
			);
		}

		$allowedPlannings = null;
		//en vue équipe on ne selectionne que les planning equipe des equipiers sélectionnés.
		if($_['view']=='teammate'){
			$plannings = array();

			foreach(Planning::loadAll(array('owner:IN'=>implode(",",$_['teammates']), 'slug'=>Planning::TEAMMATE_SLUG)) as $planning){
				$plannings[]= $planning->id;
			}
			$allowedPlannings = $plannings;
		}


		if(isset($_['plannings']) && count($_['plannings'])!=0){


			$myUser->preference('planning_selected_calendars',json_encode($_['plannings']));
			$myUser->loadPreferences();
			$_SESSION['currentUser'] = serialize($myUser);

			foreach(PlanningEvent::getAll($myUser->login,$myUser->ranks[$myFirm->id],$plannings,$start,$end,$allowedPlannings) as $event){
				if($event->startDate > $event->endDate) continue;
				$textColor = get_light($event->type->color) < 0.6 ? '#fefefefe': '#333333' ;

				$isAllDay = false;

				$eventLine = array(
					'id'						=> $event->id,
					'title' 					=> html_entity_decode($event->label,ENT_QUOTES,'UTF-8'),
					'type' 					=> $event->type->id,
					'planning' 				=> $event->planning->id,
					'planningOwner' 				=> $event->planning->owner,
					'planningDefault' 				=> $event->planning->default,
					'allDay' 				=> $isAllDay,
					'street' 				=> $event->street,
					'group' 				=> $event->group,
					'city' 					=> $event->city,
					'zip' 					=> $event->zip,
					'notificationNumber' => $event->notificationNumber,
					'notificationUnity' 	=> $event->notificationUnity,
					'start' 					=> date('Y-m-d\TH:i:s',$event->startDate),
					'end' 					=> date('Y-m-d\TH:i:s',$event->endDate),

					'backgroundColor'		=>  $event->type->color,
					'borderColor'			=>  $event->type->color,
					'textColor'				=>  $textColor,
					//'display'				=>  'block', a décommenter pour avoir la couleur plutot en fond et pas en point

					'underlineColor'		=> $event->planning->color, //todo, couleur planning a reporter quelque part sur l'event

					'planningLabel'		=> $event->planning->label,

					'editable'				=> $conf->get('planning_allow_event_edit') == true,
					'icon'					=> $event->type->icon,

					'description'			=> html_entity_decode(str_replace('\n',"\n",$event->description),ENT_QUOTES,'UTF-8'),
					'location'				=> $event->street.' '.$event->zip.' '.$event->city,
					'resources'  	=> $event->resources,
					'repeatOccurence'  	=> $event->repeatOccurence,
					'repeatUntil'  		=> $event->repeatUntil,
					'repeatYearlyMonth'  => $event->repeatYearlyMonth,
					'repeatYearlyNumber' => $event->repeatYearlyNumber,
					'repeatMonthlyDay'  	=> $event->repeatMonthlyDay,
					'repeatMonthlyNumber'=> $event->repeatMonthlyNumber,
					'repeatWeeklyDay'  	=> explode(',',$event->repeatWeeklyDay),
					'repeatDailyNumber'  => $event->repeatDailyNumber,
					'repeatType'  			=> $event->repeatType
				);

				//gestion de l'affichage récurrent
				if($event->repeatType != 'never'){

					switch($event->repeatType){


						case 'daily':
							$eventLine['rrule'] = array(
					          'dtstart' => date('Y-m-d\TH:i:s',$event->startDate),
					          'freq' => 'daily'
					        );
					        if(!empty($event->repeatDailyNumber)) $eventLine['rrule']['interval'] =(int) $event->repeatDailyNumber;
						break;
						case 'weekly':
							$eventLine['rrule'] = array(
					          'dtstart' => date('Y-m-d\TH:i:s',$event->startDate),
					          'freq' => 'weekly'
					        );
							if(!empty($event->repeatWeeklyDay)){
								foreach (explode(',',$event->repeatWeeklyDay) as $key => $value) {
									$eventLine['rrule']['byweekday'][] = (int) $value -1;
								}
							}
						break;
						case 'monthly':
							$eventLine['rrule'] = array(
					          'dtstart' => date('Y-m-d\TH:i:s',$event->startDate),
					          'freq' => 'monthly'
					        );

					        if(!empty($event->repeatMonthlyNumber))
								$eventLine['rrule']['byweekday'] = array( array('n'=> (int)$event->repeatMonthlyNumber,'weekday'=> (int)$event->repeatMonthlyDay -1));

						break;
						case 'yearly':
							$eventLine['rrule'] = array(
					          'dtstart' => date('Y-m-d\TH:i:s',$event->startDate),
					          'freq' => 'yearly'
					        );

							if(!empty($event->repeatYearlyNumber)){
								$eventLine['rrule']['interval']  =  1;
								$eventLine['rrule']['bymonth'] = [(int)$event->repeatYearlyMonth];
								$eventLine['rrule']['bymonthday'] = [(int)$event->repeatYearlyNumber];
							}

						break;
					}
					if(!empty($event->repeatUntil)) $eventLine['rrule']['until'] = date('Y-m-d',$event->repeatUntil);
					if(!empty($event->repeatOccurence)) $eventLine['rrule']['count'] = $event->repeatOccurence;

					$eventLine['duration'] = '02:00';



				}

				$events[] = $eventLine;
			}
		}

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

		$response = $events;

	});


	Action::register('planning_event_move',function(&$response){

		global $myUser,$_;
		User::check_access('planning','edit');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');
		require_once(__DIR__.SLASH.'PlanningEvent.class.php');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');

		$item = PlanningEvent::getById($_['event']['id'],1);

		if(!$item) throw new Exception("Cet événement n'existe plus, merci de rafraîchir votre planning.");
		$planning = $item->join('planning');
		if($planning->owner != $myUser->login  && !$myUser->can('planning','configure')){
				if(PlanningShare::rowCount(array('planning'=>$planning->id,'recipient'=>$myUser->login,'edit'=>1))==0)
				throw new Exception("Vous n'avez pas la permission d'éditer cet évenement", 403);
		}


		$start = explode('/',$_['event']['startDate']);
		$end = explode('/',$_['event']['endDate']);

		//date_default_timezone_set('Europe/Paris');
		$startDate = mktime($_['event']['startHour'],$_['event']['startMinut'],0,$start[1],$start[0],$start[2]);
		$endDate = mktime($_['event']['endHour'],$_['event']['endMinut'],0,$end[1],$end[0],$end[2]);

		if($_['view']=='teammate'){
			//Si l'évenement est bougé sur un equipier n'ayant pas de planning equipe, on le créé a la volée
			if($planning->owner != $_['event']['teammate']){
				$userPlanning = Planning::load(array('owner'=>$_['event']['teammate'],'slug'=>Planning::TEAMMATE_SLUG));
				if(!$userPlanning){
					$userPlanning = new Planning();
					$userPlanning->slug = Planning::TEAMMATE_SLUG;
					$userPlanning->owner = $_['event']['teammate'];
					$userPlanning->color = '#8bc34a';
					$userPlanning->label = 'Equipe';
					$userPlanning->save();
				}

				$item->planning = $userPlanning->id;
			}
		}
		$item->startDate = $startDate;
		$item->endDate = $endDate;
		$item->save();

	});


	Action::register('planning_event_resource_state',function(&$response){

			global $myUser,$_;
			User::check_access('planning','read');
			require_once(__DIR__.SLASH.'PlanningEvent.class.php');
			require_once(__DIR__.SLASH.'PlanningEventResource.class.php');

			$start = explode('/',$_['startDate']);
			$end = explode('/',$_['endDate']);

			$startDate = mktime($_['startHour'],$_['startMinut'],0,$start[1],$start[0],$start[2]);
			$endDate = mktime($_['endHour'],$_['endMinut'],0,$end[1],$end[0],$end[2]);



			$query = 'SELECT e.*,r.resource as resource FROM '.PlanningEventResource::tableName().' r LEFT JOIN {{table}} e ON r.event=e.id WHERE
				    (e.startDate BETWEEN ? AND ?) OR (e.endDate BETWEEN ? AND ?) OR (e.startDate < ? AND e.endDate > ?)
				 AND r.resource IN ('.implode(',',array_fill(0, count($_['resources']), '?')).') ';
			$data = array(
				$startDate,$endDate,$startDate,$endDate,$startDate,$endDate
			);

			foreach ($_['resources'] as $resource) $data[] = $resource;

			if(!empty($_['event'])){
				$query.= ' AND e.id!=? ';
				$data[] = $_['event'];
			}

			$response['rows'] = array();

			foreach(PlanningEvent::staticQuery($query,$data,true) as $booked){
				if(isset($_['event']) && $booked->id == $_['event']) continue;
				if(!isset($response['rows'][$booked->foreign('resource')])) $response['rows'][$booked->foreign('resource')] = array();
				$response['rows'][$booked->foreign('resource')][] = $booked->toArray();
			}




	});

	//Ajout ou modification d'élément planningevent
	Action::register('planning_event_save',function(&$response){

		global $myUser,$_;
		User::check_access('planning','edit');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');
		require_once(__DIR__.SLASH.'PlanningEvent.class.php');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');
		require_once(__DIR__.SLASH.'PlanningEventResource.class.php');

		$item = PlanningEvent::provide('id',1);

		if(!$item) throw new Exception("Cet événement n'existe plus, merci de rafraîchir votre planning.");


		$start = explode('/',$_['startDate']);
		$end = explode('/',$_['endDate']);

		$startDate = mktime($_['startHour'],$_['startMinut'],0,$start[1],$start[0],$start[2]);
		$endDate = mktime($_['endHour'],$_['endMinut'],0,$end[1],$end[0],$end[2]);

		//On ne peut pas avoir une date/heure de fin strictement similaire a la date de début (fullcalendar plante) on ajoute une minute si c'est le cas
		if($startDate == $endDate ) $endDate += 60;


		if($startDate > $endDate) throw new Exception("Dates incohérentes");

		$plannings = array();
		//Si on est en vue equipe
		if($_['view']=='teammate'){
			//on récupere les plannings d'équipe qui correspondent aux logins concernés par l'évenement
			$plannings = Planning::loadAll(array('owner:IN'=>$_['user'],'slug'=>Planning::TEAMMATE_SLUG));
			//Pour chaque login, on vérifie qu'un planning equipe existe, on le créé le cas échéant
			foreach (explode(',',$_['user']) as $user) {
				$planningExists = false;
				foreach ($plannings as $planning) {
					if($planning->owner == $user) $planningExists = true;
				}
				if(!$planningExists){
					$planning = new Planning();
					$planning->slug = Planning::TEAMMATE_SLUG;
					$planning->owner = $user;
					$planning->color = '#8bc34a';
					$planning->label = 'Equipe';
					$planning->save();
					$plannings[] = $planning;
				}
			}
		//Pour toutes les autres vues, on gère le planning de manière classique
		}else{
			$planning = $item->id==0 ? Planning::getById($_['planning']) : $item->join('planning');
			if($planning->owner != $myUser->login){
				if(PlanningShare::rowCount(array('planning'=>$planning->id,'recipient'=>$myUser->login,'edit'=>1))==0)
				throw new Exception("Vous n'avez pas la permission d'éditer cet évenement", 403);
			}
		}

		$item->label = $_['label'];
		if(!empty($_['planning'])) $item->planning = $_['planning'];
		if(isset($_['type'])) $item->type = $_['type'];
		$item->startDate = $startDate;
		$item->endDate = $endDate;
		$item->description = $_['description'];
		$item->street = $_['street'];
		$item->city = $_['city'];
		$item->zip = $_['zip'];

		if(isset($_['event-repeat-type'])){
			$item->repeatType = $_['event-repeat-type'];

			if($_['repeatEndType'] == 'occurence')
				$item->repeatOccurence = $_['event-repeat-occurences'];

			if($_['repeatEndType'] == 'until')
				$item->repeatUntil = $_['event-repeat-until'];

			$item->repeatYearlyMonth = $_['event-repeat-yearly-month'];
			$item->repeatYearlyNumber = $_['event-repeat-yearly-number'];
			$item->repeatMonthlyDay = $_['event-repeat-monthly-day'];
			$item->repeatMonthlyNumber = $_['event-repeat-monthly-number'];
			if(isset($_['weeklyDay']) && is_array($_['weeklyDay'])) $item->repeatWeeklyDay = implode(',',$_['weeklyDay']) ;
			$item->repeatDailyNumber = $_['event-repeat-daily-number'];

			$item->repeatUntil = !empty($_['event-repeat-until']) ? timestamp_date($_['event-repeat-until']) : '';
			$item->repeatOccurence = !empty($_['event-repeat-occurences']) ? $_['event-repeat-occurences'] : '';
		}

		if(isset($_['notificationNumber']) && !empty($_['notificationNumber'])){
			//Si les parametres de notifications ont changé on remet a zero l'etat de notification
			if($_['notificationNumber'] != $item->notificationNumber) $item->notificationState = '';
			$item->notificationNumber = $_['notificationNumber'];
		}
		if(isset($_['notificationUnity'])) $item->notificationUnity = $_['notificationUnity'];


		$item->save();


		PlanningEventResource::delete(array('event'=>$item->id));
		//on ajoute les reservation de ressources
		if(!empty($_['resources'])){
			foreach ($_['resources'] as $id) {
				$resource = new PlanningEventResource();
				$resource->resource = $id;
				$resource->event = $item->id;
				$resource->save();
			}
		}

		//on ajoute des copie de cet évenements aux autres planings equipiers concernés
		foreach ($plannings as $planning) {
			if($item->planning == $planning->id) continue;
			$clonedItem = clone($item);
			$clonedItem->id = null;
			$clonedItem->planning = $planning->id;
			$clonedItem->save();
		}
	});

	//Suppression d'élement planningevent
	Action::register('planning_event_delete',function(&$response){
		global $myUser,$_;
		User::check_access('planning','delete');
		require_once(__DIR__.SLASH.'PlanningEvent.class.php');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');
		$events = PlanningEvent::removeAll($myUser->login,$_['events']);
	});

	Action::register('planning_group_events_search',function(&$response){
		global $myUser,$_;
		User::check_access('planning','delete');
		require_once(__DIR__.SLASH.'PlanningEvent.class.php');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');
		$response['rows'] = PlanningEvent::loadAll(array('group'=>$_['group']));
	});


	Action::register('planning_subtype_search',function(&$response){
		global $myUser,$_;
		User::check_access('planning','read');
		require_once(__DIR__.SLASH.'PlanningEvent.class.php');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');

		$response['rows'] = array();
		foreach (PlanningEventType::loadAll(array('parent'=>$_['type'])) as $type) {
			$response['rows'][] = $type->toArray();
		}
	});


	/** TEAMMATE **/

	Action::register('planning_teammate_save',function(&$response){
		global $myUser,$_;
		User::check_access('planning','read');
		$myUser->preference('planning_teammate',implode(',',$_['teammates']));
		$myUser->loadPreferences();
		$response['teammates'] = array();
		$teammates = $myUser->preference('planning_teammate')!='' ? explode(',',$myUser->preference('planning_teammate')) : array();
		foreach ($teammates as $login) {
			$user = User::byLogin($login);
			$user->password = '';
			$row = $user->toArray();
			$row['avatar'] = $user->getAvatar();
			$response['teammates'][] = $row;
		}
	});

	Action::register('planning_teammate_sort',function(&$response){
		global $myUser,$_;
		User::check_access('planning','read');
		$myUser->preference('planning_teammate',implode(',',$_['sort']));
		$myUser->loadPreferences();
	});

	/** EVENT TYPE **/
	//Récuperation d'une liste de planningeventtype
	Action::register('planning_event_type_search',function(&$response){
		global $myUser,$_;
		User::check_access('planning','read');
		require_once(__DIR__.SLASH.'PlanningEventType.class.php');

		foreach(PlanningEventType::loadAll(array('state'=>PlanningEventType::ACTIVE),array('sort')) as $eventType){
			$row = $eventType->toArray();
			$row['textcolor'] = get_light($row['color'])> 0.5 ? '#333333':'#ffffff';
			$row['editable'] = !empty($row['editable']);
			$row['superadmin'] = $myUser->superadmin || $row['editable'];
			$row['editableOptions'] = $myUser->superadmin || $row['editable'];
			$row['class'] = !empty($eventType->parent)  ? 'planning-line-child' : '';
			$response['rows'][] = $row;
		}
	});

	Action::register('planning_event_type_save',function(&$response){
			global $myUser,$_,$conf;

			User::check_access('planning','configure');
			require_once(__DIR__.SLASH.'PlanningEventType.class.php');

			if(!isset($_['items'])) return $response;

			$existingTypes = array();
			foreach (PlanningEventType::loadAll() as $existingType) {
				$existingTypes[$existingType->id] = $existingType;
			}

			$o = 0;
			foreach ($_['items'] as $i => $item){

				$type = !empty($item['id']) ? $existingTypes[$item['id']] : new PlanningEventType();
				if($type->id!=0 && !$type->editable && !$myUser->superadmin) throw new Exception("Item non éditable");
				$type->sort = $o;
				$type->label = $item['label'];
				$type->icon = $item['icon'];
				$type->editable = $item['editable'] == '1';


				$type->color = $item['color'];
				$type->slug = slugify($item['label']);
				$type->save();
				unset($existingTypes[$item['id']]);

				$o++;

				if(isset($item['childs'])){
					foreach($item['childs'] as $u=>$subItem){
						$subtype = !empty($subItem['id']) ? $existingTypes[$subItem['id']] : new PlanningEventType();
						if($subtype->id!=0 && !$subtype->editable && !$myUser->superadmin) throw new Exception("Item non éditable");

						$subtype->label = $subItem['label'];
						$subtype->sort = $o;
						$subtype->icon = $subItem['icon'];
						$subtype->editable = $subItem['editable'] == '1';

						$subtype->parent = $type->id;
						$subtype->color = $subItem['color'];
						$subtype->slug = slugify($subItem['label']);

						$subtype->save();
						unset($existingTypes[$subItem['id']]);
						$o++;
					}
				}
			}


			//Suppression logique des types
			foreach($existingTypes as $existingType){
				$existingType->state = PlanningEventType::INACTIVE;
				$existingType->save();
			}
	});

	//Récuperation ou edition d'élément planningeventtype
	Action::register('planning_event_type_edit',function(&$response){

			global $myUser,$_;
			User::check_access('planning','configure');
			require_once(__DIR__.SLASH.'PlanningEventType.class.php');
			$response = PlanningEventType::getById($_['id']);

	});

	Action::register('planning_event_type_sort',function(&$response){

			global $myUser,$_;
			User::check_access('planning','configure');
			require_once(__DIR__.SLASH.'PlanningEventType.class.php');

			foreach ($_['sort'] as $i=>$id) {
				 PlanningEventType::change(array('sort'=>$i),array('id'=>$id));
			}

	});

	//Suppression d'élement planningeventtype
	Action::register('planning_event_type_delete',function(&$response){

			global $myUser,$_;
			User::check_access('planning','configure');
			require_once(__DIR__.SLASH.'PlanningEventType.class.php');

			$item = PlanningEventType::getById($_['id']);
			$item->state = PlanningEventType::INACTIVE;
			$item->save();

	});


	//Sauvegarde des configurations de planning
	Action::register('planning_setting_save',function(&$response){

			global $myUser,$_,$conf;
			User::check_access('planning','configure');
			foreach(Configuration::setting('planning') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}

	});

	/** PLANNINGSHARE **/
	//Récuperation d'une liste de planningshare
	Action::register('planning_share_search',function(&$response){

			global $myUser,$_;
			User::check_access('planning','read');
			require_once(__DIR__.SLASH.'PlanningShare.class.php');

			$shares = PlanningShare::loadAll(array('planning'=>$_['planning']));

			foreach($shares as $planningshare){
				$row = $planningshare->toArray();
				$row['edit'] = $row['edit']==0?null:$row['edit'];

				if($planningshare->recipientEntity=='rank'){
					$rank = Rank::getById($planningshare->recipient);
					$row['recipient'] = $rank->label;
					$row['recipientType'] = "Rang";
				}else{
					$row['recipient'] = User::byLogin($planningshare->recipient)->fullName();
					$row['recipientType'] = "Utilisateur";
				}

				$response['rows'][] = $row;
			}

	});

	//Ajout ou modification d'élément planningshare
	Action::register('planning_share_save',function(&$response){
		global $myUser,$_;
		User::check_access('planning','edit');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');

		if(empty($_['recipient'])) throw new Exception("Vous devez préciser le destinataire du partage");

		//vérifie que ce destinataire n'a pas déja un partage sur ce planning
		if(PlanningShare::rowCount(array('planning'=>$_['planning'],'recipient'=>$_['recipient'])) >0) throw new Exception("Ce destinataire a déja un partage sur ce planning, veuillez supprimer l'ancien partage avant d'en créer un nouveau");

		$planning = Planning::getById($_['planning']);
		if(!$planning) throw new Exception("Planning inexistant");
		if($planning->owner != $myUser->login) throw new Exception("Vous n'êtes pas propriétaire du planning");
		if(!$_['read'] && !$_['edit']) throw new Exception("Vous devez cocher au moins un droit de planning");

		$item = PlanningShare::provide();
		$item->planning = $planning->id;
		$item->recipient = stripslashes($_['recipient']);
		$item->recipientEntity = $_['recipientEntity'];
		$item->read = $_['read'];
		$item->edit = $_['edit'];
		$item->save();
	});



	//Suppression d'élement planningshare
	Action::register('planning_share_delete',function(&$response){
		global $myUser,$_;
		User::check_access('planning','delete');
		require_once(__DIR__.SLASH.'Planning.class.php');
		require_once(__DIR__.SLASH.'PlanningShare.class.php');

		$item = PlanningShare::provide();
		$planning = Planning::getById($item->planning);
		if($planning->owner != $myUser->login) throw new Exception("Vous n'êtes pas propriétaire du planning");

		PlanningShare::deleteById($_['id']);
	});

?>
