<?php
// declare(encoding='UTF-8');
/**
 * Service fournissant des informations sur les widgets existants et permettant d'en créer d'autres.
 *
 * Format du service :
 * /CelWidgetExport/format
 * /CelWidgetExport/csv
 *
 * Les paramêtres :
 *  - "start" indique le numéro du premier item à afficher
 *  - "limit" nombre d'items à afficher
 *
 * @internal   Mininum PHP version : 5.2
 * @category   CEL
 * @package    Services
 * @subpackage Widget
 * @version    0.1
 * @author     Delphine CAUQUIL <delphine@tela-botanica.org>
 * @license    GPL v3 <http://www.gnu.org/licenses/gpl.txt>
 * @license    CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
 * @copyright  1999-2017 Tela Botanica <accueil@tela-botanica.org>
 */


class CelWidgetManager extends Cel {

	// correspondance entre les champs de l'interface et les champs de la BD (format 2018 / 2019)
	private $parametres_autorises = array(
			'projet' => 'project',
			'type' => 'type',
			'esttype' => 'is_type',
			'langue' => 'language',
			'order' => 'order'
	);
	
	private $correspondance_config_widget= array(
			'projet' =>  'project',
			'langue' =>  'language',
			'titre' =>  'title',
			'logo' =>  'logo',
			'description' =>  'description',
			'type' =>  'type',
			'est_type' =>  'is_type',
			'style_css' =>  'css_style',
			'image_fond' =>  'image_font',
			'date_creation' =>  'date_created',
			'type_especes' =>  'taxo_restriction_type',
			'referentiel' =>  'taxo_restriction_value',
			'type_localisation' =>  'location_type',
			'localisation' =>  'location',
			'milieux' =>  'environment',
			'motscles' =>  'project_tag_name',
			'info' =>  'info',
	        'id_projet' => 'project_id'
	);
	
	private $correspondance_champs_etendus = array(
			"key" => "field_id",
			"element" => "data_type",
			"mandatory" => "is_mandatory",
			"unit" => "unit"
	);
	
	private $correspondance_champs_etendus_trad = array(
			"key" => "extended_field_id",
			"name" => "label",
			"description" => "description",
			"fieldValues" => "default_value",
			"help" => "help"
	);

	public function getRessource() {
		return $this->getElement(array());
	}

	/**
	 * Méthode appelée avec une requête de type GET.
	 */
	public function getElement($params = array()) { 
		switch(@strtolower($params[0])) { 
		case 'widget':
			$this->getWidget();
			break;
		case 'champsetendus';
			$this->getChampsEtendus();
			break;
		default:
			$this->getWidget();
		}
	}
	
	
	public function createElement($requeteDonnees) {
		unset($requeteDonnees['signup_submit']);
		if (isset($requeteDonnees['champs-supp'])) {
			$gestionchamps = new GestionChampsEtendus2($this->config);
			$champs = $this->traiterCorrespondanceChampsEtendusInterfaceBD($requeteDonnees); //var_dump($champs);exit;
			$liste = $gestionchamps->ajouterParProjet($champs); 
			unset($requeteDonnees['champs-supp']);
		}
		$requeteDonnees['est_type'] = (isset($requeteDonnees['est_type']) && $requeteDonnees['est_type']== "on") ? 1 : 0;
		$manager = new GestionWidget($this->config);
		$requeteDonnees = $this->traiterCorresponceConfigWidgetInterfaceBD($requeteDonnees);
		$retour = $manager->ajouterWidget($requeteDonnees);

		$this->envoyerJson($retour);

	}
	
	public function updateElement($uid,$params) {
		$retour = "";
		if (isset($params['projet']) && isset($params['langue'])) {
		    $manager = new GestionWidget($this->config);
		    $params['est_type'] = (isset($params['est_type']) && $params['est_type']== "on") ? 1 : 0;
		    $requeteDonnees = $this->traiterCorresponceConfigWidgetInterfaceBD($params);
			$retour = $manager->modifierWidget($params['projet'], $params['langue'], $requeteDonnees);
			
		}
		$this->envoyerJson($retour);
		return "ff";
		
	}

	private function getWidget() {
		$criteres = $this->traiterParametresAutorises($_GET); 
		$manager = new GestionWidget($this->config);
		$liste = $manager->obtenirWidget($criteres);
		$liste = $this->traiterCorresponceConfigWidgetBDInterface($liste);

		$this->envoyerJson($liste);
	}
	
