<?php
// it_assets.php – IT-Assetverwaltung (Aufbau wie lager.php)
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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);
}

/**
 * Generiert einen neuen Asset-Tag im Format "Asset-001", "Asset-002", ...
 * pro Einheit, basierend auf der höchsten vorhandenen Nummer.
 */
function generiere_asset_tag(mysqli $conn, string $einheit): string {
    $prefix = 'Asset';

    $st = $conn->prepare("
        SELECT MAX(CAST(SUBSTRING_INDEX(asset_tag, '-', -1) AS UNSIGNED)) AS maxnr
        FROM it_assets
        WHERE asset_tag LIKE CONCAT(?, '-%') AND einheit = ?
    ");
    $st->bind_param("ss", $prefix, $einheit);
    $st->execute();
    $row  = $st->get_result()->fetch_assoc();
    $st->close();

    $max  = (int)($row['maxnr'] ?? 0);
    $nr   = $max + 1;

    // Asset-001, Asset-002, ...
    return $prefix . '-' . str_pad((string)$nr, 3, '0', STR_PAD_LEFT);
}

$meldung = '';

// ---------- Kameraden-Liste für Dropdown "zugewiesen_an" ----------
$kameradenList = [];
$stKm = $conn->prepare("
    SELECT id, vorname, nachname, spindnr
    FROM kameraden
    WHERE einheit = ? AND (archiv = '' OR archiv IS NULL)
    ORDER BY nachname, vorname
");
$stKm->bind_param("s", $user_einheit);
$stKm->execute();
$rKm = $stKm->get_result();
while ($km = $rKm->fetch_assoc()) {
    $kameradenList[] = $km;
}
$stKm->close();

// ---------- IT-Asset 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 it_assets WHERE id = ? AND einheit = ?");
  $st->bind_param("is", $delId, $user_einheit);
  if ($st->execute() && $st->affected_rows > 0) {
    $meldung = "<div class='alert alert-success'>🗑️ IT-Asset wurde gelöscht.</div>";
  } else {
    $meldung = "<div class='alert alert-danger'>❌ Fehler beim Löschen oder keine Berechtigung.</div>";
  }
}

// ---------- Neues IT-Asset speichern ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['asset_speichern'])) {

  $asset_tag     = trim($_POST['asset_tag'] ?? '');
  $bezeichnung   = trim($_POST['bezeichnung'] ?? '');
  $kategorie     = trim($_POST['kategorie'] ?? '');
  $hersteller    = trim($_POST['hersteller'] ?? '');
  $modell        = trim($_POST['modell'] ?? '');
  $seriennummer  = trim($_POST['seriennummer'] ?? '');
  $standort      = trim($_POST['standort'] ?? '');
  $zugewiesen_an = trim($_POST['zugewiesen_an'] ?? '');
  $status        = trim($_POST['status'] ?? 'aktiv');
  $bemerkung     = trim($_POST['bemerkung'] ?? '');

  // Bezeichnung & Kategorie sind Pflicht, Asset-Tag kann automatisch vergeben werden
  if ($bezeichnung === '' || $kategorie === '') {
    $meldung = "<div class='alert alert-danger'>❌ Bitte mindestens Bezeichnung und Kategorie ausfüllen.</div>";
  } else {

    // Wenn kein Asset-Tag eingegeben: automatisch generieren
    if ($asset_tag === '') {
        $asset_tag = generiere_asset_tag($conn, $user_einheit);
    }

    $st = $conn->prepare("
        INSERT INTO it_assets
          (asset_tag, bezeichnung, kategorie, hersteller, modell, seriennummer,
           standort, zugewiesen_an, status, bemerkung, einheit)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    ");
    $st->bind_param(
      "sssssssssss",
      $asset_tag,
      $bezeichnung,
      $kategorie,
      $hersteller,
      $modell,
      $seriennummer,
      $standort,
      $zugewiesen_an,
      $status,
      $bemerkung,
      $user_einheit
    );

    $meldung = $st->execute()
      ? "<div class='alert alert-success'>✅ IT-Asset wurde erfolgreich gespeichert (Tag: ".h($asset_tag).").</div>"
      : "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
  }
}

// ---------- IT-Asset bearbeiten ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['asset_update'])) {

  $id           = (int)($_POST['id'] ?? 0);
  $asset_tag    = trim($_POST['asset_tag_edit'] ?? '');
  $bezeichnung  = trim($_POST['bezeichnung_edit'] ?? '');
  $kategorie    = trim($_POST['kategorie_edit'] ?? '');
  $hersteller   = trim($_POST['hersteller_edit'] ?? '');
  $modell       = trim($_POST['modell_edit'] ?? '');
  $seriennummer = trim($_POST['seriennummer_edit'] ?? '');
  $standort     = trim($_POST['standort_edit'] ?? '');
  $zugewiesen   = trim($_POST['zugewiesen_an_edit'] ?? '');
  $status       = trim($_POST['status_edit'] ?? 'aktiv');
  $bemerkung    = trim($_POST['bemerkung_edit'] ?? '');

  if ($id > 0 && $asset_tag !== '' && $bezeichnung !== '' && $kategorie !== '') {
    $st = $conn->prepare("
        UPDATE it_assets
        SET asset_tag = ?, bezeichnung = ?, kategorie = ?, hersteller = ?, modell = ?,
            seriennummer = ?, standort = ?, zugewiesen_an = ?, status = ?, bemerkung = ?
        WHERE id = ? AND einheit = ?
    ");
    $st->bind_param(
      "ssssssssssis",
      $asset_tag,
      $bezeichnung,
      $kategorie,
      $hersteller,
      $modell,
      $seriennummer,
      $standort,
      $zugewiesen,
      $status,
      $bemerkung,
      $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 Asset-Tag, Bezeichnung und Kategorie ausfüllen.</div>";
  }
}

// ---------- Filter ----------
$search   = trim($_GET['search'] ?? '');
$f_kat    = trim($_GET['kategorie'] ?? '');
$f_status = trim($_GET['status'] ?? '');

// Kategorien (nur eigene Einheit)
$katList = [];
$stK = $conn->prepare("
    SELECT kategorie, COUNT(*) cnt
    FROM it_assets
    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 (
      bezeichnung LIKE ?
      OR asset_tag LIKE ?
      OR kategorie LIKE ?
      OR standort LIKE ?
      OR zugewiesen_an LIKE ?
      OR seriennummer LIKE ?
  )";
  for($i=0;$i<6;$i++){ $params[] = $like; $types .= 's'; }
}
if ($f_kat !== '') {
  $where .= " AND kategorie = ?";
  $params[] = $f_kat; $types .= 's';
}
if ($f_status !== '') {
  $where .= " AND status = ?";
  $params[] = $f_status; $types .= 's';
}

// ---------- KPIs ----------
$sqlKpi = "
    SELECT
      COUNT(*) AS assets,
      SUM(CASE WHEN status = 'aktiv' THEN 1 ELSE 0 END) AS aktiv,
      SUM(CASE WHEN status IN ('defekt','Reparatur','in Reparatur') THEN 1 ELSE 0 END) AS defekt,
      COUNT(DISTINCT kategorie) AS cats
    FROM it_assets
    WHERE $where
";
$stKpi = $conn->prepare($sqlKpi);
bind_params($stKpi, $types, $params);
$stKpi->execute();
$K = $stKpi->get_result()->fetch_assoc() ?: ['assets'=>0,'aktiv'=>0,'defekt'=>0,'cats'=>0];

// ---------- IT-Assetliste ----------
$whereList  = $where;
$typesList  = $types;
$paramsList = $params;

$sqlList = "SELECT * FROM it_assets WHERE $whereList ORDER BY kategorie, bezeichnung, asset_tag";
$stList = $conn->prepare($sqlList);
bind_params($stList, $typesList, $paramsList);
$stList->execute();
$assets = $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", monospace;}
</style>

<div class="container my-5">
  <!-- Toolbar -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">IT-Assetverwaltung</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: Tag / Name / Standort / Nutzer"
               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>

        <select name="status" class="form-select">
          <option value="">Alle Status</option>
          <?php
            $statusOpts = ['aktiv','in Nutzung','in Reparatur','defekt','ausgemustert','Lager'];
            foreach($statusOpts as $st):
          ?>
            <option value="<?= h($st) ?>" <?= $f_status===$st?'selected':'' ?>>
              <?= h($st) ?>
            </option>
          <?php endforeach; ?>
        </select>

        <button class="btn btn-outline-primary">Anwenden</button>
        <?php if ($search!=='' || $f_kat!=='' || $f_status!==''): ?>
          <a href="it_assets.php" class="btn btn-outline-secondary">Zurücksetzen</a>
        <?php endif; ?>
      </form>

      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#assetModal">
        ➕ IT-Asset 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">Assets gesamt</div>
        <div class="kpi-val"><?= (int)$K['assets'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="kpi-card">
        <div class="kpi-sub">Aktiv</div>
        <div class="kpi-val"><?= (int)$K['aktiv'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="kpi-card">
        <div class="kpi-sub">Defekt / Reparatur</div>
        <div class="kpi-val"><?= (int)$K['defekt'] ?></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)$K['cats'] ?></div>
      </div>
    </div>
  </div>

  <!-- Tabs je Kategorie -->
  <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'=>'','status'=>$f_status]);
    ?>
    <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'],'status'=>$f_status]) ?>">
          <?= h($k['kategorie']) ?>
          <span class="badge rounded-pill text-bg-light tab-badge"><?= (int)$k['cnt'] ?></span>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>

  <!-- Tabelle -->
  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Asset-Tag</th>
            <th>Bezeichnung</th>
            <th>Kategorie</th>
            <th>Standort</th>
            <th>Zugewiesen an</th>
            <th>Status</th>
            <th style="width:80px;" class="text-end"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($assets->num_rows === 0): ?>
            <tr>
              <td colspan="7" class="text-center text-muted py-4">
                Keine IT-Assets gefunden.
              </td>
            </tr>
          <?php else: while($row = $assets->fetch_assoc()): ?>
            <tr>
              <td class="text-mono"><?= h($row['asset_tag']) ?></td>
              <td>
                <div class="fw-semibold"><?= h($row['bezeichnung']) ?></div>
                <?php if ($row['hersteller'] || $row['modell']): ?>
                  <div class="text-muted small">
                    <?= h($row['hersteller']) ?> <?= h($row['modell']) ?>
                  </div>
                <?php endif; ?>
                <?php if ($row['seriennummer']): ?>
                  <div class="text-muted small">SN: <?= h($row['seriennummer']) ?></div>
                <?php endif; ?>
              </td>
              <td><?= h($row['kategorie']) ?></td>
              <td><?= h($row['standort']) ?></td>
              <td><?= h($row['zugewiesen_an']) ?></td>
              <td>
                <?php
                  $status = $row['status'];
                  $badgeClass = 'bg-secondary';
                  if ($status === 'aktiv' || $status === 'in Nutzung') $badgeClass = 'bg-success';
                  elseif ($status === 'in Reparatur' || $status === 'Reparatur') $badgeClass = 'bg-warning text-dark';
                  elseif ($status === 'defekt') $badgeClass = 'bg-danger';
                  elseif ($status === 'ausgemustert') $badgeClass = 'bg-dark';
                  elseif ($status === 'Lager') $badgeClass = 'bg-info text-dark';
                ?>
                <span class="badge <?= $badgeClass ?>"><?= h($status) ?></span>
              </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">
                    <a class="dropdown-item"
                       href="#"
                       data-bs-toggle="modal"
                       data-bs-target="#editModal"
                       data-id="<?= (int)$row['id'] ?>"
                       data-tag="<?= h($row['asset_tag']) ?>"
                       data-bez="<?= h($row['bezeichnung']) ?>"
                       data-kat="<?= h($row['kategorie']) ?>"
                       data-hersteller="<?= h($row['hersteller']) ?>"
                       data-modell="<?= h($row['modell']) ?>"
                       data-sn="<?= h($row['seriennummer']) ?>"
                       data-standort="<?= h($row['standort']) ?>"
                       data-zugewiesen="<?= h($row['zugewiesen_an']) ?>"
                       data-status="<?= h($row['status']) ?>"
                       data-bemerkung="<?= h($row['bemerkung']) ?>"
                    >Bearbeiten</a>
                    <a class="dropdown-item"
                       href="it_asset_detail.php?id=<?= (int)$row['id'] ?>">
                      Details anzeigen
                    </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,
                           'status'=>$f_status
                         ]) ?>"
                         onclick="return confirm('❗ Dieses IT-Asset wirklich löschen?');">
                        Löschen
                      </a>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
            </tr>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: IT-Asset hinzufügen -->
<div class="modal fade" id="assetModal" tabindex="-1" aria-labelledby="assetModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="assetModalLabel">IT-Asset hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Asset-Tag</label>
            <input name="asset_tag" class="form-control"
                   placeholder="leer lassen = automatisch (z. B. Asset-001)">
          </div>
          <div class="col-md-8">
            <label class="form-label">Bezeichnung *</label>
            <input name="bezeichnung" class="form-control" required placeholder="z. B. Notebook Büro 1">
          </div>
          <div class="col-md-4">
            <label class="form-label">Kategorie *</label>
            <select name="kategorie" class="form-select" required>
              <option value="">– bitte wählen –</option>
              <option>Laptop</option>
              <option>PC</option>
              <option>Monitor</option>
              <option>Drucker</option>
              <option>Tablet</option>
              <option>Smartphone</option>
              <option>Netzwerk</option>
              <option>Server</option>
              <option>Zubehör</option>
              <option>Sonstige</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Hersteller</label>
            <input name="hersteller" class="form-control" placeholder="z. B. Dell">
          </div>
          <div class="col-md-4">
            <label class="form-label">Modell</label>
            <input name="modell" class="form-control" placeholder="z. B. Latitude 5520">
          </div>
          <div class="col-md-4">
            <label class="form-label">Seriennummer</label>
            <input name="seriennummer" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Standort</label>
            <input name="standort" class="form-control" placeholder="z. B. Büro 1, ELW, Lager">
          </div>
          <div class="col-md-4">
            <label class="form-label">Zugewiesen an</label>
            <select name="zugewiesen_an" class="form-select">
              <option value="">– nicht zugewiesen –</option>
              <?php foreach ($kameradenList as $km):
                  $label = trim($km['vorname'].' '.$km['nachname']);
                  $spind = trim((string)$km['spindnr']);
                  $text  = $label . ($spind !== '' ? ' (Spind '.$spind.')' : '');
              ?>
                <option value="<?= h($label) ?>"><?= h($text) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option>aktiv</option>
              <option>in Nutzung</option>
              <option>in Reparatur</option>
              <option>defekt</option>
              <option>ausgemustert</option>
              <option>Lager</option>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Bemerkung</label>
            <textarea name="bemerkung" class="form-control" rows="2"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="asset_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: IT-Asset bearbeiten -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel">IT-Asset 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="row g-3">
          <div class="col-md-4">
            <label class="form-label">Asset-Tag *</label>
            <input name="asset_tag_edit" id="edit_tag" class="form-control" required>
          </div>
          <div class="col-md-8">
            <label class="form-label">Bezeichnung *</label>
            <input name="bezeichnung_edit" id="edit_bez" class="form-control" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Kategorie *</label>
            <select name="kategorie_edit" id="edit_kategorie" class="form-select" required>
              <option value="">– bitte wählen –</option>
              <option>Laptop</option>
              <option>PC</option>
              <option>Monitor</option>
              <option>Drucker</option>
              <option>Tablet</option>
              <option>Smartphone</option>
              <option>Netzwerk</option>
              <option>Server</option>
              <option>Zubehör</option>
              <option>Sonstige</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Hersteller</label>
            <input name="hersteller_edit" id="edit_hersteller" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Modell</label>
            <input name="modell_edit" id="edit_modell" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Seriennummer</label>
            <input name="seriennummer_edit" id="edit_sn" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Standort</label>
            <input name="standort_edit" id="edit_standort" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Zugewiesen an</label>
            <select name="zugewiesen_an_edit" id="edit_zugewiesen" class="form-select">
              <option value="">– nicht zugewiesen –</option>
              <?php foreach ($kameradenList as $km):
                  $label = trim($km['vorname'].' '.$km['nachname']);
                  $spind = trim((string)$km['spindnr']);
                  $text  = $label . ($spind !== '' ? ' (Spind '.$spind.')' : '');
              ?>
                <option value="<?= h($label) ?>"><?= h($text) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Status</label>
            <select name="status_edit" id="edit_status" class="form-select">
              <option>aktiv</option>
              <option>in Nutzung</option>
              <option>in Reparatur</option>
              <option>defekt</option>
              <option>ausgemustert</option>
              <option>Lager</option>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Bemerkung</label>
            <textarea name="bemerkung_edit" id="edit_bemerkung" class="form-control" rows="2"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="asset_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 tag        = btn.getAttribute('data-tag') || '';
    const bez        = btn.getAttribute('data-bez') || '';
    const kat        = btn.getAttribute('data-kat') || '';
    const hersteller = btn.getAttribute('data-hersteller') || '';
    const modell     = btn.getAttribute('data-modell') || '';
    const sn         = btn.getAttribute('data-sn') || '';
    const standort   = btn.getAttribute('data-standort') || '';
    const zugewiesen = btn.getAttribute('data-zugewiesen') || '';
    const status     = btn.getAttribute('data-status') || '';
    const bemerkung  = btn.getAttribute('data-bemerkung') || '';

    document.getElementById('edit_id').value          = id;
    document.getElementById('edit_tag').value         = tag;
    document.getElementById('edit_bez').value         = bez;
    document.getElementById('edit_hersteller').value  = hersteller;
    document.getElementById('edit_modell').value      = modell;
    document.getElementById('edit_sn').value          = sn;
    document.getElementById('edit_standort').value    = standort;
    document.getElementById('edit_bemerkung').value   = bemerkung;

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

    const selStatus = document.getElementById('edit_status');
    if (selStatus) {
      Array.from(selStatus.options).forEach(o => { o.selected = (o.value === status); });
    }

    // Dropdown "zugewiesen_an_edit" auf aktuellen Wert setzen
    const selZug = document.getElementById('edit_zugewiesen');
    if (selZug) {
      let found = false;
      Array.from(selZug.options).forEach(o => {
        if (o.value === zugewiesen) {
          o.selected = true;
          found = true;
        }
      });
      // falls der aktuelle Wert nicht in der Liste ist, leerlassen (oder später erweitern)
      if (!found && zugewiesen !== '') {
        // Optional: dynamisch Option hinzufügen
        const opt = new Option(zugewiesen + ' (alt)', zugewiesen, true, true);
        selZug.add(opt);
      }
    }
  }
});
</script>

<?php
include 'includes/footer.php';
if (ob_get_level() > 0) {
    ob_end_flush();
}
?>
