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

$env = env_load(dirname(__DIR__).'/.env');
$login = strtolower($env['TWITCH_CHANNEL'] ?? '');
$uid = $login ? get_user_id($login) : null;
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $uid) {
	$title = trim($_POST['title'] ?? '');
	$opt1 = trim($_POST['opt1'] ?? '');
	$opt2 = trim($_POST['opt2'] ?? '');
	$dur = max(15, min(1800, (int)($_POST['duration'] ?? 60)));
	if ($title && $opt1 && $opt2) {
		$r = helix_post('/polls', [
			'broadcaster_id' => $uid,
			'title' => $title,
			'choices' => [
				['title' => $opt1],
				['title' => $opt2]
			],
			'duration' => $dur
		]);
		$msg = ($r['http'] === 200)
			? 'Poll oprettet ✔️'
			: 'Fejl ('.$r['http'].'): '.($r['raw'] ?? '');
	}
}
?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Poll</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrap">
	<div class="card">
		<h2>📊 Poll</h2>
		<p><a class="btn" href="index.php">← Tilbage</a></p>
		<?php if ($msg): ?>
			<p class="<?php echo strpos($msg, '✔️') !== false ? 'notice' : 'error'; ?>">
				<?php echo htmlspecialchars($msg); ?>
			</p>
		<?php endif; ?>
		<form method="post">
			<label>Titel<input name="title" required></label><br>
			<label>Valgmulighed 1<input name="opt1" required></label><br>
			<label>Valgmulighed 2<input name="opt2" required></label><br>
			<label>Varighed (sek, 15–1800)
				<input type="number" name="duration" min="15" max="1800" value="60">
			</label><br>
			<button class="btn">Opret poll</button>
		</form>
		<p class="small">Kræver scope: <code>channel:manage:polls</code>.</p>
	</div>
</div>
</body>
</html>