<?php
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;
}

$user_id      = (int)$_SESSION['user_id'];
$user_einheit = $_SESSION['einheit'] ?? '';
$is_admin     = (int)($_SESSION['is_admin'] ?? 0);

$id = (int)($_GET['id'] ?? 0);
$meldung = '';

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function fmtDate($ts){ return $ts ? date('d.m.Y H:i', strtotime($ts)) : '–'; }

// --- Ticket laden ---
$stmt = $conn->prepare("
  SELECT t.*, u.username AS bearbeiter_name
  FROM neue_tickets t
  LEFT JOIN users u ON t.bearbeiter_id = u.id
  WHERE t.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$ticket = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

// --- Zugriff: gleiche Einheit oder Admin ---
if ($is_admin === 0 && ($ticket['einheit'] ?? '') !== $user_einheit) {
    echo "<div class='container my-5'><div class='alert alert-warning'>🚫 Keine Berechtigung für dieses Ticket (falsche Einheit).</div></div>";
    include 'includes/footer.php';
    ob_end_flush();
    exit;
}

// ---------- Aktionen ----------

// Kommentar speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kommentar_absenden'])) {
    $kommentar = trim($_POST['kommentar'] ?? '');
    if ($kommentar !== '') {
        $st = $conn->prepare("INSERT INTO ticket_kommentare (ticket_id, user_id, kommentar, erstellt_am) VALUES (?, ?, ?, NOW())");
        $st->bind_param("iis", $id, $user_id, $kommentar);
        $st->execute();
        $st->close();
        $meldung = '<div class="alert alert-success">💬 Kommentar gespeichert.</div>';
    }
}

// Datei hochladen (zusätzliche Uploads)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['datei_upload'])) {
    if (!empty($_FILES['anhang']['name'])) {
        $uploadDirAbs = __DIR__ . '/uploads/tickets/';
        $uploadDirPub = 'uploads/tickets/';

        if (!is_dir($uploadDirAbs)) {
            @mkdir($uploadDirAbs, 0777, true);
        }

        $fileName = ($ticket['ticketnummer'] ?: ('T-' . $ticket['id'])) . '_' . uniqid('', true) . '_' . basename($_FILES['anhang']['name']);
        $absPath  = $uploadDirAbs . $fileName;

        if (move_uploaded_file($_FILES['anhang']['tmp_name'], $absPath)) {
            $meldung = '<div class="alert alert-success">📎 Datei erfolgreich hochgeladen.</div>';
        } else {
            $meldung = '<div class="alert alert-danger">❌ Upload fehlgeschlagen.</div>';
        }
    }
}

// Ticket übernehmen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['uebernehmen'])) {
    if ($ticket['status'] === 'offen') {
        $st = $conn->prepare("UPDATE neue_tickets SET status = 'in Bearbeitung', bearbeiter_id = ?, bearbeitet_am = NOW() WHERE id = ? AND status = 'offen'");
        $st->bind_param("ii", $user_id, $id);
        $st->execute();
        $st->close();
        $meldung = '<div class="alert alert-success">🛠️ Ticket übernommen.</div>';
        // Reload
        $stmt = $conn->prepare("SELECT t.*, u.username AS bearbeiter_name FROM neue_tickets t LEFT JOIN users u ON t.bearbeiter_id = u.id WHERE t.id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $ticket = $stmt->get_result()->fetch_assoc();
        $stmt->close();
    }
}

// Statuswechsel (Admin oder Bearbeiter, bzw. Wechsel auf „in Bearbeitung“)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['statuswechsel'])) {
    $neuer_status = $_POST['neuer_status'] ?? '';
    $erlaubt = in_array($neuer_status, ['offen','in Bearbeitung','erledigt'], true);
    $darf_setzen = ($is_admin > 0) || ($ticket['bearbeiter_id'] == $user_id) || ($neuer_status === 'in Bearbeitung');

    if ($erlaubt && $darf_setzen) {
        if ($neuer_status === 'in Bearbeitung') {
            $st = $conn->prepare("UPDATE neue_tickets SET status = ?, bearbeiter_id = ?, bearbeitet_am = NOW() WHERE id = ?");
            $st->bind_param("sii", $neuer_status, $user_id, $id);
        } elseif ($neuer_status === 'erledigt') {
            $st = $conn->prepare("UPDATE neue_tickets SET status = ?, erledigt_am = NOW() WHERE id = ?");
            $st->bind_param("si", $neuer_status, $id);
        } else { // offen
            $st = $conn->prepare("UPDATE neue_tickets SET status = ? WHERE id = ?");
            $st->bind_param("si", $neuer_status, $id);
        }
        $st->execute();
        $st->close();

        // Reload
        $stmt = $conn->prepare("SELECT t.*, u.username AS bearbeiter_name FROM neue_tickets t LEFT JOIN users u ON t.bearbeiter_id = u.id WHERE t.id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $ticket = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        $meldung = '<div class="alert alert-success">✅ Status geändert.</div>';
    } else {
        $meldung = '<div class="alert alert-warning">⚠️ Keine Berechtigung für diese Statusänderung.</div>';
    }
}

