<?php
// kameraden.php – Mannschaftsverwaltung (Modern UI)
ob_start();
session_start();

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

// Zugriffsschutz
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// CSRF Init
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

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

if (empty($user_einheit)) {
    echo '<div class="container my-5"><div class="alert alert-warning">⚠️ Keine Einheit in der Session.</div></div>';
    include 'includes/footer.php'; exit;
}

// --------------------------------------------------
// POST: 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 alert-dismissible fade show'>Ungültiger Sicherheits-Token.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    } elseif ($id > 0) {
        $stmt_sel = $conn->prepare("SELECT archiv, vorname, nachname FROM kameraden WHERE id = ? AND einheit = ?");
        $stmt_sel->bind_param("is", $id, $user_einheit);
        $stmt_sel->execute();
        $data = $stmt_sel->get_result()->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()) {
                $name = htmlspecialchars($data['vorname'] . ' ' . $data['nachname']);
                if ($neuer_status === 'x') {
                    $meldung = "<div class='alert alert-secondary alert-dismissible fade show'>🗂️ <strong>$name</strong> wurde archiviert.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
                } else {
                    $meldung = "<div class='alert alert-success alert-dismissible fade show'>👋 <strong>$name</strong> wurde reaktiviert.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
                }
            } else {
                $meldung = "<div class='alert alert-danger alert-dismissible fade show'>Fehler beim Aktualisieren.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            }
            $stmt_upd->close();
        }
    }
}

// --------------------------------------------------
// POST: Neuer Kamerad
// --------------------------------------------------
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 = ? AND einheit = ?");
        $stmt_check->bind_param("ss", $spindnr, $user_einheit);
        $stmt_check->execute();
        $check_result = $stmt_check->get_result();
        $stmt_check->close();

        if ($check_result->num_rows > 0) {
            $meldung = "<div class='alert alert-warning alert-dismissible fade show'>⚠️ Spindnummer <strong>$spindnr</strong> ist bereits vergeben!<button type='button' class='btn-close' data-bs-dismiss='alert'></button></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 alert-dismissible fade show'>✅ Kamerad erfolgreich angelegt.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            } else {
                $meldung = "<div class='alert alert-danger alert-dismissible fade show'>Fehler beim Speichern.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            }
            $stmt->close();
        }
    } else {
        $meldung = "<div class='alert alert-warning alert-dismissible fade show'>Bitte Vorname, Nachname und Spindnummer ausfüllen.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    }
}

// --------------------------------------------------
// Datenabruf (mit Suche)
// --------------------------------------------------
$sql = "SELECT id, vorname, nachname, email, spindnr, archiv FROM kameraden WHERE einheit = ?";
$params = [$user_einheit];
$types = "s";

// Filter: Archiv
if (!$show_archived) {
    $sql .= " AND (archiv IS NULL OR archiv = '')";
}

// Filter: Suche
if ($search !== '') {
    $sql .= " AND (vorname LIKE ? OR nachname LIKE ? OR spindnr LIKE ?)";
    $like = "%$search%";
    $params[] = $like; $params[] = $like; $params[] = $like;
    $types .= "sss";
}

$sql .= " ORDER BY archiv ASC, nachname ASC, vorname ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
?>

