<?php
/************************************************************
 * melder_edit.php – Meldeempfänger bearbeiten (UX-Upgrade)
 * - Einheit aus Session (harte Trennung)
 * - Kopf-Summary mit Badges & Quick-Actions
 * - Sauberes Formular (Seriennr, Typ, Kennung, Datum, Zubehör)
 * - Programmierungs-Checkboxen
 * - Direktlink zum Übergabe-Dokument (druckfertig)
 ************************************************************/
ob_start();
session_start();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';
require_once __DIR__ . '/includes/db.php';

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// Zugriff
if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit; }
$einheit = $_SESSION['einheit'] ?? '';
if ($einheit === '') {
  echo "<div class='container my-5'><div class='alert alert-danger'>❌ Keine Einheit in der Session gefunden.</div></div>";
  require_once __DIR__ . '/includes/footer.php';
  exit;
}

// CSRF
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(24)); }
$CSRF = $_SESSION['csrf_token'];
function csrf_ok($t){ return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$t); }

// ID
$id = max(0, (int)($_GET['id'] ?? 0));
if ($id <= 0) {
  echo "<div class='container my-5'><div class='alert alert-danger'>Ungültige ID.</div></div>";
  require_once __DIR__ . '/includes/footer.php';
  exit;
}

// Datensatz laden (nur eigene Einheit)
$stmt = $conn->prepare("SELECT * FROM melder WHERE id = ? AND einheit = ? LIMIT 1");
$stmt->bind_param("is", $id, $einheit);
$stmt->execute();
$melder = $stmt->get_result()->fetch_assoc();
if (!$melder) {
  echo "<div class='container my-5'><div class='alert alert-danger'>Melder nicht gefunden oder gehört nicht zu deiner Einheit.</div></div>";
  require_once __DIR__ . '/includes/footer.php';
  exit;
}

// Kameraden der Einheit für Dropdown
$stmtK = $conn->prepare("SELECT id, vorname, nachname FROM kameraden WHERE einheit = ? ORDER BY nachname ASC, vorname ASC");
$stmtK->bind_param("s", $einheit);
$stmtK->execute();
$kameraden = $stmtK->get_result();

// POST: Speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['melder_speichern'])) {
  if (!csrf_ok($_POST['csrf'] ?? '')) {
    $_SESSION['flash'] = "<div class='alert alert-danger'>❌ Sicherheitsprüfung fehlgeschlagen (CSRF).</div>";
    header("Location: melder_edit.php?id=".$id); exit;
  }

  $seriennummer  = trim($_POST['seriennummer'] ?? '');
  $typ           = trim($_POST['typ'] ?? '');
  $kennung       = trim($_POST['kennung'] ?? '');
  $ausgabe_datum = !empty($_POST['ausgabe_datum']) ? $_POST['ausgabe_datum'] : NULL;

  $ladegeraet   = isset($_POST['ladegeraet']) ? 1 : 0;
  $antenne      = isset($_POST['antenne']) ? 1 : 0;
  $schutztasche = isset($_POST['schutztasche']) ? 1 : 0;

  $kamerad_id = strlen($_POST['kamerad_id'] ?? '') ? (int)$_POST['kamerad_id'] : NULL;

  $programm_obm   = isset($_POST['programm_obm']) ? 1 : 0;
  $programm_agt   = isset($_POST['programm_agt']) ? 1 : 0;
  $programm_gg    = isset($_POST['programm_gg']) ? 1 : 0;
  $programm_ggf   = isset($_POST['programm_ggf']) ? 1 : 0;
  $programm_elw   = isset($_POST['programm_elw']) ? 1 : 0;
  $programm_fuest = isset($_POST['programm_fuest']) ? 1 : 0;
  $programm_kfb   = isset($_POST['programm_kfb']) ? 1 : 0;

  // Kamerad gehört wirklich zur Einheit?
  if (!is_null($kamerad_id)) {
    $chk = $conn->prepare("SELECT id FROM kameraden WHERE id = ? AND einheit = ? LIMIT 1");
    $chk->bind_param("is", $kamerad_id, $einheit);
    $chk->execute();
    if ($chk->get_result()->num_rows === 0) {
      $kamerad_id = NULL; // hart zurücksetzen
    }
  }

  // Update
  $stmtU = $conn->prepare("
    UPDATE melder
       SET seriennummer = ?,
           typ = ?,
           kennung = ?,
           ausgabe_datum = ?,
           ladegeraet = ?,
           antenne = ?,
           schutztasche = ?,
           kamerad_id = ?,
           programm_obm = ?,
           programm_agt = ?,
           programm_gg = ?,
           programm_ggf = ?,
           programm_elw = ?,
           programm_fuest = ?,
           programm_kfb = ?
     WHERE id = ? AND einheit = ?
  ");
  // 4s + 11i + id(i) + einheit(s) = "ssssiiiiiiiiiiiis"
  $stmtU->bind_param(
    "ssssiiiiiiiiiiiis",
    $seriennummer,
    $typ,
    $kennung,
    $ausgabe_datum,
    $ladegeraet,
    $antenne,
    $schutztasche,
    $kamerad_id,
    $programm_obm,
    $programm_agt,
    $programm_gg,
    $programm_ggf,
    $programm_elw,
    $programm_fuest,
    $programm_kfb,
    $id,
    $einheit
  );
  $stmtU->execute();

  $_SESSION['flash'] = "<div class='alert alert-success'>✅ Melder erfolgreich aktualisiert.</div>";
  header("Location: melder_edit.php?id=".$id); exit;
}

