<?php
session_start();
require_once __DIR__ . '/db.php';

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username !== '' && $password !== '') {
        $db = db();
        $st = $db->prepare('SELECT * FROM users WHERE username = ? LIMIT 1');
        $st->execute([$username]);
        $user = $st->fetch(PDO::FETCH_ASSOC);

        $ok = false;
        if ($user) {
            // Foretræk moderne kolonne 'password' (password_hash())
            if (!empty($user['password']) && password_verify($password, $user['password'])) {
                $ok = true;
            }
            // Legacy fallback: 'password_hash' (egen hash fra gammel version)
            if (!$ok && !empty($user['password_hash'])) {
                // Forventet format: enten salt$sha256(salt+pw) eller ren sha256
                $ph = $user['password_hash'];
                if (strpos($ph, '$') !== false) {
                    [$salt, $hash] = explode('$', $ph, 2);
                    $ok = (hash('sha256', $salt . $password) === $hash);
                } else {
                    $ok = (hash('sha256', $password) === $ph);
                }
            }
        }

        if ($ok) {
            $_SESSION['user'] = [
                'id'       => $user['id'],
                'username' => $user['username'],
                'role'     => $user['role'] ?: 'user',
            ];
            header('Location: index.php');
            exit;
        } else {
            $error = 'Forkert brugernavn eller adgangskode.';
        }
    } else {
        $error = 'Udfyld begge felter.';
    }
}
?>
<!DOCTYPE html>
<html lang="da">
<head>
  <meta charset="utf-8">
  <title>Login – Twitch PHP Bot</title>
  <link rel="stylesheet" href="style.css">
  <style>.login-box{max-width:400px;margin:100px auto}</style>
</head>
<body>
<div class="wrap">
  <div class="card login-box">
    <h2>🔐 Login</h2>
    <?php if ($error): ?><p class="notice" style="color:#ff8080"><?php echo htmlspecialchars($error); ?></p><?php endif; ?>
    <form method="post">
      <label>Brugernavn</label>
      <input type="text" name="username" required>
      <label>Adgangskode</label>
      <input type="password" name="password" required>
      <br>
      <button class="btn" type="submit">Log ind</button>
    </form>
  </div>
</div>
</body>
</html>
