<?php
require_once __DIR__.'/guard.php';
require_login();

$file = __DIR__.'/../data/giveaway.json';
$st = file_exists($file) ? json_decode(file_get_contents($file), true) : ['open' => false, 'entries' => [], 'winner' => null];
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	if (isset($_POST['open'])) {
		$st = ['open' => true, 'entries' => [], 'winner' => null];
		$msg = 'Giveaway åbnet.';
	}
	if (isset($_POST['close'])) {
		$st['open'] = false;
		$msg = 'Giveaway lukket.';
	}
	if (isset($_POST['draw'])) {
		$e = array_values(array_unique($st['entries']));
		if ($e) {
			$w = $e[array_rand($e)];
			$st['winner'] = $w;
			$msg = 'Vinder: @' . $w;
		} else {
			$msg = 'Ingen entries.';
		}
	}
	if (isset($_POST['clear'])) {
		$st = ['open' => false, 'entries' => [], 'winner' => null];
		$msg = 'Nulstillet.';
	}
	file_put_contents($file, json_encode($st, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
	header('Location: giveaway.php');
	exit;
}
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Giveaway</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrap">
	<div class="card">
		<h2>🎁 Giveaway</h2>
		<p><a class="btn" href="index.php">← Tilbage</a></p>
		<?php if ($msg): ?>
			<p class="notice"><?php echo htmlspecialchars($msg); ?></p>
		<?php endif; ?>
		<form method="post">
			<button class="btn" name="open" value="1">Åbn</button>
			<button class="btn" name="close" value="1">Luk</button>
			<button class="btn" name="draw" value="1">Træk vinder</button>
			<button class="btn" name="clear" value="1" onclick="return confirm('Nulstil?')">Nulstil</button>
		</form>
		<p>Status: <?php echo $st['open'] ? '<span class="badge">Åben</span>' : '<span class="badge">Lukket</span>'; ?>
			— Vinder: <?php echo $st['winner'] ? '@' . htmlspecialchars($st['winner']) : '-'; ?></p>
		<h3>Deltagere (<?php echo count(array_unique($st['entries'])); ?>)</h3>
		<ul>
			<?php foreach (array_unique($st['entries']) as $e) {
				echo '<li>@' . htmlspecialchars($e) . '</li>';
			} ?>
		</ul>
		<p class="small">Chat: <code>!join</code> deltager når giveaway er åben.</p>
	</div>
</div>
</body>
</html>