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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$meldung = '';
$user_einheit = $_SESSION['einheit'] ?? '';
$show_archived = isset($_GET['show_archived']);

// --------------------------------------------------
// Kamerad archivieren / reaktivieren
// --------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_archiv'])) {
    $csrf = $_POST['csrf_token'] ?? '';
    $id = intval($_POST['id'] ?? 0);

    if (!hash_equals($_SESSION['csrf_token'], $csrf)) {
        $meldung = "<div class='alert alert-danger'>Ungültiger Sicherheits-Token.</div>";
    } elseif ($id > 0 && $user_einheit !== '') {
        // Aktuellen Status holen
        $stmt_sel = $conn->prepare("SELECT archiv FROM kameraden WHERE id = ? AND einheit = ?");
        $stmt_sel->bind_param("is", $id, $user_einheit);
        $stmt_sel->execute();
        $res = $stmt_sel->get_result();
        $data = $res->fetch_assoc();
        $stmt_sel->close();

        if ($data) {
            $neuer_status = ($data['archiv'] === 'x') ? '' : 'x';
            $stmt_upd = $conn->prepare("UPDATE kameraden SET archiv = ? WHERE id = ? AND einheit = ?");
            $stmt_upd->bind_param("sis", $neuer_status, $id, $user_einheit);
            if ($stmt_upd->execute()) {
                if ($neuer_status === 'x') {
                    $meldung = "<div class='alert alert-warning'>Kamerad wurde archiviert.</div>";
                } else {
                    $meldung = "<div class='alert alert-success'>Kamerad wurde reaktiviert.</div>";
                }
            } else {
                $meldung = "<div class='alert alert-danger'>Fehler beim Aktualisieren.</div>";
            }
            $stmt_upd->close();
        }
    }
}

// --------------------------------------------------
// Kamerad hinzufügen
// --------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_kamerad'])) {
    $vorname = trim($_POST['vorname'] ?? '');
    $nachname = trim($_POST['nachname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $spindnr = trim($_POST['spindnr'] ?? '');

    if ($vorname && $nachname && $spindnr) {
        $stmt_check = $conn->prepare("SELECT id FROM kameraden WHERE spindnr = ?");
        $stmt_check->bind_param("s", $spindnr);
        $stmt_check->execute();
        $check_result = $stmt_check->get_result();
        $stmt_check->close();

        if ($check_result->num_rows > 0) {
            $meldung = "<div class='alert alert-danger'>Fehler: Spindnummer bereits vergeben!</div>";
        } else {
            $stmt = $conn->prepare("INSERT INTO kameraden (vorname, nachname, email, spindnr, einheit, archiv) VALUES (?, ?, ?, ?, ?, '')");
            $stmt->bind_param("sssss", $vorname, $nachname, $email, $spindnr, $user_einheit);
            if ($stmt->execute()) {
                $meldung = "<div class='alert alert-success'>Kamerad erfolgreich hinzugefügt.</div>";
            } else {
                $meldung = "<div class='alert alert-danger'>Fehler beim Speichern.</div>";
            }
            $stmt->close();
        }
    } else {
        $meldung = "<div class='alert alert-warning'>Bitte Vorname, Nachname und Spindnummer ausfüllen.</div>";
    }
}

// --------------------------------------------------
// Kameraden abrufen
// --------------------------------------------------
$query = "SELECT id, vorname, nachname, email, spindnr, archiv
          FROM kameraden
          WHERE einheit = ?";
if (!$show_archived) {
    $query .= " AND (archiv IS NULL OR archiv = '')";
}
$query .= " ORDER BY nachname ASC, vorname ASC";

$stmt_list = $conn->prepare($query);
$stmt_list->bind_param("s", $user_einheit);
$stmt_list->execute();
$result = $stmt_list->get_result();
$kameraden = $result->fetch_all(MYSQLI_ASSOC);
$stmt_list->close();
?>

<div class="container my-5">
  <h2 class="mb-4">Kameraden-Verwaltung</h2>

  <?= $meldung ?>

  <!-- Buttons -->
  <div class="d-flex justify-content-between mb-4">
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#kameradModal">
      + Neuen Kameraden hinzufügen
    </button>

    <?php if ($show_archived): ?>
      <a href="?"
         class="btn btn-outline-secondary">📂 Archiv ausblenden</a>
    <?php else: ?>
      <a href="?show_archived=1"
         class="btn btn-outline-secondary">📁 Archiv anzeigen</a>
    <?php endif; ?>
  </div>

  <!-- Modal -->
  <div class="modal fade" id="kameradModal" tabindex="-1" aria-labelledby="kameradModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <form method="post" class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="kameradModalLabel">Neuen Kameraden hinzufügen</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">Vorname</label>
            <input type="text" name="vorname" class="form-control" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Nachname</label>
            <input type="text" name="nachname" class="form-control" required>
          </div>
          <div class="mb-3">
            <label class="form-label">E-Mail (optional)</label>
            <input type="email" name="email" class="form-control">
          </div>
          <div class="mb-3">
            <label class="form-label">Spindnummer</label>
            <input type="text" name="spindnr" class="form-control" required>
          </div>
        </div>
        <div class="modal-footer">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
          <button type="submit" name="new_kamerad" class="btn btn-primary">Speichern</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Tabelle -->
  <div class="table-responsive">
    <table class="table table-bordered table-hover bg-white align-middle">
      <thead class="table-dark">
        <tr>
          <th>Vorname</th>
          <th>Nachname</th>
          <th>E-Mail</th>
          <th>Spindnummer</th>
          <th>Status</th>
          <th style="width:230px">Aktion</th>
        </tr>
      </thead>
      <tbody>
        <?php if (count($kameraden) === 0): ?>
          <tr><td colspan="6" class="text-center text-muted">Keine Kameraden gefunden.</td></tr>
        <?php else: ?>
          <?php foreach ($kameraden as $k): ?>
            <tr class="<?= $k['archiv'] === 'x' ? 'table-secondary' : '' ?>">
              <td><?= htmlspecialchars($k['vorname']) ?></td>
              <td><?= htmlspecialchars($k['nachname']) ?></td>
              <td><?= htmlspecialchars($k['email']) ?></td>
              <td><?= htmlspecialchars($k['spindnr']) ?></td>
              <td><?= $k['archiv'] === 'x' ? '<span class="badge bg-secondary">Archiviert</span>' : '<span class="badge bg-success">Aktiv</span>' ?></td>
              <td class="d-flex gap-2">
                <a href="kamerad_edit.php?id=<?= (int)$k['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>

                <form method="post" onsubmit="return confirm('Soll dieser Kamerad wirklich <?= $k['archiv'] === 'x' ? 'reaktiviert' : 'archiviert' ?> werden?');">
                  <input type="hidden" name="id" value="<?= (int)$k['id'] ?>">
                  <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                  <button type="submit" name="toggle_archiv"
                          class="btn btn-sm <?= $k['archiv'] === 'x' ? 'btn-outline-success' : 'btn-outline-warning' ?>">
                    <?= $k['archiv'] === 'x' ? 'Reaktivieren' : 'Archivieren' ?>
                  </button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

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