<?php
require __DIR__ . '/auth.php';

// Wenn schon eingeloggt, direkt zur Startseite
if (currentUser()) {
    header('Location: start.php');
    exit;
}

$error    = '';
$username = '';

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

    if ($username !== '' && $password !== '') {
        $stmt = $pdo->prepare('SELECT id, username, password FROM users WHERE username = :u');
        $stmt->execute([':u' => $username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = (int)$user['id'];
            header('Location: start.php');
            exit;
        } else {
            $error = 'Benutzername oder Passwort ist falsch.';
        }
    } else {
        $error = 'Bitte Benutzername und Passwort eingeben.';
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>EKL – Anmeldung</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" href="icons/logo.png" type="image/png">
</head>
<body>

<div id="app">
    <div class="login-shell">
        <div class="login-card">
            <h1>ANMELDUNG</h1>

            <?php if ($error): ?>
                <div class="login-error"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="post" action="login.php" class="login-form" novalidate>
                <div class="login-group">
                    <label for="username">Benutzername</label>
                    <input
                        type="text"
                        name="username"
                        id="username"
                        autocomplete="username"
                        required
                        value="<?= htmlspecialchars($username) ?>">
                </div>

                <div class="login-group">
                    <label for="password">Passwort</label>
                    <input
                        type="password"
                        name="password"
                        id="password"
                        autocomplete="current-password"
                        required>
                </div>

                <div class="login-submit">
                    <button type="submit">Anmelden</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>
</body>
</html>
