<?php
// geraete.php – Geräteübersicht (Modern UI Redesign)
ob_start();
session_start();

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

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

// --- Flash aus Session ziehen ---
$fehler   = $_SESSION['geraet_fehler']   ?? null;
$success  = $_SESSION['geraet_success']  ?? null;
$formdata = $_SESSION['geraet_formdata'] ?? [];
unset($_SESSION['geraet_fehler'], $_SESSION['geraet_success'], $_SESSION['geraet_formdata']);

// --- Session-Werte ---
$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$barcode_car  = $_GET['c'] ?? '';

// --- CSRF Token ---
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(16));
}
$CSRF = $_SESSION['csrf'];

// --- POST: Gerät aussondern ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'aussondern') {
    if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
        $_SESSION['geraet_fehler'] = 'Sicherheitsprüfung fehlgeschlagen.';
        header("Location: " . strtok($_SERVER["REQUEST_URI"],'?') . (!empty($barcode_car) ? '?c='.urlencode($barcode_car) : ''));
        exit;
    }

    $geraet_id = (int)($_POST['geraet_id'] ?? 0);

    if ($geraet_id > 0 && $user_einheit !== '') {
        $stmt = $conn->prepare("UPDATE ffw_geraete SET status = 'Ausgesondert' WHERE id = ? AND einheit = ?");
        $stmt->bind_param("is", $geraet_id, $user_einheit);
        $stmt->execute();
        $rows = $stmt->affected_rows;
        $stmt->close();

        if ($rows > 0) {
            $_SESSION['geraet_success'] = "Gerät wurde ausgesondert.";
        } else {
            $_SESSION['geraet_fehler'] = "Gerät konnte nicht ausgesondert werden.";
        }
    } else {
        $_SESSION['geraet_fehler'] = "Ungültige Anfrage.";
    }

    header("Location: " . strtok($_SERVER["REQUEST_URI"],'?') . (!empty($barcode_car) ? '?c='.urlencode($barcode_car) : ''));
    exit;
}

// --- Daten vorbereiten ---
$einheiten = $conn->query("SELECT DISTINCT einheit, gemeinde_id FROM users WHERE einheit != ''")->fetch_all(MYSQLI_ASSOC);

// Fahrzeuge der eigenen Einheit
$stmtFzg = $conn->prepare("SELECT barcode_fzg, fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE einheit = ? ORDER BY fahrzeugbezeichnung ASC");
$stmtFzg->bind_param("s", $user_einheit);
$stmtFzg->execute();
$fahrzeuge_result = $stmtFzg->get_result();

// Fahrzeugname
$fahrzeugname = '';
if (!empty($barcode_car)) {
    $stmtName = $conn->prepare("SELECT fahrzeugbezeichnung FROM ffw_fahrzeuge WHERE barcode_fzg = ? AND einheit = ?");
    $stmtName->bind_param("ss", $barcode_car, $user_einheit);
    $stmtName->execute();
    $resultName = $stmtName->get_result();
    if ($row = $resultName->fetch_assoc()) {
        $fahrzeugname = $row["fahrzeugbezeichnung"];
    }
    $stmtName->close();
}

// Geräte laden
$rows = [];
if (!empty($barcode_car)) {
  $stmt = $conn->prepare("SELECT * FROM ffw_geraete WHERE fahrzeug = ? AND einheit = ? AND status != 'Ausgesondert' ORDER BY gr, bezeichnung");
  $stmt->bind_param("ss", $barcode_car, $user_einheit);
  $stmt->execute();
  $res = $stmt->get_result();
  while ($r = $res->fetch_assoc()) { $rows[] = $r; }
}

// Dropdown-Daten
$kategorien    = $conn->query("SELECT DISTINCT kat FROM ffw_geraete WHERE kat != '' ORDER BY kat ASC");
$geraeteraeume = $conn->query("SELECT DISTINCT gr FROM ffw_geraete WHERE gr != '' ORDER BY gr ASC");
$statuswerte   = $conn->query("SELECT DISTINCT status FROM ffw_geraete WHERE status != '' ORDER BY status ASC");

