<?php

include "functions.php";
include "header.php";
include "headerline.php";
include "nav.php";


?>



<!-- Banner -->
	<section id="banner">
		<div class="content">

<?php

if(checkKaffeelisteAdmin($conn, $mailadress)){

	echo "<h2>Kaffeeliste - Hinweise</h2>";

	// Hinweis löschen
	if (isset($_GET['delete'])) {
		$id = (int)$_GET['delete'];
		$stmt = sqlsrv_query($conn, "DELETE FROM kl_hinweise WHERE id = ?", [$id]);
	}

	// Hinweis speichern
	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		$nachricht = $_POST['nachricht'];
		
		
		$gueltig_bis = $_POST['gueltig_bis']; // z.B. "2025-09-03T14:00"
		$dt = DateTime::createFromFormat('Y-m-d\TH:i', $gueltig_bis);

		if ($dt) {
			$gueltig_bis_sql = $dt->format('Y-d-m H:i:s'); // z.B. "2025-03-09 14:00:00"
		} else {
			die("Ungültiges Datumsformat");
		}

		if (!empty($nachricht) && !empty($gueltig_bis_sql)) {
			
			$stmt = sqlsrv_query($conn,
				"INSERT INTO kl_hinweise (nachricht, gueltig_bis) VALUES (?, ?)",
				[$nachricht, $gueltig_bis_sql]
			);
			
		}
	}

	// Hinweise abrufen
	$hinweise = [];
	$stmt = sqlsrv_query($conn, "SELECT id, nachricht, gueltig_bis FROM kl_hinweise ORDER BY gueltig_bis DESC");
	while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
		$hinweise[] = $row;
	}
	?>


		<h2>Neuen Hinweis hinzufügen</h2>
		<form method="post">
			<label>Nachricht:</label><br>
			<textarea name="nachricht" required></textarea><br><br>
			<label>Gültig bis:</label><br>
			<input type="datetime-local" name="gueltig_bis" required><br><br>
			<button type="submit">Speichern</button>
		</form>

		<h2>Alle Hinweise</h2>
		<?php foreach ($hinweise as $hinweis): ?>
			<div class="hinweis">
				<strong><?= htmlspecialchars($hinweis['nachricht']) ?></strong><br>
				<small>Gültig bis: <?= $hinweis['gueltig_bis']->format('d.m.Y H:i') ?></small><br>
				<a href="?delete=<?= $hinweis['id'] ?>" onclick="return confirm('Diesen Hinweis wirklich löschen?')">🗑️ Löschen</a>
			</div>
		<?php endforeach; ?>
	</body>
	</html>

<?php


}else{
	echo "<h2>Sie haben keine Zugang zu dieser Webseite</h2>";
}
?>

    </div>
</section>

<?php include "footer.php"; 

?>