<?php
// psa_edit.php – PSA bearbeiten + Historie
ob_start();
session_start();

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

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'>Einheit fehlt.</div></div>"; include 'includes/footer.php'; exit; }

// CSRF
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function statusBadge($s){
  $low = mb_strtolower(trim((string)$s));
  $cls = ($low==='einsatzbereit') ? 'success' : (($low==='nicht einsatzbereit') ? 'danger' : 'secondary');
  return "<span class='badge text-bg-$cls'>".h($s ?: '—')."</span>";
}

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

// Eintrag laden (nur eigene Einheit!)
$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.id = ? AND psa.einheit = ?
  LIMIT 1
");
$stmt->bind_param("is", $id, $einheit);
$stmt->execute();
$psa = $stmt->get_result()->fetch_assoc();

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

// Speichern (Daten)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save'])) {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  } else {
    $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'] ?? '');
    $status     = trim($_POST['status'] ?? 'Einsatzbereit');

    if ($typ && $hersteller && $modell) {
      $u = $conn->prepare("
        UPDATE psa_ausruestung
           SET typ=?, hersteller=?, modell=?, groesse=?, spindnr=?, id_code=?, status=?
         WHERE id=? AND einheit=?
      ");
      $u->bind_param("sssssssis", $typ,$hersteller,$modell,$groesse,$spindnr,$id_code,$status,$id,$einheit);
      if ($u->execute()) {
        $_SESSION['flash_psa'] = "<div class='alert alert-success'>✅ Eintrag erfolgreich gespeichert.</div>";
        header("Location: psa_edit.php?id=".$id); exit;
      } else {
        $meldung = "<div class='alert alert-danger'>❌ Fehler beim Speichern.</div>";
      }
    } else {
      $meldung = "<div class='alert alert-warning'>Bitte alle Pflichtfelder (Typ, Hersteller, Modell) ausfüllen.</div>";
    }
  }
}

// Historie hinzufügen (Wäsche/Reparatur..)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_waesche'])) {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  } else {
    $datum     = trim($_POST['waesche_datum'] ?? '');
    $kommentar = trim($_POST['waesche_kommentar'] ?? '');
    $typenSel  = $_POST['eintrag_typ'] ?? [];
    if ($datum && !empty($typenSel)) {
      $ins = $conn->prepare("INSERT INTO psa_waesche (psa_id, datum, kommentar, typ) VALUES (?,?,?,?)");
      foreach ($typenSel as $t) {
        $t = trim($t);
        if ($t==='') continue;
        $ins->bind_param("isss", $id, $datum, $kommentar, $t);
        $ins->execute();
      }
      $_SESSION['flash_psa'] = "<div class='alert alert-success'>✅ Historie gespeichert.</div>";
      header("Location: psa_edit.php?id=".$id."#waesche"); exit;
    } else {
      $meldung = "<div class='alert alert-warning'>Bitte Datum und mindestens eine Eintragsart wählen.</div>";
    }
  }
}

// Historien-Eintrag löschen (optional)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['del_hist'])) {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $meldung = "<div class='alert alert-danger'>Sicherheitsprüfung fehlgeschlagen.</div>";
  } else {
    $hid = (int)($_POST['hist_id'] ?? 0);
    // nur löschen, wenn der Eintrag zu dieser PSA gehört:
    $d = $conn->prepare("DELETE FROM psa_waesche WHERE id=? AND psa_id=?");
    $d->bind_param("ii", $hid, $id);
    $d->execute();
    $_SESSION['flash_psa'] = "<div class='alert alert-success'>🗑️ Eintrag gelöscht.</div>";
    header("Location: psa_edit.php?id=".$id."#waesche"); exit;
  }
}

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

// Historie laden + Count
$cStmt = $conn->prepare("SELECT COUNT(*) AS c FROM psa_waesche WHERE psa_id=?");
$cStmt->bind_param("i",$id);
$cStmt->execute();
$count = ($cStmt->get_result()->fetch_assoc()['c'] ?? 0);

$lStmt = $conn->prepare("SELECT * FROM psa_waesche WHERE psa_id=? ORDER BY datum DESC, id DESC");
$lStmt->bind_param("i",$id);
$lStmt->execute();
$history = $lStmt->get_result();

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

