<?php

class Filter extends Entity{
	public $id,$report,$label,$slug,$type,$default,$sort,$datasource;
	public $TABLE_NAME = 'statistic_filter';
	public $fields = array(
		'id'=>'key',
		'label'=>'string',
		'slug'=>'string',
		'report'=>'int',
		'type' => 'string',
		'default' => 'string',
		'datasource' => 'longstring',
		'sort' => 'int'
	);

	public static function getMetaTerms(){
		global $myUser;
		return array(
			'date.year' => array('value' => date('Y') ,'description' => 'Année courante'),
			'date.month' => array('value' => date('m'),'description' => 'Mois courant'),
			'date.day' => array('value' => date('d'),'description' => 'Jour courant'),
			'date.hour' => array('value' => date('H'),'description' => 'heure courante'),
			'date.minut' => array('value' => date('i'),'description' => 'Minutes courantes'),
			'date.second' => array('value' => date('s'),'description' => 'Secondes courantes'),
			'user.login' => array('value' => $myUser->login,'description' => 'Identifiant utilisateur courant')
		);
	}

	//Vérification des acces sur le widget courant ou sur le rapport du widget courant
	public function check_access($crud,$user = null){
		global $myUser,$myFirm;
		if(!isset($user)) $user = $myUser;

		//pour avoir 'lacces, l'utilisateur doit être le créateur OU avoir access au rapport OU avoir acces au widget
		return $user->login == $this->creator  ||
		 $user->can('statistic_report',$crud,$this->report) ||
		 $user->can('statistic_filter',$crud,$this->id);
	}

	public function toHtml(){

		$readony = $this->check_access('edit') ? '': ' readonly="readonly" ';

		$html = '<label title="'.$this->getSlug().'">'.$this->label.'</label>';
		$default = $this->default;
		$meta = self::getMetaTerms();

		$default = preg_replace_callback('|{{(.*)([\-\+]*)([0-9]*)}}|U', function($matches) use($meta) {
			$t = $matches[0];
			if(isset($meta[$matches[1]])) $t = $meta[$matches[1]]['value'];
			if(!empty($matches[2]) && !empty($matches[3])){
				if($matches[2]=='+') $t+=$matches[3];
				if($matches[2]=='-') $t-=$matches[3];
			}
			return $t;
		}, $default);

		switch($this->type){
			case 'list' :
				$html .= '<select class="form-control" '.$readony.' data-slug="'.$this->getSlug().'">';

				if(!empty($this->datasource)){
					list($type,$other) = explode(':', $this->datasource);
					switch($type){
						case 'plain':
							$items = explode("\n", $this->datasource);
							array_shift($items);
							foreach($items as $item){
								list($key,$value) = explode(':', $item);
								$html .= '<option value="'.$key.'" '.($default==$key ? 'selected="selected"': '').'>'.$value.'</option>';
							}
						break;
						case 'query':
							$results = self::staticQuery($other);
							foreach($results->fetchAll() as $line){
								$html .= '<option value="'.$line[0].'" '.($default==$line[0] ? 'selected="selected"': '').'>'.$line[1].'</option>';
							}
						break;
						case 'slug':
							foreach(Dictionary::childs(array("slug"=>$other)) as $line){
								$html .= '<option value="'.$line->id.'" '.($default==$line->slug ? 'selected="selected"': '').'>'.$line->label.'</option>';
							}
						break;
					}
				}
				$html .= '</select>';
			break;
			case 'date' :
				$default = explode('/',$default);
				//s'assure que les mois/jours sont sur deux nombres
				foreach ($default as $i=>$value) {
					if( ($i==0 || $i==1) && strlen($value)==1 ) $default[$i] = str_pad($value, 2,'0',STR_PAD_LEFT);
				}
				$default = implode('/',$default);
				$html .= '<input data-type="date" '.$readony.' value="'.$default.'" class="form-control" type="text" placeholder="jj/mm/aaaa"  data-slug="'.$this->getSlug().'">';
			break;
			case 'hour' :
				$html .= '<input data-type="hour" '.$readony.' value="'.$default.'" class="form-control" type="text" placeholder="08:00"  data-slug="'.$this->getSlug().'">';
			break;
			case 'user' :
				$html .= '<input class="form-control" '.$readony.' data-type="user" value="'.$default.'" type="text"  data-slug="'.$this->getSlug().'">';
			break;
			case 'year' :
				$html .= '<input class="form-control" '.$readony.' value="'.$default.'" type="number"  data-slug="'.$this->getSlug().'">';
			break;
			case 'month' :
				$months = array("Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre");
				$html .= '<select class="form-control" '.$readony.' data-slug="'.$this->getSlug().'">';
					foreach($months as $idx => $month){
						$key = $idx+1;
						$html .= '<option value="'.$key.'" '.($default==$key ? 'selected="selected"': '').'>'.$month.'</option>';
					}
				$html .= '</select>';
			break;
			case 'number' :
				$html .= '<input class="form-control" '.$readony.' value="'.$default.'" type="number"  data-slug="'.$this->getSlug().'">';
			break;
			case 'boolean' :
				$html .= '<input class="form-control" '.$readony.' '.($default=='1'?'checked="checked"':'').' type="checkbox"  data-slug="'.$this->getSlug().'">';
			break;
			default :
				$html .= '<input class="form-control" '.$readony.' value="'.$default.'" type="text"  data-slug="'.$this->getSlug().'">';
			break;
		}
		return $html;
	}

	public function getSlug(){
		return slugify($this->label);
	}

	public static function types(){
		return array(
			'text' => array('label'=>'Texte','datasource'=>false),
			'list' => array('label'=>'Liste','datasource'=>true),
			'date' => array('label'=>'Date','placeholder'=>'jj/mm/aaaaa','datasource'=>false),
			'hour' => array('label'=>'Heure','placeholder'=>'08:00','datasource'=>false),
			'user' => array('label'=>'Utilisateur','placeholder'=>'login.utilisateur','datasource'=>false),
			'number' => array('label'=>'Nombre','placeholder'=>'ex: 12','datasource'=>false),
			'year' => array('label'=>'Année','placeholder'=>'ex: 2009','datasource'=>false),
			'month' => array('label'=>'Mois','placeholder'=>'ex: 01','datasource'=>false),
			'boolean' => array('label'=>'Vrai/Faux','placeholder'=>'0 ou 1','datasource'=>false),
		);
	}
}

?>