<?php 
session_name ('erp-core');
session_start();

$start_time = microtime(TRUE);
mb_internal_encoding('UTF-8');

if(!file_exists(__DIR__.DIRECTORY_SEPARATOR.'constant.php'))
	header('location:install.php');

require_once(__DIR__.DIRECTORY_SEPARATOR.'constant.php');
require_once(__ROOT__.'function.php');
date_default_timezone_set(TIME_ZONE);

//set_error_handler('errorToException');
set_exception_handler('unhandledException');
spl_autoload_register('app_autoloader');

global $myUser,$conf,$_,$success,$myFirm;

$_ = array_map('secure_user_vars', array_merge($_POST, $_GET));
$page = isset($_SERVER['REQUEST_URI'])? basename($_SERVER['REQUEST_URI']):'';
$myUser = isset($_SESSION['currentUser']) ? unserialize($_SESSION['currentUser']) : new User();
$myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']): new Firm();

$conf = new Configuration();
$conf->getAll();

//CONFS GÉNÉRALES
Configuration::setting('configuration-global',array(
    "Général :",
    'home_page' => array("label"=>"Page d'accueil","type"=>"text","legend"=>"Laisser vide pour gérer en automatique","placeholder"=>"eg : index.php?module=example"),
    'show_application_name' => array("label"=>"Afficher le nom du programme", "legend"=>"Dans la barre de navigation / menu uniquement", "type"=>"checkbox"),
    "Gestion des clés Map Algolia API :",
    'maps_api_id' => array("label"=>"ID de l'application","type"=>"text","legend"=>"Clé API pour le composant location","placeholder"=>"eg. pl0749TULNDW..."),
    'maps_api_key' => array("label"=>"Clé publique de l'application","type"=>"password","legend"=>"Clé API pour le composant location","placeholder"=>"eg. db6788b1e4165d3370ed88a304704676..."),
    "Authentification :",
    'account_block' => array("label"=>"Activer le blocage de compte au bout de N essais","legend"=>"Tous les utilisateurs seront soumis à la règle","type"=>"checkbox"),
    'account_block_try' => array("label"=>"Nombre d'essais avant blocage du compte","legend"=>"L'utilisateur aura N tentatives pour se connecter avant d'être bloqué","type"=>"number", "placeholder"=>"eg. 10"),
    'account_block_delay' => array("label"=>"Durée de blocage", "legend"=>"(en minutes)", "type"=>"number", "placeholder"=>"eg. 30"),
    'Mots de passe <div class="btn btn-warning btn-small float-right" onclick="general_reset_password_delay()"><i class="fas fa-exclamation-triangle"></i> Forcer le renouvellement</div>',
    'password_delay'=>array("label"=>"Renouvellement", "legend"=>"Forcer l'utilisateur a renouveller son mot de passe tous les X jours (laisser vide pour désactiver)", "type"=>"number", "placeholder"=>"eg. 30"),
    'password_allow_lost'=>array("label"=>"Oubli de mot de passe", "legend"=>"Proposer la récuperation du mot de passe oublié", "type"=>"checkbox"),
    "Connectivité :",
    'offline_mode' => array("label"=>"Activer le mode hors ligne","legend"=>"(Désactive toutes les fonctionnalités ayant besoin d'un accès internet depuis le poste client cdn...)","type"=>"checkbox"),
));

//CACHE CSS & JS
$cacheVersion = 1;
if(file_exists(__DIR__.SLASH.'.git'.SLASH.'HEAD')){
	$versionFile = str_replace(array('ref: ',PHP_EOL,"\r","\n"),'',file_get_contents(__DIR__.SLASH.'.git'.SLASH.'HEAD'));
	if(file_exists(__DIR__.SLASH.'.git'.SLASH.$versionFile)){
		$cacheVersion = str_replace(array("\r","\n"),'',file_get_contents(__DIR__.SLASH.'.git'.SLASH.$versionFile));
	}
}

