<?php
// transponder.php (fix: nur Variablen an bind_param + dyn. bind Fix)
ob_start();
session_start();

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

// ─────────────────────────────────────────────────────────────
// Zugriffsschutz
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
$user_einheit = $_SESSION['einheit'] ?? '';
if ($user_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';
    ob_end_flush();
    exit;
}

// ─────────────────────────────────────────────────────────────
// Helfer
const FIXED_TYP = 'Transponder';
$fixedTyp = FIXED_TYP; // WICHTIG: nur Variable an bind_param übergeben!
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// bind_param braucht Referenzen
function refValues(array $arr){
    $refs = [];
    foreach ($arr as $k => $v) { $refs[$k] = &$arr[$k]; }
    return $refs;
}

// Flash-Messages
if (!isset($_SESSION['flash'])) $_SESSION['flash'] = [];
function flash_add($type,$msg){ $_SESSION['flash'][]=['t'=>$type,'m'=>$msg]; }
function flash_render(){
    if (empty($_SESSION['flash'])) return;
    echo "<div class='container mt-3'>";
    foreach($_SESSION['flash'] as $f){
        $map = ['success'=>'success','error'=>'danger','warn'=>'warning','info'=>'info'];
        $cls = $map[$f['t']] ?? 'secondary';
        echo "<div class='alert alert-{$cls} d-flex align-items-center gap-2 mb-2'>".$f['m']."</div>";
    }
    echo "</div>";
    $_SESSION['flash'] = [];
}

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

// PRG Redirect
function go_self(array $params = []){
    $base = strtok($_SERVER['REQUEST_URI'], '?');
    $q = array_merge($_GET, $params);
    header('Location: ' . $base . (empty($q) ? '' : '?' . http_build_query($q)));
    exit;
}

