<?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 alert-dismissible fade show">💬 Kommentar gespeichert.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></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 alert-dismissible fade show">📎 Datei erfolgreich hochgeladen.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
        } else {
            $meldung = '<div class="alert alert-danger alert-dismissible fade show">❌ Upload fehlgeschlagen.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></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 alert-dismissible fade show">🛠️ Ticket übernommen.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></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
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 alert-dismissible fade show">✅ Status geändert.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    } else {
        $meldung = '<div class="alert alert-warning alert-dismissible fade show">⚠️ Keine Berechtigung für diese Statusänderung.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    }
}

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

// Zusätzliche Uploads
$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-danger-subtle text-danger border border-danger-subtle"><i class="bi bi-circle-fill small me-1"></i>Offen</span>';
    if ($s === 'in Bearbeitung') return '<span class="badge bg-warning-subtle text-warning-emphasis border border-warning-subtle"><i class="bi bi-tools small me-1"></i>In Bearbeitung</span>';
    if ($s === 'erledigt') return '<span class="badge bg-success-subtle text-success border border-success-subtle"><i class="bi bi-check-circle-fill small me-1"></i>Erledigt</span>';
    return '<span class="badge bg-light text-dark">'.h($s).'</span>';
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" rel="stylesheet">

<style>
  body { background-color: #f4f6f9; }
  .text-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; }

  /* Ticket Header */
  .ticket-header { background: #fff; padding: 1.5rem 0; border-bottom: 1px solid #dee2e6; margin-bottom: 2rem; }

  /* Sidebar Styles */
  .sidebar-card { border: none; box-shadow: 0 1px 3px rgba(0,0,0,0.05); margin-bottom: 1.5rem; background: #fff; border-radius: 0.5rem; }
  .sidebar-header { padding: 1rem; border-bottom: 1px solid #f0f0f0; font-weight: 600; color: #495057; }
  .info-list .list-group-item { border: none; padding: 0.75rem 1rem; font-size: 0.9rem; color: #555; }
  .info-list strong { display: block; color: #212529; font-size: 0.95rem; }

  /* Chat/Comment Styles */
  .discussion-timeline { position: relative; padding-left: 0; }
  .comment-item { display: flex; gap: 1rem; margin-bottom: 1.5rem; }
  .comment-avatar {
    width: 40px; height: 40px; background: #e9ecef; border-radius: 50%;
    display: flex; align-items: center; justify-content: center; font-weight: bold; color: #495057; flex-shrink: 0;
  }
  .comment-body { background: #fff; border: 1px solid #e9ecef; border-radius: 0.5rem; padding: 1rem; width: 100%; box-shadow: 0 1px 2px rgba(0,0,0,0.02); }
  .comment-meta { font-size: 0.8rem; color: #888; margin-bottom: 0.5rem; display: flex; justify-content: space-between; }

  /* Description Box */
  .description-box { background: #fff; border: 1px solid #dee2e6; border-radius: 0.5rem; padding: 1.5rem; box-shadow: 0 2px 4px rgba(0,0,0,0.02); border-left: 4px solid #0d6efd; }

  /* Attachments in Sidebar */
  .file-list-item { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid #f0f0f0; }
  .file-list-item:last-child { border-bottom: none; }
  .file-icon { font-size: 1.5rem; color: #6c757d; }
</style>

<div class="ticket-header">
  <div class="container">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
      <div>
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb mb-1 small text-muted">
            <li class="breadcrumb-item"><a href="tickets.php" class="text-decoration-none text-secondary">Tickets</a></li>
            <li class="breadcrumb-item active"><?= h($ticket['fachbereich']) ?></li>
          </ol>
        </nav>
        <h2 class="mb-1 d-flex align-items-center gap-2">
          <span class="text-mono text-secondary">#<?= h($ticket['ticketnummer']) ?></span>
          <span><?= status_badge($ticket['status']) ?></span>
        </h2>
        <div class="text-muted small">
          Erstellt am <?= fmtDate($ticket['erstellt_am']) ?> von <strong><?= h($ticket['name']) ?></strong> &bull; Einheit: <?= h($ticket['einheit']) ?>
        </div>
      </div>

      <div class="d-flex gap-2 align-items-center">
        <?php if ($ticket['status'] === 'offen'): ?>
          <form method="post">
            <button class="btn btn-primary shadow-sm" name="uebernehmen">
               <i class="bi bi-person-check"></i> Übernehmen
            </button>
          </form>
        <?php endif; ?>

        <div class="dropdown">
          <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
            <i class="bi bi-gear"></i> Status ändern
          </button>
          <ul class="dropdown-menu dropdown-menu-end shadow p-2" style="width:220px;">
            <li><h6 class="dropdown-header">Ticket Status setzen</h6></li>
            <form method="post">
               <li><button name="statuswechsel" value="1" class="dropdown-item rounded mb-1" onclick="this.form.neuer_status.value='offen'">⚪ Offen</button></li>
               <li><button name="statuswechsel" value="1" class="dropdown-item rounded mb-1" onclick="this.form.neuer_status.value='in Bearbeitung'">🟡 In Bearbeitung</button></li>
               <li><button name="statuswechsel" value="1" class="dropdown-item rounded text-success" onclick="this.form.neuer_status.value='erledigt'">🟢 Erledigt</button></li>
               <input type="hidden" name="neuer_status" value="">
            </form>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="container pb-5">
  <?= $meldung ?>

  <div class="row g-4">

    <div class="col-lg-8">

      <div class="mb-4">
        <h5 class="mb-3 text-secondary">Problembeschreibung</h5>
        <div class="description-box">
          <div style="white-space: pre-wrap; line-height: 1.6; color: #212529;"><?= nl2br(h($ticket['beschreibung'])) ?></div>
        </div>
      </div>

      <div class="d-flex align-items-center justify-content-between mb-3 mt-5 border-bottom pb-2">
        <h5 class="mb-0 text-secondary"><i class="bi bi-chat-dots me-2"></i>Verlauf</h5>
        <span class="badge bg-light text-secondary border"><?= $kommentare->num_rows ?> Kommentare</span>
      </div>

      <div class="discussion-timeline">
        <?php if ($kommentare->num_rows > 0): ?>
          <?php while ($k = $kommentare->fetch_assoc()): ?>
            <div class="comment-item">
              <div class="comment-avatar shadow-sm">
                <?= strtoupper(substr($k['username'], 0, 1)) ?>
              </div>
              <div class="comment-body">
                <div class="comment-meta">
                  <strong><?= h($k['username']) ?></strong>
                  <span><?= fmtDate($k['erstellt_am']) ?></span>
                </div>
                <div style="white-space: pre-wrap;"><?= nl2br(h($k['kommentar'])) ?></div>
              </div>
            </div>
          <?php endwhile; ?>
        <?php else: ?>
          <div class="text-center text-muted py-4 mb-3 border rounded bg-white">
            <i class="bi bi-chat-square-text fs-3 opacity-25"></i>
            <p class="mb-0 small mt-2">Noch keine Kommentare.</p>
          </div>
        <?php endif; ?>
      </div>

      <div class="card shadow-sm border-0 mt-4">
        <div class="card-body bg-light rounded">
          <form method="post">
             <label class="form-label fw-bold">Antworten</label>
             <textarea name="kommentar" class="form-control mb-3" rows="3" placeholder="Schreiben Sie einen Kommentar..." required></textarea>
             <div class="d-flex justify-content-end">
               <button type="submit" name="kommentar_absenden" class="btn btn-dark">
                 <i class="bi bi-send-fill me-1"></i> Senden
               </button>
             </div>
          </form>
        </div>
      </div>

    </div>

    <div class="col-lg-4">

      <div class="sidebar-card">
        <div class="sidebar-header">Ticket Details</div>
        <ul class="list-group list-group-flush info-list">
          <li class="list-group-item">
            <span class="text-muted small">Bearbeiter</span>
            <strong>
              <?php if($ticket['bearbeiter_name']): ?>
                <i class="bi bi-person-fill text-primary"></i> <?= h($ticket['bearbeiter_name']) ?>
              <?php else: ?>
                <span class="text-muted fst-italic">Nicht zugewiesen</span>
              <?php endif; ?>
            </strong>
          </li>
          <li class="list-group-item">
            <div class="row">
              <div class="col-6">
                 <span class="text-muted small">Spind-Nr.</span>
                 <strong><?= h($ticket['spindnr'] ?: '–') ?></strong>
              </div>
              <div class="col-6">
                 <span class="text-muted small">Fachbereich</span>
                 <strong><?= h($ticket['fachbereich']) ?></strong>
              </div>
            </div>
          </li>
          <li class="list-group-item">
            <span class="text-muted small">E-Mail Kontakt</span>
            <div>
              <?php if($ticket['email']): ?>
                <a href="mailto:<?= h($ticket['email']) ?>" class="text-decoration-none text-truncate d-block">
                  <i class="bi bi-envelope"></i> <?= h($ticket['email']) ?>
                </a>
              <?php else: ?>
                –
              <?php endif; ?>
            </div>
          </li>
        </ul>
      </div>

      <div class="sidebar-card">
        <div class="sidebar-header d-flex justify-content-between align-items-center">
          <span>Dateien</span>
          <button class="btn btn-sm btn-light text-primary py-0" type="button" data-bs-toggle="collapse" data-bs-target="#uploadArea">
            <i class="bi bi-plus-lg"></i>
          </button>
        </div>
        <div class="card-body">

          <div class="collapse mb-3" id="uploadArea">
            <form method="post" enctype="multipart/form-data" class="p-2 bg-light rounded border">
              <input type="file" name="anhang" class="form-control form-control-sm mb-2" required>
              <button type="submit" name="datei_upload" class="btn btn-sm btn-primary w-100">Hochladen</button>
            </form>
          </div>

          <div class="d-flex flex-column gap-1">
            <?php
              $hasFiles = false;
              // Check Main File
              if (!empty($ticket['datei'])) {
                 $hasFiles = true;
                 $mainUrl = 'uploads/tickets/' . basename($ticket['datei']);
                 $ext = strtolower(pathinfo($mainUrl, PATHINFO_EXTENSION));
                 $icon = in_array($ext, ['jpg','png','jpeg']) ? 'bi-file-earmark-image text-primary' : ( $ext=='pdf'?'bi-file-earmark-pdf text-danger':'bi-file-earmark text-secondary');
            ?>
               <div class="file-list-item">
                 <i class="bi <?= $icon ?> file-icon"></i>
                 <div class="text-truncate flex-grow-1 small">
                   <a href="<?= h($mainUrl) ?>" target="_blank" class="text-dark text-decoration-none fw-bold">Hauptanhang</a>
                   <div class="text-muted" style="font-size:0.75rem">Vom Ersteller</div>
                 </div>
                 <a href="<?= h($mainUrl) ?>" class="btn btn-sm btn-light border glightbox"><i class="bi bi-eye"></i></a>
               </div>
            <?php } ?>

            <?php foreach ($uploadRows as $f):
                $hasFiles = true;
                $icon = in_array($f['ext'], ['jpg','png','jpeg']) ? 'bi-file-earmark-image text-primary' : ( $f['ext']=='pdf'?'bi-file-earmark-pdf text-danger':'bi-file-earmark text-secondary');
            ?>
               <div class="file-list-item">
                 <i class="bi <?= $icon ?> file-icon"></i>
                 <div class="text-truncate flex-grow-1 small">
                   <a href="<?= h($f['url']) ?>" target="_blank" class="text-dark text-decoration-none" title="<?= h($f['name']) ?>"><?= h($f['name']) ?></a>
                   <div class="text-muted" style="font-size:0.75rem"><?= round($f['size']/1024) ?> KB</div>
                 </div>
                 <?php if(in_array($f['ext'], ['jpg','png','jpeg'])): ?>
                    <a href="<?= h($f['url']) ?>" class="btn btn-sm btn-light border glightbox"><i class="bi bi-eye"></i></a>
                 <?php else: ?>
                    <a href="<?= h($f['url']) ?>" target="_blank" class="btn btn-sm btn-light border"><i class="bi bi-download"></i></a>
                 <?php endif; ?>
               </div>
            <?php endforeach; ?>

            <?php if (!$hasFiles): ?>
              <div class="text-muted small text-center py-2">Keine Dateien</div>
            <?php endif; ?>
          </div>
        </div>
      </div>

    </div>
  </div>
</div>

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

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