<?php

try {
	mb_internal_encoding('UTF-8');
	require_once(__DIR__.'/function.php');
	spl_autoload_register('app_autoloader');

	$_ = array_map('secure_user_vars', array_merge($_POST, $_GET));
	require_once('class/Plugin.class.php');
	$entityFolder = __DIR__.'/class/';
	
	?>

	<!DOCTYPE html>
	<html lang="fr">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content="">
		<link rel="icon" type="image/png" href="favicon.png" />

		<title>Installateur</title>

		<!-- Bootstrap core CSS -->
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<!-- Font awesome -->
		<link rel="stylesheet" href="css/fontawesome-all.min.css">
		<!-- Custom styles for this template -->
		<link href="css/main.css" rel="stylesheet">
		<link href="css/theme.css" rel="stylesheet">
		<!-- Plugin css files -->
		<?php echo Plugin::callCss("css"); ?>
	</head>

	<body>
		<!-- Fixed navbar -->
		<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
			<a class="navbar-brand" href="#">Installateur</a>
			<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
				<span class="navbar-toggler-icon"></span>
			</button>
			<div class="collapse navbar-collapse" id="navbarCollapse">
				<ul class="navbar-nav mr-auto">
					<li class="nav-item active"><a class="nav-link" href="#">Installation <span class="sr-only">(current)</span></a></li>
				</ul>
			</div>
		</nav>

		<!-- Begin page content -->
		<div class="container">
		<?php 
		$entities = array();

		foreach(glob(__DIR__.'/connector/*.class.php') as $classFile){
			require_once($classFile);
			$className = str_replace('.class.php','',basename($classFile));
			$entities[$className] = $className::label.' - '.$className::description;
		}

		//check prerequisite
		if(file_exists(__DIR__.'/constant.php')) throw new Exception('Le script est déja installé, pour recommencer l\'installation, supprimez le fichier constant.php');
		if(!is_writable (__DIR__)) throw new Exception('Le dossier '.__DIR__.' doit être accessible en ecriture, merci de taper la commande linux <br/><code>sudo chown -R www-data:www-data '.__ROOT__.'</code><br/> ou de régler le dossier en écriture via votre client ftp');
		if(!file_exists(__DIR__.'/file')) mkdir(__DIR__.'/file',0755,true);
		if(!file_exists(__DIR__.'/file/avatar')) mkdir(__DIR__.'/file/avatar',0755,true);

		//if(!extension_loaded('gd') || !function_exists('gd_info'))  throw new Exception('L\'extension php GD2  est requise, veuillez installer GD2 (sous linux : <code>sudo apt-get install php5-gd && service apache2 restart</code>)');
		//if(!in_array('sqlite',PDO::getAvailableDrivers())) throw new Exception('Le driver SQLITE est requis, veuillez installer sqlite3 (sous linux : <code>sudo apt-get install php5-sqlite && service apache2 restart</code>)');

		if(isset($_['install'])){

			$constantStream = file_get_contents(__DIR__.'/constant-sample.php');

			if(!isset($_['host'])) $_['host'] = '';
			if(!isset($_['login'])) $_['login'] = '';
			if(!isset($_['password'])) $_['password'] = '';
			if(!isset($_['database'])) $_['database'] = '';

			$cryptKey = base64_encode(time().$_['login'].mt_rand(0,1000));

			$constantStream = str_replace(
				array("{{BASE_SGBD}}","{{BASE_HOST}}","{{BASE_NAME}}","{{BASE_LOGIN}}","{{BASE_PASSWORD}}","{{ROOT_URL}}","{{CRYPT_KEY}}"),
				array($_['entity'],$_['host'],$_['name'],$_['login'],$_['password'],$_['root'],$cryptKey),$constantStream
			);

			file_put_contents(__DIR__.'/constant.php',$constantStream);

			require_once(__DIR__.'/constant.php');
			require_once(__ROOT__.'class'.SLASH.'Entity.class.php');

			


			//install entities
			Entity::install(__ROOT__.'class');

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

			//create firm 
			$firm = new Firm();
			$firm->label = 'Établissement';
			$firm->description = 'Établissement par défaut';
			$firm->save();

			//create admin rank
			$rank = new Rank();
			$rank->label = 'Administrateur';
			$rank->description = 'Dispose de tous les accès';
			$rank->save();

			//create default user
			$admin = new User();
			$admin->login = 'admin';
			$admin->password = User::password_encrypt('admin');
			$admin->firstname = 'Chuck';
			$admin->name = 'Norris'; 
			$admin->superadmin = 1; 
			$admin->rank = $rank->id;
			$admin->state = User::ACTIVE;
			$admin->save();
			$_SESSION['currentUser'] = serialize($admin);

			$userfirmrank = new UserFirmRank();
			$userfirmrank->user = $admin->login;
			$userfirmrank->firm = $firm->id;
			$userfirmrank->save();

			$sections = array();
			Plugin::callHook('section',array(&$sections));
			foreach($sections as $section=>$description){
				$right = new Right();
				$right->rank = $rank->id;
				$right->section = $section;
				$right->read = true;
				$right->edit = true;
				$right->delete = true;
				$right->configure = true;
				$right->save();
			}
			//Activation des plugins par défaut
			foreach (array('fr.idleman.factory','fr.idleman.dashboard','fr.idleman.notification') as  $plugin) {
				Plugin::state($plugin,true);
			} ?>

			<div class="alert alert-success alert-dismissable">
				<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
				<strong>Succès!</strong> La base est bien installée, l'utilisateur par défaut est <code>admin:admin</code>, pensez à changer le mot de passe rapidemment. <br>
			</div>
			<a class="btn btn-primary" href="index.php">Revenir à l'index</a>
			<?php 
		} else {

			$root = 'http'.((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')|| $_SERVER['SERVER_PORT'] == 443?'s':'').'://'.$_SERVER['HTTP_HOST'].($_SERVER['SERVER_PORT']==80?'':':'.$_SERVER['SERVER_PORT']).$_SERVER['REQUEST_URI'];
			$root = str_replace("/install.php", "", $root );
			$parts = explode('?',$root);
			$root = array_shift($parts);
			?>
			<div class="row">
				<form class="col-md-3" action="install.php" method="POST">
					<h3>Installation</h3>
					<p>Merci de bien vouloir remplir les champs ci-dessous</p>
					<label for="entity">Base de donnée</label>
					<select class="form-control" name="entity" onchange="window.location='install.php?sgbd='+$(this).val()">
						<option value="">-</option>
						<?php foreach($entities as $class=>$label): ?>
							<option <?php echo (isset($_['sgbd']) && $_['sgbd']==$class ? 'selected="selected"': '') ?> value="<?php echo $class ?>"><?php echo $label; ?></option>
						<?php endforeach; ?>
					</select><br/>

					<?php if(isset($_['sgbd']) && $_['sgbd']!=''): 
						require_once(__DIR__.'/connector/'.$_['sgbd'].'.class.php');
						foreach($_['sgbd']::fields() as $field): ?>
							<label for="<?php echo $field['id']; ?>"><?php echo $field['label']; ?></label><br/>
							<?php if(!isset($field['comment'])): ?><small><?php echo $field['comment']; ?></small><br/><?php endif; ?>
							<input type="text" class="form-control" value="<?php echo $field['default']; ?>" name="<?php echo $field['id']; ?>" id="<?php echo $field['id']; ?>"/><br/>
						<?php endforeach;  ?>

						<label for="root">Adresse web</label><br/>
						<input type="text" class="form-control" name="root" id="root" value="<?php echo $root; ?>"/><br/>

						<input type="submit" class="btn btn-primary" value="Installer" name="install"><br/><br/>
					<?php endif; ?>
				</form>
			</div>
			<?php
		}
	} catch (Exception $e) { ?>
			<div class="alert alert-danger">
				<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
				<strong>Oops!</strong> <?php echo $e->getMessage().' - '.$e->getFile().' L'.$e->getLine().'<hr/><pre>'.$e->getTraceAsString().'</pre>';
				?> 
			</div>
		<?php
	} ?>
	</div>

	<footer class="footer">
		<div class="container">
			<span class="text-muted">Installateur by <a href="mailto:valentin.carruesco@idleman.fr">@valentin carruesco<a></span>
		</div>
	</footer>

	<!-- Bootstrap core JavaScript -->
	<!-- Placed at the end of the document so the pages load faster -->
	<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
	<script>window.jQuery || document.write('<script src="js/vendor/jquery.min.js"><\/script>')</script>
	<script src="js/vendor/popper.min.js"></script>
	<script src="js/bootstrap.min.js"></script>
	<script src="js/vendor/mustache.min.js"></script>
	<script src="js/plugins.js"></script>
	<script src="js/main.js"></script>
	<?php echo Plugin::callJs(); ?>
</body>