<?php
// tickets.php – Tickets der eigenen Einheit (clean UI)
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'];
$einheit  = $_SESSION['einheit'] ?? '';
if ($einheit === '') {
    echo "<div class='container my-5'><div class='alert alert-warning'>⚠️ Keine Einheit in der Session gefunden. Bitte erneut einloggen.</div></div>";
    include 'includes/footer.php';
    exit;
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function bind_params(mysqli_stmt $stmt, string $types, array &$params){
  $a = [$types];
  foreach($params as $k=>$_){ $a[] = &$params[$k]; }
  call_user_func_array([$stmt, 'bind_param'], $a);
}

/* ------------------ Aktionen ------------------ */
// Ticket übernehmen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['uebernehmen'])) {
    $ticket_id = (int)$_POST['ticket_id'];
    $stmt = $conn->prepare("
        UPDATE neue_tickets
           SET status = 'in Bearbeitung',
               bearbeiter_id = ?,
               bearbeitet_am = NOW()
         WHERE id = ?
           AND status = 'offen'
           AND einheit = ?
    ");
    $stmt->bind_param("iis", $user_id, $ticket_id, $einheit);
    $stmt->execute();
    $stmt->close();
}

// Ticket erledigen
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['erledigt'])) {
    $ticket_id = (int)$_POST['ticket_id'];
    $stmt = $conn->prepare("
        UPDATE neue_tickets
           SET status = 'erledigt',
               erledigt_am = NOW()
         WHERE id = ?
           AND bearbeiter_id = ?
           AND einheit = ?
    ");
    $stmt->bind_param("iis", $ticket_id, $user_id, $einheit);
    $stmt->execute();
    $stmt->close();
}

/* ------------------ Filter ------------------ */
$search = trim($_GET['q'] ?? '');
$f_status = $_GET['status'] ?? ''; // '', 'offen', 'in Bearbeitung', 'erledigt'
$only_mine = isset($_GET['only_mine']) ? (int)$_GET['only_mine'] : 0; // 1 = nur meine bearbeiteten

$where = "t.einheit = ?";
$types = "s";
$params = [$einheit];

if ($search !== '') {
  $like = '%'.$search.'%';
  $where .= " AND (t.ticketnummer LIKE ? OR t.fachbereich LIKE ? OR t.name LIKE ? OR t.beschreibung LIKE ? OR COALESCE(t.spindnr,'') LIKE ?)";
  for($i=0;$i<5;$i++){ $params[] = $like; $types .= 's'; }
}
if ($f_status !== '' && in_array($f_status, ['offen','in Bearbeitung','erledigt'], true)) {
  $where .= " AND t.status = ?";
  $params[] = $f_status; $types .= 's';
}
if ($only_mine === 1) {
  $where .= " AND t.bearbeiter_id = ?";
  $params[] = $user_id; $types .= 'i';
}

/* ------------------ KPIs ------------------ */
$sqlKpi = "
  SELECT
    COUNT(*) AS total,
    SUM(CASE WHEN t.status='offen' THEN 1 ELSE 0 END) AS offen,
    SUM(CASE WHEN t.status='in Bearbeitung' THEN 1 ELSE 0 END) AS inbearb,
    SUM(CASE WHEN t.status='erledigt' THEN 1 ELSE 0 END) AS erledigt
  FROM neue_tickets t
  WHERE t.einheit = ?
";
$stK = $conn->prepare($sqlKpi);
$stK->bind_param("s", $einheit);
$stK->execute();
$K = $stK->get_result()->fetch_assoc() ?: ['total'=>0,'offen'=>0,'inbearb'=>0,'erledigt'=>0];
$stK->close();

/* ------------------ Liste ------------------ */
$sqlList = "
  SELECT t.*, u.username AS bearbeiter_name
    FROM neue_tickets t
    LEFT JOIN users u ON t.bearbeiter_id = u.id
   WHERE $where
ORDER BY t.erstellt_am DESC
";
$st = $conn->prepare($sqlList);
bind_params($st, $types, $params);
$st->execute();
$tickets = $st->get_result();
?>
<style>
  .kpi-card{border:1px solid #eee;border-radius:14px;padding:16px;background:#fff}
  .kpi-val{font-size:1.6rem;font-weight:700}
  .kpi-sub{font-size:.9rem;color:#6c757d}
  .toolbar .btn,.toolbar .form-control,.toolbar .form-select{height:38px}
  .text-mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;}
  .clamp-3{
    display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical;
    overflow:hidden; max-width: 60ch;
  }
  .table > :not(caption) > * > *{ vertical-align: middle; }
</style>

<div class="container my-5">
  <!-- Kopf + Toolbar -->
  <div class="d-flex flex-wrap justify-content-between align-items-end gap-2 mb-3">
    <div>
      <h2 class="mb-1">Ticketsystem</h2>
      <div class="text-muted small">Einheit: <span class="badge text-bg-secondary"><?= h($einheit) ?></span></div>
    </div>

    <form method="get" class="toolbar d-flex flex-wrap gap-2">
      <input type="text" name="q" class="form-control" placeholder="🔎 Suche: Nr./Fachbereich/Name/Text" value="<?= h($search) ?>">
      <select name="status" class="form-select">
        <option value="">Alle Stati</option>
        <option value="offen" <?= $f_status==='offen'?'selected':'' ?>>Offen</option>
        <option value="in Bearbeitung" <?= $f_status==='in Bearbeitung'?'selected':'' ?>>In Bearbeitung</option>
        <option value="erledigt" <?= $f_status==='erledigt'?'selected':'' ?>>Erledigt</option>
      </select>
      <div class="form-check align-self-center">
        <input class="form-check-input" type="checkbox" id="onlyMine" name="only_mine" value="1" <?= $only_mine? 'checked':'' ?>>
        <label class="form-check-label" for="onlyMine">nur meine Tickets</label>
      </div>
      <button class="btn btn-outline-primary">Anwenden</button>
      <?php if ($search!=='' || $f_status!=='' || $only_mine): ?>
        <a href="tickets.php" class="btn btn-outline-secondary">Zurücksetzen</a>
      <?php endif; ?>
    </form>
  </div>

  <!-- KPIs -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Gesamt</div><div class="kpi-val"><?= (int)$K['total'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Offen</div><div class="kpi-val"><?= (int)$K['offen'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">In Bearbeitung</div><div class="kpi-val"><?= (int)$K['inbearb'] ?></div></div></div>
    <div class="col-6 col-md-3"><div class="kpi-card"><div class="kpi-sub">Erledigt</div><div class="kpi-val"><?= (int)$K['erledigt'] ?></div></div></div>
  </div>

  <!-- Tabelle -->
  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Ticket-Nr.</th>
            <th>Fachbereich</th>
            <th>Name</th>
            <th>Spind-Nr.</th>
            <th>Beschreibung</th>
            <th>Status</th>
            <th>Bearbeiter/in</th>
            <th class="text-end" style="width:60px;"></th>
          </tr>
        </thead>
        <tbody>
        <?php if ($tickets->num_rows === 0): ?>
          <tr><td colspan="8" class="text-center text-muted py-4">Keine Tickets gefunden.</td></tr>
        <?php else: while ($t = $tickets->fetch_assoc()):
          $badge = ($t['status']==='offen')
            ? '<span class="badge bg-secondary">Offen</span>'
            : (($t['status']==='in Bearbeitung')
              ? '<span class="badge bg-warning text-dark">In Bearbeitung</span>'
              : '<span class="badge bg-success">Erledigt</span>');
        ?>
          <tr>
            <td class="text-mono">
              <a href="ticket_details.php?id=<?= (int)$t['id'] ?>" class="text-decoration-none">
                <?= h($t['ticketnummer']) ?>
              </a>
            </td>
            <td><?= h($t['fachbereich']) ?></td>
            <td><?= h($t['name']) ?></td>
            <td><?= h($t['spindnr'] ?: '–') ?></td>
            <td><div class="clamp-3"><?= nl2br(h($t['beschreibung'])) ?></div></td>
            <td><?= $badge ?></td>
            <td><?= h($t['bearbeiter_name'] ?? '–') ?></td>
            <td class="text-end">
              <div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Aktion</button>
                <div class="dropdown-menu dropdown-menu-end">
                  <a class="dropdown-item" href="ticket_details.php?id=<?= (int)$t['id'] ?>">Details</a>
                  <div class="dropdown-divider"></div>
                  <form method="post" class="px-3 py-1">
                    <input type="hidden" name="ticket_id" value="<?= (int)$t['id'] ?>">
                    <?php if ($t['status'] === 'offen'): ?>
                      <button type="submit" name="uebernehmen" class="dropdown-item">🛠️ Übernehmen</button>
                    <?php elseif ($t['status'] === 'in Bearbeitung' && (int)$t['bearbeiter_id'] === $user_id): ?>
                      <button type="submit" name="erledigt" class="dropdown-item">✅ Erledigt</button>
                    <?php else: ?>
                      <span class="dropdown-item text-muted">Keine Aktion</span>
                    <?php endif; ?>
                  </form>
                </div>
              </div>
            </td>
          </tr>
        <?php endwhile; endif; $st->close(); ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include 'includes/footer.php'; ?>
