<?php
// login.php – Login-Seite (Modern UI & Secured)
ob_start();
session_start();

// Datenbankverbindung und andere Includes
require_once "includes/db.php";
// Führe den Header am besten NACH der PHP-Logik aus, um Redirects zu ermöglichen
// require_once "includes/header.php"; // Wird später eingebunden

if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    // ⚠️ WICHTIG: Verwende Prepared Statements, um SQL Injection zu verhindern.
    // Die alte Methode mit $conn->real_escape_string bietet keinen ausreichenden Schutz!
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $user = $result->fetch_assoc()) {
        // Passwortprüfung
        if (password_verify($password, $user['password'])) {

            // --- Session-Variablen setzen ---
            $_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']);

            // Login-Historie speichern (Prepared Statement ist beibehalten)
            $ip = $_SERVER['REMOTE_ADDR'];
            $stmtHistory = $conn->prepare("INSERT INTO login_history (user_id, ip_address, action) VALUES (?, ?, 'login')");
            $stmtHistory->bind_param("is", $user['id'], $ip);
            $stmtHistory->execute();
            $stmtHistory->close();

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

<?php include "includes/header.php"; ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
/* Modernisierung des Containers und der Karte */
body {
    background-color: #f0f2f5; /* Leichter Hintergrund */
}
.login-wrapper {
    max-width: 400px;
    margin: 8vh auto; /* Etwas mehr Abstand nach oben */
    padding: 20px;
}
.login-card {
    background: #ffffff; /* Weißer Hintergrund */
    border: none;
    border-radius: 12px; /* Stärkere Abrundung */
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1); /* Moderner Schatten */
}
.login-card h2 {
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 25px;
}
.form-label {
    font-size: 0.9rem;
    font-weight: 600;
    color: #475569;
}
.input-group-text {
    background-color: #f1f5f9;
    border-right: none;
}
.form-control {
    border-left: none;
}
.btn-primary {
    transition: all 0.2s;
    font-weight: 600;
}
</style>

<div class="login-wrapper">
    <div class="card login-card p-5 shadow">
        <div class="text-center mb-4">
           <img src="img/logo2.png" width="120" height="120" alt="Logo" class="mb-3 rounded-circle border border-2">
           <h2 class="fs-4">Anmeldung</h2>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger text-center shadow-sm border-0 border-start border-4 border-danger"><?= $error ?></div>
        <?php endif; ?>

        <form method="post">
            <div class="mb-3">
                <label for="username" class="form-label">Benutzername</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-person"></i></span>
                    <input type="text" class="form-control" name="username" required autofocus>
                </div>
            </div>
            <div class="mb-4">
                <label for="password" class="form-label">Passwort</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-key"></i></span>
                    <input type="password" class="form-control" name="password" required>
                </div>
            </div>
            <button type="submit" name="login" class="btn btn-primary w-100 py-2">
                <i class="bi bi-box-arrow-in-right me-1"></i> Einloggen
            </button>

        </form>
    </div>
</div>
