<?php
ob_start();
include 'includes/db.php';
include 'includes/header.php';
include 'includes/nav.php';

// Eintrag löschen
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delId = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM transponder_schluessel WHERE id = ?");
    $stmt->bind_param("i", $delId);
    $stmt->execute();
    echo "<div class='alert alert-success'>✅ Eintrag wurde gelöscht.</div>";
}

// Eintrag bearbeiten
$editData = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    $stmt = $conn->prepare("SELECT * FROM transponder_schluessel WHERE id = ?");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $editResult = $stmt->get_result();
    if ($editResult->num_rows > 0) {
        $editData = $editResult->fetch_assoc();
    }
}

// Eintrag speichern oder aktualisieren
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $spindnr = trim($_POST['spindnr']);
    $typ = trim($_POST['typ']);
    $nummer = trim($_POST['nummer']);
    $kommentar = trim($_POST['kommentar']);
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    if ($spindnr && $typ && $nummer) {
        if ($id > 0) {
            // UPDATE
            $stmt = $conn->prepare("UPDATE transponder_schluessel SET spindnr = ?, typ = ?, nummer = ?, kommentar = ? WHERE id = ?");
            $stmt->bind_param("ssssi", $spindnr, $typ, $nummer, $kommentar, $id);
            $stmt->execute();
            echo "<div class='alert alert-success'>✅ Eintrag wurde aktualisiert.</div>";
            header("Location: transponder.php"); // ← ggf. Pfad anpassen
            exit;

        } else {
            // INSERT
            $stmt = $conn->prepare("INSERT INTO transponder_schluessel (spindnr, typ, nummer, kommentar) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $spindnr, $typ, $nummer, $kommentar);
            $stmt->execute();

        }
    } else {
        echo "<div class='alert alert-danger'>❌ Bitte alle Pflichtfelder ausfüllen.</div>";
    }
}

// Alle Einträge laden
$sql = "SELECT ts.*, k.vorname, k.nachname
        FROM transponder_schluessel ts
        LEFT JOIN kameraden k ON ts.spindnr = k.spindnr
        ORDER BY ts.spindnr ASC, ts.typ DESC";
$result = $conn->query($sql);
?>

<div class="container my-5">
    <h2 class="mb-4">🔑 Transponder- & Schlüsselverwaltung</h2>

    <form method="post" class="row g-3 mb-4">
        <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
        <div class="col-md-2">
            <input type="text" name="spindnr" class="form-control" placeholder="Spindnummer" value="<?= htmlspecialchars($editData['spindnr'] ?? '') ?>" required>
        </div>
        <div class="col-md-2">
            <select name="typ" class="form-select" required>
                <option value="">Typ wählen</option>
                <option value="Schlüssel" <?= (isset($editData['typ']) && $editData['typ'] === 'Schlüssel') ? 'selected' : '' ?>>Schlüssel</option>
                <option value="Transponder" <?= (isset($editData['typ']) && $editData['typ'] === 'Transponder') ? 'selected' : '' ?>>Transponder</option>
            </select>
        </div>
        <div class="col-md-3">
            <input type="text" name="nummer" class="form-control" placeholder="Nummer / Kennung" value="<?= htmlspecialchars($editData['nummer'] ?? '') ?>" required>
        </div>
        <div class="col-md-3">
            <input type="text" name="kommentar" class="form-control" placeholder="Kommentar (optional)" value="<?= htmlspecialchars($editData['kommentar'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <button type="submit" name="save" class="btn btn-<?= $editData ? 'warning' : 'primary' ?> w-100">
                <?= $editData ? '✏️ Aktualisieren' : '➕ Speichern' ?>
            </button>
        </div>
    </form>

    <?php if ($result && $result->num_rows > 0): ?>
    <div class="table-responsive">
        <table class="table table-bordered align-middle">
            <thead class="table-dark">
                <tr>
                    <th>Spindnr</th>
                    <th>Name</th>
                    <th>Typ</th>
                    <th>Nummer</th>
                    <th>Kommentar</th>
                    <th>Erfasst am</th>
                    <th style="width: 120px;"></th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($row['spindnr']) ?></td>
                    <td><?= htmlspecialchars($row['vorname'] . ' ' . $row['nachname']) ?></td>
                    <td><?= htmlspecialchars($row['typ']) ?></td>
                    <td><?= htmlspecialchars($row['nummer']) ?></td>
                    <td><?= htmlspecialchars($row['kommentar']) ?></td>
                    <td><?= htmlspecialchars($row['erstellt_am']) ?></td>
                    <td>
                        <a href="?edit=<?= $row['id'] ?>" class="btn btn-sm btn-warning">✏️</a>
                        <a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Wirklich löschen?')" class="btn btn-sm btn-danger">🗑️</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <p class="text-muted">Noch keine Transponder oder Schlüssel erfasst.</p>
    <?php endif; ?>
</div>

<?php include 'includes/footer.php'; ob_end_flush();  ?>
