<?php
/*
	Effet de workflow
	Modifie une entité
*/
class EntityEffect{

	//Descriptif du type d'effet
	public static function manifest($key = null){
		$manifest = array(
			'slug' => 'entity',
			'label' => 'Modifier/Supprimer une entité',
			'class' => get_called_class(),
			'path' => __FILE__,
			'icon' => 'fas fa-database',
			'color' => '#ff9f43'
		);
		if(!isset($key)) return $manifest;
		return isset($manifest[$key]) ? $manifest[$key] : '' ;
	}

	public static function actions($key = null){
		$actions = array(
			'delete' => array('label' => 'Supprimer'),
			'update' => array('label' => 'Modifier')
		);

		if(!isset($key)) return $actions;
		return isset($actions[$key]) ? $actions[$key] : array('label'=>'Non définit');
	}

	//méthode d'affichage de l'effet
	public static function form($item){
		$html  = '';
		$class = get_called_class();
		ob_start();

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

		$events = WorkflowEvent::events(null,Workflow::TYPE_LIST);
		$randomId = sha1(mt_rand(0,1000).time());

		$conditions = !empty($item['effect-conditions']) ? base64_encode(json_encode(filters_set($item['effect-conditions']['advanced']))) : '';
		$changes = !empty($item['entity-change']) ? base64_encode(utf8_decode($item['entity-change'])) : '';



		?>
		<div class="effect-block" data-id="<?php echo $randomId; ?>">
			<div class="input-group">
				<div class="input-group-text input-group-append input-group-prepend ">
				Action
				</div>
				<select data-id="entity-action" onchange="workflow_effect_entity_action($(this).closest('.workflow-effect-form'))" class="form-control entity-action" required>
				<option value = "">-</option>
				<?php foreach (self::actions() as $key => $value): ?>
					<option <?php echo !empty($item['entity-action']) && $key==$item['entity-action'] ? 'selected="selected"':'' ; ?> value="<?php echo $key; ?>"><?php echo $value['label']; ?></option>
				<?php endforeach; ?>
				</select>
				<div class="input-group-text input-group-prepend">
				Entité
				</div>
				<select onchange="workflow_effect_entity_conditions($(this).closest('.workflow-effect-form'))" data-id="entity-entity" class="form-control entity-entity" required>
					<option value = "">-</option>
					<?php foreach($events as $event): ?>
					<option data-entity="<?php echo base64_encode(json_encode($event['entity'])); ?>" <?php echo isset($item['entity-entity']) && $item['entity-entity']== $event['entity']['slug'] ? 'selected="selected"' : ''; ?> value="<?php echo $event['entity']['slug']; ?>">
						<?php echo $event['entity']['label']; ?>
					</option>
					<?php endforeach; ?>
				</select>
			</div>

			<div class="entity-effect-where-block <?php echo empty($item['entity-entity'])?'hidden':''; ?>" data-conditions="<?php echo $conditions; ?>">
				<hr/>
				<h5 class="text-muted">Conditions <i class="far fa-question-circle right" title="Utiliser le mot clé {{current}} pour acceder à l'entitée courant, exemple {{current.id}} pour récuperer son id"></i></h5>
				<div class="clear"></div>
				<div class="entity-effect-conditions"></div>
			</div>
			<div class="entity-effect-change-block <?php echo !empty($item['entity-action']) && $item['entity-action']!='update'?'hidden':''; ?>" data-changes="<?php echo $changes; ?>">
				<hr/>
				<h5 class="text-muted">Modifier les colonnes</h5>
				<div class="entity-effect-change">

					<select  class="form-control form-control-sm effect-change" onchange="effect_entity_change_add($(this).closest('.workflow-effect-form') )"></select>

					<input type="hidden" data-id="entity-change" value="<?php echo isset($item['entity-change'])?$item['entity-change']:''; ?>">
					<ul class="list-group mt-2 effect-change-fields">
						<li class="list-group-item p-2 hidden" data-slug="{{slug}}"  data-label="{{label}}" data-field-type="{{type}}">
							<div class="input-group input-group-sm">
								<div class="input-group-prepend ">
									<div class="input-group-text ">{{label}} <small class="text-primary font-weight-bold pl-2"> =</small></div>
								</div>
								<input value="{{value}}" onblur="effect_entity_change_save(this)" class="form-control value" type="text">
								<div class="btn btn-danger  btn-sm" onclick="effect_entity_change_remove(this)"><i class="fas fa-trash"></i></div>
							</div>
						</li>
					</ul>
				</div>
			</div>
		</div>

		<script type="text/javascript">
			function workflow_effect_entity_conditions(form){
				var select = form.find('.entity-entity');

				var option = $('option:selected',select);
				$('.entity-effect-conditions,.effect-change',form).html('<option value="">-</option>');
				if(select.val()==''){

					$('.entity-effect-where-block',form).addClass('hidden');
					return;
				}

				var defaultConditions = $('.entity-effect-where-block',form).attr('data-conditions');
				if(defaultConditions){
					defaultConditions = atob(defaultConditions);
				}


				var entity = JSON.parse(atob(option.attr('data-entity')));
				var html = '<select  data-id="effect-conditions" data-type="filter" data-default=\''+defaultConditions+'\' data-only-advanced>';

				for(var slug in entity.fields){
					var field = entity.fields[slug];
					html += '<option value="'+slug+'" data-filter-type="text">'+field.label+'</option>';
					$('.effect-change',form).append('<option value="'+slug+'" data-filter-type="text">'+field.label+'</option>');
				}
		       html += '</select>';
		       var whereSelect = $(html);
		       $('.entity-effect-conditions',form).html(whereSelect);

		       $('.entity-effect-where-block',form).removeClass('hidden');
		       init_components(form);
			}

			function workflow_effect_entity_action(form){
				var select = form.find('.entity-action');
				if(select.val()=='update'){
					$('.entity-effect-change-block',form).removeClass('hidden');
				}else{
					$('.entity-effect-change-block',form).addClass('hidden');
				}
			}

			function effect_entity_change_add(form,data){
				var btn = form.find('.btn-add');

				var entity = JSON.parse(atob($('[data-id="entity-entity"] option:selected').attr('data-entity')));


				if(!data){
					var data = entity.fields[$('.effect-change',form).val()];
					data.slug = $('.effect-change',form).val();
				}

				var line = $('.effect-change-fields li:eq(0)').template(data);
				$('.effect-change-fields',form).append(line);
				effect_entity_change_save(btn);
			}

			function effect_entity_change_remove(element){
				$(element).closest('li').remove();
				effect_entity_change_save(element);
			}

			function effect_entity_change_search(form){
				var changes = $('.entity-effect-change-block',form).attr('data-changes');
				changes = changes ? JSON.parse(atob(changes)) : '';
				for(var key in changes){
					var change  = changes[key];
					effect_entity_change_add(form,change);
				}
			}

			function effect_entity_change_save(element){
				var form = $(element).closest('.workflow-effect-form');
				var json = [];
				$('.effect-change-fields .list-group-item:not(:eq(0))').each(function(i,line){
					var line = $(line);
					json.push({
						value : line.find('.value').val(),
						slug : line.attr('data-slug'),
						label : line.attr('data-label')
					});
				});


				$('[data-id="entity-change"]',form).val(JSON.stringify(json));
			}

			function workflow_effect_entity_init(tr){
				var form = tr.find('.workflow-effect-form');
				workflow_effect_entity_conditions(form)
				effect_entity_change_search(form,function(){
					effect_entity_change_save(form.find('.entity-entity'));
				});
			}
		</script>

		<?php
		$html = ob_get_clean();
		return $html;
	}

