<?php
// lieferschein_liste.php – Übersicht (nur eigene Einheit)
session_start();
require_once __DIR__ . '/includes/db.php';

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

$einheit = $_SESSION['einheit'] ?? '';
if ($einheit === '') {
    require_once __DIR__ . '/includes/header.php';
    require_once __DIR__ . '/includes/nav.php';
    echo "<div class='container my-5'><div class='alert alert-warning'>⚠️ Keine Einheit in der Session gefunden. Bitte erneut einloggen.</div></div>";
    include 'includes/footer.php';
    exit;
}

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

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/* ------------------ Filter einlesen ------------------ */
$status_filter = $_GET['status'] ?? 'alle';                            // 'alle' | 'offen' | 'geliefert' | 'storniert'
$q             = trim($_GET['q'] ?? '');                                // Suche in Empfänger/ID
$date_from     = trim($_GET['from'] ?? '');                              // YYYY-MM-DD
$date_to       = trim($_GET['to'] ?? '');                                // YYYY-MM-DD

/* ------------------ Dynamische WHERE-Bedingung ------------------ */
$where  = "WHERE l.einheit = ?";
$types  = "s";
$params = [$einheit];

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

if ($q !== '') {
    $where  .= " AND (l.empfaenger LIKE ? OR CAST(l.id AS CHAR) LIKE ?)";
    $types  .= "ss";
    $like = "%{$q}%";
    $params[] = $like;
    $params[] = $like;
}

$df_ok = preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from);
$dt_ok = preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to);

if ($df_ok) {
    $where  .= " AND DATE(l.lieferdatum) >= ?";
    $types  .= "s";
    $params[] = $date_from;
}
if ($dt_ok) {
    $where  .= " AND DATE(l.lieferdatum) <= ?";
    $types  .= "s";
    $params[] = $date_to;
}

/* ------------------ KPI (für aktuelle Filter) ------------------ */
$sqlKpi = "
  SELECT
    COUNT(*)                                                  AS total,
    SUM(CASE WHEN l.status='offen'     THEN 1 ELSE 0 END)     AS offen,
    SUM(CASE WHEN l.status='geliefert' THEN 1 ELSE 0 END)     AS geliefert,
    SUM(CASE WHEN l.status='storniert' THEN 1 ELSE 0 END)     AS storniert
  FROM lieferscheine l
  $where
";
$stKpi = $conn->prepare($sqlKpi);
$stKpi->bind_param($types, ...$params);
$stKpi->execute();
$K = $stKpi->get_result()->fetch_assoc() ?: ['total'=>0,'offen'=>0,'geliefert'=>0,'storniert'=>0];
$stKpi->close();

/* ------------------ Liste ------------------ */
$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);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$ergebnisse = $stmt->get_result();
?>

<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}
  .toolbar .btn, .toolbar .form-control, .toolbar .form-select{ height:38px }
</style>

<div class="container my-5">
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">📋 Lieferscheine</h2>
      <div class="text-muted">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>

    <!-- Filter / Toolbar -->
    <form class="toolbar d-flex flex-wrap gap-2" method="get">
      <select name="status" class="form-select">
        <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>

      <input type="date" name="from" class="form-control" value="<?= h($df_ok?$date_from:'') ?>" placeholder="von">
      <input type="date" name="to"   class="form-control" value="<?= h($dt_ok?$date_to:'') ?>" placeholder="bis">

      <input type="text" name="q" class="form-control" placeholder="🔎 Suche: Empfänger / #ID" value="<?= h($q) ?>">

      <button class="btn btn-outline-primary">Anwenden</button>
      <?php if ($status_filter!=='alle' || $q!=='' || $df_ok || $dt_ok): ?>
        <a class="btn btn-outline-secondary" href="lieferschein_liste.php">Zurücksetzen</a>
      <?php endif; ?>
    </form>
  </div>

  <!-- KPIs -->
  <div class="row g-3 mt-1 mb-4">
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Gesamt</div><div class="kpi-val"><?= (int)$K['total'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Offen</div><div class="kpi-val"><?= (int)$K['offen'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Geliefert</div><div class="kpi-val"><?= (int)$K['geliefert'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Storniert</div><div class="kpi-val"><?= (int)$K['storniert'] ?></div></div></div>
  </div>

  <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:80px;">#</th>
            <th>Empfänger</th>
            <th style="width:120px;">Lieferdatum</th>
            <th>Ziel</th>
            <th style="width:140px;">Status</th>
            <th style="width:160px;">Erstellt von</th>
            <th style="width:140px;" class="text-end">Aktionen</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($ergebnisse->num_rows === 0): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">Keine Einträge gefunden.</td></tr>
          <?php else: while ($l = $ergebnisse->fetch_assoc()):
            $st = strtolower((string)$l['status']);
            $badge = $st==='offen' ? "secondary" : ($st==='geliefert' ? "success" : "danger");
          ?>
            <tr>
              <td class="text-monospace">#<?= (int)$l['id'] ?></td>
              <td><?= h($l['empfaenger']) ?></td>
              <td><?= $l['lieferdatum'] ? date('d.m.Y', strtotime($l['lieferdatum'])) : '—' ?></td>
              <td><?= h($l['zielort'] ?? '-') ?></td>
              <td><span class="badge bg-<?= $badge ?>"><?= h(ucfirst($l['status'])) ?></span></td>
              <td><?= h(trim(($l['vorname'] ?? '').' '.($l['nachname'] ?? ''))) ?></td>
              <td class="text-end">
                <div class="btn-group">
                  <a href="lieferschein_druck.php?id=<?= (int)$l['id'] ?>" class="btn btn-sm btn-outline-primary" target="_blank" title="Drucken / Vorschau">🖨️</a>
                  <?php if ($st==='offen'): ?>
                    <a href="lieferschein_rueckmeldung.php?id=<?= (int)$l['id'] ?>" class="btn btn-sm btn-outline-success" title="Rückmeldung erfassen">✅</a>
                  <?php else: ?>
                    <button class="btn btn-sm btn-outline-secondary" title="Keine Aktion" disabled>—</button>
                  <?php endif; ?>
                </div>
              </td>
            </tr>
          <?php endwhile; endif; $stmt->close(); ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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