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

// Nur für Admins zugänglich
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    echo "<div class='container mt-5'><div class='alert alert-danger'>Zugriff verweigert.</div></div>";
    exit;
}

// Status-Update verarbeiten
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ticket_id'], $_POST['status'])) {
    $ticket_id = (int)$_POST['ticket_id'];
    $status = $_POST['status'];
    $stmt = $conn->prepare("UPDATE support_tickets SET status = ?, gelesen = 1 WHERE id = ?");
    $stmt->bind_param("si", $status, $ticket_id);
    $stmt->execute();
}

// Tickets + Benutzerdaten laden
$tickets = $conn->query("
    SELECT s.*, u.vorname, u.nachname, u.email
    FROM support_tickets s
    LEFT JOIN users u ON s.user_id = u.id
    ORDER BY s.erstellt_am DESC
");
?>

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Support-Verwaltung</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-5">
  <h2 class="mb-4">📋 Support-Tickets verwalten</h2>

  <?php while ($ticket = $tickets->fetch_assoc()): ?>
    <div class="card mb-3 border-<?= $ticket['status'] === 'erledigt' ? 'success' : ($ticket['status'] === 'in Bearbeitung' ? 'warning' : 'danger') ?>">
      <div class="card-body">
        <h5 class="card-title"><?= htmlspecialchars($ticket['betreff']) ?></h5>
        <h6 class="card-subtitle mb-2 text-muted">
          Ticket #<?= $ticket['id'] ?> • <?= date('d.m.Y H:i', strtotime($ticket['erstellt_am'])) ?><br>
          Von:
          <?php if ($ticket['vorname'] && $ticket['nachname']): ?>
            <?= htmlspecialchars($ticket['vorname'] . ' ' . $ticket['nachname']) ?>
            <span class="text-muted">(<?= htmlspecialchars($ticket['email']) ?>)</span>
          <?php else: ?>
            <em>Unbekannter Benutzer</em>
          <?php endif; ?>
        </h6>
        <p class="card-text"><?= nl2br(htmlspecialchars($ticket['nachricht'])) ?></p>

        <form method="post" class="row g-2">
          <input type="hidden" name="ticket_id" value="<?= $ticket['id'] ?>">
          <div class="col-md-6">
            <select name="status" class="form-select">
              <option value="offen" <?= $ticket['status'] === 'offen' ? 'selected' : '' ?>>Offen</option>
              <option value="in Bearbeitung" <?= $ticket['status'] === 'in Bearbeitung' ? 'selected' : '' ?>>In Bearbeitung</option>
              <option value="erledigt" <?= $ticket['status'] === 'erledigt' ? 'selected' : '' ?>>Erledigt</option>
            </select>
          </div>
          <div class="col-md-6">
            <button type="submit" class="btn btn-primary w-100">Status speichern</button>
          </div>
        </form>
      </div>
    </div>
  <?php endwhile; ?>
</div>

</body>
</html>
