<?php


	/** DASHBOARD **/
	//Récuperation d'une liste de dashboard
	Action::register('dashboard_dashboard_search',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'Dashboard.class.php');

		$filters = array();
		if(!$myUser->can('dashboard','configure')) $filters['creator'] = $myUser->login;

		foreach(Dashboard::loadAll($filters,array('label','creator')) as $dashboard){
			$userName = User::byLogin($dashboard->user)->fullName();
			$dashboard->user = !empty($userName) ? $userName : $dashboard->user;
			$dashboard->mandatory = $dashboard->mandatory == 1;
			$dashboard->default = $dashboard->default == 1;
			$response['rows'][] = $dashboard;
		}
	});

	//Ajout ou modification d'élément dashboard
	Action::register('dashboard_dashboard_save',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		if($_['mandatory']==1 && !$myUser->can('dashboard','configure'))  throw new Exception("Vous n'avez pas les droits pour rendre ce dashboard obigatoire",403);
		require_once(__DIR__.SLASH.'Dashboard.class.php');

		$item = Dashboard::provide();
		if(!isset($_['user']) || empty($_['user'])) $_['user'] = $myUser->login;

		if($myUser->login!=$item->creator && !$myUser->can('dashboard','configure') && $item->id!=0)  throw new Exception("Vous n'avez pas les droits pour éditer le dashboard d'un autre utilisateur",403);
		if($myUser->login!=$_['user'] && !$myUser->can('dashboard','configure')) throw new Exception("Vous n'avez pas les droits pour créer un dashboard à un autre utilisateur");

		$item->user = $_['user'];
		$item->label = $_['label'];
		$item->icon = $_['icon'];
		$item->default = $_['default'];
		if($item->default) Dashboard::change(array('default'=>0), array('user'=>$item->user));
		$item->mandatory = $_['mandatory'];
		if($item->mandatory) Dashboard::change(array('mandatory'=>0));
		$item->save();
	});

	//Récuperation ou edition d'élément dashboard
	Action::register('dashboard_dashboard_edit',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'Dashboard.class.php');
		$response = Dashboard::getById($_['id']);
	});

	//Suppression d'élement dashboard
	Action::register('dashboard_dashboard_delete',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','delete');
		require_once(__DIR__.SLASH.'Dashboard.class.php');
		$item = Dashboard::provide();
		if($myUser->login!=$item->creator && !$myUser->can('dashboard','configure'))  throw new Exception("Vous n'avez pas les droits pour supprimer le dashboard d'un autre utilisateur",403);
		Dashboard::deleteById($_['id']);
	});

	//Sauvegarde des configurations de dashboard
	Action::register('dashboard_setting_save',function(&$response){
		global $myUser,$_,$conf;
		User::check_access('dashboard','configure');
		foreach(Configuration::setting('dashboard') as $key=>$value){
			if(!is_array($value)) continue;
			$allowed[] = $key;
		}
		foreach ($_['fields'] as $key => $value)
			if(in_array($key, $allowed)) $conf->put($key,$value);
	});

	/** DASHBOARDWIDGET **/
	//Récuperation d'une liste de dashboardwidget
	Action::register('dashboard_dashboardwidget_search',function(&$response){
	
		global $myUser,$myFirm,$_;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		require_once(__DIR__.SLASH.'DashboardWidgetShare.class.php');

		$models = DashboardWidget::models();
		$ranksId = $myUser->getRanksId($myFirm->id);
		$widgetsQry = "SELECT {{table}}.*,ds.mandatory,ds.sort as sort
			FROM {{table}}
			LEFT JOIN ".DashboardWidgetShare::tableName()." ds ON ds.widget={{table}}.id
			WHERE dashboard=?
				OR {{table}}.id IN (
					SELECT widget FROM ".DashboardWidgetShare::tableName()." WHERE (entity=? AND uid=?) OR (entity=? and uid IN (".str_repeat('?,', count($ranksId) - 1) . '?'.")) OR (entity IS NULL)
				)
				ORDER BY sort, position DESC";
		$widgets = DashboardWidget::staticQuery($widgetsQry,array_merge(array($_['dashboard'],'user',$myUser->login,'rank'),$ranksId),true);

		foreach($widgets as $widget){
			if(!isset($models[$widget->model])) continue;
			$model = clone $models[$widget->model];

			$row = $model->toArray();
			$row['id'] = $widget->id;
			$row['width'] = !empty($widget->width) && $widget->width>0 ? $widget->width : $model->defaultWidth;
			$row['position'] = $widget->position;
			$row['minified'] = $widget->minified;
			$row['dashboard'] = $widget->dashboard;

			if(!empty($widget->foreign('mandatory'))) $row['mandatory'] = $widget->foreign('mandatory');
			if(!empty($widget->foreign('sort'))) $row['position'] = $widget->foreign('sort');

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

		if(isset($response['rows'])){
			usort($response['rows'],function($a,$b){
				return $a['position'] - $b['position'];
			});
		}
	});

	//Ajout ou modification d'élément dashboardwidget
	Action::register('dashboard_dashboardwidget_save',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$item = DashboardWidget::provide();
		$item->model = $_['model'];
		$item->data = $_['data'];
		$item->position = $_['position'];
		$item->minified = $_['minified'];
		$item->dashboard = $_['dashboard'];
		$item->save();
	});

	//Récuperation ou edition d'élément dashboardwidget
	Action::register('dashboard_dashboardwidget_edit',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$response = DashboardWidget::getById($_['id']);
	});

	//Suppression d'élement dashboardwidget
	Action::register('dashboard_dashboardwidget_delete',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','delete');
		require_once(__DIR__.SLASH.'Dashboard.class.php');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::getById($_['widget']);
		if(!$widget) return;

		$dashboard = Dashboard::getById($_['dashboard']);
		if($widget->dashboard!=$dashboard->id || $dashboard->user!=$myUser->login)
			throw new Exception("Vous ne pouvez supprimer que vos propres widgets");

		$widget->deleteById($widget->id);
		$response['message'] = 'Widget supprimé';
	});

	//Resize largeur d'élement dashboardwidget
	Action::register('dashboard_dashboardwidget_resize',function(&$response){
		global $myUser,$_;
		require_once(__DIR__.SLASH.'Dashboard.class.php');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		User::check_access('dashboard','edit');

		$widget = DashboardWidget::getById($_['widget']);
		$dashboard = Dashboard::getById($widget->dashboard);
		if($widget->dashboard!=$dashboard->id || $dashboard->user!=$myUser->login)
			throw new Exception("Vous ne pouvez redimenssioner que vos propres widgets");

		$widget->width = $_['width'];
		$widget->save();
	});

	Action::register('dashboard_dashboardwidget_refresh',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','read');
		$widgets = array();
		Plugin::callHook('widget_refresh',array(&$widgets));
		$response['rows'] = $widgets;
	});

	Action::register('dashboard_dashboardwidget_add',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$widget = new DashboardWidget();
		$widget->model = $_['widget'];
		$widget->position = 666;
		$widget->minified = false;
		$widget->width = $widget->width> 0 ? $widget->width: $widget->defaultWidth ;
		$widget->dashboard = $_['dashboard'];
		$widget->save();
		$response['message'] = 'Widget ajouté';
	});

	Action::register('dashboard_dashboardwidget_save_position',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'Dashboard.class.php');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$dashboard = Dashboard::getById($_['dashboard']);

		if($dashboard->user!=$myUser->login) throw new Exception("Vous ne pouvez modifier que vos propres widgets");
		$dashboard_widgets = DashboardWidget::loadAll( array('dashboard' => $dashboard->id ) );

		foreach($_['positions'] as $move){
			foreach($dashboard_widgets as $dashboard_widget){
				if($dashboard_widget->id!=$move['id']) continue;
				$dashboard_widget->position = $move['position'];
				$dashboard_widget->save();
			}
		}
	});

	/* CLOCK */
	Action::register('dashboard_widget_clock_load',function(&$response){
		global $myUser;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.clock.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
		exit;
	});

	/* LOGS */
	Action::register('dashboard_widget_log_load',function(&$response){
		global $myUser;
		require_once('DashboardWidget.class.php');
		User::check_access('log','read');

		$widget = DashboardWidget::current();
		$widget->title = '30 derniers logs';

		ob_start();
		require_once(__DIR__.SLASH.'widget.logs.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
		exit;
	});

	/* PROFILE */
	Action::register('dashboard_widget_profile_load',function(&$response){
		global $myUser;
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		User::check_access('dashboard','read');
		$widget = DashboardWidget::current();
		if(!empty($widget->data('background-color'))) $widget->background = $widget->data('background-color');
		ob_start();
		require_once(__DIR__.SLASH.'widget.profile.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
		exit;
	});

	Action::register('dashboard_widget_profile_configure',function(&$response){
		global $myUser;
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		User::check_access('dashboard','read');
		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.profile.configure.php');
		$content = ob_get_clean();

		echo $content ;
		exit;
	});

	Action::register('dashboard_widget_profile_configure_save',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::getById($_['id']);
		$widget->data('background-color',$_['widget-profile-background-color']);
		$widget->save();
	});


	/* HTML */
	Action::register('dashboard_widget_html_load',function(&$response){
		global $myUser;
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		User::check_access('dashboard','read');
		$widget = DashboardWidget::current();
		$widget->title = $widget->data('title') != "" ? $widget->data('title') :  'Bloc HTML';
		if($widget->data('color') != "") $widget->background = $widget->data('color');
		ob_start();
		require_once(__DIR__.SLASH.'widget.html.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
		exit;
	});

	Action::register( 'dashboard_widget_html_configure',function(&$response){
		global $myUser;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.html.configure.php');
		$content = ob_get_clean();
		echo $content ;
		exit;
	});

	Action::register('dashboard_widget_html_configure_save',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::getById($_['id']);
		$widget->data('html',html_entity_decode($_['widget-html-content']));
		$widget->data('title',$_['widget-html-title']);
		$widget->data('color',$_['widget-html-color']);
		$widget->save();
	});

	/* DASHBOARD SHARE */
	/** DASHBOARDWIDGETSHARE **/
	//Récuperation d'une liste de dashboardwidgetshare
	Action::register('dashboard_widget_share_search',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','read');
		require_once(__DIR__.SLASH.'DashboardWidgetShare.class.php');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');

		$dashboardwidgetshares = DashboardWidgetShare::loadAll(array(), null,  null,array('*'), 1);
		foreach($dashboardwidgetshares as $dashboardwidgetshare){
			$row = $dashboardwidgetshare->toArray();

			$row['widget'] = $dashboardwidgetshare->join('widget')->toArray();
			$row['for'] = 'Tout le monde';
			if($row['entity'] == 'rank' ) $row['for'] = 'Rang: '. Rank::getById($row['uid'] )->label;
			if($row['entity'] == 'user' ) $row['for'] ='Utilisateur: '. User::byLogin($row['uid'] )->fullName();
			$response['rows'][] = $row;
		}
	});

	//Ajout ou modification d'élément dashboardwidgetshare
	Action::register('dashboard_widget_share_save',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'DashboardWidgetShare.class.php');
		//DashboardWidgetShare::create();
		$item = DashboardWidgetShare::provide();

		if(!isset( $_['widget']) || !is_numeric($_['widget'])) throw new Exception("Widget non spécifié ou invalide");

		$item->widget = $_['widget'];
		$item->mandatory = 1;//$_['mandatory'];

		if(isset($_['entity'])){
			$item->entity = $_['entity'];
			$item->uid = $_['uid'];
		}
		$item->sort = !isset($_['sort']) ? 0 : $_['sort'];
		$item->save();
	});


	//Récuperation ou edition d'élément dashboardwidgetshare
	Action::register('dashboard_widget_share_edit',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','edit');
		require_once(__DIR__.SLASH.'DashboardWidgetShare.class.php');
		require_once(__DIR__.SLASH.'DashboardWidget.class.php');
		$response = DashboardWidgetShare::getById($_['id'],1)->toArray();
	});

	//Suppression d'élement dashboardwidgetshare
	Action::register('dashboard_widget_share_delete',function(&$response){
		global $myUser,$_;
		User::check_access('dashboard','delete');
		require_once(__DIR__.SLASH.'DashboardWidgetShare.class.php');
		DashboardWidgetShare::deleteById($_['id']);
	});

?>
