<?php


	/** WORKFLOW **/
	//Récuperation d'une liste de workflow
	Action::register('workflow_workflow_search',function(&$response){

			global $_;
			User::check_access('workflow','read');
			require_once(__DIR__.SLASH.'Workflow.class.php');
			Workflow::create();
			// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
			$query = 'SELECT * FROM '.Workflow::tableName().' WHERE 1';
			$data = array();
			//Recherche simple
			if(!empty($_['filters']['keyword'])){
				$query .= ' AND label LIKE ?';
				$data[] = '%'.$_['filters']['keyword'].'%';
			}
			//Recherche avancée
			if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label'),$query,$data);
			//Tri des colonnes
			if(isset($_['sort'])) sort_secure_query($_['sort'],array('label'),$query,$data);
			//Pagination
			$response['pagination'] = Workflow::paginate(20,(!empty($_['page'])?$_['page']:0),$query,$data);
			$workflows = Workflow::staticQuery($query,$data,true,0);
			foreach($workflows as $workflow){
				$row = $workflow->toArray();
				$row['type'] = Workflow::types($row['type']);
				$row['label'] = truncate(html_entity_decode($row['label']),60);
				$response['rows'][] = $row;
			}


	});

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

			global $_;
			User::check_access('workflow','edit');
			require_once(__DIR__.SLASH.'Workflow.class.php');
			$item = Workflow::provide();
			$item->label = $_['label'];
			$item->icon = $_['icon'];
			$item->type = $_['type'];
			$item->entity = $_['entity'];
			$item->color = $_['color'];
			$item->cause = !empty($_['cause']) ? json_encode($_['cause']) : '{}';

			$item->save();
			$response = $item->toArray();

	});


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

			global $_;
			User::check_access('workflow','delete');
			if(empty($_['id'])) throw new Exception("Id non spécifiée");
			require_once(__DIR__.SLASH.'Workflow.class.php');
			require_once(__DIR__.SLASH.'WorkflowEffect.class.php');
			require_once(__DIR__.SLASH.'WorkflowEvent.class.php');
			Workflow::deleteById($_['id']);
			WorkflowEvent::delete(array('workflow'=>$_['id']));
			WorkflowEffect::delete(array('workflow'=>$_['id']));

	});

	//Lancement manuel d'un workflow
	Action::register('workflow_workflow_run',function(&$response){

			global $_;
			User::check_access('workflow','edit');
			require_once(__DIR__.SLASH.'Workflow.class.php');
			require_once(__DIR__.SLASH.'WorkflowEvent.class.php');
			$item = Workflow::provide();
			$parameters = array();
			WorkflowEvent::trigger($_['eventSlug'],$parameters,$item->id);

	});



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

			global $_,$conf;
			User::check_access('workflow','configure');

			//Si input file "multiple", possibilité de normlaiser le
			//tableau $_FILES récupéré avec la fonction => normalize_php_files();

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

	});

	//Récuperation des effets, des causes et des évenements pour le workflow courant
	Action::register('workflow_effect_search',function(&$response){

			global $_;
			User::check_access('workflow','read');
			require_once(__DIR__.SLASH.'WorkflowEffect.class.php');
			require_once(__DIR__.SLASH.'Workflow.class.php');

			$workflow = Workflow::provide('workflow');

			//Récuperation des effets déja définis
			foreach(WorkflowEffect::loadAll(array('workflow'=>$workflow->id),array('sort')) as $effect){
				$row = $effect->toArray();
				$row['workflow'] = $workflow->toArray();
				$classType = WorkflowEffect::types($row['type']);
				$row['type'] = $classType::manifest();
				$row['form'] = $classType::form(json_decode($effect->values,true));
				$response['rows'][] = $row;
			}

	});

	//Récuperation des effets, des causes et des évenements pour le workflow courant
	Action::register('workflow_cause_search',function(&$response){

			global $_;
			User::check_access('workflow','read');
			require_once(__DIR__.SLASH.'WorkflowEffect.class.php');
			require_once(__DIR__.SLASH.'WorkflowEvent.class.php');
			require_once(__DIR__.SLASH.'Workflow.class.php');

			$workflow = Workflow::provide('workflow');

			//Si le workflow est de type entité ou liste d'entité on récupere le type d'entité concerné dans $entity
			// pour la fournir aux causes qui utilisent les colonnes / label de l'entité
			$entity = array();
			if( in_array($workflow->type, array(Workflow::TYPE_ENTITY))  ){
				foreach(WorkflowEvent::events(null,Workflow::TYPE_ENTITY) as $eventGroup) {
					if($eventGroup['entity']['slug'] == $workflow->entity){
						$entity  = $eventGroup['entity'];
						break;
					}
				}
			}else if(in_array($workflow->type, array(Workflow::TYPE_LIST))  ){
				foreach(WorkflowEvent::events(null,Workflow::TYPE_LIST) as $eventGroup) {
					if($eventGroup['entity']['slug'] == $workflow->entity){
						$entity  = $eventGroup['entity'];
						break;
					}
				}
			}

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

			//Récuperation des causes disponibles pour ce ttype de workflow
			$availableCauses = array();
			foreach(Workflow::causes(null,$workflow->type) as $cause){

				//Si la cause demande un type de filtre custom, on demande a l'ui de l'ajouter en caché sur la page
				if(method_exists ($cause,'filter')) $response['filters'][] = $cause::filter($entity);
				$availableCauses[] = array(
					'slug' => $cause::manifest('slug'),
					'attributes' => $cause::manifest('attributes'),
					'label' => $cause::manifest('label'),
				);
			}
			//Récuperation des causes déja définies pour le workflow
			$enabledCauses = json_encode(filters_set(json_decode($workflow->cause,true)));
			//Envois des causes disponibles et des causes définies
			$response['causes'] = array( 'available' => $availableCauses, 'enabled' => $enabledCauses) ;


	});


	/** WORKFLOW EFFECT **/

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

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

			if(!empty($_['workflow'])) $item->workflow = $_['workflow'];
			if(!empty($_['effect-type'])) $item->type = $_['effect-type'];
			if(!empty($_['values'])) $item->values = json_encode($_['values']);
			if(!isset($item->sort)) $item->sort = 1000;

			$item->save();
			$response = $item->toArray();

	});

	//Tri des effets
	Action::register('workflow_workflow_effect_sort',function(&$response){

			global $_;
			User::check_access('workflow','edit');
			require_once(__DIR__.SLASH.'WorkflowEffect.class.php');

			foreach ($_['sort'] as $sort=>$id ) {
				$item = WorkflowEffect::getById($id);
				$item->sort = $sort;
				$item->save();
			}

	});

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

			global $_;
			User::check_access('workflow','edit');
			require_once(__DIR__.SLASH.'WorkflowEffect.class.php');
			require_once(__DIR__.SLASH.'Workflow.class.php');
			$response = WorkflowEffect::getById($_['id'],1);

	});

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

			global $_;
			User::check_access('workflow','delete');
			require_once(__DIR__.SLASH.'WorkflowEffect.class.php');
			WorkflowEffect::deleteById($_['id']);


	});



	/** WORKFLOW EVENT **/
	//Récuperation d'une liste de workflowevent
	Action::register('workflow_event_search',function(&$response){

			global $_;
			User::check_access('workflow','read');

			require_once(__DIR__.SLASH.'WorkflowEvent.class.php');
			require_once(__DIR__.SLASH.'Workflow.class.php');

			//Récuperation des évenements définis pour le workflow
			$workflowevents = WorkflowEvent::loadAll(array('workflow'=>$_['workflow']));
			foreach($workflowevents as $workflowevent){
				$row = WorkflowEvent::events($workflowevent->slug);
				$row['id'] = $workflowevent->id;
				$row['slug'] = $workflowevent->slug;
				$response['rows'][] = $row;
			}

			//Récuperation des évenements disponibles pour ce type de workflow
			$response['events']  = array();
			foreach(WorkflowEvent::events(null,$_['type']) as $eventGroup){
				if(!empty($_['entity']) && (!isset($eventGroup['entity']['slug']) || $eventGroup['entity']['slug']!=$_['entity'] )  ) continue;
				$response['events'] = array_merge($response['events'] ,$eventGroup['events']);
			}



	});

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

			global $_;
			User::check_access('workflow','edit');
			require_once(__DIR__.SLASH.'WorkflowEvent.class.php');
			$item = WorkflowEvent::provide();
			$item->slug = $_['event'];
			$item->workflow = $_['workflow'];
			$item->save();

	});

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

			global $_;
			User::check_access('workflow','delete');
			require_once(__DIR__.SLASH.'WorkflowEvent.class.php');
			WorkflowEvent::deleteById($_['id']);

	});


?>