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

$file_cmd = __DIR__.'/../data/commands.json';
$file_perm = __DIR__.'/../data/permissions.json';

$cmds = [];
if (file_exists($file_cmd)) {
	$cmds = json_decode(file_get_contents($file_cmd), true);
	if (!is_array($cmds)) $cmds = [];
}

$perms = [];
if (file_exists($file_perm)) {
	$perms = json_decode(file_get_contents($file_perm), true);
	if (!is_array($perms)) $perms = [];
}

$roles = ['chatter','follower','sub','vip','mod','streamer'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$new = [];
	foreach ($cmds as $n => $_) {
		$val = $_POST['role_'.$n] ?? 'chatter';
		if (!in_array($val, $roles, true)) $val = 'chatter';
		$new[$n] = $val;
	}
	file_put_contents($file_perm, json_encode($new, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
	header('Location: permissions.php?saved=1');
	exit;
}
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Rettigheder</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrap">
	<div class="card">
		<h2>🔐 Rettigheder pr. kommando</h2>
		<p><a class="btn" href="index.php">← Tilbage</a></p>
		<form method="post">
			<table>
				<tr>
					<th>!kommando</th>
					<th>Krævet rolle</th>
				</tr>
				<?php foreach ($cmds as $k => $v):
					$r = $perms[$k] ?? 'chatter'; ?>
					<tr>
						<td><?php echo '!'.htmlspecialchars($k); ?></td>
						<td>
							<select name="<?php echo 'role_'.$k; ?>">
								<?php foreach ($roles as $role): ?>
									<option value="<?php echo $role; ?>" <?php echo $r === $role ? 'selected' : ''; ?>>
										<?php echo ucfirst($role); ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
				<?php endforeach; ?>
			</table>
			<br>
			<button class="btn">Gem</button>
		</form>
		<p class="small">Follower behandles pt. som chatter (kan udvides med Helix-follow-tjek).</p>
	</div>
</div>
</body>
</html>