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

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

$id = (int)($_GET['id'] ?? 0);
$meldung = '';

// Eintrag laden (inkl. Kamerad anhand Spindnummer)
$stmt = $conn->prepare("
    SELECT psa.*, k.vorname, k.nachname
    FROM psa_ausruestung psa
    LEFT JOIN kameraden k ON psa.spindnr = k.spindnr
    WHERE psa.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$psa = $stmt->get_result()->fetch_assoc();

if (!$psa) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Eintrag nicht gefunden.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Bearbeitung speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $typ = $_POST['typ'];
    $hersteller = $_POST['hersteller'];
    $modell = $_POST['modell'];
    $groesse = $_POST['groesse'];
    $spindnr = $_POST['spindnr'];
    $id_code = $_POST['id_code'];

    if ($typ && $hersteller && $modell) {
        $stmt = $conn->prepare("UPDATE psa_ausruestung SET typ = ?, hersteller = ?, modell = ?, groesse = ?, spindnr = ?, id_code = ? WHERE id = ?");
        $stmt->bind_param("ssssssi", $typ, $hersteller, $modell, $groesse, $spindnr, $id_code, $id);
        if ($stmt->execute()) {
            $meldung = "<div class='alert alert-success'>✅ Eintrag erfolgreich gespeichert.</div>";

            // Reload mit aktualisiertem Kameraden
            $stmt = $conn->prepare("
                SELECT psa.*, k.vorname, k.nachname
                FROM psa_ausruestung psa
                LEFT JOIN kameraden k ON psa.spindnr = k.spindnr
                WHERE psa.id = ?
            ");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $psa = $stmt->get_result()->fetch_assoc();
        } else {
            $meldung = "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
        }
    } else {
        $meldung = "<div class='alert alert-warning'>Bitte alle Pflichtfelder ausfüllen.</div>";
    }
}

// Historieneintrag(e) hinzufügen (Mehrfachauswahl möglich)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_waesche'])) {
    $datum = $_POST['waesche_datum'];
    $kommentar = $_POST['waesche_kommentar'];
    $typen = $_POST['eintrag_typ'] ?? [];

    if (!empty($typen) && $datum) {
        $stmt = $conn->prepare("INSERT INTO psa_waesche (psa_id, datum, kommentar, typ) VALUES (?, ?, ?, ?)");
        foreach ($typen as $typ) {
            $stmt->bind_param("isss", $id, $datum, $kommentar, $typ);
            $stmt->execute();
        }
    }
}
?>

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

  <ul class="nav nav-tabs mb-3" id="psaTabs" role="tablist">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#daten">Daten</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#waesche">Historie</a></li>
  </ul>

  <div class="tab-content">
    <div class="tab-pane fade show active" id="daten">
      <form method="post" class="card p-4 bg-white shadow-sm">
        <div class="mb-3">
          <label class="form-label">Typ</label>
          <select name="typ" class="form-select" required>
            <option value="">– bitte wählen –</option>
            <?php
            $typen = ['Einsatzjacke', 'Einsatzhose', 'Einsatzhose AGT', 'Stiefel', 'Helm', 'Helmlampe'];
            foreach ($typen as $t): ?>
              <option value="<?= $t ?>" <?= $psa['typ'] == $t ? 'selected' : '' ?>><?= $t ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3"><label class="form-label">Hersteller</label>
          <input type="text" name="hersteller" class="form-control" value="<?= htmlspecialchars($psa['hersteller']) ?>" required>
        </div>

        <div class="mb-3"><label class="form-label">Modell</label>
          <input type="text" name="modell" class="form-control" value="<?= htmlspecialchars($psa['modell']) ?>" required>
        </div>

        <div class="mb-3"><label class="form-label">Größe</label>
          <input type="text" name="groesse" class="form-control" value="<?= htmlspecialchars($psa['groesse']) ?>">
        </div>

        <div class="mb-3"><label class="form-label">Spindnummer</label>
          <input type="text" name="spindnr" class="form-control" value="<?= htmlspecialchars($psa['spindnr']) ?>">
        </div>

        <?php if ($psa['vorname'] || $psa['nachname']): ?>
        <div class="mb-3">
          <label class="form-label">Kamerad</label>
          <input type="text" class="form-control" value="<?= htmlspecialchars($psa['vorname'] . ' ' . $psa['nachname']) ?>" readonly>
        </div>
        <?php endif; ?>

        <div class="mb-3"><label class="form-label">ID-Code</label>
          <input type="text" name="id_code" class="form-control" value="<?= htmlspecialchars($psa['id_code']) ?>">
        </div>

        <button type="submit" name="save" class="btn btn-primary">Speichern</button>
        <a href="psa.php" class="btn btn-secondary">Zurück</a>
      </form>
    </div>

    <div class="tab-pane fade" id="waesche">
      <div class="card p-4 bg-white shadow-sm">
        <form method="post">
          <h5>Eintrag hinzufügen</h5>

          <div class="mb-3">
            <label class="form-label">Eintragsart</label><br>
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="checkbox" name="eintrag_typ[]" value="Wäsche" id="waescheBox">
              <label class="form-check-label" for="waescheBox">Wäsche</label>
            </div>
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="checkbox" name="eintrag_typ[]" value="Reparatur" id="reparaturBox">
              <label class="form-check-label" for="reparaturBox">Reparatur</label>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label">Datum</label>
            <input type="date" name="waesche_datum" class="form-control" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Kommentar</label>
            <textarea name="waesche_kommentar" class="form-control"></textarea>
          </div>

          <button type="submit" name="add_waesche" class="btn btn-primary">Speichern</button>
        </form>

        <hr>
        <h5>Einträge (<?= $conn->query("SELECT COUNT(*) FROM psa_waesche WHERE psa_id = $id")->fetch_row()[0] ?>)</h5>
        <table class="table table-bordered">
          <thead><tr><th>Typ</th><th>Datum</th><th>Kommentar</th><th>Erstellt am</th></tr></thead>
          <tbody>
            <?php
            $res = $conn->query("SELECT * FROM psa_waesche WHERE psa_id = $id ORDER BY datum DESC");
            while ($w = $res->fetch_assoc()):
            ?>
            <tr>
              <td><?= htmlspecialchars($w['typ']) ?></td>
              <td><?= date('d.m.Y', strtotime($w['datum'])) ?></td>
              <td><?= nl2br(htmlspecialchars($w['kommentar'])) ?></td>
              <td><?= date('d.m.Y H:i', strtotime($w['erstellt_am'])) ?></td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

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