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

$einheit = $_SESSION['einheit'] ?? '';
$info = '';
$fehler = '';

if (!$einheit) {
    echo "<div class='container my-5'><div class='alert alert-danger'>⚠️ Einheit nicht gefunden. Bitte erneut einloggen.</div></div>";
    include 'includes/footer.php';
    exit;
}

/* ---------------- Formularverarbeitung (LOGIK UNVERÄNDERT + neue Felder) ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $strasse     = $_POST['strasse']     ?? '';
    $plz         = $_POST['plz']         ?? '';
    $ort         = $_POST['ort']         ?? '';
    $name2       = $_POST['name2']       ?? '';
    $art         = $_POST['art']         ?? '';
    $obm_1       = $_POST['obm_1']       ?? '';
    $obm_2       = $_POST['obm_2']       ?? '';
    $obm_3       = $_POST['obm_3']       ?? '';
    $geraetewart = $_POST['geraetewart'] ?? '';
    $agw         = $_POST['agw']         ?? '';
    $funkwart    = $_POST['funkwart']    ?? '';
    $psa         = $_POST['psa']         ?? '';
    $telefon     = $_POST['telefon']     ?? '';
    $email       = $_POST['email']       ?? '';

    // Prüfen ob Eintrag existiert
    $check = $conn->prepare("SELECT id FROM feuerwehren WHERE name = ?");
    $check->bind_param("s", $einheit);
    $check->execute();
    $result = $check->get_result();

    if ($result->num_rows > 0) {
        $update = $conn->prepare("
            UPDATE feuerwehren
               SET strasse=?,
                   plz=?,
                   ort=?,
                   name2=?,
                   art=?,
                   obm_1=?,
                   obm_2=?,
                   obm_3=?,
                   geraetewart=?,
                   agw=?,
                   funkwart=?,
                   psa=?,
                   telefon=?,
                   email=?
             WHERE name=?
        ");
        $update->bind_param(
            "sssssssssssssss",
            $strasse, $plz, $ort, $name2, $art, $obm_1, $obm_2, $obm_3,
            $geraetewart, $agw, $funkwart, $psa, $telefon, $email, $einheit
        );
        $update->execute();
        $info = "Einheitsdaten wurden aktualisiert.";
    } else {
        $insert = $conn->prepare("
            INSERT INTO feuerwehren
                (name, strasse, plz, ort, name2, art, obm_1, obm_2, obm_3, geraetewart, agw, funkwart, psa, telefon, email)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $insert->bind_param(
            "sssssssssssssss",
            $einheit, $strasse, $plz, $ort, $name2, $art, $obm_1, $obm_2, $obm_3,
            $geraetewart, $agw, $funkwart, $psa, $telefon, $email
        );
        $insert->execute();
        $info = "Einheitsdaten wurden gespeichert.";
    }
}

/* ---------------- Bestehende Daten laden ---------------- */
$stmt = $conn->prepare("SELECT * FROM feuerwehren WHERE name = ?");
$stmt->bind_param("s", $einheit);
$stmt->execute();
$daten = $stmt->get_result()->fetch_assoc();