	private function getChampsEtendus() {
		$champs = new GestionChampsEtendus2($this->config);
		$projet = (isset($_GET['projet'])) ? $_GET['projet'] : "";
		$langue = (isset($_GET['langue'])) ? $_GET['langue'] : "fr";
		$liste = $champs->consulterProjetChampsEtendus($projet, $langue);
		$liste = $this->traiterCorrespondanceChampsEtendusBDInterface($liste, $projet);
		
		$this->envoyerJson($liste);
	}


	protected function traiterParametresAutorises(Array $parametres) {
		$parametres_traites = array();
		
		foreach($parametres as $cle => $valeur) {
			if(is_string($valeur) && !trim($valeur)) continue;
			if(isset($this->parametres_autorises[$cle])) {
				$parametres_traites[$this->parametres_autorises[$cle]] = $valeur;
			}
		}
		return $parametres_traites;
	}
	
	protected function traiterCorresponceConfigWidgetBDInterface(Array $widgets) {
		$parametres_traites = array();
		$corresp = array_flip($this->correspondance_config_widget);
		foreach($widgets as $id => $widget) {
			foreach($widget as $cle => $valeur) {
				if(is_string($valeur) && !trim($valeur)) continue;
				if(isset($corresp[$cle])) {
					$parametres_traites[$id][$corresp[$cle]] = $valeur;
				}
			}
		}
		return $parametres_traites;
	}
	
	protected function traiterCorresponceConfigWidgetInterfaceBD(Array $parametres) {
		$parametres_traites = array();
		$corresp = $this->correspondance_config_widget;
		foreach($parametres as $cle => $valeur) {
				if(is_string($valeur) && !trim($valeur)) $valeur=NULL;
				if(isset($corresp[$cle])) {
					$parametres_traites[$corresp[$cle]] = $valeur;
				}
			}
		return $parametres_traites;
	}
	
	protected function traiterCorrespondanceChampsEtendusInterfaceBD(Array $champsinterface) {
		$champsrequete = array(); $i = 0;
		$champssupp = json_decode($champsinterface['champs-supp'], true); 
		// pour chaque champs-supp, mettre correspondance extended field et extended field trad
		foreach ($champssupp as $champ) {
			$champsrequete['ce'][$i]['project'] = $champsrequete['cet'][$i]['project'] = $champsinterface['projet'];
			$champsrequete['cet'][$i]['language_iso_code'] = $champsinterface['langue']; 
			// pour la table extended fiels champs interface => champs bd
			foreach ($this->correspondance_champs_etendus as $ci => $ce) {
				if (isset($champ[$ci]) && $champ[$ci] != "") {
					$champsrequete['ce'][$i][$ce] = $champ[$ci];
				} else {
					if ($ci == "mandatory") {
						$champsrequete['ce'][$i][$ce] = "0";
					} else {
						$champsrequete['ce'][$i][$ce] = "";
					}
				}
			}
			// pour la table extended fiels trad champs interface => champs bd
			foreach ($this->correspondance_champs_etendus_trad as $cit => $cr) {
				if (isset($champ[$cit]) && is_array($champ[$cit])) {
					$champsrequete['cet'][$i][$cr] = json_encode($champ[$cit]);
				} elseif (isset($champ[$cit]) && $champ[$cit] != "") {
					$champsrequete['cet'][$i][$cr] = $champ[$cit];
				} else {
					$champsrequete['cet'][$i][$cr] = "";
				}
			}
			$i++;
		} 
		return $champsrequete;
	}
	protected function traiterCorrespondanceChampsEtendusBDInterface(Array $champsrequete, $projet = "null") {
		$champssupp = array(); $i = 0;
		foreach ($champsrequete as $champ) {
			$champssupp[$projet]['projet'] = $champ['project'];
			$champssupp[$projet]['langue'] = $champ['language_iso_code'];
			// pour la table extended fiels champs interface => champs bd
			foreach ($this->correspondance_champs_etendus as $ci => $ce) {
				if (isset($champ[$ce]) && $champ[$ce] != "") {
				    $champssupp[$projet]['champs-supp'][$i][$ci] = $champ[$ce];
				} else {
				    $champssupp[$projet]['champs-supp'][$i][$ci]= "";
				}
			}
			// pour la table extended fiels trad champs interface => champs bd
			foreach ($this->correspondance_champs_etendus_trad as $cet => $cr) {
				if (isset($champ[$cr]) && $champ[$cr] != "") {
				    $champssupp[$projet]['champs-supp'][$i][$cet]= $champ[$cr];
				} else {
				    $champssupp[$projet]['champs-supp'][$i][$cet]="";
				}
			}$i++;
		}
		return $champssupp;
	}


}
?>