<?php
// lager.php – Lagerverwaltung (clean UI im Stil von geraete.php) + Bearbeiten (Name/Kategorie/Größe/Bestand/Mindestbestand)
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'>🗑️ Artikel wurde gelöscht.</div>";
  } else {
    $meldung = "<div class='alert alert-danger'>❌ Fehler beim Löschen oder keine Berechtigung.</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'>✅ Artikel wurde erfolgreich gespeichert.</div>"
    : "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
}

// ---------- Artikel bearbeiten (Name/Kategorie/Größe/Bestand/Mindestbestand) ----------
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'>💾 Änderungen gespeichert.</div>";
    } else {
      $meldung = "<div class='alert alert-warning'>ℹ️ Keine Änderungen oder Fehler beim Speichern.</div>";
    }
  } else {
    $meldung = "<div class='alert alert-danger'>❌ Bitte Name und Kategorie ausfüllen.</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();
?>
<style>
  .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
  .kpi-val{font-size:1.6rem;font-weight:700}
  .kpi-sub{font-size:.9rem;color:#6c757d}
  .toolbar .btn, .toolbar .form-control, .toolbar .form-select{ height:38px }
  .tab-badge{font-size:.75rem}
  .text-mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;}
</style>

<div class="container my-5">
  <!-- Toolbar (wie geraete.php) -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">Lagerverwaltung</h2>
      <div class="text-muted">Einheit: <span class="badge text-bg-secondary"><?= 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">
          <input class="form-check-input" type="checkbox" name="unter_min" value="1" id="unterMinCheck" <?= $f_underMin ? 'checked':'' ?>>
          <label class="form-check-label" for="unterMinCheck">nur Mindestbestand unterschritten</label>
        </div>
        <button class="btn btn-outline-primary">Anwenden</button>
        <?php if ($search!=='' || $f_kat!=='' || $f_underMin): ?>
          <a href="lager.php" class="btn btn-outline-secondary">Zurücksetzen</a>
        <?php endif; ?>
        <a href="?export=csv&<?= http_build_query(['search'=>$search,'kategorie'=>$f_kat,'unter_min'=>$f_underMin]) ?>" class="btn btn-outline-secondary">CSV Export</a>
      </form>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#artikelModal">➕ Artikel hinzufügen</button>
    </div>
  </div>

  <?= $meldung ?>

  <!-- 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">Artikel</div><div class="kpi-val"><?= (int)$K['items'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Gesamtbestand</div><div class="kpi-val"><?= (int)$K['stk'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Unterschritten</div><div class="kpi-val"><?= (int)$K['unter_min'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Kategorien</div><div class="kpi-val"><?= (int)$C['cats'] ?></div></div></div>
  </div>

  <!-- Tabs je Kategorie (Links mit Zählern) -->
  <ul class="nav nav-tabs mb-3" 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" role="presentation">
      <a class="nav-link <?= $f_kat===''?'active':'' ?>" href="?<?= $queryAll ?>">Alle
        <span class="badge rounded-pill text-bg-light tab-badge"><?= $sumCnt ?></span>
      </a>
    </li>
    <?php foreach($katList as $k): ?>
      <li class="nav-item" 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 text-bg-light tab-badge"><?= (int)$k['cnt'] ?></span>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>

  <!-- Tabelle (Dropdown-Menü wie in geraete.php) -->
  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Artikelnummer</th>
            <th>Name</th>
            <th>Kategorie</th>
            <th>Größe</th>
            <th class="text-end">Bestand</th>
            <th class="text-end" style="width:60px;"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($artikel->num_rows === 0): ?>
            <tr><td colspan="6" class="text-center text-muted py-4">Keine Einträge gefunden.</td></tr>
          <?php else: while($row = $artikel->fetch_assoc()):
            $warn = ((int)$row['bestand'] <= (int)$row['mindesbestand']);
          ?>
            <tr class="<?= $warn ? 'table-danger' : '' ?>">
              <td class="text-mono"><?= h($row['artikelnummer']) ?></td>
              <td>
                <div class="fw-semibold"><?= h($row['artikelname']) ?></div>
                <div class="text-muted small">Min: <?= (int)$row['mindesbestand'] ?></div>
              </td>
              <td><?= h($row['kategorie']) ?></td>
              <td><?= h($row['groesse']) ?></td>
              <td class="text-end">
                <?= (int)$row['bestand'] ?>
                <?php if ($warn): ?><span class="badge bg-danger ms-2">Mindestbestand!</span><?php endif; ?>
              </td>
              <td class="text-end">
                <div class="dropdown">
                  <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Aktionen</button>
                  <div class="dropdown-menu dropdown-menu-end">
                    <!-- Bearbeiten öffnet Modal mit den Daten der Zeile -->
                    <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'] ?>"
                    >Bearbeiten</a>

                    <a class="dropdown-item" href="lager_buchung.php?id=<?= (int)$row['id'] ?>">Buchen</a>
                    <a class="dropdown-item" href="lager_historie.php?id=<?= (int)$row['id'] ?>">Historie</a>
                    <a class="dropdown-item" href="bestellwesen.php?artikel_id=<?= (int)$row['id'] ?>">🛒 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?');">Löschen</a>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
            </tr>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: Artikel hinzufügen (gleiches Pattern wie geraete.php) -->
<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">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">
        <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>
      </div>
    </form>
  </div>
</div>

<!-- Modal: Artikel bearbeiten (Name/Kategorie/Größe/Bestand/Mindestbestand) -->
<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">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">
        <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>
      </div>
    </form>
  </div>
</div>

<script>
// Füllt den Bearbeiten-Modal mit den Daten aus der Tabellenzeile
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';

    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(); ?>