if($myUser->login==null && isset($_COOKIE[COOKIE_NAME])){
	$cookie = UserPreference::load(array('key'=>'cookie','value'=>$_COOKIE[COOKIE_NAME]));

	if($cookie!=false){
	    if(Plugin::is_active('fr.idleman.activedirectory'))
	        require_once(PLUGIN_PATH.'activedirectory'.SLASH.'activedirectory.plugin.php');
	    
	    $myUser = User::byLogin($cookie->user);
        if($myUser->origin != 'active_directory'){
            $myUser->ranks = array();
            $myUser->firms = array();
            $myUser->loadRanks();
            $myUser->loadPreferences();
        }
        
        $defaultFirm = !empty($myUser->preference('default_firm')) ? $myUser->preferences['default_firm'] : key($myUser->firms);
        $myFirm = isset($myUser->firms[$defaultFirm]) ? $myUser->firms[$defaultFirm]:key($myUser->firms);
        
        $_SESSION['currentUser'] = serialize($myUser);
        $_SESSION['firm'] = serialize($myFirm);
    }
}

$myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']): new Firm();

//MENUS
Plugin::addHook("menu_account", function(&$accountMenu){
	global $myUser;
	if(!$myUser->connected()) throw new Exception('Vous devez être connecté pour accéder à cette fonctionnalité');
	$accountMenu[]= array(
		'sort' =>0,
		'url' => 'account.php?section=global',
		'icon' => 'fas fa-angle-right',
		'label' => 'Général',
	);
});

Plugin::addHook("menu_setting", function(&$settingMenu){
	global $myUser;

	$settingMenu[]= array(
		'sort' =>0,
		'url' => 'setting.php?section=global',
		'icon' => 'fas fa-angle-right',
		'label' => 'Général',
	);
	
	if($myUser->can('plugin','configure'))
		$settingMenu[]= array(
			'sort' =>18,
			'url' => 'setting.php?section=plugin',
			'icon' => 'fas fa-angle-right',
			'label' => 'Plugins',
			'category' => 'administration'
		);

	if($myUser->can('user','configure'))
		$settingMenu[]= array(
			'sort' =>20,
			'url' => 'setting.php?section=user',
			'icon' => 'fas fa-angle-right',
			'label' => 'Utilisateurs',
			'category' => 'administration'
		);
	if($myUser->can('rank','configure'))
		$settingMenu[]= array(
			'sort' =>21,
			'url' => 'setting.php?section=rank',
			'icon' => 'fas fa-angle-right',
			'label' => 'Rangs & Accès',
			'category' => 'administration'
		);

	if($myUser->can('firm','configure'))
		$settingMenu[]= array(
			'sort' =>22,
			'url' => 'setting.php?section=firm',
			'icon' => 'fas fa-angle-right',
			'label' => 'Établissements',
			'category' => 'administration'
		);

	if($myUser->can('user','configure'))
		$settingMenu[]= array(
			'sort' =>23,
			'url' => 'setting.php?section=userfirmrank',
			'icon' => 'fas fa-angle-right',
			'label' => 'Établissement / Utilisateur / Rang',
			'category' => 'administration'
		);

	if($myUser->can('plugin','configure'))
		$settingMenu[]= array(
			'sort' =>24,
			'url' => 'setting.php?section=firmPlugin',
			'icon' => 'fas fa-angle-right',
			'label' => 'Établissement / Plugins',
			'category' => 'administration'
		);

	if($myUser->can('dictionnary','configure'))
		$settingMenu[]= array(
			'sort' =>20,
			'url' => 'setting.php?section=dictionnary',
			'icon' => 'fas fa-angle-right',
			'label' => 'Listes de valeur'
		);

	if($myUser->can('log','read'))
		$settingMenu[]= array(
			'sort' =>16,
			'url' => 'setting.php?section=log',
			'icon' => 'fas fa-angle-right',
			'label' => 'Logs',
			'category' => 'administration'
		);
	
	if($myUser->login!='')
		$settingMenu[]= array(
			'sort' =>16,
			'url' => 'setting.php?section=update',
			'icon' => 'fas fa-angle-right',
			'label' => 'Mises à jour',
			'category' => 'administration'
		);
});

Plugin::addHook("menu_main", function(&$mainMenu) {
	global $myUser;
	
	$mainMenu[] = array(
		'sort' =>0,
		'icon' => 'fas fa-home',
		'label' => 'Accueil',
		'url' => 'index.php',
		'color' => '#383838'
	);
	if(!$myUser->connected()) return;
	$settingMenu = array();
	Plugin::callHook("menu_setting", array(&$settingMenu));
});

