<?php
// lager_historie.php – Historie je Artikel (auf eigene Einheit begrenzt)
ob_start();
session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';

$id = (int)($_GET['id'] ?? 0);
$meldung = '';

if ($id <= 0 || $user_einheit === '') {
    echo "<div class='container my-5'><div class='alert alert-danger'>Ungültiger Aufruf.</div></div>";
    include 'includes/footer.php'; ob_end_flush(); exit;
}

/* ------------------ Artikel der eigenen Einheit laden ------------------ */
$stmt = $conn->prepare("SELECT * FROM lager_bestand WHERE id = ? AND einheit = ?");
$stmt->bind_param("is", $id, $user_einheit);
$stmt->execute();
$artikel = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

/* ------------------ KPIs zur Historie (Zugänge/Abgänge/Saldo) ------------------ */
$kpiStmt = $conn->prepare("
    SELECT
      COALESCE(SUM(CASE WHEN buchungstyp='Zugang' THEN anzahl END),0) AS zugang,
      COALESCE(SUM(CASE WHEN buchungstyp='Abgang' THEN anzahl END),0) AS abgang,
      MAX(datum) AS letzte_bewegung
    FROM lager_historie
    WHERE lager_id = ?
");
$kpiStmt->bind_param("i", $id);
$kpiStmt->execute();
$kpis = $kpiStmt->get_result()->fetch_assoc() ?: ['zugang'=>0,'abgang'=>0,'letzte_bewegung'=>null];
$kpiStmt->close();

$saldo = (int)$kpis['zugang'] - (int)$kpis['abgang'];

/* ------------------ Historie laden ------------------ */
$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();
$stmt_hist->close();

/* ------------------ Helper ------------------ */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<style>
  .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
  .kpi-val{font-size:1.4rem;font-weight:700}
  .kpi-sub{font-size:.9rem;color:#6c757d}
  .text-mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono","Courier New", monospace;}
</style>

<div class="container my-5">
  <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
    <a href="lager.php" class="btn btn-secondary">&laquo; Zurück</a>
    <div class="d-flex gap-2">
      <!-- HINWEIS: In export_historie.php bitte ebenfalls die Einheitsprüfung machen! -->
      <a href="export_historie.php?id=<?= (int)$id ?>" class="btn btn-success">📥 Exportieren (CSV)</a>
    </div>
  </div>

  <h2 class="mb-2">Buchungshistorie</h2>
  <div class="text-muted mb-3">
    Einheit: <span class="badge text-bg-secondary"><?= h($user_einheit) ?></span>
  </div>

  <!-- Artikel-Header -->
  <div class="card shadow-sm mb-4">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-12">
          <div class="d-flex flex-wrap align-items-center gap-3">
            <div>
              <div class="text-muted small">Artikelnummer</div>
              <div class="fw-semibold text-mono"><?= h($artikel['artikelnummer']) ?></div>
            </div>
            <div class="vr d-none d-md-block"></div>
            <div>
              <div class="text-muted small">Name</div>
              <div class="fw-semibold"><?= h($artikel['artikelname']) ?></div>
            </div>
            <div class="vr d-none d-md-block"></div>
            <div>
              <div class="text-muted small">Kategorie</div>
              <div class="fw-semibold"><?= h($artikel['kategorie'] ?: '–') ?></div>
            </div>
            <div class="vr d-none d-md-block"></div>
            <div>
              <div class="text-muted small">Größe</div>
              <div class="fw-semibold"><?= h($artikel['groesse'] ?: '–') ?></div>
            </div>
            <div class="ms-auto">
              <div class="text-muted small">Aktueller Bestand</div>
              <div class="fw-semibold"><?= (int)$artikel['bestand'] ?> <span class="text-muted">/ Min: <?= (int)$artikel['mindesbestand'] ?></span></div>
            </div>
          </div>
        </div>
      </div>

      <!-- KPIs -->
      <div class="row g-3 mt-2">
        <div class="col-6 col-md-3">
          <div class="kpi-card">
            <div class="kpi-sub">Zugänge (Σ)</div>
            <div class="kpi-val"><?= (int)$kpis['zugang'] ?></div>
          </div>
        </div>
        <div class="col-6 col-md-3">
          <div class="kpi-card">
            <div class="kpi-sub">Abgänge (Σ)</div>
            <div class="kpi-val"><?= (int)$kpis['abgang'] ?></div>
          </div>
        </div>
        <div class="col-6 col-md-3">
          <div class="kpi-card">
            <div class="kpi-sub">Saldo (Z - A)</div>
            <div class="kpi-val"><?= (int)$saldo ?></div>
          </div>
        </div>
        <div class="col-6 col-md-3">
          <div class="kpi-card">
            <div class="kpi-sub">Letzte Bewegung</div>
            <div class="kpi-val">
              <?= $kpis['letzte_bewegung'] ? date('d.m.Y H:i', strtotime($kpis['letzte_bewegung'])) : '–' ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <?php if ($historie->num_rows > 0): ?>
    <div class="card shadow-sm">
      <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th style="width:160px;">Datum</th>
              <th style="width:140px;">Buchungstyp</th>
              <th style="width:120px;" class="text-end">Anzahl</th>
              <th>Kamerad</th>
              <th>Bemerkung</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($row = $historie->fetch_assoc()): ?>
              <?php
                $isZugang = ($row['buchungstyp'] === 'Zugang');
                $badge = $isZugang
                    ? '<span class="badge bg-success">Zugang (+)</span>'
                    : '<span class="badge bg-danger">Abgang (−)</span>';
              ?>
              <tr>
                <td><?= date('d.m.Y H:i', strtotime($row['datum'])) ?></td>
                <td><?= $badge ?></td>
                <td class="text-end fw-semibold"><?= (int)$row['anzahl'] ?></td>
                <td>
                  <?php if (!empty($row['vorname']) || !empty($row['nachname'])): ?>
                    <?= h(trim(($row['vorname'] ?? '') . ' ' . ($row['nachname'] ?? ''))) ?>
                  <?php else: ?>
                    <span class="text-muted">–</span>
                  <?php endif; ?>
                </td>
                <td style="white-space: pre-wrap;"><?= nl2br(h($row['bemerkung'] ?? '')) ?></td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php else: ?>
    <div class="alert alert-info">Keine Buchungen vorhanden.</div>
  <?php endif; ?>
</div>

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