<?php
require_once "base.php";
session_start();
if(!isset($_SESSION["bootstrapAdmin"])||!isset($_SESSION["dbSetup"])||file_exists("db.php")){
	http_response_code(403);
	print("Forbidden, you don't have access to this resource.");
	exit;
}
head("Configue database");
nav();
?>
<div>
<h1>Configure the database</h1>
<p>Creating the database</p>
<?php
if($_SERVER["REQUEST_METHOD"]==="POST"){
	if(!isset($_POST['addr'])||!isset($_POST['dbname'])||!isset($_POST['uname'])){
		die("ERROR params not set");
	}
	$addr = htmlspecialchars($_POST['addr']);
	$dbname = htmlspecialchars($_POST['dbname']);
	$uname = htmlspecialchars($_POST['uname']);
	$pass = htmlspecialchars($_POST['pass']);
	$dsn = "mysql:host=$addr";
	$options = [];
	try {
		$pdo = new PDO($dsn,$uname,$pass,$options);
	} catch (PDOException $e) {
		die("Error connecting to database: ".$e->getMessage());
	}
	if(!isset($_POST['existingDB'])){
		$pdo->query("CREATE DATABASE ".$dbname." CHARACTER SET utf8mb4");
	}
	$pdo->query("USE ".$dbname.";".file_get_contents("database.sql"));

	$data="<?php\n\$host = \"".$addr.
		"\";\n\$db = \"".$dbname.
		"\";\n\$user = \"".$uname.
		"\";\n\$pass = \"".$pass.
		"\";\n\$dsn = \"mysql:host=\$host;dbname=\$db\";\n\$options = [];\ntry {\n	\$pdo = new PDO(\$dsn,\$user,\$pass,\$options);\n} catch (PDOException \$e) {\n	die(\"Error connecting to database: \".\$e->getMessage());\n}\n?>";
	$dbfile = fopen("db.php","w") or die("unable to open file db.php for writing");
	fwrite($dbfile,$data);
	fclose($dbfile);
	header("Location: logout.php");
	exit;

} else if($_SERVER["REQUEST_METHOD"]==="GET") {
?>
<form method="POST">
<table class="table table-striped table-sm">
    <thead>
	<tr>
	    <td>host</td>
	    <td>database name</td>
	    <td>username</td>
	    <td>password</td>
	</tr>
    </thead>
    <tbody>
	<tr>
		<td><input type="text" name="addr" placeholder="host" required></td>
		<td><input type="text" name="dbname" placeholder="database name" required></td>
		<td><input type="text" name="uname" placeholder="username" required></td>
		<td><input type="password" name="pass" placeholder="password"></td>
	</tr>
	<tr>
		<td colspan="4">
			<label><input oninput="inpChg()" type="checkbox" name="existingDB" id="existingDB">Don't create database</label>
			<label class="text-secondary" id="existingDBcontentsEl"><input type="checkbox" name="existingDBcontents" disabled>Don't create tables</label>
		</td>
	</tr>
    </tbody>
</table>
<input type="submit" value="Add" class="btn btn-success">
</form>
</div>
<script>
function inpChg() {
	if(document.getElementById("existingDB").checked){
		document.getElementById("existingDBcontentsEl").classList.remove("text-secondary");
		document.getElementById("existingDBcontentsEl").querySelector("input").disabled = false;
	} else {
		document.getElementById("existingDBcontentsEl").classList.add("text-secondary");
		document.getElementById("existingDBcontentsEl").querySelector("input").disabled = true;
	}
}
</script>
<?php
	footer();
}
?>
