<?php
/*
	Cause de workflow
	Compare une variable (scopée sur le workflow) en configuration avec la valeur définie dans la cause
*/
class VariableCause{

	//Descriptif de la cause
	public static function manifest($key = null){
		$manifest = array(
			'slug' => 'var',
			'label' => 'Variable',
			'type' => array(Workflow::TYPE_ALL),
			'class' => get_called_class(),
			'path' => __FILE__,
			'icon' => 'fas fa-dollar-sign',
			'attributes' => ' data-filter-type="configuration-var" ',
			'color' => '#ff9f43',
		);
		if(!isset($key)) return $manifest;
		return isset($manifest[$key]) ? $manifest[$key] : '' ;
	}

	//Type de filtre de cause custom pour cette cause (champs additionnels)
	public static function filter($entity = array()){

		$stream = '<div class="filter-value-block" data-value-type="configuration-var" data-value-selector=".filter-value:last-child">
			<div class="filter-subfield  d-inline-block">
				<i class="fas fa-dollar-sign"></i> <input type="text" data-id="var-slug" class="d-inline-block mt-2 border-0 font-weight-bold text-primary" placeholder="Nom de la variable">';
			$stream .='
			</div>
			<select class="form-control filter-operator border-0 text-primary">
				<option value="=">Égal</option>
				<option value="!=">Différent</option>
				<option value=">">Inférieur</option>
				<option value="<">Supérieur</option>
				<option value="like">Contient</option>
			</select>
			<input type="text" class="form-control filter-value" >
		</div>';

		return $stream;;
	}

	//Méthode de vérification de la cause
	public static function check($filter,$parameters = array()){
		global $conf;

		//On récupere sans passer par le $conf->get dont le cache session n'ets aps compatible avec les workflows
		$theConf = Configuration::load(array('key'=>'workflow-var'));
		$confValue = !$theConf ? '{}' : decrypt($theConf->value);
		$workflowVars = json_decode($confValue,true);

		$varValue = isset($workflowVars[$filter['subcolumn']['var-slug']]) ? $workflowVars[$filter['subcolumn']['var-slug']] :'';

		global $conf;
		switch($filter['operator']){
			case '=':
				if($varValue != $filter['value'][0]) return false;
			break;
			case '!=':
				if($varValue == $filter['value'][0]) return false;
			break;
			case '<':
				if($varValue > $filter['value'][0]) return false;
			break;
			case '>':
				if($varValue < $filter['value'][0]) return false;
			break;
			case 'like':
				if( strpos(  mb_strtolower($varValue), mb_strtolower($filter['value'][0]) ) === false  ) return false;
			break;
		}
		return true;
	}


}

?>