// ---------- Daten für Anzeige ----------

// Zusätzliche Uploads (Dateien mit Ticketnummer-Prefix)
$uploadRows = [];
$uploadDirAbs = __DIR__ . '/uploads/tickets/';
$uploadDirPub = 'uploads/tickets/';
if (is_dir($uploadDirAbs)) {
    $prefix = ($ticket['ticketnummer'] ?: ('T-' . $ticket['id'])) . "_";
    $matches = glob($uploadDirAbs . $prefix . "*");
    if ($matches) {
        foreach ($matches as $abs) {
            $basename = basename($abs);
            $uploadRows[] = [
                'name' => $basename,
                'url'  => $uploadDirPub . $basename,
                'ext'  => strtolower(pathinfo($basename, PATHINFO_EXTENSION)),
                'size' => filesize($abs)
            ];
        }
    }
}

// Kommentare laden
$st = $conn->prepare("
  SELECT k.*, u.username
  FROM ticket_kommentare k
  LEFT JOIN users u ON k.user_id = u.id
  WHERE k.ticket_id = ?
  ORDER BY k.erstellt_am ASC
");
$st->bind_param("i", $id);
$st->execute();
$kommentare = $st->get_result();
$st->close();

// Badge Helper
function status_badge(string $s): string {
    $s = trim($s);
    if ($s === 'offen') return '<span class="badge bg-secondary">Offen</span>';
    if ($s === 'in Bearbeitung') return '<span class="badge bg-warning text-dark">In Bearbeitung</span>';
    if ($s === 'erledigt') return '<span class="badge bg-success">Erledigt</span>';
    return '<span class="badge bg-light text-dark">'.h($s).'</span>';
}

// ggf. optionale Spalten abfedern
$ticket_email = $ticket['email'] ?? '';
$ticket_datei = $ticket['datei']  ?? '';
?>
<link href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" rel="stylesheet">
<style>
  .meta-table th { width: 260px; white-space: nowrap; }
  .text-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; }
</style>

