<?php



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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'StatisticReport.class.php');

			$report = isset($_['report']) && !empty($_['report']) ? StatisticReport::getByid($_['report']) : new StatisticReport();
			$report->fromArray($_);
			$report->save();
			$response['id'] = $report->id;

	});

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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'Widget.class.php');
			if(!isset($_['id'])) throw new Exception('ID widget non spécifié');
			$widget = Widget::getById($_['id']);
			$widget->fromArray($_);
			$widget->save();
			$response['label'] = $widget->label;

	});

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

			global $myUser,$_;
			User::check_access('statistic','read');
			require_once(__DIR__.SLASH.'Widget.class.php');
			$widget = Widget::getById($_['id']);
			ob_start();
			require_once(__DIR__.SLASH.'page.propertie.php');
			$response['html'] = ob_get_clean();

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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'Widget.class.php');
			$widget = Widget::getById($_['id']);

			require_once(__DIR__.SLASH.'View.class.php');
			View::require_all();

			$widget->meta = json_decode($widget->meta,true);
			if(!is_array($widget->meta)) $widget->meta = array();
			if(!isset($widget->meta['properties'])) $widget->meta['properties'] = array();
			if(!is_null($widget->view)){
				foreach ($widget->view::option() as $key => $value) {
					if(isset($_[$key])) $widget->meta['properties'][$key]= $_[$key];
				}
			}

			$widget->meta = json_encode($widget->meta);
			$widget->save();


	});


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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'Widget.class.php');
			if(!isset($_['widgets'])) return;

			$widgets = array();
			foreach(Widget::loadAll(array('report'=>$_['report'])) as $item)
				$widgets[$item->id] = $item;

			$lastId = false;
			foreach ($_['widgets'] as $widgetInfos) {
				$widget = (isset($widgetInfos['id']) && isset($widgets[$widgetInfos['id']])) ? $widgets[$widgetInfos['id']] : new Widget();
				$widget->fromArray($widgetInfos);
				$widget->report = $_['report'];

				if(isset($widgetInfos['id']) && !$myUser->can('statistic','edit',$widgetInfos['id'])) continue;

				$widget->save();

				if(!isset($widgetInfos['id'])){
					$response['lastId'] = $widget->id;

					$class = WidgetElement::getType('query');
					$element = new $class();
					$element->fromArray(array(
						'widget' => $widget->id,
						'label' => 'Requete 1',
						'connection' => 1,
						'sql' => 'SELECT 1 legende1,2 legende2,3 legende3',
						'sort' => 0
					));
					$element->slug='requete-1';
					$element->save();

					$class = WidgetElement::getType('treatment');
					$element = new $class();
					$element->fromArray(array(
						'widget' => $widget->id,
						'label' => 'Traitement 1',
						'source' => '$output = array();

foreach($data[\'requete-1\'] as $index=>$element){
  foreach($element as $key=>$row){
  	if(is_int($key)) continue;
  	$outputRow[$key] = $row;
  }
  $output[] = $outputRow;
}

return $output[0];',
						'sort' => 1
					));
					$element->slug='traitement-1';
					$element->save();

					// Si création de widget, on créée les droits d'accès pour l'auteur
	            $form = array();
	            $form['uid'] = $widget->id;
	            $form['read'] = $form['edit'] = $form['delete'] = $form['configure'] = 1;
	            $form['recursive'] = 0;
	            $form['targetScope'] = 'user';
	            $form['targetUid'] = $myUser->login;
	            $form['scope'] = 'statistic';

	            $myUser->loadRights();
	            $_SESSION['currentUser'] = serialize($myUser);
				}
			}

	});

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

			global $myUser,$_;
			User::check_access('statistic','delete');
			require_once(__DIR__.SLASH.'Widget.class.php');


			$widget = Widget::getById($_['id']);
			if(!$myUser->can('statistic','delete',$widget->id) ) throw new Exception("Permission refusée");

			$widget->remove();

	});

	Action::register('stats_export_view_table',function(&$response){
		global $myUser,$_;
		User::check_access('statistic','read');
		require_once(__DIR__.SLASH.'Widget.class.php');
		require_once(__DIR__.SLASH.'WidgetElement.class.php');
		require_once(__DIR__.SLASH.'View.class.php');
		View::require_all();



		$widget = Widget::provide();
		if(!$widget) throw new Exception("Widget non spécifié ou inexistant en base");

		$filters = isset($_['filters']) ? $_['filters'] : array();

		$item = array();
		try {
			$item = $widget->toArray();
			$view = $widget->view;
			if($view==null) return;
			$results = $widget->cascadePreview($filters);
			$results = $view::toArray($results);
			$output = array();
			foreach($results as $result){
				if(!is_array($result)) continue;
				$output[] = array_map('strip_tags', $result);
			}

			$xlsx = Excel::exportArray($output, null , 'Statistiques');

			File::downloadStream($xlsx,'export-tableau-'.date('d-m-Y-H').'.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			exit();
		} catch(Exception $e) {
			$item['html'] = '<div class="alert alert-danger"> <strong>WIDGET EN ERREUR</strong><p>Erreur de paramétrage du widget</p> <br>'.$e->getMessage().'</div>';
		}
	});

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

			global $myUser,$_;
			User::check_access('statistic','read');
			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'StatisticReport.class.php');

			$widgets = array();


			foreach(Widget::loadAll(array('report'=>$_['report'])) as $widget){
				if(!$myUser->can('statistic_report','read',$widget->report) && !$myUser->can('statistic_widget','read',$widget->id)) continue;

				$row = $widget->toArray();
				$row['edit'] = $myUser->can('statistic','edit',$widget->id);
				$row['delete'] = $myUser->can('statistic','delete',$widget->id);
				$widgets[] = $row;
			}

			$response['widgets'] = $widgets;

	});

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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'Connection.class.php');

			$reponse['rows'] = array();
			$connection = Connection::getById($_['connection']);

			foreach($connection->tables() as $table)
				$response['rows'][] = array('table'=>$table);

	});

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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'Connection.class.php');

			$reponse['rows'] = array();
			$connection = Connection::getById($_['connection']);

			foreach($connection->columns($_['table']) as $column)
				$response['rows'][] = $column;

	});

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

			global $myUser,$_;
			User::check_access('statistic','read');

			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			require_once(__DIR__.SLASH.'View.class.php');
			View::require_all();


			$widgets = Widget::loadAll(array('report'=>$_['report']));
			$filters = isset($_['filters']) ? $_['filters'] : array();



			$logs = array();

			foreach($widgets as $widget){

				$options = array();
				$meta = json_decode($widget->meta,true);
				if(is_array($meta) && isset($meta['properties'])) 	$options['properties']  = $meta['properties'];

				if($myUser->login != $widget->creator && !$myUser->can('statistic_report','read',$widget->report) &&  !$myUser->can('statistic_widget','read',$widget->id)) continue;

				$item = array();
				try {
					$item = $widget->toArray();
					$view = $widget->view;
					$logs[] = $item['label'];
					if($view==null) continue;

					$results = $widget->cascadePreview($filters);
					$item['html'] =  $view::toHtml($widget->label,$results,$options);
				} catch(Exception $e) {
					$item['html'] = '<div class="alert alert-danger"> <strong>WIDGET EN ERREUR</strong><p>Erreur de paramétrage du widget</p> <br>'.$e->getMessage().'</div>';
				}
				$response['widgets'][] = $item;
			}
			Log::put('Consultation du rapport '.$_['report'].(isset($_['filters']) ? '. Filtres : '.json_encode($_['filters']) : '').'. Blocs consultés :'.json_encode($logs), 'Statistiques');

	});

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

			User::check_access('statistic','edit');

			ob_start();
			require_once(__DIR__.SLASH.'edit_widget.php');
			$response['content'] = ob_get_clean();

	});

	////////////////////
	//ELEMENTS WIDGET //
	////////////////////
	Action::register('stats_search_widget_element',function(&$response){

			global $myUser,$_;
			require_once(__DIR__.SLASH.'WidgetElement.class.php');

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

			$elements = WidgetElement::getElementsByWidget($_['id']);
			foreach ($elements as $element) {
				$row = $element->toArray();
				$row['type'] = get_class($element);
				$row['typeLabel'] = $element->typeLabel;
				$row['icon'] = $element->icon;
				$row['label'] = html_entity_decode($row['label']);
				$response['rows'][] = $row;
			}

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			User::check_access('statistic','edit');
			$filters = isset($_['filters']) ? $_['filters'] : array();
			$widget = Widget::getById($_['id']);
			$data = WidgetElement::cascadePreview($_['type'],$_['id'],$filters,$widget);
			//$data  = end($data);

			$response['data'] = json_encode($data['data'] ,JSON_PRETTY_PRINT);
			if(isset($data['meta'])) $response['meta'] = $data['meta'] ;

			if($response['data']==false)
				$response['data'] = json_encode(array_map_recursive('utf8_encode', $data)  ,JSON_PRETTY_PRINT);

			if($response['data']==false)
				$response['data'] = json_encode(array_map_recursive('utf8_decode', $data)  ,JSON_PRETTY_PRINT);

	});

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

			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			require_once(__DIR__.SLASH.'Widget.class.php');
			global $myUser,$_;
			User::check_access('statistic','delete');

			if(!isset($_['type'])) return;
			$class = WidgetElement::getType($_['type']);

			$element = isset($_['id']) ? $class::getById($_['id']) : new $class();

			$widget = Widget::getById($element->widget);

			if(!$widget->check_access('delete')) throw new Exception('permission denied');

			$class::delete(array('id'=>$_['id']));

	});

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

			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			global $myUser,$_;
			User::check_access('statistic','edit');



			foreach ($_['sort'] as $i=>$element) {
				$class = $element['type'];
				require_once(__DIR__.SLASH.'element'.SLASH.$class.'.class.php');
				$element = $class::getById($element['id']);

				$widget = Widget::getById($element->widget);
				if(!$widget->check_access('edit')) continue;

				$element->sort=$i;
				$element->save();
			}



	});

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

			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			global $myUser,$_;

			User::check_access('statistic','edit');
			if(!isset($_['type'])) return;
			$class = WidgetElement::getType($_['type']);
			$element = isset($_['id']) ? $class::getById($_['id']) : new $class();



			$response['script'] = $element->javascript;
			$response['edit'] = '<div id="editor">'.$element->editor().'</div>';

			$filters = isset($_['filters']) ? $_['filters'] : array();


			$response['data'] = '{}';


	});


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

			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			require_once(__DIR__.SLASH.'Widget.class.php');
			global $myUser,$_;

			User::check_access('statistic','edit');

			if(!isset($_['type'])) return;
			$class = WidgetElement::getType($_['type']);
			$element = isset($_['id']) ? $class::getById($_['id']) : new $class();

			$widget = Widget::getById($element->widget);
			if(!$widget->check_access('edit')) return;

			$response = $element->toArray();
			$response['type'] = $_['type'];

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'WidgetElement.class.php');
			User::check_access('statistic','edit');
			$class = WidgetElement::getType($_['type']);
			$element = isset($_['id']) ? $class::getById($_['id']) : new $class();

			if(!isset($element->sort) || $element->sort == '') $element->sort = 1000;
			$element->fromArray($_);

			$widget = Widget::getById($element->widget);

			if(!$widget->check_access('edit')) return;

			if($class == 'Treatment'){
				$output = array();
				$tmpPath = File::temp().uniqid('check_syntax_error_', true).'.tmp';

				file_put_contents($tmpPath, "<?php ".html_entity_decode($element->source));

				exec('php -l '.$tmpPath.' 2<&1', $output, $return);

				if(preg_match('/n\'est pas reconnu/is', $output[0])) throw new Exception('Merci d\'installer PHP-cli pour utiliser ce module');
				$noSyntaxError = false;
				foreach ($output as $line) {
					if(preg_match('/No syntax errors detected/is', $line)) $noSyntaxError = true;
				}

				if(!$noSyntaxError && isset($output[1])) throw new Exception('Erreur de parsing du code php de traitement : '. preg_replace("/\sin\s.*(\son.*)/i", "$1", $output[1]));


				unlink($tmpPath);
			}

			if(empty($element->slug)) $element->slug = slugify($element->label);

			$element->save();

	});

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

			global $myUser,$_;
			User::check_access('statistic','edit');

			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'View.class.php');
			View::require_all();

			$filter = isset($_['filter'])? $_['filter'] : array();
			$filters = isset($_['filters']) ? $_['filters'] : array();

			$widget = Widget::getById($_['widget']);
			$results = $widget->cascadePreview($filters);

			$options = array();
			$meta = json_decode($widget->meta,true);
			if(is_array($meta) && isset($meta['properties'])) 	$options['properties']  = $meta['properties'];

			$html = '<div><label><i class="fas fa-chart-pie"></i> Rendu</label>';
			$html .= isset($_['view']) ? $_['view']::toHtml('Prévisualisation',$results,$options) : '<br/>Aucune vue sélectionnée, choisissez une vue sur le panneau de gauche';
			$html .= '</div>';

			$response['html'] = $html;

	});


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

			global $myUser,$_;
			User::check_access('statistic','configure');
			require_once(__DIR__.SLASH.'StatisticReport.class.php');
			$maxSize = 200000000 ;
			foreach ($_FILES['file']['tmp_name'] as $i=>$temp) {

				if($_FILES['file']['type'][$i] != 'application/x-zip-compressed') throw new Exception("Type de fichier non accpté");
				if($_FILES['file']['size'][$i] > $maxSize) throw new Exception("Taille de l'import trop importante, max :".$maxSize);

				StatisticReport::import($_FILES['file']['tmp_name'][$i]);

			};


	});

	Action::register('stats_export_report',function(&$response){
		global $myUser,$_;
		User::check_access('statistic','configure');
		require_once(__DIR__.SLASH.'StatisticReport.class.php');
		require_once(__DIR__.SLASH.'Widget.class.php');

		$report = StatisticReport::getById($_['id']);

		File::downloadStream($report->export(), $name= slugify($report->label).'-'.date('d-m-Y h.i').'.zip', $mime='application/zip');

		exit();
	});

	Action::register('stats_delete_report',function(&$response){
		global $myUser,$_;
		User::check_access('statistic','delete');
		require_once(__DIR__.SLASH.'StatisticReport.class.php');


		$report = StatisticReport::provide();
		$report->remove();
		header('location: index.php?module=statistic');
		exit();
	});

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

			global $myUser,$_;
			User::check_access('statistic','configure');
			Plugin::need('statistic/WidgetElement');
			require_once(__DIR__.SLASH.'element'.SLASH.'Query.class.php');
			$query = Query::provide();
			if(!$query) throw new Exception("Requête non identifiée");
			$query->connection = $_['connection'];
			$query->save();

	});

	//FILTERS
	Action::register('stats_save_filter',function(&$response){

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Filter.class.php');
			User::check_access('statistic','edit');

			$filter = isset($_['id']) ? Filter::getById($_['id']) : new Filter();
			$filter->fromArray($_);
			$filter->default = str_replace(' ','',$filter->default);
			$filter->save();



	});

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

			global $myUser,$_;
			User::check_access('statistic','edit');
			require_once(__DIR__.SLASH.'Filter.class.php');
			if(isset($_['sort']) && !empty($_['sort'])){
				foreach ($_['sort'] as $sort => $id) {
					$item = Filter::getById($id);
					$item->sort = $sort;
					$item->save();
				}
			}

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Filter.class.php');
			User::check_access('statistic','read');

			foreach(Filter::loadAll(array('report'=>$_['report']),array('sort ASC')) as $filter){
				$filter->slug = slugify($filter->label);
				$row = $filter->toArray();
				$row['label'] = html_entity_decode($row['label']);
				$response['rows'][] = $row;
			}

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Filter.class.php');
			User::check_access('statistic','edit');

			$filter = Filter::getById($_['id']);
			$response = $filter;

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Filter.class.php');
			User::check_access('statistic','delete');

			Filter::deleteById($_['id']);

	});

 	//CONNECTION
	Action::register('stats_search_connection',function(&$response){

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Connection.class.php');
			User::check_access('statistic','edit');

			foreach(Connection::loadAll() as $connection)
				$response['rows'][] = $connection;

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Connection.class.php');
			User::check_access('statistic','configure');

			if(empty($_['label'])) throw new Exception("Libellé obligatoire");
			if(empty($_['handler'])) throw new Exception("Type de base obligatoire");

			$connection = isset($_['id']) && !empty($_['id']) ? Connection::getById($_['id']) : new Connection();
			$connection->label = $_['label'];
			$connection->handler = $_['handler'];
			$connection->meta = json_encode($_['meta']);


			//test readonly
			/*try{
	   			if(!$connection->readOnly())  throw new Exception("Permissions trops larges sur la base, merci de specifier un compte en lecture seule");
			} catch(PDOException $ex) {
				if($ex->getCode() == 1045) throw  new Exception('Identifiant ou mot de passe incorrect');
				throw $ex;
			}*/
			$connection->save();

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Connection.class.php');
			User::check_access('statistic','configure');

			$response['html'] = '';
			if(empty($_['handler'])) return;
			$handler= str_replace('.', '', $_['handler']);
			require_once(__ROOT__.SLASH.'connector'.SLASH.$handler.'.class.php');

			foreach($handler::fields() as $field){

				$response['html'] .= '<div class="input-group mb-3"><div class="input-group-prepend">
				    <label class="input-group-text"  for="'.$field['id'].'">'.$field['label'].'</label></div>';

				if(!isset($field['comment']))
					$response['html'] .= '<small>'.$field['comment'].'</small><br/>';
				$response['html'] .= '<input type="text" class="form-control" value="'.$field['default'].'" name="'.$field['id'].'" id="'.$field['id'].'"/></div>';
			 }



	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Connection.class.php');
			User::check_access('statistic','configure');

			$connection = Connection::getById($_['id']);
			$tableNumber = $connection->test();
			$response['message'] = $tableNumber.' tables trouvées';

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Connection.class.php');
			User::check_access('statistic','configure');

			$connection = Connection::getById($_['id']);
			$connection->meta = json_decode($connection->meta,true);
			$response = $connection;

	});

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

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Connection.class.php');
			User::check_access('statistic','configure');

			Connection::deleteById($_['id']);

	});

	/* WIDGET */
	Action::register('stats_widget_load',function(&$response){
		global $myUser;
		User::check_access('read','statistic');
		require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');

		$widget = DashboardWidget::current();
		if( $widget->data('title') == ""){
			$widget->title =  'Bloc statistiques';
		}else{
			$widget->title =  '';
			$widget->icon = '';
		}

		if($widget->data('color') != "") $widget->background = $widget->data('color');

		ob_start();
		require_once(__DIR__.SLASH.'widget.php');
		$widget->content = ob_get_clean();

		echo json_encode($widget);
		exit();
	});

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

			global $myUser,$_;
			User::check_access('statistic','read');
			require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');

			$widget = DashboardWidget::getById($_['id']);
			$widget->data('stats',$_['stats']);
			$widget->save();

	});

	Action::register('stats_widget_configure',function(&$response){
		global $myUser;
		User::check_access('statistic','read');
		require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');

		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.configure.php');
		$content = ob_get_clean();
		echo $content ;
	});

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

			global $myUser,$_;
			User::check_access('statistic','read');
			require_once(__DIR__.SLASH.'Widget.class.php');
			require_once(__DIR__.SLASH.'StatisticReport.class.php');


			$response['rows'] = array();
			if($_['keyword'] == '') return;

			foreach(Widget::staticQuery('SELECT w.*,r.label as report FROM {{table}} w LEFT JOIN '.StatisticReport::tableName().' r ON r.id=w.report WHERE w.label LIKE ?',array('%'.$_['keyword'].'%')) as $row){

				if($row['creator'] != $myUser->login && !$myUser->can('statistic','read',$row['id'])) continue;


				$row['name'] = $row['label'];
				$response['rows'][] = $row;
			}

	});




?>
