<?php
require_once __DIR__.'/api.php';
$env = env_load(dirname(__DIR__).'/.env');
$login = strtolower($env['TWITCH_CHANNEL'] ?? '');
$uid = $login ? get_user_id($login) : null;
$cb = $env['EVENTSUB_CALLBACK'] ?? '';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $uid && $cb) {
	foreach ([
		'channel.cheer',
		'channel.subscribe',
		'channel.subscription.message',
		'channel.subscription.gift'
	] as $t) {
		$r = helix_post('/eventsub/subscriptions', [
			'type' => $t,
			'version' => '1',
			'condition' => ['broadcaster_user_id' => $uid],
			'transport' => [
				'method' => 'webhook',
				'callback' => $cb,
				'secret' => $env['EVENTSUB_SECRET'] ?? 'change_this_secret'
			]
		]);
		$msg .= $t . ': HTTP ' . $r['http'] . ' ' . substr($r['raw'] ?? '', 0, 120) . "\n";
	}
}
?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>EventSub Setup</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div class="wrap">
		<div class="card">
			<h2>⚡ EventSub Setup</h2>
			<p><a class="btn" href="index.php">← Tilbage</a></p>
			<?php if ($msg): ?>
				<pre><?php echo htmlspecialchars($msg); ?></pre>
			<?php endif; ?>
			<form method="post">
				<p>Callback: <code><?php echo htmlspecialchars($cb ?: 'mangler EVENTSUB_CALLBACK'); ?></code></p>
				<button class="btn" <?php echo (!$uid || !$cb) ? 'disabled' : ''; ?>>Opret abonnementer</button>
			</form>
			<p class="small">Brug en offentlig URL (fx ngrok) der peger på <code>/bot/web/eventsub.php</code>.</p>
		</div>
	</div>
</body>
</html>