<?php
include 'includes/header.php';
include 'includes/nav.php';
include 'includes/db.php';
session_start();

/* -------------------- Zugriff & Setup -------------------- */
$einheit = $_SESSION['einheit'] ?? '';
if (empty($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;
}

$meldung   = '';
$search    = trim($_GET['search'] ?? '');
$activeTab = '';

$typen = ['Einsatzjacke', 'Einsatzhose', 'Einsatzhose AGT', 'Stiefel', 'Helm', 'Helmlampe'];

/* -------------------- Status-Helfer -------------------- */
if (!function_exists('statusClass')) {
    function statusClass(string $s): string {
        $s = mb_strtolower(trim($s));
        if ($s === 'einsatzbereit') return 'badge text-bg-success';
        if ($s === 'nicht einsatzbereit') return 'badge text-bg-danger';
        return 'badge text-bg-secondary';
    }
}
if (!function_exists('statusLabel')) {
    function statusLabel(string $s): string {
        $raw = trim($s);
        $low = mb_strtolower($raw);
        if ($low === 'einsatzbereit') return 'Einsatzbereit';
        if ($low === 'nicht einsatzbereit') return 'Nicht Einsatzbereit';
        return $raw !== '' ? $raw : '—';
    }
}
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/* -------------------- Löschen (nur eigene Einheit) -------------------- */
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delId = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM psa_ausruestung WHERE id = ? AND einheit = ?");
    $stmt->bind_param("is", $delId, $einheit);
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $meldung = "<div class='alert alert-success'>🗑️ Eintrag erfolgreich gelöscht.</div>";
        } else {
            $meldung = "<div class='alert alert-info'>ℹ️ Kein Eintrag deiner Einheit gefunden (nichts gelöscht).</div>";
        }
    } else {
        $meldung = "<div class='alert alert-danger'>❌ Fehler beim Löschen.</div>";
    }
}

/* -------------------- Hinzufügen (nur eigene Einheit) -------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_psa'])) {
    $typ               = trim($_POST['typ'] ?? '');
    $hersteller        = trim($_POST['hersteller'] ?? '');
    $modell            = trim($_POST['modell'] ?? '');
    $groesse           = trim($_POST['groesse'] ?? '');
    $spindnr           = trim($_POST['spindnr'] ?? '');
    $id_code           = trim($_POST['id_code'] ?? '');
    $charge            = trim($_POST['charge'] ?? '');
    $herstellungsjahr  = trim($_POST['herstellungsjahr'] ?? '');
    $status            = trim($_POST['status'] ?? 'Einsatzbereit');

    if ($typ && $hersteller && $modell) {
        $stmt = $conn->prepare("
            INSERT INTO psa_ausruestung
              (typ, hersteller, modell, groesse, spindnr, id_code, charge, herstellungsjahr, status, einheit)
            VALUES (?,?,?,?,?,?,?,?,?,?)
        ");
        $stmt->bind_param("ssssssssss", $typ, $hersteller, $modell, $groesse, $spindnr, $id_code, $charge, $herstellungsjahr, $status, $einheit);
        $meldung = $stmt->execute()
            ? "<div class='alert alert-success'>✅ PSA gespeichert.</div>"
            : "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
    } else {
        $meldung = "<div class='alert alert-warning'>Bitte alle Pflichtfelder ausfüllen.</div>";
    }
}

/* -------------------- CSV-Export (Einheit + Suche) -------------------- */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $filename = 'psa_export_' . date('Y-m-d') . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header("Content-Disposition: attachment; filename=\"$filename\"");
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Typ','Hersteller','Modell','Größe','Spind','Kamerad','ID-Code','Charge','Herstellungsjahr','Status','Einheit']);

    $like = '%' . $search . '%';
    $sql = "
        SELECT psa.*, k.vorname, k.nachname
          FROM psa_ausruestung psa
     LEFT JOIN kameraden k
            ON psa.spindnr = k.spindnr
           AND k.einheit = psa.einheit
         WHERE psa.einheit = ?
           AND (? = '' OR psa.id_code LIKE ?)
         ORDER BY psa.typ, CAST(psa.spindnr AS UNSIGNED), psa.id DESC
    ";
    $st = $conn->prepare($sql);
    $st->bind_param('sss', $einheit, $search, $like);
    $st->execute();
    $res = $st->get_result();
    while ($r = $res->fetch_assoc()){
        $kamerad = trim(($r['vorname'] ?? '').' '.($r['nachname'] ?? ''));
        fputcsv($out, [
            $r['typ'],
            $r['hersteller'],
            $r['modell'],
            $r['groesse'],
            $r['spindnr'],
            $kamerad,
            $r['id_code'],
            $r['charge'],
            $r['herstellungsjahr'],
            statusLabel($r['status']),
            $r['einheit'],
        ]);
    }
    fclose($out);
    exit;
}

