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

// Artikel abrufen
$id = (int)($_GET['id'] ?? 0);

$stmt = $conn->prepare("SELECT * FROM lager_bestand WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$artikel = $stmt->get_result()->fetch_assoc();

if (!$artikel) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Artikel nicht gefunden.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Historie abrufen
$stmt_hist = $conn->prepare("SELECT h.*, k.vorname, k.nachname FROM lager_historie h
LEFT JOIN kameraden k ON h.kamerad_id = k.id
WHERE h.lager_id = ?
ORDER BY h.datum DESC");
$stmt_hist->bind_param("i", $id);
$stmt_hist->execute();
$historie = $stmt_hist->get_result();
?>

<div class="container my-5">
  <div class="d-flex justify-content-between mb-4">
    <a href="lager.php" class="btn btn-secondary">&laquo; Zurück</a>

    <a href="export_historie.php?id=<?= $id ?>" class="btn btn-success">
      📥 Exportieren (CSV)
    </a>
  </div>
  <h2 class="mb-4">Buchungshistorie für: <?= htmlspecialchars($artikel['artikelname']) ?></h2>

  <?php if ($historie->num_rows > 0): ?>
    <div class="table-responsive">
      <table class="table table-bordered table-hover bg-white align-middle">
        <thead class="table-dark">
          <tr>
            <th>Datum</th>
            <th>Buchungstyp</th>
            <th>Anzahl</th>
            <th>Kamerad</th>
            <th>Bemerkung</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($row = $historie->fetch_assoc()): ?>
            <tr class="<?= $row['buchungstyp'] == 'Zugang' ? 'table-success' : 'table-danger' ?>">
              <td><?= date('d.m.Y H:i', strtotime($row['datum'])) ?></td>
              <td><?= htmlspecialchars($row['buchungstyp']) ?></td>
              <td><?= $row['anzahl'] ?></td>
              <td>
                <?= $row['vorname'] && $row['nachname'] ? htmlspecialchars($row['vorname'] . ' ' . $row['nachname']) : '-' ?>
              </td>
              <td><?= nl2br(htmlspecialchars($row['bemerkung'])) ?></td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  <?php else: ?>
    <div class="alert alert-info">Keine Buchungen vorhanden.</div>
  <?php endif; ?>
</div>


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