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

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

$admin_id  = $_SESSION['user_id'];
$ticket_id = (int)($_GET['id'] ?? 0);
if (!$ticket_id) { header('Location: author_tickets.php'); exit; }

// ── POST: Send reply ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['respond'])) {
    $message    = trim($_POST['response_message'] ?? '');
    $new_status = $_POST['new_status'] ?? '';
    $valid_s    = ['open', 'in_progress', 'resolved', 'closed'];

    if (empty($message)) {
        $flash_error = "Response message cannot be empty.";
    } elseif (!in_array($new_status, $valid_s)) {
        $flash_error = "Invalid status selected.";
    } else {
        try {
            $pdo->beginTransaction();

            // Insert admin reply
            $pdo->prepare("
                INSERT INTO ticket_messages (ticket_id, sender_id, sender_type, message, is_read, created_at)
                VALUES (?, ?, 'admin', ?, 0, NOW())
            ")->execute([$ticket_id, $admin_id, $message]);

            // Update ticket status
            $pdo->prepare("
                UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE ticket_id = ?
            ")->execute([$new_status, $ticket_id]);

            $pdo->commit();

            // Email notification to author
            try {
                $row = $pdo->prepare("
                    SELECT t.ticket_id, t.subject, u.first_name, u.last_name, u.email
                    FROM support_tickets t
                    JOIN users u ON u.user_id = t.user_id
                    WHERE t.ticket_id = ?
                ");
                $row->execute([$ticket_id]);
                $td = $row->fetch(PDO::FETCH_ASSOC);

                if ($td && !empty($td['email'])) {
                    $to   = $td['email'];
                    $name = trim(($td['first_name'] ?? '') . ' ' . ($td['last_name'] ?? '')) ?: 'Author';
                    $subj = "Response to Your Ticket #" . $td['ticket_id'] . " – " . $td['subject'];
                    $body = "
                    <html><body style='font-family:Arial,sans-serif;color:#333;line-height:1.6'>
                    <div style='max-width:600px;margin:0 auto;padding:20px'>
                      <div style='background:#1B3F6E;color:white;padding:20px;border-radius:8px 8px 0 0;text-align:center'>
                        <h2 style='margin:0'>Ticket Update</h2>
                      </div>
                      <div style='background:#F8FAFC;padding:24px;border:1px solid #E2E8F0;border-radius:0 0 8px 8px'>
                        <p>Dear {$name},</p>
                        <p>We have responded to your support ticket.</p>
                        <table style='width:100%;border-collapse:collapse;margin:16px 0'>
                          <tr><td style='padding:8px;font-weight:bold;color:#64748B;width:140px'>Ticket #</td><td style='padding:8px;font-family:monospace'>" . (int)$td['ticket_id'] . "</td></tr>
                          <tr style='background:#F1F5F9'><td style='padding:8px;font-weight:bold;color:#64748B'>Subject</td><td style='padding:8px'>" . htmlspecialchars($td['subject']) . "</td></tr>
                          <tr><td style='padding:8px;font-weight:bold;color:#64748B'>New Status</td><td style='padding:8px'>" . ucfirst(str_replace('_', ' ', $new_status)) . "</td></tr>
                        </table>
                        <div style='background:#D1FAE5;border-left:4px solid #059669;padding:16px;border-radius:4px;margin:16px 0'>
                          <strong style='color:#065F46'>Admin Response:</strong><br>
                          " . nl2br(htmlspecialchars($message)) . "
                        </div>
                        <p>Log in to your author portal to view the full conversation.</p>
                        <p style='color:#64748B;font-size:13px'>Best regards,<br>Editorial Support Team<br>Communeglobal</p>
                      </div>
                    </div>
                    </body></html>";

                    if (function_exists('sendAWSMail')) {
                        sendAWSMail($to, $subj, $body);
                    } elseif (function_exists('sendAuthorGmail')) {
                        sendAuthorGmail($to, $subj, $body);
                    } else {
                        $headers  = "MIME-Version: 1.0\r\nContent-type:text/html;charset=UTF-8\r\n";
                        $headers .= "From: Editorial Office <noreply@communeglobal.com>\r\n";
                        @mail($to, $subj, $body, $headers);
                    }
                }
            } catch (Exception $e) { /* email fail — silent */ }

            header("Location: author_ticket_view.php?id={$ticket_id}&success=1");
            exit;

        } catch (PDOException $e) {
            $pdo->rollBack();
            $flash_error = "Database error: " . $e->getMessage();
        }
    }
}

// ── Load ticket ───────────────────────────────────────────
$stmt = $pdo->prepare("
    SELECT t.*,
           u.first_name, u.last_name, u.email AS author_email, u.username,
           u.user_id AS author_user_id, u.title AS author_title,
           u.phone_country_code, u.phone_number,
           u.institutional_email,
           s.submission_id AS sub_id,
           mi.article_title AS submission_title,
           s.tracking_code,
           s.submission_status,
           j.name AS journal_name,
           adm.first_name AS adm_first, adm.last_name AS adm_last
    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
    LEFT JOIN journals j ON j.journal_id = s.journal_id
    LEFT JOIN admin_users adm ON adm.id = ?
    WHERE t.ticket_id = ? AND t.user_type = 'author'
");
$stmt->execute([$admin_id, $ticket_id]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$ticket) { header('Location: author_tickets.php'); exit; }

// Mark author messages as read
$pdo->prepare("UPDATE ticket_messages SET is_read=1 WHERE ticket_id=? AND sender_type='user'")->execute([$ticket_id]);

// ── Load messages ─────────────────────────────────────────
$msgStmt = $pdo->prepare("
    SELECT m.*,
           u.first_name, u.last_name, u.username,
           au.first_name AS adm_first, au.last_name AS adm_last
    FROM ticket_messages m
    LEFT JOIN users u ON m.sender_type = 'user' AND m.sender_id = u.user_id
    LEFT JOIN admin_users au ON m.sender_type = 'admin' AND m.sender_id = au.id
    WHERE m.ticket_id = ?
    ORDER BY m.created_at ASC
");
$msgStmt->execute([$ticket_id]);
$messages = $msgStmt->fetchAll(PDO::FETCH_ASSOC);

// Author stats
try {
    $qs = $pdo->prepare("SELECT COUNT(*) FROM submissions WHERE user_id=?");
    $qs->execute([$ticket['author_user_id']]);
    $totalSubs = (int)$qs->fetchColumn();

    $qa = $pdo->prepare("SELECT COUNT(*) FROM submissions WHERE user_id=? AND submission_status='accepted'");
    $qa->execute([$ticket['author_user_id']]);
    $acceptedSubs = (int)$qa->fetchColumn();
} catch(PDOException $e) { $totalSubs = 0; $acceptedSubs = 0; }

$authorName = trim(($ticket['first_name'] ?? '') . ' ' . ($ticket['last_name'] ?? '')) ?: ($ticket['username'] ?? '—');
$isClosed   = $ticket['status'] === 'closed';

$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 Ticket #<?= (int)$ticket_id ?> — 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-100,.dark .border-gray-200{border-color:#334155}
body.dark .text-gray-800{color:#F1F5F9}
body.dark .text-gray-700{color:#CBD5E1}
body.dark .text-gray-600{color:#94A3B8}
body.dark .text-gray-500{color:#64748B}
body.dark textarea,body.dark select{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}

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

/* Submission status */
.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}

/* Conversation bubbles */
.bubble-author{background:#FFF7ED;border-left:3px solid #F97316;border-radius:0 10px 10px 10px}
.bubble-admin{background:#F0FDF4;border-left:3px solid #10B981;border-radius:10px 0 10px 10px}
body.dark .bubble-author{background:#431407;border-color:#F97316}
body.dark .bubble-admin{background:#064E3B;border-color:#10B981}

/* Cards */
.info-card{background:white;border-radius:12px;border:1px solid #E2E8F0;overflow:hidden}
body.dark .info-card{background:#1E293B;border-color:#334155}
.info-card-hdr{padding:12px 16px;background:#F8FAFC;border-bottom:1px solid #E2E8F0;display:flex;align-items:center;justify-content:space-between}
body.dark .info-card-hdr{background:#0F172A;border-color:#334155}

/* Original message */
.orig-msg{background:#FFF7ED;border-left:4px solid #F97316;border-radius:0 8px 8px 0}
body.dark .orig-msg{background:#1E293B;border-color:#F97316}

/* Form */
.inp{width:100%;border:1px solid #D1D5DB;border-radius:8px;padding:9px 12px;font-size:13px;color:#374151;outline:none;transition:border-color .15s}
.inp:focus{border-color:#3B82F6;box-shadow:0 0 0 3px rgba(59,130,246,.1)}
body.dark .inp{background:#334155;border-color:#475569;color:#E2E8F0}
</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>
      <a href="author_tickets.php" class="text-gray-400 hover:text-orange-600 transition">
        <i class="fas fa-arrow-left text-sm"></i>
      </a>
      <div class="flex items-center gap-2 text-sm">
        <a href="author_tickets.php" class="text-gray-400 hover:text-orange-600 transition">Author Tickets</a>
        <i class="fas fa-chevron-right text-xs text-gray-300"></i>
        <span class="font-bold text-gray-800 font-mono">#<?= (int)$ticket_id ?></span>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <span class="px-3 py-1 rounded-full text-xs font-bold s-<?= $ticket['status'] ?>">
        <?= ucfirst(str_replace('_', ' ', $ticket['status'])) ?>
      </span>
      <span class="px-3 py-1 rounded-full text-xs font-bold p-<?= $ticket['priority'] ?? 'low' ?>">
        <?= ucfirst($ticket['priority'] ?? 'low') ?>
      </span>
      <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>
  </div>

  <main class="p-5">

    <!-- Flash messages -->
    <?php if (isset($_GET['success'])): ?>
    <div class="bg-emerald-50 border border-emerald-300 text-emerald-700 rounded-xl px-5 py-3 mb-4 flex items-center gap-2 text-sm">
      <i class="fas fa-check-circle"></i> Response sent successfully!
    </div>
    <?php endif; ?>
    <?php if (!empty($flash_error)): ?>
    <div class="bg-red-50 border border-red-300 text-red-700 rounded-xl px-5 py-3 mb-4 flex items-center gap-2 text-sm">
      <i class="fas fa-exclamation-circle"></i> <?= p($flash_error) ?>
    </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 xl:grid-cols-3 gap-5">

      <!-- ── Left: Ticket + Thread + Reply ──────────────── -->
      <div class="xl:col-span-2 space-y-5">

        <!-- Ticket Info -->
        <div class="info-card">
          <div class="info-card-hdr">
            <div class="flex items-center gap-2">
              <i class="fas fa-ticket-alt text-orange-500 text-sm"></i>
              <span class="font-bold text-gray-800 text-sm">Ticket Details</span>
            </div>
            <span class="font-mono text-xs text-gray-400">#<?= (int)$ticket_id ?></span>
          </div>
          <div class="p-5">

            <h2 class="text-lg font-bold text-gray-800 mb-4"><?= p($ticket['subject']) ?></h2>

            <!-- Meta grid -->
            <div class="grid grid-cols-2 md:grid-cols-3 gap-4 mb-5 text-sm">
              <div>
                <div class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Author</div>
                <div class="font-semibold text-gray-800"><?= p($authorName) ?></div>
                <div class="text-xs text-gray-400"><?= p($ticket['author_email'] ?? '') ?></div>
              </div>
              <div>
                <div class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Category</div>
                <div class="text-gray-700"><?= p($ticket['category'] ?? 'General') ?></div>
              </div>
              <div>
                <div class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Created</div>
                <div class="text-gray-700"><?= date('d M Y', strtotime($ticket['created_at'])) ?></div>
                <div class="text-xs text-gray-400"><?= date('H:i', strtotime($ticket['created_at'])) ?></div>
              </div>
              <div>
                <div class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Last Updated</div>
                <div class="text-gray-700"><?= date('d M Y', strtotime($ticket['updated_at'])) ?></div>
                <div class="text-xs text-gray-400"><?= date('H:i', strtotime($ticket['updated_at'])) ?></div>
              </div>
              <div>
                <div class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-1">Messages</div>
                <div class="font-bold text-gray-800"><?= count($messages) ?></div>
              </div>
            </div>

            <!-- Related submission -->
            <?php if (!empty($ticket['tracking_code'])): ?>
            <div class="bg-blue-50 border border-blue-100 rounded-xl p-3 mb-5 flex items-start gap-3">
              <i class="fas fa-file-alt text-blue-400 mt-0.5 flex-shrink-0"></i>
              <div class="flex-1 min-w-0">
                <div class="text-xs font-bold text-blue-500 uppercase tracking-wide mb-1">Related Submission</div>
                <div class="flex flex-wrap items-center gap-2 mb-1">
                  <span class="font-mono text-sm font-bold text-blue-700"><?= p($ticket['tracking_code']) ?></span>
                  <?php if (!empty($ticket['submission_status'])): ?>
                  <span class="text-xs font-semibold ss-<?= $ticket['submission_status'] ?> px-2 py-0.5 rounded-full">
                    <?= ucfirst(str_replace('_', ' ', $ticket['submission_status'])) ?>
                  </span>
                  <?php endif; ?>
                </div>
                <?php if (!empty($ticket['submission_title'])): ?>
                <div class="text-sm text-gray-600 truncate"><?= p($ticket['submission_title']) ?></div>
                <?php endif; ?>
                <?php if (!empty($ticket['journal_name'])): ?>
                <div class="text-xs text-gray-400 mt-0.5"><?= p($ticket['journal_name']) ?></div>
                <?php endif; ?>
                <a href="submission_view.php?id=<?= (int)$ticket['sub_id'] ?>"
                   class="text-xs text-blue-600 hover:underline mt-1 inline-flex items-center gap-1">
                  <i class="fas fa-external-link-alt text-[10px]"></i> View submission →
                </a>
              </div>
            </div>
            <?php endif; ?>

            <!-- Original message (first message) -->
            <div>
              <div class="text-xs font-bold text-gray-500 uppercase tracking-wide mb-2">Original Message</div>
              <div class="orig-msg p-4 text-sm text-gray-700 leading-relaxed whitespace-pre-wrap rounded">
                <?php
                // Show the very first message from ticket_messages, or fallback to old message column
                $firstMsg = !empty($messages) ? $messages[0]['message'] : ($ticket['message'] ?? '');
                echo p($firstMsg);
                ?>
              </div>
            </div>

          </div>
        </div>

        <!-- Conversation Thread (messages after the first) -->
        <?php $threadMessages = array_slice($messages, 1); ?>
        <?php if (!empty($threadMessages)): ?>
        <div class="info-card">
          <div class="info-card-hdr">
            <span class="font-bold text-gray-800 text-sm flex items-center gap-2">
              <i class="fas fa-comments text-indigo-500 text-sm"></i>
              Conversation Thread
            </span>
            <span class="text-xs text-gray-400"><?= count($threadMessages) ?> follow-up message<?= count($threadMessages) !== 1 ? 's' : '' ?></span>
          </div>
          <div class="p-5 space-y-4 max-h-[520px] overflow-y-auto" id="thread">
            <?php foreach ($threadMessages as $msg):
              $isAdmin = $msg['sender_type'] === 'admin';
              if ($isAdmin) {
                  $sender = trim(($msg['adm_first'] ?? '') . ' ' . ($msg['adm_last'] ?? '')) ?: 'Admin';
              } else {
                  $sender = trim(($msg['first_name'] ?? '') . ' ' . ($msg['last_name'] ?? '')) ?: ($msg['username'] ?? '?');
              }
              $initial = strtoupper(substr($sender, 0, 1));
            ?>
            <div class="<?= $isAdmin ? 'ml-6' : 'mr-6' ?>">
              <div class="bubble-<?= $isAdmin ? 'admin' : 'author' ?> p-4 rounded-xl">
                <div class="flex items-center justify-between mb-2 gap-3">
                  <div class="flex items-center gap-2">
                    <div class="w-7 h-7 rounded-full <?= $isAdmin ? 'bg-emerald-100 text-emerald-700' : 'bg-orange-100 text-orange-700' ?> flex items-center justify-center text-xs font-bold flex-shrink-0">
                      <?= $initial ?>
                    </div>
                    <span class="font-semibold text-gray-800 text-sm"><?= p($sender) ?></span>
                    <?php if ($isAdmin): ?>
                    <span class="text-xs bg-emerald-600 text-white px-2 py-0.5 rounded-full">Admin</span>
                    <?php else: ?>
                    <span class="text-xs bg-orange-500 text-white px-2 py-0.5 rounded-full">Author</span>
                    <?php endif; ?>
                  </div>
                  <span class="text-xs text-gray-400 whitespace-nowrap">
                    <?= date('d M Y, H:i', strtotime($msg['created_at'])) ?>
                  </span>
                </div>
                <p class="text-sm text-gray-700 leading-relaxed whitespace-pre-wrap"><?= p($msg['message']) ?></p>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Reply Form -->
        <?php if (!$isClosed): ?>
        <div class="info-card">
          <div class="info-card-hdr">
            <span class="font-bold text-gray-800 text-sm flex items-center gap-2">
              <i class="fas fa-reply text-green-500 text-sm"></i>
              Send Response
            </span>
          </div>
          <div class="p-5">
            <form method="POST" id="replyForm">
              <input type="hidden" name="respond" value="1">
              <div class="mb-4">
                <label class="block text-xs font-bold text-gray-500 uppercase tracking-wide mb-2">
                  Response Message <span class="text-red-500">*</span>
                </label>
                <textarea name="response_message" id="replyText" rows="6" required
                          class="inp resize-y"
                          placeholder="Type your response to the author…"></textarea>
                <div class="flex justify-between mt-1">
                  <span class="text-xs text-gray-400">Be clear and professional.</span>
                  <span id="charCount" class="text-xs text-gray-400">0 chars</span>
                </div>
              </div>
              <div class="mb-5">
                <label class="block text-xs font-bold text-gray-500 uppercase tracking-wide mb-2">
                  Update Status <span class="text-red-500">*</span>
                </label>
                <select name="new_status" class="inp" required>
                  <option value="open"        <?= $ticket['status']==='open'        ? 'selected' : '' ?>>Open</option>
                  <option value="in_progress" <?= $ticket['status']==='in_progress' ? 'selected' : '' ?>>In Progress</option>
                  <option value="resolved">Resolved</option>
                  <option value="closed">Closed</option>
                </select>
              </div>
              <div class="flex gap-3 flex-wrap">
                <button type="submit"
                        class="bg-orange-600 hover:bg-orange-700 text-white px-6 py-2.5 rounded-lg font-bold text-sm flex items-center gap-2 transition">
                  <i class="fas fa-paper-plane text-xs"></i> Send Response
                </button>
                <button type="button" onclick="document.getElementById('replyText').value=''"
                        class="border border-gray-300 text-gray-600 hover:bg-gray-50 px-4 py-2.5 rounded-lg font-semibold text-sm transition">
                  Clear
                </button>
                <a href="author_tickets.php"
                   class="border border-gray-300 text-gray-500 hover:bg-gray-50 px-4 py-2.5 rounded-lg font-semibold text-sm transition flex items-center gap-1">
                  <i class="fas fa-arrow-left text-xs"></i> Back to List
                </a>
              </div>
            </form>
          </div>
        </div>
        <?php else: ?>
        <div class="bg-gray-100 border border-gray-300 text-gray-600 rounded-xl px-5 py-4 flex items-center gap-3 text-sm">
          <i class="fas fa-lock text-gray-400"></i>
          <span>This ticket is <strong>closed</strong> and no longer accepts responses.</span>
          <a href="author_tickets.php" class="ml-auto text-orange-600 hover:underline text-xs">← Back to list</a>
        </div>
        <?php endif; ?>

      </div><!-- /left -->

      <!-- ── Right: Info sidebar ─────────────────────────── -->
      <div class="space-y-4">

        <!-- Author Info -->
        <div class="info-card">
          <div class="info-card-hdr">
            <span class="text-xs font-bold text-gray-500 uppercase tracking-wide">Author Info</span>
          </div>
          <div class="p-4 space-y-3">
            <div class="flex items-center gap-3">
              <div class="w-10 h-10 rounded-full bg-orange-100 text-orange-700 flex items-center justify-center text-sm font-bold flex-shrink-0">
                <?= strtoupper(substr($ticket['first_name'] ?? '?', 0, 1) . substr($ticket['last_name'] ?? '', 0, 1)) ?>
              </div>
              <div>
                <div class="font-bold text-gray-800 text-sm">
                  <?php if (!empty($ticket['author_title'])): ?><?= p($ticket['author_title']) ?> <?php endif; ?>
                  <?= p($authorName) ?>
                </div>
                <div class="text-xs text-gray-400"><?= p($ticket['author_email'] ?? '') ?></div>
              </div>
            </div>
            <?php if (!empty($ticket['institutional_email'])): ?>
            <div class="text-xs text-gray-500">
              <i class="fas fa-university text-gray-400 mr-1"></i>
              <?= p($ticket['institutional_email']) ?>
            </div>
            <?php endif; ?>
            <?php if (!empty($ticket['phone_number'])): ?>
            <div class="text-xs text-gray-500">
              <i class="fas fa-phone text-gray-400 mr-1"></i>
              <?= p(($ticket['phone_country_code'] ?? '') . ' ' . $ticket['phone_number']) ?>
            </div>
            <?php endif; ?>
            <div class="grid grid-cols-2 gap-2 pt-2 border-t border-gray-100">
              <div class="text-center bg-gray-50 rounded-lg p-2">
                <div class="font-bold text-gray-800"><?= $totalSubs ?></div>
                <div class="text-xs text-gray-400">Submissions</div>
              </div>
              <div class="text-center bg-gray-50 rounded-lg p-2">
                <div class="font-bold text-emerald-600"><?= $acceptedSubs ?></div>
                <div class="text-xs text-gray-400">Accepted</div>
              </div>
            </div>
            <?php if ($ticket['author_user_id']): ?>
            <a href="user_view.php?id=<?= (int)$ticket['author_user_id'] ?>"
               class="block w-full text-center 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-user mr-1"></i> View Author Profile
            </a>
            <?php endif; ?>
          </div>
        </div>

        <!-- Ticket Status -->
        <div class="info-card">
          <div class="info-card-hdr">
            <span class="text-xs font-bold text-gray-500 uppercase tracking-wide">Ticket Status</span>
          </div>
          <div class="p-4 space-y-3">
            <div>
              <div class="text-xs text-gray-400 mb-1">Current Status</div>
              <span class="px-3 py-1 rounded-full text-xs font-bold s-<?= $ticket['status'] ?>">
                <?= ucfirst(str_replace('_', ' ', $ticket['status'])) ?>
              </span>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">Priority</div>
              <span class="px-3 py-1 rounded-full text-xs font-bold p-<?= $ticket['priority'] ?? 'low' ?>">
                <?= ucfirst($ticket['priority'] ?? 'low') ?>
              </span>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">Category</div>
              <span class="text-sm text-gray-700 font-medium"><?= p($ticket['category'] ?? 'General') ?></span>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">Messages</div>
              <span class="font-bold text-gray-800"><?= count($messages) ?></span>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">Ticket ID</div>
              <span class="font-mono text-xs text-gray-600">#<?= (int)$ticket_id ?></span>
            </div>
            <div>
              <div class="text-xs text-gray-400 mb-1">Opened</div>
              <span class="text-sm text-gray-700"><?= date('d M Y', strtotime($ticket['created_at'])) ?></span>
            </div>
          </div>
        </div>

        <!-- Quick Status Update (no message) -->
        <?php if (!$isClosed): ?>
        <div class="info-card">
          <div class="info-card-hdr">
            <span class="text-xs font-bold text-gray-500 uppercase tracking-wide">Quick Status Update</span>
          </div>
          <div class="p-4">
            <p class="text-xs text-gray-400 mb-3">Change status without sending a reply message.</p>
            <form method="POST" id="quickStatusForm">
              <input type="hidden" name="respond" value="1">
              <input type="hidden" name="response_message" value="[Status updated by admin]">
              <select name="new_status" class="inp text-sm mb-3">
                <option value="open"        <?= $ticket['status']==='open'        ? 'selected' : '' ?>>Open</option>
                <option value="in_progress" <?= $ticket['status']==='in_progress' ? 'selected' : '' ?>>In Progress</option>
                <option value="resolved">Resolved</option>
                <option value="closed">Closed</option>
              </select>
              <button type="submit" class="w-full bg-slate-700 hover:bg-slate-800 text-white py-2 rounded-lg text-xs font-bold transition">
                Update Status
              </button>
            </form>
          </div>
        </div>
        <?php endif; ?>

        <!-- Nav links -->
        <div class="info-card">
          <div class="p-4 space-y-2">
            <a href="author_tickets.php" class="flex items-center gap-2 text-sm text-gray-600 hover:text-orange-600 transition py-1">
              <i class="fas fa-list text-xs w-4 text-center"></i> All Author Tickets
            </a>
            <?php if (!empty($ticket['sub_id'])): ?>
            <a href="submission_view.php?id=<?= (int)$ticket['sub_id'] ?>" class="flex items-center gap-2 text-sm text-gray-600 hover:text-blue-600 transition py-1">
              <i class="fas fa-file-alt text-xs w-4 text-center"></i> View Submission
            </a>
            <a href="submission_review.php?id=<?= (int)$ticket['sub_id'] ?>" class="flex items-center gap-2 text-sm text-gray-600 hover:text-blue-600 transition py-1">
              <i class="fas fa-user-check text-xs w-4 text-center"></i> Review Management
            </a>
            <?php endif; ?>
          </div>
        </div>

      </div><!-- /right -->
    </div><!-- /grid -->
  </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');
}

// Char counter
const ta = document.getElementById('replyText');
const cc = document.getElementById('charCount');
if (ta && cc) {
    ta.addEventListener('input', () => { cc.textContent = ta.value.length + ' chars'; });
}

// Scroll thread to bottom
const thread = document.getElementById('thread');
if (thread) thread.scrollTop = thread.scrollHeight;

// Confirm close
document.querySelectorAll('[name=new_status]').forEach(sel => {
    sel.addEventListener('change', function(){
        if (this.value === 'closed' && !confirm('Mark this ticket as Closed? The author will no longer be able to add replies.')) {
            this.value = '<?= $ticket['status'] ?>';
        }
    });
});
</script>
</body>
</html>