/* -------------------- Aktiven Tab anhand der Suche bestimmen -------------------- */
if ($search !== '') {
    $stmtTab = $conn->prepare("SELECT typ FROM psa_ausruestung WHERE einheit = ? AND id_code LIKE ? LIMIT 1");
    $likeSearch = '%' . $search . '%';
    $stmtTab->bind_param("ss", $einheit, $likeSearch);
    $stmtTab->execute();
    $resTab = $stmtTab->get_result();
    if ($rowTab = $resTab->fetch_assoc()) $activeTab = $rowTab['typ'];
}

/* -------------------- Zähler pro Typ (respektiert Suche) -------------------- */
$typeCounts = [];
$stc = $conn->prepare("
    SELECT typ, COUNT(*) as cnt
      FROM psa_ausruestung
     WHERE einheit = ?
       AND (? = '' OR id_code LIKE ?)
  GROUP BY typ
");
$stc->bind_param('sss', $einheit, $search, $likeSearch);
$likeSearch = '%' . $search . '%';
$stc->execute();
$cr = $stc->get_result();
while ($c = $cr->fetch_assoc()) $typeCounts[$c['typ']] = (int)$c['cnt'];

/* -------------------- UI -------------------- */
?>
<style>
  .toolbar { display:flex; gap:12px; flex-wrap:wrap; align-items:center; justify-content:space-between; }
  .card-soft { border:1px solid #eee; border-radius:12px; }
  .empty-card { border:1px dashed #ced4da; border-radius:12px; background:#f8f9fa; }
  .tab-badge { font-size:.75rem; }
</style>

<div class="container my-5">
  <div class="d-flex justify-content-between align-items-end flex-wrap gap-2 mb-3">
    <div>
      <h2 class="mb-1">PSA-Verwaltung</h2>
      <div class="text-muted">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>
    <div class="toolbar">
      <form method="get" class="d-flex align-items-center gap-2">
        <input type="text" name="search" class="form-control" placeholder="🔍 ID-Code durchsuchen" value="<?= h($search) ?>">
        <button type="submit" class="btn btn-outline-primary">Suchen</button>
        <?php if ($search !== ''): ?>
          <a class="btn btn-outline-secondary" href="psa.php">Zurücksetzen</a>
        <?php endif; ?>
        <a href="?export=csv&search=<?= urlencode($search) ?>" class="btn btn-outline-secondary">CSV Export</a>
      </form>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#psaModal">+ Neue PSA</button>
    </div>
  </div>

  <?= $meldung ?>

  <!-- Tabs mit Zähler -->
  <ul class="nav nav-tabs mb-3" role="tablist">
    <?php foreach ($typen as $i => $typ):
      $isActive = ($typ === $activeTab) || ($i === 0 && $activeTab === '');
      $count    = $typeCounts[$typ] ?? 0;
    ?>
      <li class="nav-item" role="presentation">
        <a class="nav-link <?= $isActive ? 'active' : '' ?>" id="tab-<?= $i ?>" data-bs-toggle="tab" href="#tab-content-<?= $i ?>" role="tab">
          <?= h($typ) ?>
          <span class="badge rounded-pill text-bg-light tab-badge"><?= $count ?></span>
        </a>
      </li>
    <?php endforeach; ?>
  </ul>

  <div class="tab-content">
    <?php foreach ($typen as $i => $typ):
      $isActive = ($typ === $activeTab) || ($i === 0 && $activeTab === '');
    ?>
      <div class="tab-pane fade <?= $isActive ? 'show active' : '' ?>" id="tab-content-<?= $i ?>" role="tabpanel">
        <?php
        // Query pro Tab (nur eigene Einheit, Suche nur auf id_code)
        $stmt = $conn->prepare("
          SELECT psa.*, k.vorname, k.nachname
            FROM psa_ausruestung psa
       LEFT JOIN kameraden k
              ON psa.spindnr = k.spindnr
             AND k.einheit = psa.einheit
           WHERE psa.typ = ?
             AND psa.einheit = ?
             AND (? = '' OR psa.id_code LIKE ?)
        ORDER BY CAST(psa.spindnr AS UNSIGNED), psa.id DESC
        ");
        $like = '%' . $search . '%';
        $stmt->bind_param("ssss", $typ, $einheit, $search, $like);
        $stmt->execute();
        $result = $stmt->get_result();
        ?>

        <?php if ($result->num_rows === 0): ?>
          <div class="empty-card p-4 text-center my-4">
            <div class="fs-5 mb-2">Keine Einträge gefunden</div>
            <div class="text-muted mb-3">Für „<?= h($typ) ?>” <?= $search!=='' ? "und Suchbegriff „".h($search)."” " : '' ?>liegen keine Datensätze vor.</div>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#psaModal">Jetzt neuen Eintrag anlegen</button>
          </div>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-hover align-middle bg-white">
              <thead class="table-light">
                <tr>
                  <th>Hersteller</th>
                  <th>Modell</th>
                  <th>Größe</th>
                  <th>Spind</th>
                  <th>Kamerad</th>
                  <th>ID-Code</th>
                  <th>Charge</th>
                  <th>Jahr</th>
                  <th>Status</th>
                  <th class="text-end">Aktion</th>
                </tr>
              </thead>
              <tbody>
                <?php while ($row = $result->fetch_assoc()):
                  $kamerad = trim(($row['vorname'] ?? '').' '.($row['nachname'] ?? ''));
                ?>
                  <tr>
                    <td><?= h($row['hersteller']) ?></td>
                    <td><?= h($row['modell']) ?></td>
                    <td><?= h($row['groesse']) ?></td>
                    <td><span class="text-monospace"><?= h($row['spindnr']) ?></span></td>
                    <td><?= $kamerad !== '' ? h($kamerad) : '<span class="text-muted">–</span>' ?></td>
                    <td><?= h($row['id_code']) ?></td>
                    <td><?= h($row['charge']) ?></td>
                    <td><?= h($row['herstellungsjahr']) ?></td>
                    <td><span class="<?= statusClass($row['status']) ?>"><?= h(statusLabel($row['status'])) ?></span></td>
                    <td class="text-end">
                      <div class="btn-group">
                        <a href="psa_edit.php?id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
                        <a href="?delete=<?= (int)$row['id'] ?>&search=<?= urlencode($search) ?>"
                           class="btn btn-sm btn-outline-danger"
                           onclick="return confirm('⚠️ Diesen PSA-Eintrag wirklich löschen?');">Löschen</a>
                      </div>
                    </td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- Modal: Neue PSA -->
<div class="modal fade" id="psaModal" tabindex="-1" aria-labelledby="psaModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="psaModalLabel">Neue PSA erfassen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Typ*</label>
          <select name="typ" class="form-select" required>
            <option value="">– bitte wählen –</option>
            <?php foreach ($typen as $t): ?>
              <option><?= h($t) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="mb-3"><label class="form-label">Hersteller*</label><input type="text" name="hersteller" class="form-control" required></div>
        <div class="mb-3"><label class="form-label">Modell*</label><input type="text" name="modell" class="form-control" required></div>
        <div class="mb-3"><label class="form-label">Größe</label><input type="text" name="groesse" class="form-control"></div>
        <div class="mb-3"><label class="form-label">Spindnummer</label><input type="text" name="spindnr" class="form-control"></div>
        <div class="mb-3"><label class="form-label">ID-Code</label><input type="text" name="id_code" class="form-control"></div>
        <div class="mb-3"><label class="form-label">Charge</label><input type="text" name="charge" class="form-control"></div>
        <div class="mb-3">
          <label class="form-label">Herstellungsjahr</label>
          <input type="number" name="herstellungsjahr" class="form-control" min="2000" max="<?= date('Y') ?>">
        </div>
        <div class="mb-0">
          <label class="form-label">Status</label>
          <select name="status" class="form-select">
            <option value="Einsatzbereit">Einsatzbereit</option>
            <option value="Nicht Einsatzbereit">Nicht Einsatzbereit</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="save_psa" class="btn btn-primary">Speichern</button>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
  // Beim direkten Aufruf aktivieren wir ggf. den Tab, der zur Suche passt
  const activeTab = <?= json_encode($activeTab, JSON_UNESCAPED_UNICODE) ?>;
  const typen = <?= json_encode($typen, JSON_UNESCAPED_UNICODE) ?>;
  const index = typen.indexOf(activeTab);
  if (index !== -1) {
    const triggerEl = document.querySelector(`a.nav-link[href='#tab-content-${index}']`);
    if (triggerEl) new bootstrap.Tab(triggerEl).show();
  }
});
</script>

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