<?php
// lager.php – Lagerverwaltung (Listenansicht / Modern Table UI)
ob_start();
session_start();

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

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

$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$user_rechte  = (int)($_SESSION['is_admin'] ?? 0); // 0=Standard, >=1 darf löschen

if ($user_einheit === '') {
  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;
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function bind_params(mysqli_stmt $stmt, string $types, array &$params){ $a = [$types]; foreach($params as $k=>$_){ $a[] = &$params[$k]; } call_user_func_array([$stmt, 'bind_param'], $a); }

$meldung = '';

// ---------- Artikel löschen (nur eigene Einheit + Rechte) ----------
if (isset($_GET['delete']) && is_numeric($_GET['delete']) && $user_rechte >= 1) {
  $delId = (int)$_GET['delete'];
  $st = $conn->prepare("DELETE FROM lager_bestand WHERE id = ? AND einheit = ?");
  $st->bind_param("is", $delId, $user_einheit);
  if ($st->execute() && $st->affected_rows > 0) {
    $meldung = "<div class='alert alert-success alert-dismissible fade show'>🗑️ Artikel wurde gelöscht.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
  } else {
    $meldung = "<div class='alert alert-danger alert-dismissible fade show'>❌ Fehler beim Löschen oder keine Berechtigung.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
  }
}

// ---------- Artikelnummer-Generator (pro Einheit fortlaufend) ----------
function generiere_artikelnummer(string $kategorie, mysqli $conn, string $einheit): string {
  $prefix_map = [
    'PSA-Einsatzjacke' => 'PSA','PSA-Einsatzhose' => 'PSA','PSA-Einsatzhose AGT' => 'PSA',
    'PSA-Handschuhe' => 'PSA','PSA-Helmlampe' => 'PSA','PSA-Helm' => 'PSA','PSA-Stiefel' => 'PSA',
    'Dienstbekleidung' => 'DB','Uniform' => 'UNI','Diverse' => 'DIV'
  ];
  $prefix = $prefix_map[$kategorie] ?? 'ART';
  $q = $conn->prepare("SELECT COUNT(*) anzahl FROM lager_bestand WHERE artikelnummer LIKE CONCAT(?, '-%') AND einheit = ?");
  $q->bind_param("ss", $prefix, $einheit);
  $q->execute();
  $n = (int)($q->get_result()->fetch_assoc()['anzahl'] ?? 0);
  return $prefix . '-' . str_pad($n + 1, 4, '0', STR_PAD_LEFT);
}

// ---------- Artikel speichern ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['artikel_speichern'])) {
  $kat = trim($_POST['kategorie'] ?? '');
  $artikelnummer = generiere_artikelnummer($kat, $conn, $user_einheit);

  $st = $conn->prepare("INSERT INTO lager_bestand
    (artikelnummer, artikelname, kategorie, groesse, bestand, mindesbestand, einheit)
    VALUES (?,?,?,?,?,?,?)");
  $st->bind_param(
    "ssssiss",
    $artikelnummer,
    $_POST['artikelname'],
    $kat,
    $_POST['groesse'],
    $_POST['bestand'],
    $_POST['mindesbestand'],
    $user_einheit
  );
  $meldung = $st->execute()
    ? "<div class='alert alert-success alert-dismissible fade show'>✅ Artikel wurde erfolgreich gespeichert.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>"
    : "<div class='alert alert-danger alert-dismissible fade show'>❌ Fehler beim Speichern.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
}

// ---------- Artikel bearbeiten (Update) ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['artikel_update'])) {
  $id      = (int)($_POST['id'] ?? 0);
  $name    = trim($_POST['artikelname_edit'] ?? '');
  $kategorie = trim($_POST['kategorie_edit'] ?? '');
  $groesse = trim($_POST['groesse_edit'] ?? '');
  $bestand = (int)($_POST['bestand_edit'] ?? 0);
  $minbest = (int)($_POST['mindesbestand_edit'] ?? 0);

  if ($id > 0 && $name !== '' && $kategorie !== '') {
    $st = $conn->prepare("UPDATE lager_bestand
                          SET artikelname = ?, kategorie = ?, groesse = ?, bestand = ?, mindesbestand = ?
                          WHERE id = ? AND einheit = ?");
    $st->bind_param("sssiiis", $name, $kategorie, $groesse, $bestand, $minbest, $id, $user_einheit);
    if ($st->execute() && $st->affected_rows >= 0) {
      $meldung = "<div class='alert alert-success alert-dismissible fade show'>💾 Änderungen gespeichert.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    } else {
      $meldung = "<div class='alert alert-warning alert-dismissible fade show'>ℹ️ Keine Änderungen oder Fehler beim Speichern.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    }
  } else {
    $meldung = "<div class='alert alert-danger alert-dismissible fade show'>❌ Bitte Name und Kategorie ausfüllen.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
  }
}

// ---------- Filter ----------
$search     = trim($_GET['search'] ?? '');
$f_kat      = trim($_GET['kategorie'] ?? '');
$f_underMin = isset($_GET['unter_min']) ? (int)$_GET['unter_min'] : 0; // 1 = nur Mindestbestand unterschritten

// Kategorien (nur eigene Einheit)
$katList = [];
$stK = $conn->prepare("SELECT kategorie, COUNT(*) cnt FROM lager_bestand WHERE einheit = ? GROUP BY kategorie ORDER BY kategorie");
$stK->bind_param("s", $user_einheit);
$stK->execute();
$rK = $stK->get_result();
while($row = $rK->fetch_assoc()){ $katList[] = $row; }

// Dynamic WHERE
$where  = "einheit = ?";
$types  = "s";
$params = [$user_einheit];

if ($search !== '') {
  $like = '%'.$search.'%';
  $where .= " AND (artikelname LIKE ? OR artikelnummer LIKE ? OR kategorie LIKE ? OR groesse LIKE ?)";
  for($i=0;$i<4;$i++){ $params[] = $like; $types .= 's'; }
}
if ($f_kat !== '') {
  $where .= " AND kategorie = ?";
  $params[] = $f_kat; $types .= 's';
}
if ($f_underMin === 1) {
  $where .= " AND bestand <= mindesbestand";
}

// ---------- CSV-Export (respektiert Filter) ----------
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
  $fn = 'lager_export_' . date('Y-m-d') . '.csv';
  header('Content-Type: text/csv; charset=utf-8');
  header("Content-Disposition: attachment; filename=\"$fn\"");
  $out = fopen('php://output','w');
  fputcsv($out, ['Artikelnummer','Name','Kategorie','Größe','Bestand','Mindestbestand','Einheit']);

  $sqlE = "SELECT artikelnummer, artikelname, kategorie, groesse, bestand, mindesbestand, einheit
           FROM lager_bestand WHERE $where ORDER BY kategorie, artikelname";
  $stE = $conn->prepare($sqlE); bind_params($stE, $types, $params);
  $stE->execute();
  $resE = $stE->get_result();
  while($r=$resE->fetch_assoc()){
    fputcsv($out, [
      $r['artikelnummer'],$r['artikelname'],$r['kategorie'],$r['groesse'],
      (int)$r['bestand'], (int)$r['mindesbestand'], $r['einheit']
    ]);
  }
  fclose($out); exit;
}

// ---------- KPIs ----------
$sqlKpi = "SELECT
             COUNT(*) AS items,
             COALESCE(SUM(bestand),0) AS stk,
             SUM(CASE WHEN bestand <= mindesbestand THEN 1 ELSE 0 END) AS unter_min
           FROM lager_bestand WHERE $where";
$stKpi = $conn->prepare($sqlKpi); bind_params($stKpi, $types, $params); $stKpi->execute();
$K = $stKpi->get_result()->fetch_assoc() ?: ['items'=>0,'stk'=>0,'unter_min'=>0];

$sqlCatCnt = "SELECT COUNT(DISTINCT kategorie) AS cats FROM lager_bestand WHERE $where";
$stCC = $conn->prepare($sqlCatCnt); bind_params($stCC, $types, $params); $stCC->execute();
$C = $stCC->get_result()->fetch_assoc() ?: ['cats'=>0];

// ---------- Artikelliste (rollenabhängig wie vorher) ----------
$whereList  = $where;
$typesList  = $types;
$paramsList = $params;

if ($user_rechte == 2) { // PSA-Viewer
  $whereList .= " AND kategorie LIKE 'PSA%'";
}
if ($user_rechte == 3) { // Dienstbekleidung/Uniform-Viewer
  $whereList .= " AND kategorie IN ('Dienstbekleidung','Uniform')";
}

$sqlList = "SELECT * FROM lager_bestand WHERE $whereList ORDER BY kategorie, artikelname";
$stList = $conn->prepare($sqlList); bind_params($stList, $typesList, $paramsList); $stList->execute();
$artikel = $stList->get_result();
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<style>
  /* KPI Cards Styling */
  .kpi-card-modern {
      border: none; border-radius: 12px; padding: 16px;
      background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.05); height: 100%;
      transition: transform 0.2s;
  }
  .kpi-val{font-size:1.5rem;font-weight:700; color: #1e293b;}
  .kpi-sub{font-size:.85rem;color:#6c757d; font-weight: 500;}
  .kpi-icon { width: 42px; height: 42px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; margin-bottom: 12px; }

  /* Filter Toolbar Styling */
  .toolbar .btn, .toolbar .form-control, .toolbar .form-select{ height:38px; font-size:0.9rem; }
  .toolbar .form-control { max-width: 300px; }
  .tab-badge{font-size:.75rem}
  .text-mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;}

  /* Modern Table Styling (Konstant dunkel und lesbar) */
  .table-modern th { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; background: #f8fafc; font-weight: 600; border-bottom: 2px solid #e2e8f0; }
  .table-modern td { vertical-align: middle; border-bottom: 1px solid #f1f5f9; padding: 12px 16px; color: #1e293b; }
  .table-modern tr:hover { background-color: #f8fafc; }
  .table-modern .text-muted { color: #94a3b8 !important; }

  /* Tabs (Fix: Schriftfarbe dunkel, wie gewünscht) */
  .nav-pills .nav-link {
      color: #334155 !important;
      font-weight: 500;
      border-radius: 6px;
      padding: 0.6rem 1rem;
      border: 1px solid transparent;
      transition: background-color 0.2s; /* Für fließenden Übergang */
  }
  .nav-pills .nav-link.active {
      background-color: #e2e8f0 !important;
      color: #000000 !important;
      font-weight: 700;
      border: 1px solid #cbd5e1;
  }
  .nav-pills .nav-link:hover:not(.active) {
      background-color: #f1f5f9;
  }
  .nav-pills .nav-link .badge {
      background-color: #94a3b8 !important;
      color: white !important;
  }
  .nav-pills .nav-link.active .badge {
      background-color: #0d6efd !important;
  }

</style>

<div class="container my-5">
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-3 mb-4">
    <div>
      <h2 class="fw-bold mb-1"><i class="bi bi-box-seam-fill text-primary me-2"></i> Lagerverwaltung</h2>
      <div class="text-muted">Einheit: <span class="badge bg-secondary-subtle text-secondary border"><?= h($user_einheit) ?></span></div>
    </div>
    <div class="toolbar d-flex flex-wrap gap-2">
      <form method="get" class="d-flex flex-wrap gap-2">
        <input type="text" name="search" class="form-control" placeholder="🔍 Suche: Name/Nummer/Kategorie/Größe" value="<?= h($search) ?>">
        <select name="kategorie" class="form-select">
          <option value="">Alle Kategorien</option>
          <?php foreach($katList as $k): ?>
            <option value="<?= h($k['kategorie']) ?>" <?= $f_kat===$k['kategorie']?'selected':'' ?>>
              <?= h($k['kategorie']) ?>
            </option>
          <?php endforeach; ?>
        </select>
        <div class="form-check align-self-center ps-4">
          <input class="form-check-input" type="checkbox" name="unter_min" value="1" id="unterMinCheck" <?= $f_underMin ? 'checked':'' ?>>
          <label class="form-check-label small text-muted" for="unterMinCheck">nur Mindestbestand unterschritten</label>
        </div>
        <button class="btn btn-primary shadow-sm"><i class="bi bi-funnel"></i> Anwenden</button>
        <?php if ($search!=='' || $f_kat!=='' || $f_underMin): ?>
          <a href="lager.php" class="btn btn-outline-secondary" title="Filter zurücksetzen"><i class="bi bi-x-lg"></i></a>
        <?php endif; ?>
        <a href="?export=csv&<?= http_build_query(['search'=>$search,'kategorie'=>$f_kat,'unter_min'=>$f_underMin]) ?>" class="btn btn-outline-secondary">
            <i class="bi bi-download"></i> CSV
        </a>
      </form>
      <button class="btn btn-success shadow-sm" data-bs-toggle="modal" data-bs-target="#artikelModal">
          <i class="bi bi-plus-lg"></i> Artikel hinzufügen
      </button>
    </div>
  </div>

  <?= $meldung ?>

  <div class="row g-3 mt-1 mb-4">
    <div class="col-6 col-md-3">
        <div class="kpi-card-modern d-flex flex-column align-items-start">
            <div class="kpi-icon bg-primary-subtle text-primary"><i class="bi bi-tags-fill"></i></div>
            <div class="kpi-val"><?= (int)$K['items'] ?></div>
            <div class="kpi-sub">Artikel (Typen)</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="kpi-card-modern d-flex flex-column align-items-start">
            <div class="kpi-icon bg-success-subtle text-success"><i class="bi bi-box-fill"></i></div>
            <div class="kpi-val"><?= (int)$K['stk'] ?></div>
            <div class="kpi-sub">Gesamtbestand (Stk.)</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="kpi-card-modern d-flex flex-column align-items-start">
            <div class="kpi-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle-fill"></i></div>
            <div class="kpi-val"><?= (int)$K['unter_min'] ?></div>
            <div class="kpi-sub">Mindestbestand!</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="kpi-card-modern d-flex flex-column align-items-start">
            <div class="kpi-icon bg-info-subtle text-info"><i class="bi bi-list-nested"></i></div>
            <div class="kpi-val"><?= (int)$C['cats'] ?></div>
            <div class="kpi-sub">Kategorien</div>
        </div>
    </div>
  </div>

  <ul class="nav nav-pills mb-3 border-bottom pb-2" role="tablist">
    <?php
      $sumCnt = 0; foreach($katList as $x){ $sumCnt += (int)$x['cnt']; }
      $queryAll = http_build_query(['search'=>$search,'kategorie'=>'','unter_min'=>$f_underMin]);
    ?>
    <li class="nav-item me-2" role="presentation">
      <a class="nav-link <?= $f_kat===''?'active':'' ?>" href="?<?= $queryAll ?>">Alle Artikel
        <span class="badge rounded-pill tab-badge"><?= $sumCnt ?></span>
      </a>
    </li>
    <?php foreach($katList as $k): ?>
      <li class="nav-item me-2" role="presentation">
        <a class="nav-link <?= $f_kat===$k['kategorie']?'active':'' ?>"
           href="?<?= http_build_query(['search'=>$search,'kategorie'=>$k['kategorie'],'unter_min'=>$f_underMin]) ?>">
          <?= h($k['kategorie']) ?>
          <span class="badge rounded-pill tab-badge"><?= (int)$k['cnt'] ?></span>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>

  <div class="card shadow-sm border-0">
    <div class="table-responsive">
      <table class="table table-modern align-middle mb-0">
        <thead>
          <tr>
            <th class="ps-4">Artikel</th>
            <th>Artikelnummer</th>
            <th>Kategorie</th>
            <th>Größe</th>
            <th class="text-end">Bestand</th>
            <th class="text-end">Min. Bestand</th>
            <th class="text-end pe-4" style="width: 80px;"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($artikel->num_rows === 0): ?>
            <tr>
                <td colspan="7" class="text-center py-5">
                    <i class="bi bi-box-fill fs-1 opacity-25 text-muted"></i>
                    <p class="mt-3 mb-0">Keine Lagerartikel gefunden, die den Filtern entsprechen.</p>
                </td>
            </tr>
          <?php else: while($row = $artikel->fetch_assoc()):
            $warn = ((int)$row['bestand'] <= (int)$row['mindestbestand']);
          ?>
            <tr class="<?= $warn ? 'table-warning bg-opacity-25' : '' ?>">
              <td class="ps-4">
                <div class="fw-bold <?= $warn ? 'text-danger' : 'text-dark' ?>"><?= h($row['artikelname']) ?></div>
                <?php if ($warn): ?><span class="badge bg-danger-subtle text-danger">Muss nachbestellt werden!</span><?php endif; ?>
              </td>
              <td class="text-mono small text-muted"><?= h($row['artikelnummer']) ?></td>
              <td><?= h($row['kategorie']) ?></td>
              <td><span class="badge bg-light text-dark border"><?= h($row['groesse']) ?: '—' ?></span></td>
              <td class="text-end fw-bold fs-6 <?= $warn ? 'text-danger' : 'text-success' ?>"><?= (int)$row['bestand'] ?></td>
              <td class="text-end text-muted"><?= (int)$row['mindesbestand'] ?></td>
              <td class="text-end pe-4">
                <div class="dropdown">
                  <button class="btn btn-sm btn-light rounded-circle shadow-sm" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-three-dots-vertical"></i>
                  </button>
                  <div class="dropdown-menu dropdown-menu-end shadow">
                    <a class="dropdown-item"
                       href="#"
                       data-bs-toggle="modal"
                       data-bs-target="#editModal"
                       data-id="<?= (int)$row['id'] ?>"
                       data-name="<?= h($row['artikelname']) ?>"
                       data-kat="<?= h($row['kategorie']) ?>"
                       data-groesse="<?= h($row['groesse']) ?>"
                       data-bestand="<?= (int)$row['bestand'] ?>"
                       data-min="<?= (int)$row['mindesbestand'] ?>">
                        <i class="bi bi-pencil me-2"></i> Bearbeiten
                    </a>
                    <a class="dropdown-item" href="lager_buchung.php?id=<?= (int)$row['id'] ?>"><i class="bi bi-arrow-left-right me-2"></i> Buchen</a>
                    <a class="dropdown-item" href="lager_historie.php?id=<?= (int)$row['id'] ?>"><i class="bi bi-clock-history me-2"></i> Historie</a>
                    <a class="dropdown-item" href="bestellwesen.php?artikel_id=<?= (int)$row['id'] ?>"><i class="bi bi-cart me-2"></i> Bestellen</a>
                    <?php if ($user_rechte >= 1): ?>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item text-danger"
                         href="?<?= http_build_query(['delete'=>(int)$row['id'],'search'=>$search,'kategorie'=>$f_kat,'unter_min'=>$f_underMin]) ?>"
                         onclick="return confirm('❗ Diesen Artikel wirklich löschen?');">
                          <i class="bi bi-trash me-2"></i> Löschen
                      </a>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
            </tr>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade" id="artikelModal" tabindex="-1" aria-labelledby="artikelModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="artikelModalLabel"><i class="bi bi-plus-circle me-2 text-success"></i> Artikel hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3"><label class="form-label">Artikelname</label><input name="artikelname" class="form-control" required></div>
        <div class="mb-3">
          <label class="form-label">Kategorie</label>
          <select name="kategorie" class="form-select" required>
            <option value="">– bitte wählen –</option>
            <option>PSA-Einsatzjacke</option>
            <option>PSA-Einsatzhose</option>
            <option>PSA-Einsatzhose AGT</option>
            <option>PSA-Handschuhe</option>
            <option>PSA-Helmlampe</option>
            <option>PSA-Helm</option>
            <option>PSA-Stiefel</option>
            <option>Dienstbekleidung</option>
            <option>Uniform</option>
            <option>Diverse</option>
          </select>
        </div>
        <div class="mb-3"><label class="form-label">Größe</label><input name="groesse" class="form-control"></div>
        <div class="row">
          <div class="col-md-6 mb-3"><label class="form-label">Bestand</label><input type="number" name="bestand" class="form-control" value="0" min="0"></div>
          <div class="col-md-6 mb-3"><label class="form-label">Mindestbestand</label><input type="number" name="mindesbestand" class="form-control" value="0" min="0"></div>
        </div>
      </div>
      <div class="modal-footer bg-light">
        <button type="submit" name="artikel_speichern" class="btn btn-primary">Speichern</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
        <a class="btn btn-outline-info" href="#" id="newArtikelBuchenLink" style="display:none;"><i class="bi bi-arrow-left-right me-2"></i> Zum Buchen</a>
      </div>
    </form>
  </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel"><i class="bi bi-pencil-square me-2 text-primary"></i> Artikel bearbeiten</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit_id">
        <div class="mb-3">
          <label class="form-label">Artikelname</label>
          <input name="artikelname_edit" id="edit_name" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Kategorie</label>
          <select name="kategorie_edit" id="edit_kategorie" class="form-select" required>
            <option value="">– bitte wählen –</option>
            <option>PSA-Einsatzjacke</option>
            <option>PSA-Einsatzhose</option>
            <option>PSA-Einsatzhose AGT</option>
            <option>PSA-Handschuhe</option>
            <option>PSA-Helmlampe</option>
            <option>PSA-Helm</option>
            <option>PSA-Stiefel</option>
            <option>Dienstbekleidung</option>
            <option>Uniform</option>
            <option>Diverse</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">Größe</label>
          <input name="groesse_edit" id="edit_groesse" class="form-control">
        </div>
        <div class="row">
          <div class="col-md-6 mb-0">
            <label class="form-label">Bestand</label>
            <input type="number" name="bestand_edit" id="edit_bestand" class="form-control" min="0">
          </div>
          <div class="col-md-6 mb-0">
            <label class="form-label">Mindestbestand</label>
            <input type="number" name="mindesbestand_edit" id="edit_min" class="form-control" min="0">
          </div>
        </div>
      </div>
      <div class="modal-footer bg-light">
        <button type="submit" name="artikel_update" class="btn btn-primary">Änderungen speichern</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
        <a class="btn btn-outline-info" href="#" id="editModalBuchenLink"><i class="bi bi-arrow-left-right me-2"></i> Zum Buchen</a>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener('show.bs.modal', function (ev) {
  if (ev.target && ev.target.id === 'editModal') {
    const btn = ev.relatedTarget;
    if (!btn) return;
   
    const id      = btn.getAttribute('data-id');
    const name    = btn.getAttribute('data-name') || '';
    const kat     = btn.getAttribute('data-kat') || '';
    const groesse = btn.getAttribute('data-groesse') || '';
    const bestand = btn.getAttribute('data-bestand') || '0';
    const min     = btn.getAttribute('data-min') || '0';

    const buchenLink = ev.target.querySelector('#editModalBuchenLink');
    if (buchenLink) {
        buchenLink.href = `lager_buchung.php?id=${id}`;
    }

    document.getElementById('edit_id').value = id;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_groesse').value = groesse;
    document.getElementById('edit_bestand').value = bestand;
    document.getElementById('edit_min').value = min;

    const sel = document.getElementById('edit_kategorie');
    if (sel) {
      Array.from(sel.options).forEach(o => { o.selected = (o.value === kat); });
    }
  }
});
</script>

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