<style>
  /* Modern Table Styling (Consistent with other pages) */
  .avatar-circle {
      width: 38px; height: 38px;
      background-color: #e2e8f0; color: #475569;
      border-radius: 50%;
      display: flex; align-items: center; justify-content: center;
      font-weight: 700; font-size: 0.9rem;
      margin-right: 12px;
      text-transform: uppercase;
  }
  .table-modern th { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; background: #f8fafc; font-weight: 600; border-bottom: 2px solid #e2e8f0; }
  .table-modern td { vertical-align: middle; border-bottom: 1px solid #f1f5f9; padding: 12px 16px; color: #1e293b; }
  .table-modern tr:hover { background-color: #f8fafc; }

  /* Text Readability */
  .text-dark-primary { color: #1e293b; }
  .text-dark-secondary { color: #64748b; }
</style>

<div class="container my-5">

  <div class="d-flex flex-wrap justify-content-between align-items-end gap-3 mb-4">
    <div>
      <h2 class="fw-bold mb-1"><i class="bi bi-people-fill text-primary"></i> Mannschaft</h2>
      <div class="text-muted small">Verwaltung der Einheit <span class="badge bg-secondary-subtle text-secondary border"><?= htmlspecialchars($user_einheit) ?></span></div>
    </div>

    <div class="d-flex flex-wrap gap-2">
      <form method="get" class="d-flex gap-2">
         <?php if($show_archived): ?><input type="hidden" name="show_archived" value="1"><?php endif; ?>
         <div class="input-group">
            <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control border-start-0 ps-0" placeholder="Name oder Spind..." value="<?= htmlspecialchars($search) ?>">
         </div>
      </form>

      <a href="?show_archived=<?= $show_archived ? '0' : '1' ?><?= $search ? '&search='.urlencode($search) : '' ?>"
         class="btn <?= $show_archived ? 'btn-secondary' : 'btn-outline-secondary' ?>">
         <?= $show_archived ? '<i class="bi bi-archive-fill"></i> Archiv ausblenden' : '<i class="bi bi-archive"></i> Archiv zeigen' ?>
      </a>

      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#kameradModal">
        <i class="bi bi-person-plus-fill"></i> Neu
      </button>
    </div>
  </div>

  <?= $meldung ?>

  <div class="card shadow-sm border-0">
    <div class="table-responsive">
      <table class="table table-modern align-middle mb-0">
        <thead>
          <tr>
            <th class="ps-4">Kamerad/in</th>
            <th>Kontakt</th>
            <th>Spind-Nr.</th>
            <th>Status</th>
            <th class="text-end pe-4"></th>
          </tr>
        </thead>
        <tbody>
          <?php if ($result->num_rows === 0): ?>
            <tr>
              <td colspan="5" class="text-center py-5">
                <i class="bi bi-person-slash fs-1 text-muted opacity-25"></i>
                <p class="text-muted mt-2 mb-0">Keine Einträge gefunden.</p>
              </td>
            </tr>
          <?php else: while ($row = $result->fetch_assoc()):
              // Initialen berechnen
              $initials = substr($row['vorname'], 0, 1) . substr($row['nachname'], 0, 1);
              $isArchived = ($row['archiv'] === 'x');
              $rowClass = $isArchived ? 'opacity-75 bg-light' : '';
          ?>
            <tr class="<?= $rowClass ?>">
              <td class="ps-4">
                <div class="d-flex align-items-center">
                  <div class="avatar-circle <?= $isArchived ? 'bg-secondary text-white' : '' ?>">
                    <?= htmlspecialchars($initials) ?>
                  </div>
                  <div>
                    <div class="fw-bold text-dark-primary fs-6">
                        <?= htmlspecialchars($row['nachname'] . ', ' . $row['vorname']) ?>
                    </div>
                  </div>
                </div>
              </td>

              <td>
                <?php if (!empty($row['email'])): ?>
                   <a href="mailto:<?= htmlspecialchars($row['email']) ?>" class="text-decoration-none text-dark-secondary">
                     <i class="bi bi-envelope me-1"></i> <?= htmlspecialchars($row['email']) ?>
                   </a>
                <?php else: ?>
                   <span class="text-muted small">–</span>
                <?php endif; ?>
              </td>

              <td>
                <span class="font-monospace bg-white border px-2 py-1 rounded fw-bold text-dark-primary">
                    <?= htmlspecialchars($row['spindnr']) ?>
                </span>
              </td>

              <td>
                <?php if ($isArchived): ?>
                  <span class="badge bg-secondary">Archiviert</span>
                <?php else: ?>
                  <span class="badge bg-success-subtle text-success border border-success-subtle">Aktiv</span>
                <?php endif; ?>
              </td>

              <td class="text-end pe-4">
                <div class="dropdown">
                  <button class="btn btn-sm btn-light rounded-circle shadow-sm" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-three-dots-vertical"></i>
                  </button>
                  <ul class="dropdown-menu dropdown-menu-end border-0 shadow">
                    <li>
                        <a class="dropdown-item" href="kamerad_edit.php?id=<?= (int)$row['id'] ?>">
                            <i class="bi bi-pencil me-2 text-muted"></i> Bearbeiten
                        </a>
                    </li>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                      <form method="post" class="d-inline">
                         <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                         <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                         <button type="submit" name="toggle_archiv" class="dropdown-item <?= $isArchived ? 'text-success' : 'text-secondary' ?>">
                            <?php if($isArchived): ?>
                                <i class="bi bi-box-arrow-up me-2"></i> Reaktivieren
                            <?php else: ?>
                                <i class="bi bi-archive me-2"></i> Archivieren
                            <?php endif; ?>
                         </button>
                      </form>
                    </li>
                  </ul>
                </div>
              </td>
            </tr>
          <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade" id="kameradModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-person-plus-fill text-primary me-2"></i>Neuen Kameraden hinzufügen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">

        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label small fw-bold">Vorname *</label>
                <input type="text" name="vorname" class="form-control" required>
            </div>
            <div class="col-md-6">
                <label class="form-label small fw-bold">Nachname *</label>
                <input type="text" name="nachname" class="form-control" required>
            </div>

            <div class="col-12">
                <label class="form-label small fw-bold">E-Mail Adresse</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                    <input type="email" name="email" class="form-control" placeholder="optional">
                </div>
            </div>

            <div class="col-12">
                <label class="form-label small fw-bold">Spindnummer *</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-key"></i></span>
                    <input type="text" name="spindnr" class="form-control" required>
                </div>
                <div class="form-text">Muss innerhalb der Einheit eindeutig sein.</div>
            </div>
        </div>

      </div>
      <div class="modal-footer bg-light">
        <input type="hidden" name="csrf_token" value="<?= $_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 px-4">Speichern</button>
      </div>
    </form>
  </div>
</div>

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