<?php
ob_start();
session_start();
include 'includes/db.php';
include 'includes/header.php';
include 'includes/nav.php';

$meldung = '';
$spindnr = $_GET['spindnr'] ?? null;

// Wenn kein Spind übergeben wurde
if (!$spindnr) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Keine Spindnummer angegeben.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Kamerad laden
$stmt = $conn->prepare("SELECT * FROM kameraden WHERE spindnr = ?");
$stmt->bind_param("s", $spindnr);
$stmt->execute();
$kamerad = $stmt->get_result()->fetch_assoc();

if (!$kamerad) {
    echo "<div class='container my-5'><div class='alert alert-danger'>Kamerad nicht gefunden.</div></div>";
    include 'includes/footer.php';
    exit;
}

// Authentifizierung per PIN
if (!isset($_SESSION['auth_spindnr']) || $_SESSION['auth_spindnr'] !== $spindnr) {
    // PIN setzen
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pin_erstellen'])) {
        $neuer_pin = intval($_POST['neuer_pin']);
        if ($neuer_pin >= 1000 && $neuer_pin <= 9999) {
            $stmt = $conn->prepare("UPDATE kameraden SET pin = ? WHERE spindnr = ? AND pin = 0");
            $stmt->bind_param("is", $neuer_pin, $spindnr);
            $stmt->execute();
            if ($stmt->affected_rows > 0) {
                $meldung = '<div class="alert alert-success mt-3">✅ PIN wurde erfolgreich gesetzt. Bitte jetzt einloggen.</div>';
            } else {
                $meldung = '<div class="alert alert-danger mt-3">❌ PIN konnte nicht gesetzt werden oder existiert bereits.</div>';
            }
        } else {
            $meldung = '<div class="alert alert-warning mt-3">❗ Bitte eine 4-stellige Zahl als PIN eingeben.</div>';
        }
    }

    // PIN-Eingabe prüfen
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pin_eingabe'])) {
        $eingegebene_pin = $_POST['pin'];
        $stmt = $conn->prepare("SELECT * FROM kameraden WHERE spindnr = ? AND pin = ?");
        $stmt->bind_param("si", $spindnr, $eingegebene_pin);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $_SESSION['auth_spindnr'] = $spindnr;
            $_SESSION['vorbefuellung'] = [
                'name' => $row['vorname'] . ' ' . $row['nachname'],
                'email' => $row['email'],
                'spindnr' => $spindnr
            ];
            header("Location: ?spindnr=" . urlencode($spindnr));
            exit;
        } else {
            $meldung = '<div class="alert alert-danger mt-3">❌ Falscher PIN!</div>';
        }
    }

    // Wenn noch kein PIN gesetzt ist
    if (intval($kamerad['pin']) === 0) {
        echo "<div class='container my-5'><div class='col-lg-6 mx-auto'><h3 class='mb-4'>🔐 PIN erstellen</h3>{$meldung}<form method='post' class='card p-4 shadow-sm'><input type='number' name='neuer_pin' class='form-control mb-3' placeholder='4-stelliger PIN' required><button type='submit' name='pin_erstellen' class='btn btn-success w-100'>🔒 PIN setzen</button></form></div></div>";
        include 'includes/footer.php';
        ob_end_flush();
        exit;
    } else {
        echo "<div class='container my-5'><div class='col-lg-6 mx-auto'><h3 class='mb-4'>🔐 PIN-Eingabe</h3>{$meldung}<form method='post' class='card p-4 shadow-sm'><input type='password' name='pin' class='form-control mb-3' placeholder='PIN' required><button type='submit' name='pin_eingabe' class='btn btn-primary w-100'>✅ Bestätigen</button></form></div></div>";
        include 'includes/footer.php';
        ob_end_flush();
        exit;
    }
}

// Melder laden
$stmt = $conn->prepare("SELECT typ, seriennummer FROM melder WHERE kamerad_id = ?");
$stmt->bind_param("i", $kamerad['id']);
$stmt->execute();
$melder = $stmt->get_result();

// PSA laden
$stmt = $conn->prepare("SELECT typ, groesse, hersteller, modell, status, id_code FROM psa_ausruestung WHERE spindnr = ?");
$stmt->bind_param("s", $spindnr);
$stmt->execute();
$psa = $stmt->get_result();

// Transponder und Schlüssel
$stmt = $conn->prepare("SELECT * FROM transponder_schluessel WHERE spindnr = ?");
$stmt->bind_param("s", $spindnr);
$stmt->execute();
$ts = $stmt->get_result();

