<?php 

session_start();
$errors = array();

$hostErr = $userErr = $passErr = $dbsErr = $urlErr = "";
$host = $user = $password = $dbs = $pass = $base_url = "";
$mail_host = $mail_port = $mail_smtp = $mail_from = $mail_fromname = $mail_secure = "";
$mailhostErr = $portErr = $smtpErr = $fromErr = $fromnameErr = $secureErr = "";

if (isset($_POST['vytvorit_db'])) {

	if (empty($_POST["host"])) {
	   	$hostErr = "Host nevyplněn (defaultně je: localhost).";
	} else {
		$host = $_POST["host"];
	}

	if (empty($_POST["user"])) {
	   	$userErr = "Uživatel nevyplněn.";
	} else {
		$user = $_POST["user"];
	}

	if (isset($_POST["password"])) {
	   	$password = $_POST["password"];
	} 

	if (empty($_POST["dbs"])) {
	   	$dbsErr = "Jméno databáze nevyplněno.";
	} else {
		$dbs = $_POST["dbs"];
	}

	if (empty($_POST["path"])) {
	   	$urlErr = "Musíte vyplnit domému aplikace.";
	} else {
		$base_url = $_POST["path"];
	}

	if (empty($_POST["mail_host"])) {
	   	$mailhostErr = "Musíte vyplnit mail host.";
	} else {
		$mail_host = $_POST["mail_host"];
	}

	if (empty($_POST["mail_port"])) {
	   	$portErr = "Musíte vyplnit port.";
	} else {
		$mail_port = $_POST["mail_port"];
	}

	if (empty($_POST["mail_from"])) {
	   	$fromErr = "Musíte vyplnit výchozí email aplikace.";
	} else {
		$mail_from = $_POST["mail_from"];
	}

	if (empty($_POST["mail_fromname"])) {
	   	$fromnameErr = "Musíte zvolit název aplikace.";
	} else {
		$mail_fromname = $_POST["mail_fromname"];
	}

	if (empty($_POST["mail_secure"])) {
	   	$secureErr = "Musíte zvolit typ sekuritizace.";
	} else {
		$mail_secure = $_POST["mail_secure"];
	}


	$pass = "$2y$10$5y2TXn8WUFUL9H8sovHeaeOwibEcjARCf./BwZ/OP6ZX044Hr4Wce";


		if (empty($host)) { array_push($errors, "host"); }
		if (empty($user)) { array_push($errors, "user"); }
		if (empty($dbs)) { array_push($errors, "dbs"); }
		if (empty($base_url)) { array_push($errors, "base_url"); }

	if (count($errors) == 0) {

		$conn = new mysqli($host,$user,$password);

		if ($conn->connect_error) {
  			$_SESSION['zprava'] = "Chybné údaje!" . " " . "Chyba: ". " " . $conn->connect_error;
		} else {
			$sql = "DROP DATABASE IF EXISTS $dbs;";
			$sql .= "CREATE DATABASE $dbs;";
			$sql .= "USE $dbs;";
			$sql .= "DROP TABLE IF EXISTS `users`;";
			$sql .= "CREATE TABLE `users` (
						`user_id`  int(11)                                      NOT NULL AUTO_INCREMENT,
						`name` varchar(30) COLLATE utf8_czech_ci                NOT NULL,
						`pass` varchar(60) COLLATE utf8_czech_ci                NOT NULL,
						`role`     enum ('user', 'admin') COLLATE utf8_czech_ci NOT NULL DEFAULT 'user',
						PRIMARY KEY (`user_id`),
						UNIQUE KEY `name` (`name`) USING BTREE
					) DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci;";
			$sql .= "DROP TABLE IF EXISTS `events`;";
			$sql .= "CREATE TABLE `events` (
						`event_id`  int(11) NOT NULL AUTO_INCREMENT,
						`name`      varchar(50) COLLATE utf8_czech_ci DEFAULT NULL,
						`url`       varchar(50) COLLATE utf8_czech_ci DEFAULT NULL,
						`popis` 	text COLLATE utf8_czech_ci DEFAULT NULL,
						`otevreno`	tinyint COLLATE utf8_czech_ci DEFAULT 0,
						`created_at`	timestamp COLLATE utf8_czech_ci NOT NULL,
						PRIMARY KEY (`event_id`),
						UNIQUE KEY `url` (`url`)
					) DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci;";
			$sql .= "DROP TABLE IF EXISTS `invitations`;";
			$sql .= "CREATE TABLE `invitations` (
						`invitation_id`  int(11) NOT NULL AUTO_INCREMENT,
						`name`      varchar(50) COLLATE utf8_czech_ci DEFAULT NULL,
						`body`      text COLLATE utf8_czech_ci DEFAULT NULL,
						`event_id` 	int(11) COLLATE utf8_czech_ci DEFAULT NULL,
						`created_at`	timestamp COLLATE utf8_czech_ci NOT NULL,
						`edited_at`	varchar(30) COLLATE utf8_czech_ci NOT NULL,
						PRIMARY KEY (`invitation_id`),
						FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE,
						UNIQUE KEY `event_id` (`event_id`) USING BTREE
					) DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci;";
			$sql .= "DROP TABLE IF EXISTS `adress`;";
			$sql .= "CREATE TABLE `adress` (
						`adress_id`  int(11) NOT NULL AUTO_INCREMENT,
						`name`      varchar(50) COLLATE utf8_czech_ci DEFAULT NULL,
						`event_id` 	int(11) COLLATE utf8_czech_ci DEFAULT NULL,
						PRIMARY KEY (`adress_id`),
						FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE,
						UNIQUE KEY `event_id` (`event_id`) USING BTREE
					) DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci;";
			$sql .= "DROP TABLE IF EXISTS `contacts`;";		
			$sql .= "CREATE TABLE `contacts` (
						`contact_id`  int(11) NOT NULL AUTO_INCREMENT,
						`mail`      varchar(80) COLLATE utf8_czech_ci DEFAULT NULL,
						`name`      varchar(80) COLLATE utf8_czech_ci DEFAULT NULL,
						`token`      varchar(80) COLLATE utf8_czech_ci DEFAULT NULL,
						`active`      tinyint COLLATE utf8_czech_ci DEFAULT 1,
						`created_at`	timestamp COLLATE utf8_czech_ci NOT NULL,
						`adress_id` 	int(11) COLLATE utf8_czech_ci DEFAULT NULL,
						`salt` 	varchar(80) COLLATE utf8_czech_ci DEFAULT NULL,
						PRIMARY KEY (`contact_id`),
						FOREIGN KEY (`adress_id`) REFERENCES `adress` (`adress_id`) ON DELETE CASCADE ON UPDATE CASCADE,
						UNIQUE KEY `salt` (`salt`) USING BTREE
					) DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci;";
			$sql .= "INSERT INTO users (name,pass,role) VALUES ('admin', '$pass', 'admin')";

			$open = fopen('../app/config/local.neon', 'w') or die("O - Soubor local.neon není přístupný, nebo neexistuje!");

			$neon = 'parameters:'. PHP_EOL .' mail:'. PHP_EOL .'  host: '.$mail_host. PHP_EOL .'  port: '.$mail_port. PHP_EOL .'  from: '.$mail_from. PHP_EOL .'  fromname: '.$mail_fromname. PHP_EOL .'  secure: '.$mail_secure. PHP_EOL .' database:'.PHP_EOL.'  host: '.$host.PHP_EOL.'  dbname: '.$dbs.PHP_EOL.'  user: '.$user.PHP_EOL.'  pass: '.$password.PHP_EOL.'  url: '.$base_url;

			fwrite($open, $neon) or die("W - Soubor local.neon není přístupný, nebo neexistuje!");

			if ($conn->multi_query($sql) === TRUE) {
			   $_SESSION['zprava'] = "Databáze vytvořena. Nyní smažte adresář /configurator !";
			} else {
			  $_SESSION['zprava'] = "Nelze vytvořit databázi!" . $sql . "<br>" . $conn->error;
			}
    	}
    	$conn->close();
	} 
}

