<?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'];

?>

<style>
  /* --- Tab Design (Identisch zu psa.php) --- */

  /* Standard Zustand (Inaktiv) */
  .nav-tabs .nav-link {
      background-color: #f8f9fa; /* Hellgrauer Hintergrund */
      color: #000000 !important; /* SCHWARZE SCHRIFT ERZWINGEN */
      font-weight: 500;
      border: 1px solid #dee2e6;
      border-bottom: none;
      margin-right: 2px;
  }

  /* Hover Zustand */
  .nav-tabs .nav-link:hover {
      background-color: #e9ecef;
      color: #000000 !important;
      border-color: #dee2e6;
  }

  /* Aktiver Zustand */
  .nav-tabs .nav-link.active {
      background-color: #ffffff !important; /* Weißer Hintergrund */
      color: #000000 !important; /* Schwarze Schrift */
      font-weight: 800; /* Extra Fett */
      border-color: #dee2e6 #dee2e6 #fff; /* Rahmen unten offen */
      border-top: 3px solid #0d6efd; /* Blauer Akzent oben */
  }

  /* Container unter den Tabs */
  .tab-content-container {
      background: #fff;
      border: 1px solid #dee2e6;
      border-top: none;
      border-bottom-left-radius: 0.375rem;
      border-bottom-right-radius: 0.375rem;
      box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
      padding: 1.5rem; /* Padding für den Inhalt */
  }

  /* Tabelle */
  .table-modern th {
      font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px;
      color: #6c757d; background: #f8f9fa; font-weight: 600;
      border-bottom: 2px solid #e9ecef;
  }
  .table-modern td {
      vertical-align: middle;
      border-bottom: 1px solid #f1f5f9;
      padding: 10px 8px;
      color: #212529;
  }
</style>

<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">
    <div class="col-lg-8">

      <ul class="nav nav-tabs border-bottom-0" 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-container">
        <div class="tab-content">

          <div class="tab-pane fade show active" id="daten" role="tabpanel">
            <form method="post">
              <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label fw-bold">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 fw-bold">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 fw-bold">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 fw-bold">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 text-muted">Kamerad (aus Spindzuordnung)</label>
                  <input type="text" class="form-control bg-light" value="<?= h(trim(($psa['vorname'] ?? '').' '.($psa['nachname'] ?? ''))) ?>" readonly>
                </div>
                <?php endif; ?>
              </div>

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

          <div class="tab-pane fade" id="waesche" role="tabpanel">

              <form method="post" class="mb-4">
                <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                <h5 class="mb-3 border-bottom pb-2">Eintrag hinzufügen</h5>

                <div class="mb-2 fw-bold">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"><i class="bi bi-plus-lg"></i> Hinzufügen</button>
                </div>
              </form>

              <hr class="my-4">

              <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Verlauf <span class="badge bg-light text-dark border ms-2"><?= (int)$count ?></span></h5>
              </div>

              <?php if ($count == 0): ?>
                <div class="alert alert-light border text-center text-muted">Noch keine Historie vorhanden.</div>
              <?php else: ?>
                <div class="table-responsive">
                  <table class="table table-modern align-middle mb-0">
                    <thead>
                      <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 class="small text-muted"><?= $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 border-0" name="del_hist" title="Löschen"><i class="bi bi-trash"></i></button>
                            </form>
                          </td>
                        </tr>
                      <?php endwhile; ?>
                    </tbody>
                  </table>
                </div>
              <?php endif; ?>

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

    <div class="col-lg-4">
      <div class="card shadow-sm border-0">
        <div class="card-body">
          <h5 class="card-title mb-3 fw-bold border-bottom pb-2">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">
        <i class="bi bi-info-circle me-1"></i> Die Zuordnung zum Kameraden erfolgt automatisch über die Spindnummer.
      </div>
    </div>
  </div>
</div>

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