<?php

	/** DYNAMICFORM **/
	//Récuperation d'une liste de dynamicform
	Action::register('dynamicform_form_search',function(&$response){
		global $_,$myFirm;
		User::check_access('dynamicform','read');
		Plugin::need('dynamicform/DynamicForm');

		$dynamicforms = DynamicForm::loadAll(array('state'=>DynamicForm::ACTIVE,'firm:IN'=>array($myFirm->id,0)));
		foreach($dynamicforms as $dynamicform){
			$row = $dynamicform->toArray();
			$row['firmLegend'] = $row['firm'] == 0 ? 'Tous': Firm::getById($row['firm'])->label;
			$row['created'] = complete_date($row['created']).' à '.date('H:i',$row['created']);
			$response['rows'][] = $row;
		}
	});

	//Ajout ou modification d'élément dynamicform
	Action::register('dynamicform_form_save',function(&$response){
		global $_,$myFirm;
		User::check_access('dynamicform','edit');
		Plugin::need('dynamicform/DynamicForm,dynamicform/DynamicField');

		$item = DynamicForm::provide();
		$item->slug = slugify($_['slug']);
		$item->color = $_['color'];

		$item->firm = $_['allFirm'] ? 0 : $myFirm->id  ;

		$item->state = DynamicForm::ACTIVE;
		$item->icon = $_['icon'];
		$item->label = $_['label'];

		if(empty($item->slug)) $item->slug = generateSlug($item->label,DynamicForm::class,'slug');

		$oldFields =  array();
		if($item->id != 0){
			foreach (DynamicField::loadAll(array('form'=>$item->id)) as $key => $field) {
			 	$oldFields[$field->id] = $field;
			}
		}
		$item->save();

		$response = $item->toArray();

		if(!empty($_['rows'])){
			foreach ($_['rows'] as $i => $columns) {
				foreach ($columns as $u => $fields) {
					foreach ($fields as $o => $fieldData) {
						$field = new DynamicField();
						$field->fromArray($fieldData);

						$field->form = $item->id;
						$field->row = $i;
						$field->state = DynamicField::ACTIVE;
						if(empty($field->slug)){
							$field->slug = generateSlug($item->slug.'_'.$field->label, DynamicField::class, 'slug', '_');
						}else{
							$field->slug =  slugify($field->slug);
						}
						if(count(DynamicField::loadAll(array('id:!='=>$field->id, 'slug'=>$field->slug, 'state'=>DynamicForm::ACTIVE))) > 0) throw new Exception('Slug de champ déjà utilisé');
						$field->sort = $o;
						$field->column = $u;
						$field->meta = isset($field->meta) && !empty($field->meta) ? base64_decode($field->meta) : null;

						if(isset($oldFields[$field->id])) unset($oldFields[$field->id]);
						$field->save();
					}
				}
			}
		}

		//supression des anciens champs non redéfinis
		foreach ($oldFields as $oldField)
			DynamicField::deleteById($oldField->id);
	});




	//Suppression d'élement dynamicform
	Action::register('dynamicform_form_delete',function(&$response){
		global $_;
		User::check_access('dynamicform','delete');
		Plugin::need('dynamicform/DynamicForm');

		$item = DynamicForm::getById($_['id']);
		$item->state = DynamicForm::INACTIVE;
		$item->save();
	});


	/** DYNAMICFIELD **/
	//Récuperation d'une liste de dynamicfield
	Action::register('dynamicform_field_search',function(&$response){
		global $_;
		User::check_access('dynamicform','read');
		Plugin::need('dynamicform/DynamicForm');
		$response['rows'] = DynamicForm::get_fields_layout(array('id'=>$_['form']));
	});





	//Sauvegarde des configurations de dynamicform
	Action::register('dynamicform_setting_save',function(&$response){
		global $_,$conf;
		User::check_access('dynamicform','configure');

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

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



	//Affichage des champs de saisie des metas de champs dynamiques
	Action::register('dynamicform_field_setting_change',function(&$response){
		global $_;
		User::check_access('dynamicform','read');
		$fieldtype = FieldType::available($_['type']);
		$html = '';

		if(property_exists($fieldtype, 'settings')){
			$types = FieldType::available();
			$settingsValues = isset($_['settings']) ? json_decode(base64_decode($_['settings']),true) : array();
			foreach($fieldtype->settings as $key=>$field){
				//$fieldtype->settings[$key]['value'] = '';
				if(!isset($settingsValues[$key])) continue;
				$fieldtype->settings[$key]['value'] = is_string($settingsValues[$key])?$settingsValues[$key]:json_encode($settingsValues[$key]);
			}

			$fields = FieldType::toForm($fieldtype->settings, $types);

			foreach($fields as $field){
				$html .= '<span '.(isset($field['data']['block-class']) ? "class=\"".$field['data']['block-class']."\"":'').'>';
				$html .= $field['label'];
				$html .= isset($field['data']['before']) ? $field['data']['before'] : '';
				$html .= $field['input'];
				$html .= isset($field['data']['after']) ? $field['data']['after'] : '';
				$html .= '</span>';
			}
			$response[] = $html;
		}
	});

	//Gestion des fichiers
	Action::register('dynamicform_handle_file',function(&$response){
		global $_;
		Plugin::need('dynamicform/DynamicField');

		//options de base pour le upload/delete/download
		$options = array(
			'access' => 'document', // crud sur summary,
			'size' => '10000000', // taille max
			'limit' => 1,
			'path'=>isset($_['path']) ? $_['path'] : '',
			'namespace'=>isset($_['data']['scope']) ? $_['data']['scope'] : ''
		);

		//si search gestion des datas pour le path + settings champ dynamique
		if(isset($_['data']) && isset($_['data']['slug'])){
			$field = DynamicField::load(array('slug'=>$_['data']['slug']));

			$meta = isset($field) ? json_decode($field->meta,true) : array();

			$folder = 'tmp';

			if(isset($_['data']['scope']) && isset($_['data']['id']) && !empty($_['data']['scope']) && !empty($_['data']['id']))
				$folder = $_['data']['scope'].SLASH.$_['data']['id'];

			if(empty($meta['limit'])) $meta['limit'] = 1;
			if(isset($meta['storage']) && !empty($meta['storage']))
				$folder = $meta['storage'];

			$meta['storage'] = $folder;
			if($meta['limit']>1) $meta['storage'] .= SLASH.$field->slug;
			$meta['storage'] .= SLASH.'*';


			$options = array_merge($options,$meta);
		}

		File::handle_component($options,$response);
	});


?>
