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

$db = new PDO('sqlite:' . dirname(__DIR__) . '/data/app.db');
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['open'])) {
        $db->exec('UPDATE raffle_state SET open = 1');
        $msg = 'Raffle åben.';
    }

    if (isset($_POST['close'])) {
        $db->exec('UPDATE raffle_state SET open = 0');
        $msg = 'Raffle lukket.';
    }

    if (isset($_POST['cost'])) {
        $cost = max(1, (int)$_POST['cost']);
        $stmt = $db->prepare('UPDATE raffle_state SET ticket_cost = :cost');
        $stmt->execute([':cost' => $cost]);
        $msg = 'Billetpris opdateret.';
    }

    if (isset($_POST['clear'])) {
        $db->exec('DELETE FROM raffle_entries');
        $msg = 'Entries nulstillet.';
    }

    if (isset($_POST['draw'])) {
        $rows = $db->query('SELECT user_login FROM raffle_entries')->fetchAll(PDO::FETCH_COLUMN);
        if ($rows) {
            $winner = $rows[array_rand($rows)];
            $msg = 'Vinder: @' . htmlspecialchars($winner);
        } else {
            $msg = 'Ingen entries.';
        }
    }
}

$state = $db->query('SELECT * FROM raffle_state WHERE id = 1')->fetch(PDO::FETCH_ASSOC);
$count = $db->query('SELECT COUNT(*) FROM raffle_entries')->fetchColumn();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Raffle</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrap">
    <div class="card">
        <h2>🎟️ Raffle</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">
            <p>
                Status:
                <?php echo $state['open']
                    ? '<span class="badge">Åben</span>'
                    : '<span class="badge">Lukket</span>'; ?>
                – Billetpris: <strong><?php echo (int)$state['ticket_cost']; ?></strong>
                – Entries: <strong><?php echo (int)$count; ?></strong>
            </p>

            <label>
                Ny billetpris
                <input name="cost" type="number" min="1" value="<?php echo (int)$state['ticket_cost']; ?>">
            </label>
            <br>
            <button class="btn" name="open" value="1">Åbn</button>
            <button class="btn" name="close" value="1">Luk</button>
            <button class="btn" name="clear" value="1">Nulstil</button>
            <button class="btn" name="draw" value="1">Træk vinder</button>
        </form>

        <p class="small">Chat: <code>!buy X</code> køber billetter for points.</p>
    </div>
</div>
</body>
</html>
