<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

$admin_id = $_SESSION['user_id'];

// ── Filters ───────────────────────────────────────────────
$status_filter   = $_GET['status']   ?? 'all';
$priority_filter = $_GET['priority'] ?? 'all';
$search          = trim($_GET['search'] ?? '');

// ── Build WHERE ───────────────────────────────────────────
$where  = ["t.user_type = 'author'"];
$params = [];

if ($status_filter !== 'all') {
    $where[]  = "t.status = ?";
    $params[] = $status_filter;
}
if ($priority_filter !== 'all') {
    $where[]  = "t.priority = ?";
    $params[] = $priority_filter;
}
if (!empty($search)) {
    $where[]  = "(t.ticket_id LIKE ? OR t.subject LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ?)";
    $sp       = "%$search%";
    $params   = array_merge($params, [$sp,$sp,$sp,$sp,$sp]);
}

$whereSQL = implode(' AND ', $where);

// ── Tickets query ─────────────────────────────────────────
$stmt = $pdo->prepare("
    SELECT t.*,
           u.first_name, u.last_name, u.email AS author_email, u.username,
           s.submission_id AS sub_id,
           mi.article_title AS submission_title,
           s.tracking_code,
           s.submission_status,
           (SELECT COUNT(*) FROM ticket_messages m WHERE m.ticket_id = t.ticket_id) AS reply_count,
           (SELECT COUNT(*) FROM ticket_messages m
            WHERE m.ticket_id = t.ticket_id
              AND m.sender_type = 'user'
              AND m.created_at > COALESCE(
                  (SELECT MAX(m2.created_at) FROM ticket_messages m2
                   WHERE m2.ticket_id = t.ticket_id AND m2.sender_type = 'admin'),
                  '2000-01-01'
              )) AS unread_count
    FROM support_tickets t
    LEFT JOIN users u ON t.user_id = u.user_id
    LEFT JOIN submissions s ON t.submission_id = s.submission_id
    LEFT JOIN manuscript_info mi ON mi.submission_id = t.submission_id
    WHERE $whereSQL
    ORDER BY
        CASE t.priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END,
        t.created_at DESC
");
$stmt->execute($params);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ── Stats ─────────────────────────────────────────────────
$stats = $pdo->query("
    SELECT
        COUNT(*)                                          AS total,
        SUM(IF(status='open',        1, 0))               AS open_count,
        SUM(IF(status='in_progress', 1, 0))               AS in_progress,
        SUM(IF(status='resolved',    1, 0))               AS resolved,
        SUM(IF(status='closed',      1, 0))               AS closed,
        SUM(IF(priority='high',      1, 0))               AS cnt_high
    FROM support_tickets
    WHERE user_type = 'author'
")->fetch(PDO::FETCH_ASSOC);

$active_section = 'author_tickets';
function p($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Author Tickets — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body{font-family:'Roboto',sans-serif;margin:0;height:100vh;overflow:hidden}
body.dark{background:#0F172A;color:#E2E8F0}
.sidebar{width:250px;background:#1E293B;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto}
.sidebar.collapsed{width:70px}
.sidebar.collapsed .sidebar-title{display:none}
.content{margin-left:250px;transition:margin-left .3s;height:100vh;overflow-y:auto}
.content.collapsed-sidebar{margin-left:70px}
.nav-item{padding:10px 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center}
.nav-item:hover{background:#334155}
.nav-item.active{background:#334155;border-left:3px solid #3B82F6}
body.dark .bg-white{background:#1E293B}
body.dark .bg-gray-50{background:#0F172A}
body.dark .border-gray-200{border-color:#334155}
body.dark .text-gray-800{color:#F1F5F9}
body.dark .text-gray-600{color:#94A3B8}
body.dark .text-gray-500{color:#64748B}
body.dark input,body.dark select,body.dark textarea{background:#334155;border-color:#475569;color:#E2E8F0}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}

/* Status */
.s-open{background:#DBEAFE;color:#1E40AF}
.s-in_progress{background:#FEF3C7;color:#92400E}
.s-resolved{background:#D1FAE5;color:#065F46}
.s-closed{background:#F3F4F6;color:#374151}
body.dark .s-open{background:#1E3A5F;color:#93C5FD}
body.dark .s-in_progress{background:#451A03;color:#FCD34D}
body.dark .s-resolved{background:#064E3B;color:#6EE7B7}
body.dark .s-closed{background:#1F2937;color:#9CA3AF}

/* Priority */
.p-high{background:#FED7AA;color:#9A3412}
.p-medium{background:#FEF3C7;color:#92400E}
.p-low{background:#F3F4F6;color:#4B5563}

/* Unread dot */
.unread-dot{width:8px;height:8px;background:#EF4444;border-radius:50%;flex-shrink:0}

/* Stat card */
.stat-card{transition:transform .2s,box-shadow .2s}
.stat-card:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.12)}

/* Row hover */
tr.ticket-row:hover td{background:#F8FAFC}
body.dark tr.ticket-row:hover td{background:#1E293B}

/* Submission status pill */
.ss-submitted{background:#DBEAFE;color:#1E40AF}
.ss-under_review{background:#FEF3C7;color:#92400E}
.ss-accepted{background:#D1FAE5;color:#065F46}
.ss-rejected{background:#FEE2E2;color:#991B1B}
</style>
</head>
<body class="bg-slate-100">

<button onclick="toggleMobile()" class="fixed top-3 left-3 z-20 bg-slate-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

  <!-- Topbar -->
  <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" class="text-gray-400 hover:text-gray-600 hidden md:block">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <div class="flex items-center gap-2 text-sm text-gray-500">
        <a href="index.php" class="hover:text-blue-600"><i class="fas fa-home"></i></a>
        <i class="fas fa-chevron-right text-xs text-gray-300"></i>
        <span class="text-gray-800 font-bold flex items-center gap-2">
          <i class="fas fa-ticket-alt text-orange-500"></i> Author Tickets
        </span>
      </div>
    </div>
    <button id="darkToggle" class="text-gray-400 hover:text-gray-600 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
      <i class="fas fa-moon text-sm"></i>
    </button>
  </div>

  <main class="p-6">

    <!-- Stat Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
      <?php
      $statCards = [
        ['Total',       $stats['total'],         'fa-layer-group',  'text-slate-600',  'bg-slate-100',  ''],
        ['Open',        $stats['open_count'],    'fa-door-open',    'text-blue-600',   'bg-blue-100',   'open'],
        ['In Progress', $stats['in_progress'],   'fa-spinner',      'text-amber-600',  'bg-amber-100',  'in_progress'],
        ['Resolved',    $stats['resolved'],      'fa-check-circle', 'text-emerald-600','bg-emerald-100','resolved'],
        ['Closed',      $stats['closed'],        'fa-lock',         'text-gray-500',   'bg-gray-100',   'closed'],
        ['High Priority',$stats['cnt_high'],     'fa-fire',         'text-red-600',    'bg-red-100',    ''],
      ];
      foreach ($statCards as [$label,$val,$icon,$color,$ibg,$sf]): ?>
      <div class="stat-card bg-white rounded-xl p-4 shadow-sm border border-gray-100 cursor-pointer"
           onclick="<?= $sf ? "filterStatus('$sf')" : '' ?>">
        <div class="w-8 h-8 <?= $ibg ?> rounded-lg flex items-center justify-center mb-2">
          <i class="fas <?= $icon ?> <?= $color ?> text-sm"></i>
        </div>
        <div class="text-2xl font-bold text-gray-800"><?= (int)($val ?? 0) ?></div>
        <div class="text-xs text-gray-500 font-medium uppercase tracking-wide mt-0.5"><?= $label ?></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Filter Bar -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-5">
      <form method="GET" id="filterForm" class="flex flex-wrap gap-3 items-end">
        <div class="flex-1 min-w-[160px]">
          <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">Status</label>
          <select name="status" onchange="this.form.submit()" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400">
            <option value="all"         <?= $status_filter==='all'         ?'selected':'' ?>>All Status</option>
            <option value="open"        <?= $status_filter==='open'        ?'selected':'' ?>>Open</option>
            <option value="in_progress" <?= $status_filter==='in_progress' ?'selected':'' ?>>In Progress</option>
            <option value="resolved"    <?= $status_filter==='resolved'    ?'selected':'' ?>>Resolved</option>
            <option value="closed"      <?= $status_filter==='closed'      ?'selected':'' ?>>Closed</option>
          </select>
        </div>
        <div class="flex-1 min-w-[140px]">
          <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">Priority</label>
          <select name="priority" onchange="this.form.submit()" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400">
            <option value="all"    <?= $priority_filter==='all'    ?'selected':'' ?>>All Priorities</option>
            <option value="high"   <?= $priority_filter==='high'   ?'selected':'' ?>>🔴 High</option>
            <option value="medium" <?= $priority_filter==='medium' ?'selected':'' ?>>🟡 Medium</option>
            <option value="low"    <?= $priority_filter==='low'    ?'selected':'' ?>>⚪ Low</option>
          </select>
        </div>
        <div class="flex-1 min-w-[200px]">
          <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">Search</label>
          <div class="relative">
            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
            <input type="text" name="search" value="<?= p($search) ?>"
                   placeholder="Ticket #, subject, author name…"
                   class="w-full border border-gray-300 rounded-lg pl-8 pr-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400">
          </div>
        </div>
        <div class="flex gap-2">
          <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-semibold transition flex items-center gap-2">
            <i class="fas fa-search text-xs"></i> Search
          </button>
          <?php if ($search || $status_filter !== 'all' || $priority_filter !== 'all'): ?>
          <a href="author_tickets.php" class="border border-gray-300 text-gray-500 hover:bg-gray-50 px-3 py-2 rounded-lg text-sm flex items-center gap-1 transition">
            <i class="fas fa-times text-xs"></i> Clear
          </a>
          <?php endif; ?>
        </div>
      </form>
      <div class="mt-3 text-xs text-gray-400">
        Showing <strong class="text-gray-700"><?= count($tickets) ?></strong> ticket<?= count($tickets) !== 1 ? 's' : '' ?>
        <?= ($search || $status_filter !== 'all' || $priority_filter !== 'all') ? '(filtered)' : '' ?>
      </div>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
      <div class="overflow-x-auto">
        <?php if (empty($tickets)): ?>
        <div class="text-center py-16">
          <i class="fas fa-ticket-alt text-5xl text-gray-200 mb-4 block"></i>
          <p class="text-gray-500 font-medium">No author tickets found</p>
          <p class="text-gray-400 text-sm mt-1">
            <?= ($search || $status_filter !== 'all' || $priority_filter !== 'all') ? 'Try adjusting your filters' : 'No author support tickets submitted yet' ?>
          </p>
        </div>
        <?php else: ?>
        <table class="w-full text-sm">
          <thead class="bg-gray-50 border-b border-gray-200">
            <tr>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Ticket #</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Author</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Subject / Category</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Submission</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Priority</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Status</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Replies</th>
              <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wide">Date</th>
              <th class="px-4 py-3 text-center text-xs font-bold text-gray-500 uppercase tracking-wide">Action</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-100">
          <?php foreach ($tickets as $t):
            $unread = (int)($t['unread_count'] ?? 0);
            $name   = trim(($t['first_name'] ?? '') . ' ' . ($t['last_name'] ?? '')) ?: ($t['username'] ?? '—');
          ?>
          <tr class="ticket-row transition-colors">

            <!-- Ticket # -->
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <?php if ($unread > 0): ?>
                <span class="unread-dot" title="<?= $unread ?> unread message<?= $unread !== 1 ? 's' : '' ?>"></span>
                <?php endif; ?>
                <span class="font-mono text-xs font-bold text-gray-700">#<?= (int)$t['ticket_id'] ?></span>
              </div>
            </td>

            <!-- Author -->
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <div class="w-7 h-7 rounded-full bg-orange-100 text-orange-700 flex items-center justify-content-center items-center justify-center text-xs font-bold flex-shrink-0">
                  <?= strtoupper(substr($t['first_name'] ?? '?', 0, 1)) ?>
                </div>
                <div>
                  <div class="font-semibold text-gray-800 text-sm"><?= p($name) ?></div>
                  <div class="text-xs text-gray-400 truncate max-w-[130px]"><?= p($t['author_email'] ?? '') ?></div>
                </div>
              </div>
            </td>

            <!-- Subject + Category -->
            <td class="px-4 py-3 max-w-[200px]">
              <div class="truncate text-gray-700 font-medium" title="<?= p($t['subject']) ?>"><?= p($t['subject']) ?></div>
              <?php if (!empty($t['category'])): ?>
              <span class="text-xs bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded mt-0.5 inline-block"><?= p($t['category']) ?></span>
              <?php endif; ?>
            </td>

            <!-- Submission -->
            <td class="px-4 py-3">
              <?php if (!empty($t['tracking_code'])): ?>
              <div class="flex flex-col gap-0.5">
                <span class="font-mono text-xs bg-blue-50 text-blue-600 px-2 py-0.5 rounded w-fit"><?= p($t['tracking_code']) ?></span>
                <?php if (!empty($t['submission_title'])): ?>
                <div class="text-xs text-gray-400 truncate max-w-[120px]" title="<?= p($t['submission_title']) ?>">
                  <?= p(mb_strimwidth($t['submission_title'], 0, 35, '…')) ?>
                </div>
                <?php endif; ?>
                <?php if (!empty($t['submission_status'])): ?>
                <span class="text-xs font-semibold ss-<?= $t['submission_status'] ?> px-1.5 py-0.5 rounded w-fit">
                  <?= ucfirst(str_replace('_', ' ', $t['submission_status'])) ?>
                </span>
                <?php endif; ?>
              </div>
              <?php else: ?>
              <span class="text-gray-300 text-xs">—</span>
              <?php endif; ?>
            </td>

            <!-- Priority -->
            <td class="px-4 py-3">
              <span class="px-2 py-1 rounded-full text-xs font-bold p-<?= strtolower($t['priority'] ?? 'low') ?>">
                <?= ucfirst($t['priority'] ?? 'low') ?>
              </span>
            </td>

            <!-- Status -->
            <td class="px-4 py-3">
              <span class="px-2 py-1 rounded-full text-xs font-bold s-<?= $t['status'] ?>">
                <?= ucfirst(str_replace('_', ' ', $t['status'])) ?>
              </span>
            </td>

            <!-- Replies -->
            <td class="px-4 py-3 text-center">
              <?php if ((int)$t['reply_count'] > 0): ?>
              <span class="inline-flex items-center gap-1 text-xs font-semibold text-gray-600 bg-gray-100 px-2 py-0.5 rounded-full">
                <i class="fas fa-comments text-[10px]"></i> <?= (int)$t['reply_count'] ?>
                <?php if ($unread > 0): ?>
                <span class="bg-red-500 text-white text-[9px] rounded-full px-1 font-bold"><?= $unread ?> new</span>
                <?php endif; ?>
              </span>
              <?php else: ?>
              <span class="text-xs text-gray-300">—</span>
              <?php endif; ?>
            </td>

            <!-- Date -->
            <td class="px-4 py-3 whitespace-nowrap">
              <div class="text-xs text-gray-600 font-medium"><?= date('d M Y', strtotime($t['created_at'])) ?></div>
              <div class="text-xs text-gray-400"><?= date('H:i', strtotime($t['created_at'])) ?></div>
            </td>

            <!-- Action -->
            <td class="px-4 py-3 text-center">
              <a href="author_ticket_view.php?id=<?= (int)$t['ticket_id'] ?>"
                 class="inline-flex items-center gap-1.5 bg-orange-50 hover:bg-orange-100 text-orange-700 border border-orange-200 px-3 py-1.5 rounded-lg text-xs font-bold transition">
                <i class="fas fa-eye text-[10px]"></i>
                View<?php if ($unread > 0): ?> <span class="bg-red-500 text-white rounded-full w-3.5 h-3.5 text-[9px] flex items-center justify-center font-bold"><?= $unread ?></span><?php endif; ?>
              </a>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <?php endif; ?>
      </div>
    </div>

  </main>
</div>

<script>
let sc = false;
function toggleMobile(){ document.getElementById('sidebar')?.classList.toggle('mobile-open'); }
function toggleSidebar(){
    sc = !sc;
    document.getElementById('sidebar')?.classList.toggle('collapsed', sc);
    document.getElementById('content')?.classList.toggle('collapsed-sidebar', sc);
}
document.getElementById('darkToggle').addEventListener('click', function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('dm', document.body.classList.contains('dark') ? '1' : '0');
});
if (localStorage.getItem('dm') === '1') {
    document.body.classList.add('dark');
    document.getElementById('darkToggle').querySelector('i').classList.replace('fa-moon', 'fa-sun');
}
function filterStatus(s) {
    const f = document.querySelector('[name=status]');
    if (f) { f.value = s; document.getElementById('filterForm').submit(); }
}
document.querySelector('[name=search]')?.addEventListener('keypress', e => {
    if (e.key === 'Enter') document.getElementById('filterForm').submit();
});
</script>
</body>
</html>