?>

<head>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>Portál | První spuštění</title>
	<link rel="stylesheet" href="../www/css/font-awesome.css">
	<link rel="stylesheet" href="../www/css/bootstrap_new.css">

	<style>
		.zpravy {
			color: red;
			text-align: center;
		}
		.chyby {
			color: red;
			text-align: center;
		}

		.stred {
			padding: 0;
			margin: 0 auto;
			text-align: center;
		}

		.first_run {
			text-align: center;
			width: 580px;
			margin: 0 auto;
			margin-top: 20px;
		}

		.login_config {
			text-align: center;
			width: 400px;
			margin: 0 auto;
		}

		p {
			text-align: inherit;
		}
	</style>

</head>
<body>
	<div class="first_run">
		<a href=""><h4>První spuštění aplikace</h4></a>
		<hr>
		<p>Vítejte v konfigurátoru aplikace. Ve formuláři níže prosím vyplňte <b>správně všechny údaje</b> - jedná se o údaje, které se používají k připojení k <b>databázovému serveru</b>. Více informací naleznete v implementačním nebo uživatelském manuálu.</p>
	</div>
	<div class="login_config">
		<form method="POST" action="index.php">
			<p>Databáze</p>
			<span style="color:red;"><?php echo $hostErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-cloud"></i></span>
				</div>
				<input type="text" name="host" class="form-control input_user" placeholder="Host">
				<span class="error">*</span>
			</div>
			<span style="color:red;"><?php echo $userErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-smile-o"></i></span>
				</div>
				<input type="text" name="user" class="form-control input_user" placeholder="Uživatel">
				<span class="error">*</span>
			</div>
			
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-key"></i></span>
				</div>
				<input type="password" name="password" class="form-control input_pass" placeholder="Heslo">
				<span class="error">-</span>
			</div>
			<span style="color:red;"><?php echo $dbsErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-database"></i></span>
				</div>
				<input type="text" name="dbs" class="form-control input_user" placeholder="Jméno DB bez diakritiky">
				<span class="error">*</span>
			</div>

			<p>Mailer</p>
			<span style="color:red;"><?php echo $mailhostErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-cloud"></i></span>
				</div>
				<input type="text" name="mail_host" class="form-control input_user" placeholder="Mail host">
				<span class="error">*</span>
			</div>
			<span style="color:red;"><?php echo $portErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-file"></i></span>
				</div>
				<input type="text" name="mail_port" class="form-control input_user" placeholder="Mail port">
				<span class="error">*</span>
			</div>
			<span style="color:red;"><?php echo $fromErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-envelope"></i></span>
				</div>
				<input type="text" name="mail_from" class="form-control input_user" placeholder="Výchozí e-mail aplikace">
				<span class="error">*</span>
			</div>
			<span style="color:red;"><?php echo $fromnameErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-share"></i></span>
				</div>
				<input type="text" name="mail_fromname" class="form-control input_user" placeholder="Jméno aplikace">
				<span class="error">*</span>
			</div>
			<span style="color:red;"><?php echo $secureErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text"><i class="fa fa-key"></i></span>
				</div>
				<input type="text" name="mail_secure" class="form-control input_user" placeholder="Sekuritizace (ssl,tls,none)">
				<span class="error">*</span>
			</div>
			
			<p>Adresa aplikace</p>
			<span style="color:red;"><?php echo $urlErr;?></span>
			<div class="input-group mb-3">
				<div class="input-group-append">
					<span class="input-group-text">https://</i></span>
				</div>
				<input type="text" name="path" class="form-control input_user" placeholder="mojeadresa.cz">
				<span class="error">*</span>
			</div>

			<?php if (isset($_SESSION['zprava'])) : ?>
			      <div class="zpravy" >
			      	<p>
			          <?php 
			          	echo $_SESSION['zprava']; 
			          	unset($_SESSION['zprava']);
			          ?>
			      	</p>
			      </div>
			<?php endif ?>

			<br>
			<p>Konfigurátor vytvoří celou databázi včetně ukázkových dat a základní uživatelský účet admin. Je doporučeno po přihlášení do aplikace <b>změnit heslo</b> k účtu administrátora. Více informací v manuálech.</p>
			<p style="color:red; text-decoration: underline;">Po úspěšné konfiguraci smažte adresář "configurator"!</p>
			<div class="stred">
				<h5>Výchozí uživatel aplikace</h5>
				<b>Jméno:</b> admin
				<br>
				<b>Heslo:</b> admin
			</div>
			<br>
			<div class="d-flex justify-content-center mt-3">
				 <button type="submit" name="vytvorit_db">Uložit a pokračovat</button>
			</div>
				
		</form>
	</div>
</body>