/* ---------------- Helper ---------------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
$arten = ['Ortswehr', 'Schwerpunktwehr', 'Stützpunktwehr'];
?>
<style>
  .card-elev { border:1px solid #e9ecef; border-radius:1rem; box-shadow:0 6px 20px rgba(0,0,0,.06); }
  .section-title { font-weight:600; font-size:1.05rem; color:#0d6efd; display:flex; align-items:center; gap:.5rem; }
  .muted-hint { font-size:.925rem; color:#6c757d; }
</style>

<div class="container my-5">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h1 class="mb-0">🏘️ Meine Einheit – <?= h($einheit) ?></h1>
    <a href="index.php" class="btn btn-outline-secondary">Zurück</a>
  </div>

  <?php if ($info): ?>
    <div class="alert alert-success"><?= h($info) ?></div>
  <?php endif; ?>
  <?php if ($fehler): ?>
    <div class="alert alert-danger"><?= h($fehler) ?></div>
  <?php endif; ?>

  <form method="post">
    <!-- Basisdaten -->
    <div class="card card-elev mb-4">
      <div class="card-body">
        <div class="section-title"><i class="bi bi-building"></i> Basisdaten</div>
        <div class="row g-3 mt-1">
          <div class="col-md-6">
            <label class="form-label">Öffentlicher Name (z. B. „FF <?= h($einheit) ?>“)</label>
            <input type="text" name="name2" class="form-control" value="<?= h($daten['name2'] ?? '') ?>">
            <div class="form-text muted-hint">Wird z. B. in Druckansichten oder Übersichten gezeigt.</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Art der Feuerwehr *</label>
            <select name="art" class="form-select" required>
              <option value="">Bitte wählen</option>
              <?php foreach ($arten as $a): ?>
                <option value="<?= h($a) ?>" <?= (($daten['art'] ?? '') === $a) ? 'selected' : '' ?>><?= h($a) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>
    </div>

    <!-- Anschrift -->
    <div class="card card-elev mb-4">
      <div class="card-body">
        <div class="section-title"><i class="bi bi-geo-alt"></i> Anschrift</div>
        <div class="row g-3 mt-1">
          <div class="col-md-6">
            <label class="form-label">Straße</label>
            <input type="text" name="strasse" class="form-control" value="<?= h($daten['strasse'] ?? '') ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">PLZ</label>
            <input type="text" name="plz" class="form-control" value="<?= h($daten['plz'] ?? '') ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">Ort</label>
            <input type="text" name="ort" class="form-control" value="<?= h($daten['ort'] ?? '') ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- Ansprechpartner -->
    <div class="card card-elev mb-4">
      <div class="card-body">
        <div class="section-title"><i class="bi bi-people"></i> Ansprechpartner</div>
        <div class="row g-3 mt-1">
          <div class="col-md-4">
            <label class="form-label">Ortsbrandmeister 1</label>
            <input type="text" name="obm_1" class="form-control" value="<?= h($daten['obm_1'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Ortsbrandmeister 2</label>
            <input type="text" name="obm_2" class="form-control" value="<?= h($daten['obm_2'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Ortsbrandmeister 3</label>
            <input type="text" name="obm_3" class="form-control" value="<?= h($daten['obm_3'] ?? '') ?>">
          </div>

          <div class="col-md-4">
            <label class="form-label">Gerätewart</label>
            <input type="text" name="geraetewart" class="form-control" value="<?= h($daten['geraetewart'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Atemschutzgerätewart</label>
            <input type="text" name="agw" class="form-control" value="<?= h($daten['agw'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Funkwart</label>
            <input type="text" name="funkwart" class="form-control" value="<?= h($daten['funkwart'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">PSA (Beauftragter)</label>
            <input type="text" name="psa" class="form-control" value="<?= h($daten['psa'] ?? '') ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- Kontakt -->
    <div class="card card-elev mb-4">
      <div class="card-body">
        <div class="section-title"><i class="bi bi-telephone"></i> Kontakt</div>
        <div class="row g-3 mt-1">
          <div class="col-md-6">
            <label class="form-label">Telefon</label>
            <input type="text" name="telefon" class="form-control" value="<?= h($daten['telefon'] ?? '') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">E-Mail</label>
            <input type="email" name="email" class="form-control" value="<?= h($daten['email'] ?? '') ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- Aktionen -->
    <div class="d-flex gap-2">
      <button type="submit" class="btn btn-primary">💾 Speichern</button>
      <a href="index.php" class="btn btn-outline-secondary">Abbrechen</a>
    </div>
  </form>

  <!-- Vorschau-Box -->
  <div class="card card-elev mt-4">
    <div class="card-body">
      <div class="section-title"><i class="bi bi-eye"></i> Vorschau</div>
      <div class="mt-2">
        <div class="row">
          <div class="col-md-6">
            <strong><?= h($daten['name2'] ?? '') ?></strong><br>
            <?= h($daten['strasse'] ?? '') ?><br>
            <?= h(($daten['plz'] ?? '').' '.($daten['ort'] ?? '')) ?><br>
            <span class="badge text-bg-light"><?= h($daten['art'] ?? '') ?></span>
          </div>
          <div class="col-md-6">
            <div><strong>OrtsBM:</strong> <?= h($daten['obm_1'] ?? '-') ?><?= ($daten['obm_2'] ?? '') ? ', '.h($daten['obm_2']) : '' ?><?= ($daten['obm_3'] ?? '') ? ', '.h($daten['obm_3']) : '' ?></div>
            <div><strong>Gerätewart:</strong> <?= h($daten['geraetewart'] ?? '-') ?></div>
            <div><strong>AGW:</strong> <?= h($daten['agw'] ?? '-') ?></div>
            <div><strong>Funkwart:</strong> <?= h($daten['funkwart'] ?? '-') ?></div>
            <div><strong>PSA:</strong> <?= h($daten['psa'] ?? '-') ?></div>
            <div class="mt-2 muted-hint">
              <?= h($daten['telefon'] ?? '') ?><?= ($daten['telefon'] && $daten['email']) ? ' • ' : '' ?><?= h($daten['email'] ?? '') ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

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