<?php
global $_,$conf;
switch($_['action']){

	/** SKETCH **/
	//Récuperation d'une liste de sketch
	case 'hackpoint_sketch_search':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');

			
			// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
			$query = 'SELECT * FROM '.Sketch::tableName().' WHERE 1';
			$data = array();
			//Recherche simple
			if(!empty($_['filters']['keyword'])){
				$query .= ' AND label LIKE ?';
				$data[] = '%'.$_['filters']['keyword'].'%';
			}

			//Recherche avancée
			if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label'),$query,$data);

			//Tri des colonnes
			if(isset($_['sort'])) sort_secure_query($_['sort'],array('label'),$query,$data);

			//Pagination
			$response['pagination'] = Sketch::paginate(2,(!empty($_['page'])?$_['page']:0),$query,$data);

			$sketchs = Sketch::staticQuery($query,$data,true,0);
			

			
			foreach($sketchs as $sketch){
				$row = $sketch->toArray();
				$row['picture'] = $sketch->picture();
				$row['created'] = relative_time($row['created']);
				$response['rows'][] = $row;
			}
		});
	break;
	
	//Ajout ou modification d'élément sketch
	case 'hackpoint_sketch_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			$item = Sketch::getById($_['id']);
			if(isset($_['label'])) $item->label = $_['label'];
			if(isset($_['state'])) $item->state = $_['state'];
			if(isset($_['comment']))  $item->comment = $_['comment'];
			$item->save();
		});
	break;
	
	case 'hackpoint_sketch_add':
		global $myUser,$_;
		if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
		require_once(__DIR__.SLASH.'Sketch.class.php');
		$sketch = new Sketch();
		$sketch->label = 'Sketch Sans titre';
		$sketch->state = false;
		$sketch->comment = 'Nouveau sketch sans commentaires';
		$sketch->save();

		require_once(__DIR__.SLASH.'Resource.class.php');
		$item = new Resource();
		$item->label = 'Documentation';
		$item->sort = 0;
		$item->type = 'readme';
		$item->content = '# Documentation';
		$item->sketch = $sketch->id;
		$item->save();

		header('location: index.php?module=hackpoint&page=sheet.sketch&id='.$sketch->id);
	
	break;

	//Suppression d'élement sketch
	case 'hackpoint_sketch_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Sketch.class.php');
			Sketch::removeById($_['id']);
			
		});
	break;

	
	//Sauvegarde des configurations de hackpoint
	case 'hackpoint_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('hackpoint','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('hackpoint') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}
		});
	break;
	
	/** RESOURCE **/
	//Récuperation d'une liste de resource
	case 'hackpoint_resource_search':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Resource.class.php');

			foreach(Resource::loadAll(array('sketch'=>$_['sketch']),array('sort')) as $resource){
				$row = $resource->toArray();
				$type = $resource->type();
				$row['type'] = $type;
				$response['rows'][] = $row;
			}
		});
	break;

	case 'hackpoint_resource_edit':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Resource.class.php');
			$item = Resource::provide();
			$response = $item->toHtml();
		});
	break;

	//Sauveagrde du contenu d'une resource
	case 'hackpoint_resource_save_content':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Resource.class.php');
			$item = Resource::provide();
			$item->content = $_['content'];
			$item->save();
		});
	break;
	
	//Ajout ou modification d'élément resource
	case 'hackpoint_resource_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourceType.class.php');
			$item = Resource::provide();

			if(!isset($_['type']) && $item->id!=0) $_['type'] = $item->type;
			$type = ResourceType::types($_['type']);
			
			if(isset($_['label'])) $item->label = $_['label'];
			if($item->id==0){
				$item->label = $type['label'];
				$item->sort = 100;
				$item->type = $_['type'];
				if(isset($type['default'])) $item->content = $type['default'] ;
				$item->sketch = $_['sketch'];
			}
			
			$item->save();
			$response = $item->toArray();
		});
	break;
	
	case 'hackpoint_resource_sort':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Resource.class.php');
			require_once(__DIR__.SLASH.'ResourceType.class.php');
			foreach($_['sort'] as $sort=>$id){
				$resource =  Resource::getById($id);
				$resource->sort = $sort;
				$resource->save();
			}
		});
	break;	

	//Suppression d'élement resource
	case 'hackpoint_resource_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Resource.class.php');
			Resource::deleteById($_['id']);
			
		});
	break;

	
	//Sauvegarde des configurations de hackpoint
	case 'hackpoint_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('hackpoint','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('hackpoint') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}
		});
	break;
	


	//Suppression document
	case 'resource_delete_document':
	Action::write(function(&$response){
		global $myUser,$_;
		if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
		require_once(__DIR__.SLASH.'Resource.class.php');
		if(!isset($_['path']) ) throw new Exception("Chemin non spécifié ou non numerique");
		//Le premier argument est un namspace de sécurité 
		//et assure que le fichier sera toujours cloisoné dans un contexte file/hackpoint/sketch
		$path = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($_['path']) : $_['path'];
		File::delete('hackpoint'.SLASH.'sketch',$path);
	});
	break;

	case 'resource_add_document':
	Action::write(function(&$response){
		global $myUser,$_;
		if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
		require_once(__DIR__.SLASH.'Resource.class.php');

		$resource = Resource::provide();
		$folder = $resource->directory();

		if(!file_exists($folder)) mkdir($folder,0755,true);

		foreach ($_['files'] as $file) {

			$name = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($file['name']) : $file['name'];
			$row = File::move(File::temp().$file['path'],str_replace(File::dir(),'',$folder).SLASH.$name);
			$row['url'] = 'action.php?action=hackpoint_download_file&file='.base64_encode('sketch'.SLASH.$resource->sketch.SLASH.$resource->id.SLASH.rawurlencode($file['name']));
			$row['oldPath'] = $file['path'];
			$response['files'][] = $row;
		}
		
	});
	break;



		/** PART **/
	//Récuperation d'une liste de part
	case 'hackpoint_part_search':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','read')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Part.class.php');

			
			// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
			$query = 'SELECT * FROM '.Part::tableName().' WHERE 1';
			$data = array();
			//Recherche simple
			if(!empty($_['filters']['keyword'])){
				$query .= ' AND label LIKE ?';
				$data[] = '%'.$_['filters']['keyword'].'%';
			}

			//Recherche avancée
			if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label'),$query,$data);

			//Tri des colonnes
			if(isset($_['sort'])) sort_secure_query($_['sort'],array('label'),$query,$data);

			//Pagination
			$response['pagination'] = Part::paginate(2,(!empty($_['page'])?$_['page']:0),$query,$data);

			$parts = Part::staticQuery($query,$data,true,0);
			

			
			foreach($parts as $part){
				$row = $part->toArray();
				$response['rows'][] = $row;
			}
		});
	break;
	
	//Ajout ou modification d'élément part
	case 'hackpoint_part_save':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','edit')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Part.class.php');
			$item = Part::provide();
			$item->label = $_['label'];
			$item->price = $_['price'];
			$item->link = $_['link'];
			$item->brand = $_['brand'];
			$item->save();
		});
	break;
	
	

	//Suppression d'élement part
	case 'hackpoint_part_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('hackpoint','delete')) throw new Exception("Permissions insuffisantes",403);
			require_once(__DIR__.SLASH.'Part.class.php');
			Part::deleteById($_['id']);
			
		});
	break;


	//Suppression d'élement part
	case 'hackpoint_download_file':
		Action::write(function(&$response){
			global $myUser,$_;
			$file = str_replace(array('..'),array(''),base64_decode($_['file']));
			$file = File::dir().'hackpoint'.SLASH.$file;
			File::downloadFile($file);
		});
	break;


	
	//Sauvegarde des configurations de hackpoint
	case 'hackpoint_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('hackpoint','configure')) throw new Exception("Permissions insuffisantes",403);
			foreach(Configuration::setting('hackpoint') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value) {
				if(in_array($key, $allowed))
					$conf->put($key,$value);
			}
		});
	break;
	
}
?>