// Flash
$flash = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);

// Hilfswerte
$kameraName = '';
if (!empty($melder['kamerad_id'])) {
  $q = $conn->prepare("SELECT vorname, nachname FROM kameraden WHERE id=? AND einheit=? LIMIT 1");
  $q->bind_param('is', $melder['kamerad_id'], $einheit);
  $q->execute();
  if ($r = $q->get_result()->fetch_assoc()) {
    $kameraName = trim(($r['vorname'] ?? '').' '.($r['nachname'] ?? ''));
  }
}
$zugeordnetBadge = $kameraName
  ? "<span class='badge text-bg-success'><i class=\"bi bi-person-check\"></i> zugeordnet</span>"
  : "<span class='badge text-bg-secondary'><i class=\"bi bi-person\"></i> frei</span>";

$zube = [];
if ((int)$melder['ladegeraet']===1)   $zube[] = "<span class='badge rounded-pill text-bg-dark'>Ladegerät</span>";
if ((int)$melder['antenne']===1)      $zube[] = "<span class='badge rounded-pill text-bg-dark'>Antenne</span>";
if ((int)$melder['schutztasche']===1) $zube[] = "<span class='badge rounded-pill text-bg-dark'>Schutztasche</span>";
$zubeHtml = empty($zube) ? "<span class='text-muted'>–</span>" : implode(' ', $zube);