// KPI berechnen
$total = count($rows);
$frei  = 0;
$f30   = 0;
$f7    = 0;
$now   = time();

foreach ($rows as $r) {
    if (mb_strtolower((string)$r['status']) === 'frei') $frei++;

    $lpruef_ts = is_numeric($r['lpruefung'] ?? null) ? (int)$r['lpruefung'] : 0;
    $naechste  = $lpruef_ts > 0 ? strtotime('+1 year', $lpruef_ts) : 0;
    if ($naechste > 0) {
        $tage = floor(($naechste - $now) / 86400);
        if ($tage < 30) $f30++;
        if ($tage < 7)  $f7++;
    }
}

// Favoriten laden
$geraeteFav = [];
if ($total > 0) {
    $ids = array_map(fn($r)=>(int)$r['id'], $rows);
    $in  = implode(',', array_fill(0, count($ids), '?'));
    $typesFav = str_repeat('i', count($ids));
    $stmtFav = $conn->prepare("SELECT geraet_id FROM ffw_favoriten WHERE user_id = ? AND geraet_id IN ($in)");
    $stmtFav->bind_param('i'.$typesFav, $user_id, ...$ids);
    $stmtFav->execute();
    $rf = $stmtFav->get_result();
    while($f = $rf->fetch_assoc()){ $geraeteFav[(int)$f['geraet_id']] = true; }
    $stmtFav->close();
}

// --- Helper für Badges ---
function getStatusBadge($s) {
    $sLow = mb_strtolower($s);
    if(str_contains($sLow, 'frei') || str_contains($sLow, 'einsatzbereit')) return '<span class="badge bg-success-subtle text-success border border-success-subtle"><i class="bi bi-check-circle me-1"></i>'.$s.'</span>';
    if(str_contains($sLow, 'wartung') || str_contains($sLow, 'rep')) return '<span class="badge bg-warning-subtle text-warning-emphasis border border-warning-subtle"><i class="bi bi-tools me-1"></i>'.$s.'</span>';
    if(str_contains($sLow, 'defekt') || str_contains($sLow, 'fehlt')) return '<span class="badge bg-danger-subtle text-danger border border-danger-subtle"><i class="bi bi-x-circle me-1"></i>'.$s.'</span>';
    return '<span class="badge bg-light text-dark border">'.$s.'</span>';
}
?>