// Ticketverarbeitung
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ticket_absenden'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']) ?: '-';
    $fachbereich = trim($_POST['fachbereich']);
    $beschreibung = trim($_POST['beschreibung']);
    $ticketnummer = 'T-' . date('Ymd') . '-' . rand(1000, 9999);

    if ($name && $fachbereich && $beschreibung) {
        $stmt = $conn->prepare("INSERT INTO neue_tickets (ticketnummer, fachbereich, name, spindnr, beschreibung, status, erstellt_am) VALUES (?, ?, ?, ?, ?, 'offen', NOW())");
        $stmt->bind_param("sssss", $ticketnummer, $fachbereich, $name, $spindnr, $beschreibung);
        $stmt->execute();

        unset($_SESSION['auth_spindnr'], $_SESSION['vorbefuellung']);
        $meldung = '<div class="alert alert-success mt-3">✅ Ticket wurde erfolgreich erstellt.</div>';
    } else {
        $meldung = '<div class="alert alert-danger mt-3">❌ Bitte alle Pflichtfelder ausfüllen!</div>';
    }
}
?>

<div class="container my-5">
  <h2 class="mb-4">🧾 Ausrüstung von <?= htmlspecialchars($kamerad['vorname'] . ' ' . $kamerad['nachname']) ?></h2>

  <div class="row mb-4">
    <div class="col-md-6">
      <h5>🔔 Melder</h5>
      <?php if ($melder->num_rows > 0): ?>
        <ul class="list-group">
          <?php while ($m = $melder->fetch_assoc()): ?>
            <li class="list-group-item">Typ: <?= htmlspecialchars($m['typ']) ?> | SN: <?= htmlspecialchars($m['seriennummer']) ?></li>
          <?php endwhile; ?>
        </ul>
      <?php else: ?><p class="text-muted">Kein Melder vorhanden.</p><?php endif; ?>
    </div>
    <div class="col-md-6">
      <h5>🗝️ Transponder & Schlüssel</h5>
      <?php if ($ts->num_rows > 0): ?>
        <ul class="list-group">
          <?php while ($t = $ts->fetch_assoc()): ?>
            <li class="list-group-item"><?= htmlspecialchars($t['typ']) ?>: <?= htmlspecialchars($t['nummer']) ?></li>
          <?php endwhile; ?>
        </ul>
      <?php else: ?><p class="text-muted">Keine Schlüssel / Transponder.</p><?php endif; ?>
    </div>
  </div>

  <h5 class="mb-3">👕 Persönliche Schutzausrüstung (PSA)</h5>
  <?php if ($psa->num_rows > 0): ?>
    <div class="table-responsive">
      <table class="table table-bordered">
        <thead class="table-light">
          <tr>
            <th>Typ</th><th>Größe</th><th>Hersteller</th><th>Modell</th><th>Status</th><th>ID-Code</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($p = $psa->fetch_assoc()): ?>
            <tr>
              <td><?= htmlspecialchars($p['typ']) ?></td>
              <td><?= htmlspecialchars($p['groesse']) ?></td>
              <td><?= htmlspecialchars($p['hersteller']) ?></td>
              <td><?= htmlspecialchars($p['modell']) ?></td>
              <td><?= htmlspecialchars($p['status']) ?></td>
              <td><?= htmlspecialchars($p['id_code']) ?></td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  <?php else: ?><p class="text-muted">Keine PSA-Daten vorhanden.</p><?php endif; ?>

  <hr class="my-5">

  <h2 class="mb-4 text-center">🛠️ Neues Ticket erstellen</h2>
  <?= $meldung ?>
  <form method="post" enctype="multipart/form-data" class="card p-4 bg-white shadow-sm">
    <div class="mb-3">
      <label class="form-label">Name *</label>
      <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($kamerad['vorname'] . ' ' . $kamerad['nachname']) ?>" required>
    </div>
    <div class="mb-3">
      <label class="form-label">E-Mail *</label>
      <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($kamerad['email']) ?>">
    </div>
    <div class="mb-3">
      <label class="form-label">Spindnummer</label>
      <input type="text" name="spindnr" class="form-control" value="<?= htmlspecialchars($spindnr) ?>" readonly>
    </div>
    <div class="mb-3">
      <label class="form-label">Fachbereich *</label>
      <select name="fachbereich" class="form-select" required>
        <option value="">-- Bitte auswählen --</option>
        <option value="Ortsbrandmeister">Ortsbrandmeister</option>
        <option value="PSA">PSA</option>
        <option value="Dienstbekleidung">Dienstbekleidung</option>
        <option value="Uniform">Uniform</option>
        <option value="Melder">Melder / Schlüssel / Transponder</option>
        <option value="Gerät">Geräte</option>
      </select>
    </div>
    <div class="mb-3">
      <label class="form-label">Beschreibung *</label>
      <textarea name="beschreibung" class="form-control" rows="4" required></textarea>
    </div>
    <div class="mb-3">
      <label class="form-label">Anhang (Bild oder PDF)</label>
      <input type="file" name="anhang" class="form-control" accept=".jpg,.jpeg,.png,.pdf">
    </div>
    <button type="submit" name="ticket_absenden" class="btn btn-primary w-100">✅ Ticket absenden</button>
  </form>
</div>

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