	public static function run($effect,$parameters = array()){
		global $conf;
		$logs = '';

		if( in_array($parameters['workflow']['type'] , array( Workflow::TYPE_ENTITY, Workflow::TYPE_LIST))  ){
			if(isset($parameters['current'])) $parameters['current'] = $parameters['current']->toArray();
			if(isset($parameters['old'])) $parameters['old'] = $parameters['old']->toArray();
		}
		$effect->values['entity-entity'] = template($effect->values['entity-entity'],$parameters,true);

		//var_dump($effect,$parameters);
		$entitySlug = $effect->values['entity-entity'];

		$entity = array();
		foreach ( WorkflowEvent::events(null,Workflow::TYPE_LIST) as $event) {
			if($event['entity']['slug'] == $entitySlug){
				$entity = $event['entity'];
				break;
			}
		}


		//var_dump($effect);
		$filters = array();
		foreach($effect->values['effect-conditions']['advanced'] as $filter){
			if(isset($filter['value']) && isset($filter['value'][0])) $filter['value'][0] = template($filter['value'][0],$parameters,true);
			$filters[] = $filter;
		}
		$whereQuery = 'SELECT id FROM {{table}} WHERE 1 ';

		$queryData = array();
		filter_secure_query($filters,array_keys($entity['fields']),$whereQuery,$queryData);

		$targetsQuery = $entity['class']::staticQuery($whereQuery,$queryData);
		foreach ($targetsQuery->fetchAll() as $line)
			$targetsIds[] = $line['id'];


		//récuperation de l'entité cible de l'effet
		require_once($entity['file']);

		switch($effect->values['entity-action']){
			case 'update':
				$changes = array();
				foreach(json_decode($effect->values['entity-change'],true) as $field){
					$changes[$field['slug']] = $field['value'];
				}

				$entity['class']::change($changes,array('id:IN'=>$targetsIds));
			break;
			case 'delete':
				$entity['class']::delete(array('id:IN'=>$targetsIds));
			break;
		}


		$logs .= '<i class="'.self::manifest('icon').'"></i> Lancement de "'.self::manifest('label').'"<br>';
		$results = true;

		$logs .= 'Résultat '.$results.'<br>';

		return $logs;
	}
}

?>