<?php

include('templates/header.php');
include('db.php');

if (empty($_POST)) {
?>
<div id="cloud_create">
	<form method="post" action="create.php">
		<label for="ftext">Description du nuage</label>
		<input type="text" id="ftext" name="ftext" placeholder="Votre texte ici">
		<label for="fduration">Durée de vie du nuage</label>
		<select id="fduration" name="fduration">
<?php
	foreach (DataBase::OPTIONS_DURATION as $name => $duration) {
		echo sprintf('<option valu="%s">%s</option>', $name, $name);
	}
?>
		</select>
		<label for="fsize">Nombre de mots par entrée (entre 1 et 9)</label>
		<input type="number" id="fsize" name="fsize" min="1" max="9">
		<input type="submit" value="Créer">
	</form>
</div>
<?php
} else {

$db = new DataBase();
if (!$db->isInit()) {
	echo 'Error db init';
	return;
}

$db->cleanCloud();

$length = 6;
$token = bin2hex(random_bytes($length));
if (isset($_POST['fsize']) && is_numeric($_POST['fsize'])) {
	$size = $_POST['fsize'];
} else {
	$size = 3;
}
if (isset($_POST['ftext'])) {
	$text = $_POST['ftext'];
} else {
	$text = '';
}
if (isset($_POST['fduration']) && in_array($_POST['fduration'], DataBase::OPTIONS_DURATION)) {
	$duration = $_POST['fduration'];
} else {
	$duration = DataBase::DEFAULT_DURATION;
}
$cpt = 0;
while (!$db->createCloud($token, $text, $size, $duration) && $cpt < 10) {
	$token = bin2hex(random_bytes($length));
	$cpt++;
}
?>

<div id="cloud_links">
	<div id="cloud_links_results" class="cloud_link">
		<span class="label">Voici le lien pour visualiser le nuage de mots</span>
		<span class="link">
			<a href="result.php?id=<?php echo $token ?>">id=<?php echo $token ?></a>
		</span>
	</div>
	<div id="cloud_links_vote" class="cloud_link">
		<span class="label">Voici le lien pour participer au nuage</span>
		<span class="link">
			<a href="index.php?id=<?php echo $token ?>">id=<?php echo $token ?></a>
		</span>
	</div>
</div>
<?php
}
include('templates/footer.php');