<?php
session_start();
include('inc/db.php');

$error = '';

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

    $stmt = mysqli_prepare($conn, "SELECT id, username, password, email, role FROM users WHERE username = ?");
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "s", $username);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $user = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);

        if ($user && isset($user['role']) && password_verify($password, $user['password'])) {
            // Authentifizierung erfolgreich, Session-Variablen setzen
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $username;
            $_SESSION['email'] = $user['email'];
            $_SESSION['role'] = $user['role'];

            // Neuen Login-Token für die geräteübergreifende Anmeldung erstellen
            $token = bin2hex(random_bytes(32));
            $expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));

            // Token in der neuen `login_tokens` Tabelle speichern
            $sql_token = "INSERT INTO login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)";
            $stmt_token = mysqli_prepare($conn, $sql_token);
            mysqli_stmt_bind_param($stmt_token, "iss", $user['id'], $token, $expires_at);
            mysqli_stmt_execute($stmt_token);
            mysqli_stmt_close($stmt_token);

            // Cookie mit dem Token setzen
            setcookie('remember_token', $token, time() + (86400 * 30), "/");

            header("Location: index.php");
            exit();
        } else {
            $error = "Login fehlgeschlagen.";
        }
    } else {
        $error = "Datenbankfehler.";
    }
}

require_once 'inc/public_header.php';
?>
<div class="container d-flex justify-content-center align-items-start py-4 pt-5">
    <div class="card bg-light shadow w-100" style="max-width: 400px;">
        <div class="card-body">
            <h4 class="card-title text-center mb-4 fs-3">DoMiLi Login</h4>
            <?php if ($error) { ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo $error; ?>
                </div>
            <?php } ?>
            <form method="post" action="">
                <div class="mb-3">
                    <label for="username" class="form-label">Benutzername</label>
                    <input type="text" class="form-control form-control-lg" id="username" name="username" required autofocus>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Passwort</label>
                    <input type="password" class="form-control form-control-lg" id="password" name="password" required>
                </div>
                <div class="d-grid">
                    <button type="submit" class="btn btn-primary btn-lg">Einloggen</button>
                </div>
                <div class="text-center mt-3">
                    <a href="forgot_password.php" class="text-decoration-none">Passwort vergessen?</a>
                </div>
            </form>
        </div>
    </div>
</div>
<?php include('inc/footer.php'); ?>