Plugin::addHook("menu_user", function(&$userMenu){
	global $myUser,$myFirm;

	$rankLabels = array();
	if($myUser->superadmin){
	    $rankLabels[] = 'Super Admin';
	} else {
	    if(isset($myUser->ranks[$myFirm->id])){
		    foreach($myUser->ranks[$myFirm->id] as $rank){
		    	$rankLabels[] = $rank->label;
		    }
		}
	}

	if(count($rankLabels)!=0){
	    $rankLabels = '<div class="firm-ranks"><ul><li>'.implode('</li><li>',$rankLabels).'</li></ul></div>';
	} else {
	    $rankLabels = '';
	}

	$userMenu[]= array(
		'sort' =>-2,
		'custom' => "<div class='firm-item' onclick='event.stopPropagation();'><small>Rang : ".$rankLabels."</small></div><div class='dropdown-divider'></div>",
	);

	if(count($myUser->firms)>1){
		$userIcon = 'far fa-user';
		$options = '';

		foreach ($myUser->firms as $firm) {
			$options .= '<option '.($myFirm->id == $firm->id ? "selected='selected'":"").' value="'.$firm->id.'">'.$firm->label.'</option>';
		}
		
		$userMenu[]= array(
			'sort' =>1,
			'custom' => "<div class='firm-item' onclick='event.stopPropagation();'><small>Établissement : </small><select class=\"form-control form-control-sm\" onchange=\"window.location='action.php?action=select_firm&firm='+$(this).val();\">".$options."</select></div><div class='dropdown-divider'></div>",
		);

	} else {
		$userIcon = 'fas fa-user';
		$userMenu[]= array(
			'sort' =>-1,
			'custom' => "<div class='firm-item' onclick='event.stopPropagation();'><small>Établissement : ".$myFirm->label."</small></div><div class='dropdown-divider'></div>",
		);
	}

	if($myUser->can('account','read'))
		$userMenu[]= array(
			'sort' =>0,
			'label' => 'Mon compte',
			'icon' => $userIcon,
			'url' => 'account.php'
		);

	if($myUser->can('setting_global', 'read'))
		$userMenu[]= array(
			'sort' =>1,
			'icon' => 'fas fa-cog',
			'label' => 'Réglages',
			'url' => 'setting.php'
		);

	$userMenu[]= array(
		'sort' =>100,
		'icon' => 'fas fa-sign-out-alt',
		'label' => 'Déconnexion',
		'url' => 'action.php?action=logout'
	);
});

Plugin::addHook("content_setting", function(){
	global $_;
	$_['section'] = !isset($_['section']) ? 'global': $_['section'];
	if(in_array($_['section'],array('global','plugin','rank','right','user','firm','userfirmrank','firmPlugin','log','dictionnary','update')) && file_exists('setting.'.$_['section'].'.php'))
		require_once('setting.'.$_['section'].'.php');
});
Plugin::addHook("content_account", function(){
	global $_;
	$_['section'] = !isset($_['section']) ? 'global': $_['section'];
	if(in_array($_['section'],array('global')) && file_exists('account.'.$_['section'].'.php'))
		require_once('account.'.$_['section'].'.php');
});

Plugin::addHook("section",function(&$sections){
	$sections['setting_global'] = 'Gestion des parametres globaux';
	$sections['user'] = 'Gestion des utilisateurs';
	$sections['firm'] = 'Gestion des établissements';
	$sections['plugin'] = 'Gestion des plugins';
	$sections['rank'] = 'Gestion des rangs et droits';
	$sections['log'] = 'Gestion des logs programme';
	$sections['dictionnary'] = 'Gestion des listes programme';
	$sections['file'] = 'Gestion des fichiers';
	$sections['account'] = 'Gestion du compte courant';
});

Plugin::addHook("cron",function(){
	if(date('H:i')!='01:00') return;
	//Clear automatique des logs
	global $conf;
	foreach(Log::staticQuery('SELECT DISTINCT category FROM {{table}}',array(),true) as $log): 
		$slug = slugify($log->category);
		$key = 'log_retention_time_'.$slug;
		if($conf->get($key)=='') continue;
		Log::clear($conf->get($key));
	endforeach; 
});

Plugin::includeAll();

?>