// URL zum Übergabe-Dokument
$docUrl = "uebergabe_druck.php?typ=Melder&id=".(int)$melder['id'];
?>
<style>
  .summary-card .muted { color:#6c757d; }
  .summary-grid { display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
  @media (max-width: 768px){ .summary-grid { grid-template-columns: 1fr; } }
</style>

<div class="container my-4">
  <a href="melder.php" class="btn btn-outline-secondary mb-3"><i class="bi bi-arrow-left"></i> Zurück</a>

  <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
    <h2 class="mb-0">📟 Melder bearbeiten
      <small class="text-muted">#<?= (int)$melder['id'] ?></small>
    </h2>
    <div class="d-flex gap-2">
      <a href="<?= h($docUrl) ?>" class="btn btn-primary">
        <i class="bi bi-file-earmark-text"></i> Übergabe-Dokument
      </a>
    </div>
  </div>

  <?= $flash ?>

  <!-- Kopf-Summary -->
  <div class="card shadow-sm summary-card mt-3">
    <div class="card-body">
      <div class="summary-grid">
        <div>
          <div class="muted">Kennung</div>
          <div class="fs-5 fw-semibold"><?= h($melder['kennung'] ?: '–') ?></div>
        </div>
        <div>
          <div class="muted">Seriennummer</div>
          <div class="fs-5 text-monospace"><?= h($melder['seriennummer']) ?></div>
        </div>
        <div>
          <div class="muted">Typ</div>
          <div class="fs-6"><?= h($melder['typ']) ?></div>
        </div>
        <div>
          <div class="muted">Zuordnung</div>
          <div class="fs-6">
            <?= $kameraName ? h($kameraName) : '–' ?> &nbsp; <?= $zugeordnetBadge ?>
          </div>
        </div>
        <div>
          <div class="muted">Ausgabe-Datum</div>
          <div class="fs-6"><?= $melder['ausgabe_datum'] ? date('d.m.Y', strtotime($melder['ausgabe_datum'])) : '–' ?></div>
        </div>
        <div>
          <div class="muted">Zubehör</div>
          <div class="fs-6"><?= $zubeHtml ?></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Formular -->
  <form method="post" class="card shadow-sm p-4 mt-3">
    <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label">Seriennummer *</label>
        <input type="text" name="seriennummer" class="form-control" value="<?= h($melder['seriennummer']) ?>" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Typ *</label>
        <input type="text" name="typ" class="form-control" value="<?= h($melder['typ']) ?>" required>
      </div>

      <div class="col-md-6">
        <label class="form-label">Kennung</label>
        <input type="text" name="kennung" class="form-control" value="<?= h($melder['kennung']) ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Ausgabe-Datum</label>
        <input type="date" name="ausgabe_datum" class="form-control" value="<?= h($melder['ausgabe_datum']) ?>">
      </div>

      <div class="col-md-6">
        <label class="form-label">Kamerad</label>
        <select name="kamerad_id" class="form-select">
          <option value="">– Keine Auswahl –</option>
          <?php mysqli_data_seek($kameraden,0); while ($k = $kameraden->fetch_assoc()): ?>
            <option value="<?= (int)$k['id'] ?>" <?= ((int)$melder['kamerad_id'] === (int)$k['id']) ? 'selected' : '' ?>>
              <?= h($k['nachname'].', '.$k['vorname']) ?>
            </option>
          <?php endwhile; ?>
        </select>
      </div>

      <div class="col-md-6">
        <label class="form-label d-block">Zubehör</label>
        <div class="d-flex flex-wrap gap-3">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="ladegeraet" id="ladegeraet" <?= $melder['ladegeraet'] ? 'checked' : '' ?>>
            <label class="form-check-label" for="ladegeraet">Ladegerät</label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="antenne" id="antenne" <?= $melder['antenne'] ? 'checked' : '' ?>>
            <label class="form-check-label" for="antenne">Antenne</label>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="schutztasche" id="schutztasche" <?= $melder['schutztasche'] ? 'checked' : '' ?>>
            <label class="form-check-label" for="schutztasche">Schutztasche</label>
          </div>
        </div>
      </div>

      <div class="col-12">
        <label class="form-label"><b>Programmierungen</b></label>
        <div class="row g-2">
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_obm" id="programm_obm" <?= $melder['programm_obm'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_obm">Ortsbrandmeister</label>
            </div>
          </div>
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_agt" id="programm_agt" <?= $melder['programm_agt'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_agt">Atemschutz</label>
            </div>
          </div>
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_gg" id="programm_gg" <?= $melder['programm_gg'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_gg">Gefahrgutgruppe</label>
            </div>
          </div>
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_ggf" id="programm_ggf" <?= $melder['programm_ggf'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_ggf">Gefahrgutgruppenführer</label>
            </div>
          </div>
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_elw" id="programm_elw" <?= $melder['programm_elw'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_elw">ELW</label>
            </div>
          </div>
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_fuest" id="programm_fuest" <?= $melder['programm_fuest'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_fuest">FüST</label>
            </div>
          </div>
          <div class="col-sm-6 col-md-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="programm_kfb" id="programm_kfb" <?= $melder['programm_kfb'] ? 'checked' : '' ?>>
              <label class="form-check-label" for="programm_kfb">KFB</label>
            </div>
          </div>
        </div>
      </div>

    </div>

    <div class="d-flex justify-content-between align-items-center mt-4">
      <div class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
      <div class="d-flex gap-2">
        <a href="<?= h($docUrl) ?>" class="btn btn-outline-primary">
          <i class="bi bi-file-earmark-text"></i> Übergabe-Dokument
        </a>
        <button type="submit" name="melder_speichern" class="btn btn-primary">
          <i class="bi bi-save"></i> Speichern
        </button>
      </div>
    </div>
  </form>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ob_end_flush(); ?>
