<?php


	Action::register('factory_search_part',function(&$response){

			global $myUser,$_;
			User::check_access('factory','read');
			require_once(__DIR__.SLASH.'Template.class.php');
			$i = 0;
			foreach(Template::all($_['template']) as $key=>$template):
				$response['rows'][] = array(
					'active' => $i==0,
					'langage' =>  $template['syntax'],
					'label' => $key
				);
				$i++;
			endforeach;

	});

	Action::register('factory_search_filters',function(&$response){

			global $myUser,$_;
			User::check_access('factory','read');
			require_once(__DIR__.SLASH.'Template.class.php');
			$response['rows'] = Template::filters($_['template']);

	});

	Action::register('factory_autocomplete_plugin',function(&$response){

			global $myUser,$_;
			User::check_access('factory','read');
			$response['rows']  = array();
			foreach(glob(__ROOT__.PLUGIN_PATH.'*') as $pluginPath){
				if(!is_dir($pluginPath)) continue;
				$plugin = basename($pluginPath);
				if(preg_match('|'.$_['keyword'].'|i', $plugin)){

					$manifestPath = $pluginPath.SLASH.'app.json';

					$manifest = array(
						'value' => $plugin,
						'label' => $plugin,
						'name' => $plugin
					);
					if(file_exists($manifestPath)){
						$manifest = json_decode(file_get_contents($pluginPath.SLASH.'app.json'),true);
						$manifest['value'] = $plugin;
						$manifest['label'] = $manifest['name'];
						$manifest['name'] = $manifest['value'];

						if(empty($manifest['icon'])) $manifest['icon'] = 'fas fa-question';
						if(empty($manifest['color'])) $manifest['color'] = '#273c75';
					}

					$response['rows'][] = $manifest;
				}
			}

	});



	Action::register('factory_autocomplete_entity',function(&$response){

			global $myUser,$_;
			$response['rows']  = array();

			User::check_access('factory','read');

			if(isset($_['plugin']) && $_['plugin'] == 'false'){
				//si plugin = false on prends toutes les classes du projet
				$classDirectory = array_merge(glob(__ROOT__.'class'.SLASH.'*.class.php'),glob(__ROOT__.PLUGIN_PATH.'*'.SLASH.'*.class.php'));
			}else if(empty($_['plugin']) || $_['plugin']=='core'){
				//si plugin = vide ou core on prends les classes core du projet
				$classDirectory = glob(__ROOT__.'class'.SLASH.'*.class.php');
			}else{
				//si plugin != vide et != false ou core on prends les classes du plugin ciblé
				$classDirectory = glob(__ROOT__.PLUGIN_PATH.$_['plugin'].SLASH.'*.class.php');
			}

			foreach($classDirectory as $path){
				if(is_dir($path)) continue;

				$parent = basename(dirname($path));
				$entity = str_replace('.class.php','',basename($path));

				if(preg_match('|'.$_['keyword'].'|i', $entity)) $response['rows'][] = array(
					'name'=> $entity,
					'parent' => $parent,
					'path' => $path,
					'value'=> $entity
				);
			}

	});
	Action::register('factory_autocomplete_entity_select',function(&$response){

			global $myUser,$_;
			User::check_access('factory','read');
			$response['rows']  = array();
			$path = __ROOT__.PLUGIN_PATH.$_['plugin'].SLASH.$_['entity'].'.class.php';

			if(empty($_['plugin']) || $_['plugin']=='core')	 $path = __ROOT__.'class'.SLASH.$_['entity'].'.class.php';

			if(!file_exists($path)) return;

			//new version via fields object
			require_once($path);
			$item = new $_['entity']();
			global $databases_credentials;

			$sgbd = $databases_credentials[$item->baseUid]['connector'];
			$types = FieldType::available();
			$typesKey = array_keys($types );

			$response['label'] = $_['entity']::entityLabel();
			foreach ($item->fields as $field => $type) {
				if(in_array($field, array('id', 'created', 'updated', 'creator', 'updater'))) continue;
				if(!is_array($type)) $type = array('type'=>$type,'label'=>$field );

				if(isset($type['link']) ){
					$type['type'] = 'entity-external-entity';

				}

				$type['key'] =  $field;
				$response['rows'][] = $type;
			}


	});

	Action::register('factory_render',function(&$response){
		User::check_access('factory','read');
		global $myUser,$_;
		require_once(__DIR__.SLASH.'Template.class.php');

		$entity = factory_sanitize($_['entity']);
		$table = factory_sanitize($_['entity'], true);
		$plugin = factory_sanitize($_['plugin']);
		$entityLabel = !empty($_['entityLabel']) ? addslashes($_['entityLabel']) : $_['entity'] ;
		$description = isset($_['description']) ? $_['description'] : '';
		$fields =  array();
		$links =  array();

		$categories = Template::types();
		$types = array();

		$types = array_merge($categories['Types sql (deprecated)'],$categories['Types programmes']);

		if(isset($_['fields'])){
			foreach ($_['fields']  as $key => $value){
				if($key=='' || $key==1)continue;
				if(empty($value['label'])) $value['label'] = ucfirst($key);

				$value['key'] = lcFirst(factory_sanitize($key));
				$value['label_escaped'] = addslashes($value['label']);

				//gestion des entité liées
				if($value['type'] == 'entity-external-entity'){
					$type = $types['integer'];



					$link = array('linkedKey'=>$value['key']);
					if(!isset($value['entityPath'])) $value['entityPath'] = '';


					$value['entityRelativePath'] = str_replace(__ROOT__,'',$value['entityPath']);

					$class = str_replace('.class.php','',basename($value['entityPath']));
					$link['linkedEntity'] = $class;
					$link['linkedPath'] = $value['entityPath'];
					$link['linkedRelativePath'] = str_replace(__ROOT__,'',$link['linkedPath']);
					$link['linkedRequirePath'] = '__ROOT__.SLASH.\''.$link['linkedRelativePath'].'\'';
					$links[] = $link;
				}else{
					$type = $types[$value['type']];
				}
				//Pour pouvoir acceder au nom de l'entité dans une boucle de field
				$value['Entity'] = $entity;
				$value['entity'] = strtolower($entity);


				$value['type'] = $type->slug;

				foreach (array_keys($types) as $slug)
					$value['is'.ucfirst($slug)] = false;


				$value['is'.ucfirst($value['type'])] = true;


				switch($value['type']){
					case 'list':
					case 'choice':
						$value['values'] = array($value['key'].'-1'=>$value['label']);

					break;
					case 'dictionary':
						$value['attributes']['data-slug'] =	'"'.strtolower($plugin).'_'.strtolower($entity).'_'.$value['key'].'"';
					break;
					case 'int':
					case 'integer':
						$value['value'] = '<?php echo $'.$value['entity'].'->'.$value['key'].'; ?>';
					break;
					case 'image':
					case 'file':
						$value['attributes']['data-action'] = '"'.strtolower($plugin).'_'.strtolower($entity).'_'.$value['key'].'"';
						$value['attributes']['data-id'] = '"'.$value['key'].'"';
						$value['attributes']['data-data'] = "'{\"id\":\"<?php echo \$".$value['entity']."->id; ?>\"}'";
					break;
					default:
						$value['value'] = '<?php echo $'.$value['entity'].'->'.$value['key'].'; ?>';
					break;
				}




				$value['id'] = ''.$value['key'].'';
				$value['input'] = FieldType::toHtml($value,$types);
				$value['input'] = $value['input']['input'];

				$value['attributes']['value'] = '';
				$value['input_novalue'] =FieldType::toHtml($value,$types);
				$value['input_novalue'] = $value['input_novalue']['input'];

				$value['type'] =  $type->toArray();

				//mapping slug fieldtype / slug recherche avancée

				$value['type']['search-slug'] = $value['type']['slug'];

				$fields[lcfirst(factory_sanitize($key))] = $value;
			}
		}


		$templates = Template::all($_['template']);
		$template = $templates[$_['part']];


		$data = array(
			'Entity' => $entity,
			'entity' => strtolower($entity),
			'ENTITY' => strtoupper($entity),
			'EntityLabel' => $entityLabel,
			'entityLabel' => strtolower($entityLabel),
			'ENTITYLABEL' => strtoupper($entityLabel),
			'table' => $table,
			'user.fullname' => $myUser->fullName(),
			'user.mail' => $myUser->mail,
			'plugin' => strtolower($plugin),
			'PLUGIN' => strtoupper($plugin),
			'Plugin' => ucfirst(strtolower($plugin)),
			'Plugin.label' => ucfirst(strtolower($_['pluginLabel'])),
			'plugin.label' => $_['pluginLabel'],
			'plugin.color' => $_['plugin-color'],
			'plugin.icon' => $_['plugin-icon'],
			'fields' => $fields,
			'links' => $links,
			'linksCount' => count($links)> 0 ? 1: 0,
			'description' => $description,
		);


		$filters = Template::filters($_['template']);


		foreach ($filters  as $filter)
			$data[$filter['slug']] = isset($_['filters']) && in_array($filter['slug'], $_['filters']);


		foreach(array('-','_','.') as $symbol){
			$readable = factory_sanitize(str_replace(' ',$symbol,trim($_['entity'])),false,'_.-');
			$readable = mb_strtolower($readable);
			if(strpos($readable,$plugin.$symbol) === 0)
				$readable = substr($readable, strlen($plugin.$symbol));

			$data['entity'.$symbol.'readable'] = $readable;
		}
		//genere un id plugin_entité en déduplicant si entité = plugin
		$data['plugin_entity_deduplicate'] = $data['plugin'] == $data['entity_readable'] ? $data['plugin'] : $data['plugin'].'_'.$data['entity_readable'];
		$data['plugin_table_deduplicate'] = $data['plugin'] == $data['table'] ? $data['plugin'] : $data['plugin'].'_'.$data['table'];



		$stream = file($template['file']);
		array_shift($stream);
		$stream = implode($stream);

		$stream = template($stream,$data,true);


		//remplacement des [-[-value-]-] par {{value}} (mustache escape)
		$stream = preg_replace('/\[-\[-(.*)-\]-\]/isU', '{{$1}}', $stream);

		if(isset($_['generate']) && $_['generate']==1){

			if(!isset($_['plugin']) || !isset($_['entity'])) return;

			$relativePath = str_replace(Template::dir($_['template']),'',$template['file']);
			$relativePath = template($relativePath,$data,true);

			$pluginPath = PLUGIN_PATH.strtolower($plugin);
			$filePath = $pluginPath.SLASH.$relativePath;

			$parentFolder = dirname($filePath);
			if(!file_exists($parentFolder)) mkdir($parentFolder,0755,true);
			file_put_contents($filePath,$stream);
		}
		echo htmlentities($stream);
		exit();
	});


?>