// ─────────────────────────────────────────────────────────────
// Filter & Pagination
$q       = trim($_GET['q'] ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset  = ($page - 1) * $perPage;

// ─────────────────────────────────────────────────────────────
// Aktionen
if ($_SERVER['REQUEST_METHOD']==='POST') {
    $action = $_POST['action'] ?? '';
    $token  = $_POST['csrf'] ?? '';
    if (!csrf_check($token)) {
        flash_add('error','❌ Sicherheitsprüfung fehlgeschlagen (CSRF). Bitte erneut versuchen.');
        go_self();
    }

    if ($action === 'save') {
        $id        = (int)($_POST['id'] ?? 0);
        $spindnr   = trim($_POST['spindnr'] ?? '');
        $nummer    = trim($_POST['nummer'] ?? '');
        $kommentar = trim($_POST['kommentar'] ?? '');

        if ($spindnr === '' || $nummer === '') {
            flash_add('error', '❌ Bitte Spindnummer und Nummer ausfüllen.');
            go_self();
        }

        if ($id > 0) {
            // UPDATE
            $stmt = $conn->prepare("
                UPDATE transponder_schluessel
                SET spindnr = ?, nummer = ?, kommentar = ?
                WHERE id = ? AND einheit = ? AND typ = ?
            ");
            // nur Variablen!
            $einheitVar = $user_einheit;
            $typVar = $fixedTyp;
            $stmt->bind_param('sssiss', $spindnr, $nummer, $kommentar, $id, $einheitVar, $typVar);
            $ok = $stmt->execute();
            if ($ok && $stmt->affected_rows >= 0) {
                flash_add('success', '✅ Eintrag aktualisiert.');
            } else {
                flash_add('warn', 'ℹ️ Eintrag konnte nicht aktualisiert werden (Einheit/Typ prüfen).');
            }
            go_self();
        } else {
            // INSERT
            $stmt = $conn->prepare("
                INSERT INTO transponder_schluessel (spindnr, typ, nummer, kommentar, einheit)
                VALUES (?, ?, ?, ?, ?)
            ");
            $einheitVar = $user_einheit;
            $typVar = $fixedTyp;
            $stmt->bind_param('sssss', $spindnr, $typVar, $nummer, $kommentar, $einheitVar);
            $ok = $stmt->execute();
            if ($ok && $stmt->affected_rows > 0) {
                flash_add('success', '✅ Transponder gespeichert.');
            } else {
                flash_add('error', '❌ Konnte nicht gespeichert werden.');
            }
            go_self();
        }
    }

    if ($action === 'delete') {
        $delId = (int)($_POST['id'] ?? 0);
        if ($delId > 0) {
            $stmt = $conn->prepare("DELETE FROM transponder_schluessel WHERE id = ? AND einheit = ? AND typ = ?");
            $einheitVar = $user_einheit;
            $typVar = $fixedTyp;
            $stmt->bind_param('iss', $delId, $einheitVar, $typVar);
            $stmt->execute();
            if ($stmt->affected_rows > 0) {
                flash_add('success', '🗑️ Eintrag gelöscht.');
            } else {
                flash_add('warn', 'ℹ️ Kein passender Eintrag gefunden.');
            }
        }
        go_self();
    }
}

// ─────────────────────────────────────────────────────────────
// Edit laden (optional)
$editData = null;
if (isset($_GET['edit']) && ctype_digit($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    $stmt = $conn->prepare("SELECT * FROM transponder_schluessel WHERE id = ? AND einheit = ? AND typ = ?");
    $einheitVar = $user_einheit;
    $typVar = $fixedTyp;
    $stmt->bind_param('iss', $editId, $einheitVar, $typVar);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows === 1) {
        $editData = $res->fetch_assoc();
    } else {
        flash_add('warn','ℹ️ Der Eintrag ist nicht (mehr) verfügbar.');
        go_self();
    }
}

// ─────────────────────────────────────────────────────────────
// Liste (Count + Data)
$where  = "ts.typ = ? AND ts.einheit = ?";
$params = [$fixedTyp, $user_einheit];
$types  = 'ss';

if ($q !== '') {
    $where .= " AND (ts.spindnr LIKE ? OR ts.nummer LIKE ? OR CONCAT(COALESCE(k.vorname,''),' ',COALESCE(k.nachname,'')) LIKE ?)";
    $like = "%{$q}%";
    $params[] = $like; $types .= 's';
    $params[] = $like; $types .= 's';
    $params[] = $like; $types .= 's';
}

// COUNT
$sqlCount = "
    SELECT COUNT(*) AS cnt
    FROM transponder_schluessel ts
    LEFT JOIN kameraden k
      ON ts.spindnr = k.spindnr
     AND k.einheit = ?
    WHERE {$where}
";
$paramsCount = array_merge([$user_einheit], $params);
$typesCount  = 's' . $types;
$stmt = $conn->prepare($sqlCount);
$tmp = array_merge([$typesCount], $paramsCount);
call_user_func_array([$stmt, 'bind_param'], refValues($tmp));
$stmt->execute();
$total = (int)($stmt->get_result()->fetch_assoc()['cnt'] ?? 0);

// Pagination bounds
$maxPage = max(1, (int)ceil($total / $perPage));
if ($page > $maxPage) { $page = $maxPage; $offset = ($page-1)*$perPage; }

// DATA
$sqlData = "
    SELECT ts.*, k.vorname, k.nachname
    FROM transponder_schluessel ts
    LEFT JOIN kameraden k
      ON ts.spindnr = k.spindnr
     AND k.einheit = ?
    WHERE {$where}
    ORDER BY ts.nummer ASC, ts.id DESC
    LIMIT ? OFFSET ?
";
$paramsData = array_merge([$user_einheit], $params, [$perPage, $offset]);
$typesData  = $typesCount . 'ii';
$stmt = $conn->prepare($sqlData);
$tmp = array_merge([$typesData], $paramsData);
call_user_func_array([$stmt, 'bind_param'], refValues($tmp));
$stmt->execute();
$list = $stmt->get_result();

// ─────────────────────────────────────────────────────────────
// UI
flash_render();
?>
<div class="container my-4">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
    <div>
      <h2 class="mb-0">🔑 Transponderverwaltung
        <small class="badge text-bg-secondary align-middle ms-2">Einheit: <?= h($user_einheit) ?></small>
      </h2>
      <div class="text-muted small mt-1"><?= number_format($total,0,',','.') ?> Einträge</div>
    </div>
    <div class="d-flex gap-2">
      <form class="d-flex" method="get" action="">
        <input type="text" class="form-control" name="q" value="<?= h($q) ?>" placeholder="Suche: Spindnr, Name, Nummer…">
        <button class="btn btn-outline-primary ms-2" type="submit"><i class="bi bi-search"></i> Suchen</button>
        <?php if ($q !== ''): ?>
          <a class="btn btn-outline-secondary ms-2" href="?"><i class="bi bi-x-circle"></i> Reset</a>
        <?php endif; ?>
      </form>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalEdit"
              onclick="window.TX.openCreate()">
        <i class="bi bi-plus-circle"></i> Neu
      </button>
    </div>
  </div>
</div>

<div class="container">
  <?php if ($list && $list->num_rows > 0): ?>
    <div class="table-responsive">
      <table class="table table-hover align-middle">
        <thead class="table-light">
          <tr>
            <th style="width:110px;">Spindnr</th>
            <th>Name</th>
            <th style="width:180px;">Nummer</th>
            <th>Kommentar</th>
            <th style="width:92px;" class="text-end">Aktion</th>
          </tr>
        </thead>
        <tbody>
          <?php while($row = $list->fetch_assoc()):
                $name = trim(($row['vorname'] ?? '').' '.($row['nachname'] ?? ''));
                if ($name==='') $name = '—';
                $erst = $row['erstellt_am'] ?? '';
                $spBadge = $row['spindnr'] !== '' ? "<span class='badge text-bg-primary'>".h($row['spindnr'])."</span>" : '—';
          ?>
          <tr>
            <td><?= $spBadge ?></td>
            <td><?= h($name) ?></td>
            <td><span class="badge text-bg-dark"><?= h($row['nummer']) ?></span></td>
            <td class="text-truncate" style="max-width: 360px;"><?= h($row['kommentar']) ?></td>

            <td class="text-end">
              <div class="btn-group">
                <a class="btn btn-sm btn-success" title="Dokument erstellen"
                   href="uebergabe_druck.php?typ=Transponder&id=<?= (int)$row['id'] ?>" target="_blank" rel="noopener">
                  <i class="bi bi-file-earmark-text"></i>
                </a>
                <button class="btn btn-sm btn-warning" title="Bearbeiten"
                        data-bs-toggle="modal" data-bs-target="#modalEdit"
                        onclick='window.TX.openEdit(<?= (int)$row["id"] ?>, <?= json_encode($row, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>)'>
                  <i class="bi bi-pencil-square"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" title="Löschen"
                        data-bs-toggle="modal" data-bs-target="#modalDelete"
                        onclick='window.TX.openDelete(<?= (int)$row["id"] ?>, <?= json_encode((string)$row["nummer"]) ?>)'>
                  <i class="bi bi-trash"></i>
                </button>
              </div>
            </td>

          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>

    <?php if ($maxPage > 1): ?>
      <nav aria-label="Seiten">
        <ul class="pagination justify-content-center my-4">
          <?php
          function pageLink($p){
            $q = $_GET; $q['page'] = $p;
            return '?' . http_build_query($q);
          }
          ?>
          <li class="page-item <?= $page<=1?'disabled':'' ?>">
            <a class="page-link" href="<?= $page<=1?'#':h(pageLink($page-1)) ?>" tabindex="-1">&laquo;</a>
          </li>
          <?php
          $window = 2;
          $start = max(1, $page-$window);
          $end   = min($maxPage, $page+$window);
          if ($start>1){
            echo '<li class="page-item"><a class="page-link" href="'.h(pageLink(1)).'">1</a></li>';
            if ($start>2) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
          }
          for($p=$start;$p<=$end;$p++){
            $active = $p===$page ? 'active' : '';
            echo '<li class="page-item '.$active.'"><a class="page-link" href="'.h(pageLink($p)).'">'.$p.'</a></li>';
          }
          if ($end<$maxPage){
            if ($end<$maxPage-1) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
            echo '<li class="page-item"><a class="page-link" href="'.h(pageLink($maxPage)).'">'.$maxPage.'</a></li>';
          }
          ?>
          <li class="page-item <?= $page>=$maxPage?'disabled':'' ?>">
            <a class="page-link" href="<?= $page>=$maxPage?'#':h(pageLink($page+1)) ?>">&raquo;</a>
          </li>
        </ul>
      </nav>
    <?php endif; ?>

  <?php else: ?>
    <div class="alert alert-info my-4">
      <i class="bi bi-info-circle"></i> Noch keine Transponder erfasst. Klicke auf <strong>Neu</strong>, um den ersten Eintrag anzulegen.
    </div>
  <?php endif; ?>
</div>

<!-- Modal: Neu/Bearbeiten -->
<div class="modal fade" id="modalEdit" tabindex="-1" aria-labelledby="modalEditLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <form class="modal-content" method="post" action="">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="id" id="form-id" value="">
      <div class="modal-header">
        <h5 class="modal-title" id="modalEditLabel"><i class="bi bi-pass"></i> Transponder</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-3">
            <label class="form-label">Spindnummer *</label>
            <input type="text" class="form-control" name="spindnr" id="form-spindnr" placeholder="z. B. 104" required>
          </div>
          <div class="col-md-3">
            <label class="form-label">Typ</label>
            <input type="text" class="form-control" value="<?= h($fixedTyp) ?>" readonly>
          </div>
          <div class="col-md-6">
            <label class="form-label">Nummer / Kennung *</label>
            <input type="text" class="form-control" name="nummer" id="form-nummer" placeholder="z. B. T-2025-001" required>
          </div>
          <div class="col-12">
            <label class="form-label">Kommentar</label>
            <input type="text" class="form-control" name="kommentar" id="form-kommentar" placeholder="optional">
          </div>
          <div class="col-12">
            <div class="form-text">
              <i class="bi bi-shield-lock"></i> Eintrag wird automatisch für Einheit <strong><?= h($user_einheit) ?></strong> gespeichert.
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer justify-content-between">
        <div class="text-muted small"><span class="text-danger">*</span> Pflichtfelder</div>
        <div>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Abbrechen</button>
          <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Speichern</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Modal: Löschen -->
<div class="modal fade" id="modalDelete" tabindex="-1" aria-labelledby="modalDeleteLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <form class="modal-content" method="post" action="">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="id" id="delete-id" value="">
      <div class="modal-header">
        <h5 class="modal-title" id="modalDeleteLabel">Eintrag löschen?</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
      </div>
      <div class="modal-body">
        <p>Möchtest du den Transponder <strong id="delete-label">–</strong> wirklich löschen?</p>
        <p class="text-muted small mb-0"><i class="bi bi-exclamation-triangle"></i> Dieser Vorgang kann nicht rückgängig gemacht werden.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Abbrechen</button>
        <button type="submit" class="btn btn-danger"><i class="bi bi-trash"></i> Löschen</button>
      </div>
    </form>
  </div>
</div>

<script>
// Modale Helper
window.TX = {
  openCreate(){
    document.getElementById('modalEditLabel').textContent = 'Neuen Transponder anlegen';
    document.getElementById('form-id').value = '';
    document.getElementById('form-spindnr').value = '';
    document.getElementById('form-nummer').value = '';
    document.getElementById('form-kommentar').value = '';
  },
  openEdit(id, row){
    document.getElementById('modalEditLabel').textContent = 'Transponder bearbeiten';
    document.getElementById('form-id').value = id;
    document.getElementById('form-spindnr').value = (row.spindnr ?? '');
    document.getElementById('form-nummer').value = (row.nummer ?? '');
    document.getElementById('form-kommentar').value = (row.kommentar ?? '');
  },
  openDelete(id, label){
    document.getElementById('delete-id').value = id;
    document.getElementById('delete-label').textContent = label || '–';
  }
};
</script>

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