?>
<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 bearbeiten</h2>
      <div class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>
    <div class="d-flex gap-2">
      <a href="psa.php" class="btn btn-outline-secondary">Zurück</a>
    </div>
  </div>

  <?= $flash ?: $meldung ?>

  <div class="row g-4">
    <!-- Hauptinhalte -->
    <div class="col-lg-8">
      <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" role="tab">Daten</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#waesche" role="tab">Historie (<?= (int)$count ?>)</a></li>
      </ul>

      <div class="tab-content">
        <!-- TAB: Daten -->
        <div class="tab-pane fade show active" id="daten" role="tabpanel">
          <form method="post" class="card p-4 bg-white shadow-sm">
            <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
            <div class="row g-3">
              <div class="col-md-6">
                <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 value="<?= h($t) ?>" <?= $psa['typ']===$t ? 'selected' : '' ?>><?= h($t) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Status</label>
                <select name="status" class="form-select" required>
                  <option value="Einsatzbereit" <?= $psa['status']==='Einsatzbereit' ? 'selected' : '' ?>>Einsatzbereit</option>
                  <option value="Nicht Einsatzbereit" <?= $psa['status']==='Nicht Einsatzbereit' ? 'selected' : '' ?>>Nicht Einsatzbereit</option>
                </select>
              </div>

              <div class="col-md-6">
                <label class="form-label">Hersteller*</label>
                <input type="text" name="hersteller" class="form-control" value="<?= h($psa['hersteller']) ?>" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">Modell*</label>
                <input type="text" name="modell" class="form-control" value="<?= h($psa['modell']) ?>" required>
              </div>

              <div class="col-md-4">
                <label class="form-label">Größe</label>
                <input type="text" name="groesse" class="form-control" value="<?= h($psa['groesse']) ?>">
              </div>
              <div class="col-md-4">
                <label class="form-label">Spindnummer</label>
                <input type="text" name="spindnr" class="form-control text-monospace" value="<?= h($psa['spindnr']) ?>">
              </div>
              <div class="col-md-4">
                <label class="form-label">ID-Code</label>
                <input type="text" name="id_code" class="form-control" value="<?= h($psa['id_code']) ?>">
              </div>

              <?php if (($psa['vorname'] ?? '') || ($psa['nachname'] ?? '')): ?>
              <div class="col-12">
                <label class="form-label">Kamerad (aus Spindzuordnung)</label>
                <input type="text" class="form-control" value="<?= h(trim(($psa['vorname'] ?? '').' '.($psa['nachname'] ?? ''))) ?>" readonly>
              </div>
              <?php endif; ?>
            </div>

            <div class="d-flex gap-2 mt-4">
              <button type="submit" name="save" class="btn btn-primary">Speichern</button>
              <a href="psa.php" class="btn btn-secondary">Abbrechen</a>
            </div>
          </form>
        </div>

        <!-- TAB: Historie -->
        <div class="tab-pane fade" id="waesche" role="tabpanel">
          <div class="card p-4 bg-white shadow-sm">
            <form method="post" class="mb-4">
              <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
              <h5 class="mb-3">Eintrag hinzufügen</h5>

              <div class="mb-2">Eintragsart</div>
              <div class="d-flex flex-wrap gap-3 mb-3">
                <?php
                  $arten = ['Wäsche','Reparatur','Pflege','Prüfung'];
                  foreach($arten as $a): $idc = 't_'.md5($a);
                ?>
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="eintrag_typ[]" value="<?= h($a) ?>" id="<?= $idc ?>">
                    <label class="form-check-label" for="<?= $idc ?>"><?= h($a) ?></label>
                  </div>
                <?php endforeach; ?>
              </div>

              <div class="row g-3">
                <div class="col-md-4">
                  <label class="form-label">Datum*</label>
                  <input type="date" name="waesche_datum" class="form-control" required>
                </div>
                <div class="col-md-8">
                  <label class="form-label">Kommentar</label>
                  <input type="text" name="waesche_kommentar" class="form-control" placeholder="z. B. Innenfutter gereinigt">
                </div>
              </div>

              <div class="mt-3">
                <button type="submit" name="add_waesche" class="btn btn-success">Speichern</button>
              </div>
            </form>

            <hr>
            <div class="d-flex justify-content-between align-items-center mb-2">
              <h5 class="mb-0">Einträge <span class="badge text-bg-secondary"><?= (int)$count ?></span></h5>
            </div>

            <?php if ($count == 0): ?>
              <div class="alert alert-light border">Noch keine Historie vorhanden.</div>
            <?php else: ?>
              <div class="table-responsive">
                <table class="table table-sm align-middle">
                  <thead class="table-light">
                    <tr>
                      <th style="min-width:140px;">Typ</th>
                      <th style="min-width:120px;">Datum</th>
                      <th>Kommentar</th>
                      <th style="min-width:140px;">Erstellt am</th>
                      <th class="text-end" style="width:80px;">Aktion</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php while($w = $history->fetch_assoc()): ?>
                      <tr>
                        <td><span class="badge text-bg-dark"><?= h($w['typ']) ?></span></td>
                        <td><?= $w['datum'] ? date('d.m.Y', strtotime($w['datum'])) : '—' ?></td>
                        <td><?= nl2br(h($w['kommentar'])) ?></td>
                        <td><?= $w['erstellt_am'] ? date('d.m.Y H:i', strtotime($w['erstellt_am'])) : '—' ?></td>
                        <td class="text-end">
                          <form method="post" onsubmit="return confirm('Diesen Eintrag löschen?');">
                            <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                            <input type="hidden" name="hist_id" value="<?= (int)$w['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger" name="del_hist">Löschen</button>
                          </form>
                        </td>
                      </tr>
                    <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            <?php endif; ?>

          </div>
        </div>
      </div>
    </div>

    <!-- Sidebar -->
    <div class="col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3">Kurzinfo</h5>
          <div class="mb-2"><span class="text-muted">Typ:</span> <strong><?= h($psa['typ']) ?></strong></div>
          <div class="mb-2"><span class="text-muted">Status:</span> <?= statusBadge($psa['status']) ?></div>
          <div class="mb-2"><span class="text-muted">Hersteller:</span> <?= h($psa['hersteller'] ?: '—') ?></div>
          <div class="mb-2"><span class="text-muted">Modell:</span> <?= h($psa['modell'] ?: '—') ?></div>
          <div class="mb-2"><span class="text-muted">Größe:</span> <?= h($psa['groesse'] ?: '—') ?></div>
          <div class="mb-2"><span class="text-muted">Spind:</span> <span class="text-monospace"><?= h($psa['spindnr'] ?: '—') ?></span></div>
          <div class="mb-2"><span class="text-muted">ID-Code:</span> <?= h($psa['id_code'] ?: '—') ?></div>
          <div class="mb-0"><span class="text-muted">Kamerad:</span> <?= h(trim(($psa['vorname'] ?? '').' '.($psa['nachname'] ?? '')) ?: '—') ?></div>
        </div>
      </div>
      <div class="small text-muted mt-2">
        Hinweis: Die Zuordnung zum Kameraden erfolgt über die Spindnummer.
      </div>
    </div>
  </div>
</div>

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