<style>
  /* Modern Table Styles */
  .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 tr td .text-muted { color: #94a3b8 !important; }

  /* KPI Cards */
  .kpi-card { 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-card:hover { transform: translateY(-2px); box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
  .kpi-icon { width: 42px; height: 42px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; margin-bottom: 12px; }
  .kpi-val { font-size: 1.5rem; font-weight: 700; color: #1e293b; line-height: 1; margin-bottom: 4px; }
  .kpi-sub { font-size: 0.85rem; color: #64748b; font-weight: 500; }

  /* Filter Chips */
  .filter-chip {
    border-radius: 20px;
    border: 1px solid #e2e8f0;
    padding: 0.4rem 0.8rem;
    cursor: pointer;
    user-select: none;
    font-size: 0.85rem;
    background: white;
    color: #475569;
    transition: all 0.2s;
  }
  .filter-chip:hover { background: #f1f5f9; }
  .filter-chip.active { background: #0f172a; color: white; border-color: #0f172a; }
  .filter-chip i { margin-right: 4px; }
</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-tools text-primary"></i> Geräteübersicht</h2>
      <?php if ($fahrzeugname): ?>
        <div class="text-muted">Fahrzeug: <span class="fw-semibold text-dark"><?= htmlspecialchars($fahrzeugname) ?></span></div>
      <?php else: ?>
        <div class="text-muted">Bitte ein Fahrzeug auswählen.</div>
      <?php endif; ?>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#geraeteModal">
        <i class="bi bi-plus-lg me-1"></i> Gerät hinzufügen
      </button>
    </div>
  </div>

  <?php if ($fehler): ?>
    <div class="alert alert-danger shadow-sm border-0 border-start border-4 border-danger"><?= htmlspecialchars($fehler) ?></div>
  <?php endif; ?>
  <?php if ($success): ?>
    <div class="alert alert-success shadow-sm border-0 border-start border-4 border-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <form method="get" class="card shadow-sm border-0 mb-4">
    <div class="card-body p-3 bg-light rounded">
      <div class="row g-3 align-items-center">
        <div class="col-md-6">
          <label class="form-label mb-1 small fw-bold text-uppercase text-muted">Fahrzeug wechseln</label>
          <select name="c" id="c" onchange="this.form.submit()" class="form-select border-0 shadow-sm">
            <option value="">– Bitte Fahrzeug wählen –</option>
            <?php if ($fahrzeuge_result): while ($fzg = $fahrzeuge_result->fetch_assoc()): ?>
              <option value="<?= htmlspecialchars($fzg['barcode_fzg']) ?>" <?= ($fzg['barcode_fzg'] == $barcode_car ? 'selected' : '') ?>>
                <?= htmlspecialchars($fzg['fahrzeugbezeichnung']) ?>
              </option>
            <?php endwhile; endif; ?>
          </select>
        </div>
        <div class="col-md-6 text-md-end">
          <span class="text-muted small">Aktive Einheit: <span class="badge bg-secondary-subtle text-secondary border"><?= htmlspecialchars($user_einheit) ?></span></span>
        </div>
      </div>
    </div>
  </form>

  <?php if (!empty($barcode_car)): ?>
    <div class="row g-3 mb-4">
      <div class="col-6 col-md-3">
          <div class="kpi-card">
              <div class="kpi-icon bg-primary-subtle text-primary"><i class="bi bi-box-seam"></i></div>
              <div class="kpi-val"><?= $total ?></div>
              <div class="kpi-sub">Geräte Gesamt</div>
          </div>
      </div>
      <div class="col-6 col-md-3">
          <div class="kpi-card">
              <div class="kpi-icon bg-success-subtle text-success"><i class="bi bi-check-lg"></i></div>
              <div class="kpi-val"><?= $frei ?></div>
              <div class="kpi-sub">Status "Frei"</div>
          </div>
      </div>
      <div class="col-6 col-md-3">
          <div class="kpi-card">
              <div class="kpi-icon bg-warning-subtle text-warning-emphasis"><i class="bi bi-exclamation-circle"></i></div>
              <div class="kpi-val"><?= $f30 ?></div>
              <div class="kpi-sub">Prüfung &lt; 30 Tage</div>
          </div>
      </div>
      <div class="col-6 col-md-3">
          <div class="kpi-card">
              <div class="kpi-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
              <div class="kpi-val"><?= $f7 ?></div>
              <div class="kpi-sub">Prüfung &lt; 7 Tage</div>
          </div>
      </div>
    </div>

    <div class="card shadow-sm border-0 mb-3">
      <div class="card-body p-3">
        <div class="d-flex flex-wrap align-items-center gap-3">
          <div class="input-group" style="max-width:300px">
              <span class="input-group-text bg-white border-end-0 text-muted"><i class="bi bi-search"></i></span>
              <input type="text" id="q" class="form-control border-start-0 ps-0" placeholder="Suche...">
          </div>

          <div class="vr d-none d-md-block h-100 my-1"></div>

          <div class="d-flex flex-wrap gap-2">
            <span class="filter-chip" data-filter="due:good"><i class="bi bi-check-circle text-success"></i>Prüfung OK</span>
            <span class="filter-chip" data-filter="due:warn"><i class="bi bi-exclamation-circle text-warning"></i>&lt; 30 Tage</span>
            <span class="filter-chip" data-filter="due:bad"><i class="bi bi-exclamation-triangle text-danger"></i>&lt; 7 Tage</span>
            <span class="filter-chip" data-filter="fav:yes"><i class="bi bi-star-fill text-warning"></i>Favoriten</span>
          </div>

          <div class="ms-auto">
            <button class="btn btn-link text-decoration-none text-muted small p-0" id="resetFilters">Filter löschen</button>
          </div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm border-0">
      <div class="table-responsive">
        <table class="table table-modern align-middle mb-0" id="tbl">
          <thead>
            <tr>
              <th class="ps-4">Gerätebezeichnung</th>
              <th>Barcode</th>
              <th>Raum</th>
              <th>Status</th>
              <th>Prüfungen</th>
              <th class="text-end pe-4"></th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($rows)): ?>
            <tr><td colspan="6" class="text-center text-muted py-5"><i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>Keine Geräte gefunden.</td></tr>
          <?php else: foreach ($rows as $row):
            // Logik
            $lpruef_ts = is_numeric($row['lpruefung'] ?? null) ? (int)$row['lpruefung'] : 0;
            $naechste  = $lpruef_ts > 0 ? strtotime('+1 year', $lpruef_ts) : 0;
            $tage_diff = $naechste > 0 ? floor(($naechste - time()) / 86400) : null;

            // Due Klasse (für Filter und Farbe)
            $dueCls = 'due-good'; $dateColor = 'text-success';
            if (!is_null($tage_diff)) {
              if ($tage_diff < 7)       { $dueCls = 'due-bad'; $dateColor = 'text-danger fw-bold'; }
              elseif ($tage_diff < 30)  { $dueCls = 'due-warn'; $dateColor = 'text-warning fw-bold'; }
            } else {
              $dueCls = ''; $dateColor = 'text-muted';
            }

            $is_fav = !empty($geraeteFav[(int)$row['id']]);
          ?>
            <tr data-search="<?= htmlspecialchars(strtolower(($row['bezeichnung']??'').' '.$row['barcode'].' '.$row['kat'].' '.$row['gr'].' '.$row['status'])) ?>"
                data-due="<?= $dueCls ?: 'none' ?>"
                data-fav="<?= $is_fav ? 'yes' : 'no' ?>">

              <td class="ps-4">
                <div class="d-flex align-items-center">
                    <?php if($is_fav): ?><i class="bi bi-star-fill text-warning me-2 small"></i><?php endif; ?>
                    <div>
                        <div class="fw-bold text-dark"><?= htmlspecialchars($row['bezeichnung']) ?></div>
                        <div class="small text-muted"><?= htmlspecialchars($row['kat'] ?: '—') ?></div>
                    </div>
                </div>
              </td>
              <td><span class="font-monospace bg-light border px-2 py-1 rounded small"><?= htmlspecialchars($row['barcode']) ?></span></td>
              <td><?= htmlspecialchars($row['gr'] ?: '—') ?></td>
              <td><?= getStatusBadge($row['status'] ?: '—') ?></td>
              <td>
                  <div class="small">
                      <div class="text-muted">Letzte: <?= $lpruef_ts > 0 ? date("d.m.y", $lpruef_ts) : '—' ?></div>
                      <div class="<?= $dateColor ?>">Nächste: <?= $naechste > 0 ? date("d.m.y", $naechste) : '—' ?></div>
                  </div>
              </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>
                  <ul class="dropdown-menu dropdown-menu-end border-0 shadow">
                    <form method="post" action="geraet_edit.php">
                      <input type="hidden" name="barcode" value="<?= htmlspecialchars($row['barcode']) ?>">
                      <li><button type="submit" class="dropdown-item"><i class="bi bi-pencil me-2 text-muted"></i>Bearbeiten</button></li>
                    </form>

                    <form method="post" action="favorit_toggle.php">
                      <input type="hidden" name="geraet_id" value="<?= (int)$row['id'] ?>">
                      <li><button class="dropdown-item" name="toggle_fav">
                         <?php if($is_fav): ?>
                            <i class="bi bi-star me-2 text-muted"></i>Favorit entfernen
                         <?php else: ?>
                            <i class="bi bi-star-fill me-2 text-warning"></i>Als Favorit merken
                         <?php endif; ?>
                      </button></li>
                    </form>

                    <?php if (mb_strtolower($row['status']) !== 'ausgesondert'): ?>
                      <li><hr class="dropdown-divider"></li>
                      <form method="post" onsubmit="return confirm('Soll dieses Gerät wirklich ausgesondert werden?');">
                        <input type="hidden" name="action" value="aussondern">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                        <input type="hidden" name="geraet_id" value="<?= (int)$row['id'] ?>">
                        <li><button type="submit" class="dropdown-item text-danger"><i class="bi bi-trash me-2"></i>Aussondern</button></li>
                      </form>
                    <?php endif; ?>
                  </ul>
                </div>
              </td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php else: ?>
    <div class="text-center py-5">
        <i class="bi bi-truck display-1 text-muted opacity-25"></i>
        <h4 class="mt-3 text-muted">Kein Fahrzeug ausgewählt</h4>
        <p class="text-muted">Bitte wähle oben ein Fahrzeug, um dessen Inventar zu sehen.</p>
    </div>
  <?php endif; ?>

</div>

<div class="modal fade <?= $fehler ? 'show d-block' : '' ?>" id="geraeteModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form method="post" action="geraet_add.php" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-plus-circle text-primary me-2"></i>Neues Gerät hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <?php
        $stmtFzg->execute();
        $fahrzeuge_neu = $stmtFzg->get_result();
        ?>
        <div class="row g-3">

          <div class="col-12"><h6 class="text-primary border-bottom pb-2 mb-0">Standort & Zuordnung</h6></div>

          <div class="col-md-6">
            <label class="form-label small fw-bold">Einheit</label>
            <select name="einheit" id="einheit" class="form-select" required onchange="setGemeinde(this.value)">
              <option value="">Bitte wählen</option>
              <?php foreach ($einheiten as $e): ?>
                <option value="<?= htmlspecialchars($e['einheit']) ?>" <?= ($formdata['einheit'] ?? '') === $e['einheit'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($e['einheit']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-bold">Fahrzeug</label>
            <select name="fahrzeug" class="form-select" required>
              <option value="">Bitte wählen</option>
              <?php while ($f = $fahrzeuge_neu->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($f['barcode_fzg']) ?>" <?= ($formdata['fahrzeug'] ?? '') === $f['barcode_fzg'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($f['fahrzeugbezeichnung']) ?>
                </option>
              <?php endwhile; ?>
            </select>
          </div>

          <input type="hidden" name="gemeinde" id="gemeinde" value="<?= htmlspecialchars($formdata['gemeinde'] ?? '') ?>">

          <div class="col-12 mt-4"><h6 class="text-primary border-bottom pb-2 mb-0">Gerätedetails</h6></div>

          <div class="col-md-8">
            <label class="form-label small fw-bold">Bezeichnung</label>
            <input type="text" name="bezeichnung" class="form-control" required value="<?= htmlspecialchars($formdata['bezeichnung'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label small fw-bold">Barcode</label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-qr-code"></i></span>
                <input type="text" name="barcode" id="barcode" class="form-control" required value="<?= htmlspecialchars($formdata['barcode'] ?? '') ?>">
            </div>
            <div id="barcode-feedback" class="small mt-1"></div>
          </div>

          <div class="col-md-4">
            <label class="form-label small fw-bold">Kategorie</label>
            <select name="kat" class="form-select">
              <option value="">– Wählen –</option>
              <?php if ($kategorien) while ($k = $kategorien->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($k['kat']) ?>" <?= ($formdata['kat'] ?? '') === $k['kat'] ? 'selected' : '' ?>><?= htmlspecialchars($k['kat']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label small fw-bold">Geräteraum</label>
            <select name="gr" class="form-select">
              <option value="">– Wählen –</option>
              <?php if ($geraeteraeume) while ($g = $geraeteraeume->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($g['gr']) ?>" <?= ($formdata['gr'] ?? '') === $g['gr'] ? 'selected' : '' ?>><?= htmlspecialchars($g['gr']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label small fw-bold">Status</label>
            <select name="status" class="form-select">
              <option value="">– Wählen –</option>
              <?php if ($statuswerte) while ($s = $statuswerte->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($s['status']) ?>" <?= ($formdata['status'] ?? '') === $s['status'] ? 'selected' : '' ?>><?= htmlspecialchars($s['status']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="col-md-6">
            <label class="form-label small fw-bold">Letzte Prüfung</label>
            <input type="date" name="lpruefung" class="form-control" value="<?= htmlspecialchars($formdata['lpruefung'] ?? '') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-bold">Baujahr</label>
            <input type="number" name="baujahr" class="form-control" min="1900" max="<?= date('Y') ?>" value="<?= htmlspecialchars($formdata['baujahr'] ?? '') ?>">
          </div>

        </div>
      </div>
      <div class="modal-footer bg-light">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
        <button type="submit" class="btn btn-success px-4" id="submitBtn">Speichern</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const einheitZuGemeinde = <?= json_encode(array_column($einheiten, 'gemeinde_id', 'einheit'), JSON_UNESCAPED_UNICODE) ?>;
function setGemeinde(einheit) {
  document.getElementById('gemeinde').value = einheitZuGemeinde[einheit] ?? '';
}

document.addEventListener("DOMContentLoaded", function () {
  // Barcode Livecheck
  const barcodeInput = document.getElementById('barcode');
  const einheitSelect = document.getElementById('einheit');
  const feedback = document.getElementById('barcode-feedback');
  const submitBtn = document.getElementById('submitBtn');

  async function checkBarcode() {
    if (!barcodeInput || !einheitSelect) return;
    const barcode = barcodeInput.value.trim();
    const einheit = einheitSelect.value;

    if (!barcode || !einheit) {
      feedback.textContent = '';
      feedback.className = 'small mt-1';
      if (submitBtn) submitBtn.disabled = false;
      return;
    }
    try {
      const res = await fetch(`ajax_check_barcode.php?barcode=${encodeURIComponent(barcode)}&einheit=${encodeURIComponent(einheit)}`);
      const data = await res.json();
      if (data.exists) {
        feedback.innerHTML = '<i class="bi bi-x-circle"></i> Barcode bereits vergeben';
        feedback.className = 'text-danger small mt-1 fw-bold';
        if (submitBtn) submitBtn.disabled = true;
      } else {
        feedback.innerHTML = '<i class="bi bi-check-circle"></i> Verfügbar';
        feedback.className = 'text-success small mt-1 fw-bold';
        if (submitBtn) submitBtn.disabled = false;
      }
    } catch (err) {
      feedback.textContent = '';
      if (submitBtn) submitBtn.disabled = false;
    }
  }
  if (barcodeInput) barcodeInput.addEventListener('input', checkBarcode);
  if (einheitSelect) einheitSelect.addEventListener('change', checkBarcode);

  // Client-Filter / Suche
  const q = document.getElementById('q');
  const chips = document.querySelectorAll('.filter-chip');
  const reset = document.getElementById('resetFilters');
  const rows = Array.from(document.querySelectorAll('#tbl tbody tr'));

  function applyFilters() {
    const text = (q.value || '').trim().toLowerCase();
    const active = Array.from(chips).filter(c => c.classList.contains('active')).map(c => c.dataset.filter);

    rows.forEach(tr => {
      const s = tr.dataset.search || '';
      const due = tr.dataset.due || 'none';
      const fav = tr.dataset.fav || 'no';

      let ok = true;
      if (text) ok = ok && s.includes(text);

      for (const f of active) {
        if (f.startsWith('due:')) {
          const want = f.split(':')[1];
          ok = ok && (due === want);
        }
        if (f === 'fav:yes') ok = ok && (fav === 'yes');
      }

      tr.style.display = ok ? '' : 'none';
    });
  }

  chips.forEach(c => c.addEventListener('click', () => { c.classList.toggle('active'); applyFilters(); }));
  if (q) q.addEventListener('input', applyFilters);
  if (reset) reset.addEventListener('click', (e) => {
    e.preventDefault();
    q.value = '';
    chips.forEach(c => c.classList.remove('active'));
    applyFilters();
  });
});
</script>
