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

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

$einheit = $_SESSION['einheit'];

// Filter nach Status (optional)
$status_filter = $_GET['status'] ?? 'alle';
$where = "WHERE l.einheit = ?";
$params = [$einheit];

if (in_array($status_filter, ['offen', 'geliefert', 'storniert'])) {
    $where .= " AND l.status = ?";
    $params[] = $status_filter;
}

$sql = "
SELECT l.*, u.vorname, u.nachname, a.bezeichnung AS zielort
FROM lieferscheine l
LEFT JOIN users u ON l.erstellt_von = u.id
LEFT JOIN adressen a ON l.adresse_id = a.id
$where
ORDER BY l.erstellt_am DESC
";
$stmt = $conn->prepare($sql);
$types = str_repeat("s", count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
$ergebnisse = $stmt->get_result();
?>

<div class="container my-5">
  <h2>📋 Lieferscheine</h2>

  <form class="row g-3 mb-3" method="get">
    <div class="col-auto">
      <select name="status" class="form-select" onchange="this.form.submit()">
        <option value="alle" <?= $status_filter == 'alle' ? 'selected' : '' ?>>Alle</option>
        <option value="offen" <?= $status_filter == 'offen' ? 'selected' : '' ?>>Offen</option>
        <option value="geliefert" <?= $status_filter == 'geliefert' ? 'selected' : '' ?>>Geliefert</option>
        <option value="storniert" <?= $status_filter == 'storniert' ? 'selected' : '' ?>>Storniert</option>
      </select>
    </div>
  </form>

  <div class="table-responsive">
    <table class="table table-bordered">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Empfänger</th>
          <th>Datum</th>
          <th>Ziel</th>
          <th>Status</th>
          <th>Aktion</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($l = $ergebnisse->fetch_assoc()): ?>
          <tr>
            <td><?= $l['id'] ?></td>
            <td><?= htmlspecialchars($l['empfaenger']) ?></td>
            <td><?= date('d.m.Y', strtotime($l['lieferdatum'])) ?></td>
            <td><?= htmlspecialchars($l['zielort']) ?></td>
            <td>
              <span class="badge bg-<?=
                $l['status'] == 'offen' ? 'secondary' :
                ($l['status'] == 'geliefert' ? 'success' : 'danger') ?>">
                <?= ucfirst($l['status']) ?>
              </span>
            </td>
            <td>
              <a href="lieferschein_druck.php?id=<?= $l['id'] ?>" class="btn btn-sm btn-outline-primary" target="_blank">🖨️</a>
              <?php if ($l['status'] == 'offen'): ?>
                <a href="lieferschein_rueckmeldung.php?id=<?= $l['id'] ?>" class="btn btn-sm btn-outline-success">✅ Rückmeldung</a>
              <?php endif; ?>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

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