<?php
include "includes/db.php";
ob_start(); session_start();

if (isset($_POST['login'])) {
    $username = $conn->real_escape_string($_POST['username']);
    $password = $_POST['password'];

    $sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
    $result = $conn->query($sql);

    if ($result && $user = $result->fetch_assoc()) {
        if (password_verify($password, $user['password'])) {
            $_SESSION['user'] = $user['username'];
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['is_admin'] = $user['is_admin'];
            $_SESSION['einheit'] = $user['einheit'];
            $_SESSION['feuerwehr_id'] = $user['feuerwehr_id'];
            $_SESSION['gemeinde_id'] = $user['gemeinde_id'];
            $_SESSION['lk_id'] = $user['lk_id'];
            $_SESSION['user_vorname'] = $user['vorname'];
            $_SESSION['user_nachname'] = $user['nachname'];
            $_SESSION['user_rolle'] = $user['rolle'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['root'] = $user['root'];

            // Nach erfolgreichem Passwort-Check
            $conn->query("UPDATE users SET eingeloggt = 1 WHERE id = " . (int)$user['id']);

            $ip = $_SERVER['REMOTE_ADDR'];
            $stmt = $conn->prepare("INSERT INTO login_history (user_id, ip_address, action) VALUES (?, ?, 'login')");
            $stmt->bind_param("is", $user['id'], $ip);
            $stmt->execute();



            header("Location: index.php");
            exit();
        } else {
            $error = "❌ Falsches Passwort.";
        }
    } else {
        $error = "⚠️ Benutzer nicht gefunden.";
    }



}
?>

<?php include "includes/header.php"; ?>

<style>
.login-wrapper {
    max-width: 400px;
    margin: 60px auto;
}
.login-card {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
}
.login-card h2 {
    font-weight: 600;
}
</style>

<div class="login-wrapper">
    <div class="card login-card p-4 shadow">
      <center><img src="../img/logo2.png" width="250px" height="250px"></center>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger text-center"><?= $error ?></div>
        <?php endif; ?>

        <form method="post">
            <div class="mb-3">
                <label for="username" class="form-label">Benutzername</label>
                <input type="text" class="form-control" name="username" required autofocus>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Passwort</label>
                <input type="password" class="form-control" name="password" required>
            </div>
            <button type="submit" name="login" class="btn btn-primary w-100">🔒 Einloggen</button>
        </form>
    </div>
</div>

<?php include "includes/footer.php"; ?>
