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

$einheit = $_SESSION['einheit'] ?? '';
$meldung = '';

// PSA löschen
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()) {
        $meldung = "<div class='alert alert-success'>🗑️ Eintrag erfolgreich gelöscht.</div>";
    } else {
        $meldung = "<div class='alert alert-danger'>❌ Fehler beim Löschen.</div>";
    }
}

// PSA hinzufügen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_psa'])) {
    $typ = $_POST['typ'];
    $hersteller = $_POST['hersteller'];
    $modell = $_POST['modell'];
    $groesse = $_POST['groesse'];
    $spindnr = $_POST['spindnr'];
    $id_code = $_POST['id_code'];
    $charge = $_POST['charge'];
    $herstellungsjahr = $_POST['herstellungsjahr'];
    $status = $_POST['status'];

    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);
        if ($stmt->execute()) {
            $meldung = "<div class='alert alert-success'>✅ PSA gespeichert.</div>";
        } else {
            $meldung = "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
        }
    } else {
        $meldung = "<div class='alert alert-warning'>Bitte alle Pflichtfelder ausfüllen.</div>";
    }
}

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

<div class="container my-5">
  <h2 class="mb-4">PSA-Verwaltung</h2>
  <?= $meldung ?>

  <button class="btn btn-primary mb-4" data-bs-toggle="modal" data-bs-target="#psaModal">+ Neue PSA</button>

  <ul class="nav nav-tabs mb-3" role="tablist">
    <?php foreach ($typen as $i => $typ): ?>
      <li class="nav-item" role="presentation">
        <a class="nav-link <?= $i === 0 ? 'active' : '' ?>" id="tab-<?= $i ?>" data-bs-toggle="tab" href="#tab-content-<?= $i ?>" role="tab"><?= $typ ?></a>
      </li>
    <?php endforeach; ?>
  </ul>

  <div class="tab-content">
    <?php foreach ($typen as $i => $typ): ?>
      <div class="tab-pane fade <?= $i === 0 ? 'show active' : '' ?>" id="tab-content-<?= $i ?>" role="tabpanel">
        <div class="table-responsive">
          <table class="table table-bordered table-hover bg-white">
            <thead class="table-dark">
              <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>Aktion</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $result = $conn->query("
                SELECT psa.*, k.vorname, k.nachname
                FROM psa_ausruestung psa
                LEFT JOIN kameraden k ON psa.spindnr = k.spindnr
                WHERE psa.typ = '$typ' AND psa.einheit = '$einheit'
                ORDER BY CAST(psa.spindnr AS UNSIGNED)
              ");

              while ($row = $result->fetch_assoc()):
              ?>
                <tr>
                  <td><?= htmlspecialchars($row['hersteller']) ?></td>
                  <td><?= htmlspecialchars($row['modell']) ?></td>
                  <td><?= htmlspecialchars($row['groesse']) ?></td>
                  <td><?= htmlspecialchars($row['spindnr']) ?></td>
                  <td><?= htmlspecialchars($row['vorname'] . ' ' . $row['nachname']) ?></td>
                  <td><?= htmlspecialchars($row['id_code']) ?></td>
                  <td><?= htmlspecialchars($row['charge']) ?></td>
                  <td><?= htmlspecialchars($row['herstellungsjahr']) ?></td>
                  <td><?= htmlspecialchars($row['status']) ?></td>
                  <td>
                    <a href="psa_edit.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
                    <a href="?delete=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger"
                       onclick="return confirm('⚠️ Diesen PSA-Eintrag wirklich löschen?');">
                      Löschen
                    </a>
                  </td>
                </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- Modal zur Eingabe -->
<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 $typ): ?>
              <option><?= $typ ?></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-3">
          <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>

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