<?php
// login.php

require_once __DIR__ . '/lib/bootstrap.php';

// 1) DB-Verbindung (einmal)
$conn = db_connect();

// 2) POST-Verarbeitung VOR jeglicher Ausgabe
$loginError = null;
$loginInfo = null;

if (isset($_GET['registered']) && $_GET['registered'] === '1')
{
    $loginInfo = 'Registrierung erfolgreich. Du kannst dich jetzt einloggen.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $uname = '';

    if (isset($_POST['uname']))
    {
        $uname = trim($_POST['uname']);
    }

    if (isset($_POST['pw']))
    {
        $pw = $_POST['pw'];
    }
    else
    {
        $pw = '';
    }


    // Basic Validierung
    if ($uname === '' || $pw === '')
    {
        $loginError = "Bitte Username und Passwort eingeben.";
    }
    else
    {
        // Login ist SELECT, mit Prepared Statement (sicher) und ?-Platzhalter
        $stmt = mysqli_prepare(
                $conn,
                "SELECT userID, displayName, passwordHash FROM users WHERE displayName = ? LIMIT 1"
        );

        if (!$stmt)
        {
            $loginError = "Datenbankfehler.";
        }
        else
        {
            mysqli_stmt_bind_param($stmt, "s", $uname);
            mysqli_stmt_execute($stmt);

            $result = mysqli_stmt_get_result($stmt);

            $user = null;

            if ($result)
            {
                $user = mysqli_fetch_assoc($result);
            }

            // Passwort prüfen: Eingabe gegen gespeicherten Hash (password_hash/password_verify)
            if ($user && password_verify($pw, $user['passwordHash']))
            {
                // Optional: Rehash, falls Algorithmus/Cost geändert wurde
                if (password_needs_rehash($user['passwordHash'], PASSWORD_DEFAULT))
                {
                    $newHash = password_hash($pw, PASSWORD_DEFAULT);
                    $upd = mysqli_prepare($conn, "UPDATE users SET passwordHash = ? WHERE userID = ?");
                    if ($upd)
                    {
                        $userID = (int)$user['userID'];
                        mysqli_stmt_bind_param($upd, "si", $newHash, $userID);
                        mysqli_stmt_execute($upd);
                        mysqli_stmt_close($upd);
                    }
                }

                $_SESSION['user_id'] = (int)$user['userID'];
                $_SESSION['displayName'] = $user['displayName'];

                mysqli_stmt_close($stmt);
                mysqli_close($conn);

                header("Location: account.php");
                exit;
            }

            $loginError = "Ungültige Zugangsdaten.";
            mysqli_stmt_close($stmt);
        }
    }
}

include 'header.php';
?>

<main class="auth" role="main">
    <section class="auth__grid" aria-label="Login Bereich">
        <div class="auth__card">
            <header class="auth__header">
                <h2 class="auth__title">Login</h2>
            </header>

            <?php if ($loginInfo): ?>
                <p class="auth__alert__sucess"
                   role="status"><?php echo htmlspecialchars($loginInfo, ENT_QUOTES, 'UTF-8'); ?></p>
            <?php endif; ?>

            <?php if ($loginError): ?>
                <p class="auth__alert__error"
                   role="alert"><?php echo htmlspecialchars($loginError, ENT_QUOTES, 'UTF-8'); ?></p>
            <?php endif; ?>

            <form class="auth__form" action="login.php" method="POST" autocomplete="on">
                <div class="auth__field">
                    <label for="uname">Username</label>
                    <input type="text" id="uname" name="uname" inputmode="text" autocomplete="username" required>
                </div>

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

                <div class="auth__actions">
                    <input class="auth__submit" type="submit" value="Einloggen">
                </div>
            </form>

            <div class="auth__links">
                <p class="auth__muted">Neu hier? <a href="register.php">Account erstellen</a></p>
            </div>
        </div>
    </section>
</main>

<?php
mysqli_close($conn);
include 'footer.php';
?>
