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

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

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

// 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();

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

$meldung = '';

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

// Datei hochladen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['datei_upload'])) {
    if (!empty($_FILES['anhang']['name'])) {
        $uploadDir = 'uploads/tickets/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $fileName = $ticket['ticketnummer'] . '_' . uniqid() . '_' . basename($_FILES['anhang']['name']);
        move_uploaded_file($_FILES['anhang']['tmp_name'], $uploadDir . $fileName);
        $meldung = '<div class="alert alert-success mt-3">Datei erfolgreich hochgeladen.</div>';
    }
}

// Statuswechsel
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['statuswechsel'])) {
    $neuer_status = $_POST['neuer_status'];
    if (in_array($neuer_status, ['offen', 'in Bearbeitung', 'erledigt'])) {
        if ($neuer_status == 'in Bearbeitung') {
            $stmt = $conn->prepare("UPDATE neue_tickets SET status = ?, bearbeiter_id = ?, bearbeitet_am = NOW() WHERE id = ?");
            $stmt->bind_param("sii", $neuer_status, $user_id, $id);
        } elseif ($neuer_status == 'erledigt') {
            $stmt = $conn->prepare("UPDATE neue_tickets SET status = ?, erledigt_am = NOW() WHERE id = ?");
            $stmt->bind_param("si", $neuer_status, $id);
        } else {
            $stmt = $conn->prepare("UPDATE neue_tickets SET status = ? WHERE id = ?");
            $stmt->bind_param("si", $neuer_status, $id);
        }
        $stmt->execute();
        $meldung = '<div class="alert alert-success mt-3">Status erfolgreich geändert.</div>';
    }
}

// Dateien laden
$uploads = [];
$uploadDir = 'uploads/tickets/';
if (is_dir($uploadDir)) {
    $pattern = $uploadDir . $ticket['ticketnummer'] . "_*";
    $uploads = glob($pattern);
}

// Kommentare laden
$stmt = $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");
$stmt->bind_param("i", $id);
$stmt->execute();
$kommentare = $stmt->get_result();
?>

<!-- Lightbox CSS -->
<link href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" rel="stylesheet">

<div class="container my-5">
  <a href="tickets.php" class="btn btn-secondary mb-4">&laquo; Zurück</a>
  <h2 class="mb-4">Ticket: <?= htmlspecialchars($ticket['ticketnummer']) ?></h2>

  <?= $meldung ?>

  <div class="card mb-4">
    <div class="card-body">
      <h5 class="card-title">Allgemeine Informationen</h5>
      <p><strong>Fachbereich:</strong> <?= htmlspecialchars($ticket['fachbereich']) ?></p>
      <p><strong>Name:</strong> <?= htmlspecialchars($ticket['name']) ?></p>
      <p><strong>Spindnummer:</strong> <?= htmlspecialchars($ticket['spindnr'] ?? '-') ?></p>
      <p><strong>Beschreibung:</strong><br><?= nl2br(htmlspecialchars($ticket['beschreibung'])) ?></p>
      <p><strong>Status:</strong>
        <?php if ($ticket['status'] == 'offen'): ?>
          <span class="badge bg-secondary">Offen</span>
        <?php elseif ($ticket['status'] == 'in Bearbeitung'): ?>
          <span class="badge bg-warning text-dark">In Bearbeitung</span>
        <?php else: ?>
          <span class="badge bg-success">Erledigt</span>
        <?php endif; ?>
      </p>
      <p><strong>Bearbeiter:</strong> <?= htmlspecialchars($ticket['bearbeiter_name'] ?? '-') ?></p>

      <form method="post" class="mt-3">
        <div class="input-group">
          <select name="neuer_status" class="form-select" required>
            <option value="">-- Status ändern --</option>
            <option value="offen">Offen</option>
            <option value="in Bearbeitung">In Bearbeitung</option>
            <option value="erledigt">Erledigt</option>
          </select>
          <button type="submit" name="statuswechsel" class="btn btn-primary">Ändern</button>
        </div>
      </form>
    </div>
  </div>

  <div class="card mb-4">
    <div class="card-body">
      <h5 class="card-title">Anhänge</h5>

      <?php if (count($uploads) > 0): ?>
        <div class="row">
          <?php foreach ($uploads as $file): ?>
            <div class="col-6 col-md-3 mb-3 text-center">
              <?php
              $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
              if (in_array($ext, ['jpg', 'jpeg', 'png'])): ?>
                <a href="<?= $file ?>" class="glightbox" data-gallery="ticket-anhang">
                  <img src="<?= $file ?>" alt="Bild" class="img-fluid rounded shadow-sm" style="max-height: 150px; object-fit: cover;">
                </a>
                <small class="d-block text-muted mt-2"><?= basename($file) ?></small>

              <?php elseif ($ext === 'pdf'): ?>
                <a href="<?= $file ?>" target="_blank" class="text-decoration-none">
                  <div class="d-flex flex-column align-items-center">
                    <img src="https://cdn-icons-png.flaticon.com/512/337/337946.png" alt="PDF" style="width: 60px; height: 60px;">
                    <small class="text-muted"><?= basename($file) ?></small>
                  </div>
                </a>

              <?php else: ?>
                <a href="<?= $file ?>" target="_blank" class="btn btn-outline-secondary w-100">
                  📁 <?= basename($file) ?>
                </a>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      <?php else: ?>
        <p class="text-muted">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>

  <div class="card">
    <div class="card-body">
      <h5 class="card-title">Kommentare</h5>
      <?php if ($kommentare->num_rows > 0): ?>
        <?php while ($k = $kommentare->fetch_assoc()): ?>
          <div class="mb-3 border-bottom pb-2">
            <strong><?= htmlspecialchars($k['username'] ?? 'Unbekannt') ?></strong> am <?= date('d.m.Y H:i', strtotime($k['erstellt_am'])) ?>:
            <div><?= nl2br(htmlspecialchars($k['kommentar'])) ?></div>
          </div>
        <?php endwhile; ?>
      <?php else: ?>
        <p class="text-muted">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>

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

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