<div class="container my-5">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <a href="tickets.php" class="btn btn-outline-secondary btn-sm">&laquo; Zurück</a>
      <h2 class="mt-2 mb-0">
        Ticket <span class="text-mono"><?= h($ticket['ticketnummer']) ?></span>
      </h2>
      <div class="text-muted">Einheit: <span class="badge text-bg-secondary"><?= h($ticket['einheit'] ?? '–') ?></span></div>
    </div>
    <div class="btn-group">
      <?php if ($ticket['status'] === 'offen'): ?>
        <form method="post">
          <button class="btn btn-primary" name="uebernehmen">🛠️ Übernehmen</button>
        </form>
      <?php endif; ?>
      <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Aktionen</button>
      <div class="dropdown-menu dropdown-menu-end p-3" style="min-width:280px">
        <form method="post" class="d-flex gap-2">
          <select name="neuer_status" class="form-select form-select-sm" required>
            <option value="">-- Status wählen --</option>
            <option value="offen">Offen</option>
            <option value="in Bearbeitung">In Bearbeitung</option>
            <option value="erledigt">Erledigt</option>
          </select>
          <button class="btn btn-sm btn-primary" name="statuswechsel">Speichern</button>
        </form>
      </div>
    </div>
  </div>

  <?= $meldung ?>

  <!-- Meta-Informationen sauber in Tabelle -->
  <div class="card mb-4">
    <div class="card-body">
      <h5 class="card-title mb-3">Allgemeine Informationen</h5>
      <div class="table-responsive">
        <table class="table table-borderless meta-table align-middle mb-0">
          <tbody>
            <tr><th>Fachbereich</th><td><?= h($ticket['fachbereich']) ?></td></tr>
            <tr><th>Meldende Person</th><td><?= h($ticket['name']) ?></td></tr>
            <tr><th>E-Mail</th><td><?= $ticket_email ? h($ticket_email) : '–' ?></td></tr>
            <tr><th>Spind-Nr.</th><td><?= h($ticket['spindnr'] ?: '–') ?></td></tr>
            <tr><th>Status</th><td><?= status_badge($ticket['status']) ?></td></tr>
            <tr><th>Bearbeiter/in</th><td><?= h($ticket['bearbeiter_name'] ?? '–') ?></td></tr>
            <tr><th>Erstellt am</th><td><?= fmtDate($ticket['erstellt_am'] ?? null) ?></td></tr>
            <tr><th>In Bearbeitung seit</th><td><?= fmtDate($ticket['bearbeitet_am'] ?? null) ?></td></tr>
            <tr><th>Erledigt am</th><td><?= fmtDate($ticket['erledigt_am'] ?? null) ?></td></tr>
            <tr>
              <th>Beschreibung</th>
              <td style="white-space: pre-wrap"><?= nl2br(h($ticket['beschreibung'])) ?></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Anhänge: Haupt-Upload + weitere Uploads in sauberer Tabelle -->
  <div class="card mb-4">
    <div class="card-body">
      <h5 class="card-title mb-3">Anhänge</h5>

      <?php
      $hatEtwas = false;

      // Haupt-Upload (Spalte `datei`), wenn vorhanden
      if ($ticket_datei) {
          $hatEtwas = true;
          $mainFile = 'uploads/tickets/' . basename($ticket_datei);
          $extMain  = strtolower(pathinfo($mainFile, PATHINFO_EXTENSION));
          ?>
          <div class="mb-3">
            <div class="small text-muted mb-1">Haupt-Upload</div>
            <?php if (in_array($extMain, ['jpg','jpeg','png'])): ?>
              <a href="<?= h($mainFile) ?>" class="glightbox" data-gallery="ticket-anhang">
                <img src="<?= h($mainFile) ?>" class="img-fluid rounded shadow-sm" style="max-height:160px;object-fit:cover">
              </a>
            <?php elseif ($extMain === 'pdf'): ?>
              <a href="<?= h($mainFile) ?>" target="_blank" class="btn btn-sm btn-outline-primary">PDF ansehen</a>
            <?php else: ?>
              <a href="<?= h($mainFile) ?>" target="_blank" class="btn btn-sm btn-outline-secondary">Datei herunterladen</a>
            <?php endif; ?>
          </div>
          <?php
      }

      if (!empty($uploadRows)) {
          $hatEtwas = true; ?>
          <div class="table-responsive">
            <table class="table table-hover align-middle">
              <thead class="table-light">
                <tr>
                  <th style="width:48px">Typ</th>
                  <th>Dateiname</th>
                  <th class="text-end">Größe</th>
                  <th class="text-end" style="width:120px">Aktion</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($uploadRows as $f):
                  $isImg = in_array($f['ext'], ['jpg','jpeg','png']);
                  $isPdf = ($f['ext'] === 'pdf');
                  $sizeHuman = $f['size'] >= 1048576
                    ? number_format($f['size']/1048576, 2, ',', '.') . ' MB'
                    : number_format(max(1,$f['size']/1024), 0, ',', '.') . ' KB';
                ?>
                  <tr>
                    <td class="text-center">
                      <?php if ($isImg): ?>
                        🖼️
                      <?php elseif ($isPdf): ?>
                        📄
                      <?php else: ?>
                        📁
                      <?php endif; ?>
                    </td>
                    <td class="text-break"><?= h($f['name']) ?></td>
                    <td class="text-end"><?= $sizeHuman ?></td>
                    <td class="text-end">
                      <?php if ($isImg): ?>
                        <a href="<?= h($f['url']) ?>" class="btn btn-sm btn-outline-primary glightbox" data-gallery="ticket-anhang">Ansehen</a>
                      <?php elseif ($isPdf): ?>
                        <a href="<?= h($f['url']) ?>" target="_blank" class="btn btn-sm btn-outline-primary">Öffnen</a>
                      <?php else: ?>
                        <a href="<?= h($f['url']) ?>" target="_blank" class="btn btn-sm btn-outline-secondary">Download</a>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
      <?php } ?>

      <?php if (!$hatEtwas): ?>
        <p class="text-muted mb-0">Keine Anhänge vorhanden.</p>
      <?php endif; ?>
    </div>

    <div class="card-footer">
      <form method="post" enctype="multipart/form-data" class="d-flex flex-column flex-md-row align-items-start gap-2">
        <input type="file" name="anhang" class="form-control" required accept=".jpg,.jpeg,.png,.pdf">
        <button type="submit" name="datei_upload" class="btn btn-primary">📎 Datei hochladen</button>
      </form>
    </div>
  </div>

  <!-- Kommentare sauber als Liste -->
  <div class="card">
    <div class="card-body">
      <h5 class="card-title mb-3">Kommentare</h5>
      <?php if ($kommentare->num_rows > 0): ?>
        <div class="list-group">
          <?php while ($k = $kommentare->fetch_assoc()): ?>
            <div class="list-group-item">
              <div class="d-flex justify-content-between">
                <strong><?= h($k['username'] ?? 'Unbekannt') ?></strong>
                <span class="text-muted small"><?= fmtDate($k['erstellt_am'] ?? null) ?></span>
              </div>
              <div class="mt-1" style="white-space:pre-wrap"><?= nl2br(h($k['kommentar'])) ?></div>
            </div>
          <?php endwhile; ?>
        </div>
      <?php else: ?>
        <p class="text-muted mb-0">Noch keine Kommentare.</p>
      <?php endif; ?>
    </div>
    <div class="card-footer">
      <form method="post">
        <div class="mb-2">
          <textarea name="kommentar" class="form-control" placeholder="Kommentar schreiben..." required></textarea>
        </div>
        <button type="submit" name="kommentar_absenden" class="btn btn-dark">💬 Kommentar speichern</button>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/glightbox/dist/js/glightbox.min.js"></script>
<script>
  GLightbox({ selector: '.glightbox' });
</script>

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