<?php
// ============================================================
//  my_tickets.php  —  Author: View & Reply to My Tickets
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

$pageTitle  = 'My Tickets';
$activePage = 'my_tickets';

// ── AJAX: Get messages for a ticket ──────────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'get_messages') {
    header('Content-Type: application/json');
    $tid = (int)($_GET['ticket_id'] ?? 0);
    try {
        $chk = db()->prepare(
            "SELECT t.*, s.tracking_code AS sub_code, s.submission_status AS sub_status, mi.article_title AS sub_title
             FROM support_tickets t
             LEFT JOIN submissions s ON s.submission_id = t.submission_id
             LEFT JOIN manuscript_info mi ON mi.submission_id = t.submission_id
             WHERE t.ticket_id=? AND t.user_id=?"
        );
        $chk->execute([$tid, $user_id]);
        $ticket = $chk->fetch(PDO::FETCH_ASSOC);
        if (!$ticket) { echo json_encode(['success'=>false,'message'=>'Not found']); exit; }

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

        $msgs = db()->prepare("SELECT tm.*, u.first_name, u.last_name FROM ticket_messages tm LEFT JOIN users u ON u.user_id=tm.sender_id WHERE tm.ticket_id=? ORDER BY tm.created_at ASC");
        $msgs->execute([$tid]);
        echo json_encode(['success'=>true,'ticket'=>$ticket,'messages'=>$msgs->fetchAll(PDO::FETCH_ASSOC)]);
    } catch(Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
    exit;
}

// ── AJAX: Reply to a ticket ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_reply'])) {
    header('Content-Type: application/json');
    $tid     = (int)($_POST['ticket_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    try {
        $chk = db()->prepare("SELECT ticket_id, status FROM support_tickets WHERE ticket_id=? AND user_id=?");
        $chk->execute([$tid, $user_id]);
        $ticket = $chk->fetch(PDO::FETCH_ASSOC);
        if (!$ticket) { echo json_encode(['success'=>false,'message'=>'Ticket not found']); exit; }
        if (!$message) { echo json_encode(['success'=>false,'message'=>'Message cannot be empty']); exit; }
        if ($ticket['status'] === 'closed') { echo json_encode(['success'=>false,'message'=>'This ticket is closed']); exit; }

        db()->prepare("INSERT INTO ticket_messages (ticket_id, sender_id, sender_type, message, created_at) VALUES (?,?,'user',?,NOW())")
            ->execute([$tid, $user_id, $message]);
        // Reopen if resolved
        if ($ticket['status'] === 'resolved') {
            db()->prepare("UPDATE support_tickets SET status='open', updated_at=NOW() WHERE ticket_id=?")->execute([$tid]);
        } else {
            db()->prepare("UPDATE support_tickets SET updated_at=NOW() WHERE ticket_id=?")->execute([$tid]);
        }
        echo json_encode(['success'=>true]);
    } catch(Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
    exit;
}

// ── AJAX: Close a ticket ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_close'])) {
    header('Content-Type: application/json');
    $tid = (int)($_POST['ticket_id'] ?? 0);
    try {
        $chk = db()->prepare("SELECT ticket_id FROM support_tickets WHERE ticket_id=? AND user_id=?");
        $chk->execute([$tid, $user_id]);
        if (!$chk->fetch()) { echo json_encode(['success'=>false,'message'=>'Not found']); exit; }
        db()->prepare("UPDATE support_tickets SET status='closed', updated_at=NOW() WHERE ticket_id=?")->execute([$tid]);
        echo json_encode(['success'=>true]);
    } catch(Exception $e) { echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
    exit;
}

// ── Load all tickets for this user ───────────────────────────
$filterStatus = $_GET['status'] ?? 'all';
try {
    $sql = "SELECT t.*,
            (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id=t.ticket_id) AS msg_count,
            (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id=t.ticket_id AND sender_type='admin' AND is_read=0) AS unread_count,
            s.tracking_code AS sub_code,
            s.submission_status AS sub_status,
            mi.article_title AS sub_title
            FROM support_tickets t
            LEFT JOIN submissions s ON s.submission_id = t.submission_id
            LEFT JOIN manuscript_info mi ON mi.submission_id = t.submission_id
            WHERE t.user_id=?";
    $params = [$user_id];
    if ($filterStatus !== 'all') { $sql .= " AND t.status=?"; $params[] = $filterStatus; }
    $sql .= " ORDER BY t.updated_at DESC";
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) { $tickets = []; }

// Count by status
try {
    $cs = db()->prepare("SELECT status, COUNT(*) as cnt FROM support_tickets WHERE user_id=? GROUP BY status");
    $cs->execute([$user_id]);
    $statusCounts = []; foreach ($cs->fetchAll(PDO::FETCH_ASSOC) as $r) $statusCounts[$r['status']] = (int)$r['cnt'];
} catch(PDOException $e) { $statusCounts = []; }
$totalCount = array_sum($statusCounts);

function statusBadge($s) {
    $map = ['open'=>['#1D4ED8','#EFF6FF','Open'],'in_progress'=>['#D97706','#FFFBEB','In Progress'],'resolved'=>['#16A34A','#F0FDF4','Resolved'],'closed'=>['#6B7280','#F9FAFB','Closed']];
    $d = $map[$s] ?? ['#6B7280','#F9FAFB',ucfirst($s)];
    return "<span style='display:inline-flex;align-items:center;padding:2px 10px;border-radius:20px;font-size:11.5px;font-weight:700;color:{$d[0]};background:{$d[1]}'>{$d[2]}</span>";
}
function priorityDot($p) {
    $map = ['low'=>'#22C55E','medium'=>'#F59E0B','high'=>'#EF4444'];
    $c = $map[$p] ?? '#9CA3AF';
    return "<span style='display:inline-block;width:8px;height:8px;border-radius:50%;background:$c;margin-right:5px'></span>";
}

require_once __DIR__ . '/_layout.php';
?>

<style>
.au-main { padding: 24px 28px 60px; }

/* Header row */
.myt-header {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 20px; flex-wrap: wrap; gap: 12px;
}
.myt-header-title { font-size: 18px; font-weight: 700; color: var(--text); }
.btn-raise {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 9px 18px; background: var(--blue); color: #fff;
  border: none; border-radius: 8px; font-family: var(--font);
  font-size: 13.5px; font-weight: 700; cursor: pointer;
  transition: background .15s; text-decoration: none;
}
.btn-raise:hover { background: #132B50; }

/* Status filter tabs */
.myt-tabs {
  display: flex; gap: 6px; margin-bottom: 18px; flex-wrap: wrap;
}
.myt-tab {
  padding: 6px 14px; border-radius: 20px; font-size: 12.5px; font-weight: 600;
  cursor: pointer; border: 1.5px solid var(--border);
  background: var(--white); color: var(--muted); transition: all .15s;
  text-decoration: none; display: inline-block;
}
.myt-tab:hover { border-color: var(--blue); color: var(--blue); }
.myt-tab.active { background: var(--blue); color: #fff; border-color: var(--blue); }
.myt-tab .badge {
  display: inline-flex; align-items: center; justify-content: center;
  width: 18px; height: 18px; border-radius: 50%; font-size: 10px;
  font-weight: 700; margin-left: 5px;
  background: rgba(255,255,255,.25); color: inherit;
}

/* Ticket list */
.myt-list { display: flex; flex-direction: column; gap: 10px; }

.myt-ticket {
  background: var(--white); border: 1px solid var(--border);
  border-radius: 10px; padding: 16px 20px;
  cursor: pointer; transition: all .15s;
  position: relative;
}
.myt-ticket:hover { border-color: var(--blue); box-shadow: 0 2px 8px rgba(27,63,110,.1); }
.myt-ticket.has-unread { border-left: 4px solid var(--blue); }

.myt-ticket-top {
  display: flex; align-items: flex-start;
  justify-content: space-between; gap: 12px; margin-bottom: 8px;
}
.myt-ticket-subject { font-size: 14.5px; font-weight: 700; color: var(--text); }
.myt-ticket-meta {
  display: flex; align-items: center; gap: 14px;
  font-size: 12px; color: var(--muted); flex-wrap: wrap;
}
.myt-ticket-meta span { display: flex; align-items: center; gap: 4px; }
.myt-unread-badge {
  position: absolute; top: 12px; right: 16px;
  background: var(--blue); color: #fff;
  font-size: 10px; font-weight: 700; padding: 2px 7px;
  border-radius: 10px;
}

/* Empty state */
.myt-empty {
  text-align: center; padding: 60px 20px;
  background: var(--white); border-radius: 12px;
  border: 1px solid var(--border);
}
.myt-empty-icon { font-size: 48px; margin-bottom: 16px; }
.myt-empty-title { font-size: 16px; font-weight: 700; color: var(--text); margin-bottom: 8px; }
.myt-empty-sub { font-size: 13px; color: var(--muted); margin-bottom: 20px; }

/* ── TICKET DETAIL MODAL ─────────────────────────────────── */
.tk-modal-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,.5);
  z-index: 600; display: none; align-items: center; justify-content: center;
  padding: 20px;
}
.tk-modal-overlay.open { display: flex; }
.tk-modal {
  background: var(--white); border-radius: 14px; width: 100%;
  max-width: 700px; max-height: 88vh;
  display: flex; flex-direction: column;
  box-shadow: 0 20px 60px rgba(0,0,0,.25);
  animation: mslide .25s ease;
}
@keyframes mslide { from{transform:translateY(20px);opacity:0} to{transform:translateY(0);opacity:1} }

.tk-modal-top {
  display: flex; align-items: flex-start; justify-content: space-between;
  padding: 20px 22px; border-bottom: 1px solid var(--border); flex-shrink: 0;
}
.tk-modal-title { font-size: 15px; font-weight: 700; color: var(--text); margin-bottom: 6px; }
.tk-modal-meta  { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.tk-modal-close {
  background: none; border: none; cursor: pointer; color: var(--muted);
  font-size: 20px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0;
}
.tk-modal-close:hover { background: #F3F4F6; }

/* Messages scroll area */
.tk-messages {
  flex: 1; overflow-y: auto; padding: 18px 22px;
  display: flex; flex-direction: column; gap: 14px;
}
.tk-msg {
  display: flex; flex-direction: column; max-width: 85%;
}
.tk-msg.user  { align-self: flex-end; align-items: flex-end; }
.tk-msg.admin { align-self: flex-start; align-items: flex-start; }

.tk-msg-sender {
  font-size: 11.5px; font-weight: 600; color: var(--muted);
  margin-bottom: 4px; padding: 0 4px;
}
.tk-msg-bubble {
  padding: 11px 15px; border-radius: 12px; font-size: 13.5px;
  line-height: 1.6; white-space: pre-wrap; word-break: break-word;
}
.tk-msg.user  .tk-msg-bubble { background: var(--blue); color: #fff; border-radius: 12px 12px 2px 12px; }
.tk-msg.admin .tk-msg-bubble { background: #F3F4F6; color: var(--text); border-radius: 12px 12px 12px 2px; }
.tk-msg-time {
  font-size: 10.5px; color: var(--muted); margin-top: 3px; padding: 0 4px;
}

/* Reply area */
.tk-reply-area {
  padding: 16px 22px; border-top: 1px solid var(--border); flex-shrink: 0;
}
.tk-reply-closed {
  text-align: center; padding: 14px; font-size: 13px;
  color: var(--muted); background: #F9FAFB; border-radius: 8px;
}
.tk-reply-row { display: flex; gap: 10px; align-items: flex-end; }
.tk-reply-input {
  flex: 1; padding: 10px 14px; border: 1.5px solid var(--border);
  border-radius: 8px; font-family: var(--font); font-size: 13.5px;
  color: var(--text); outline: none; resize: none; min-height: 44px;
  max-height: 120px; transition: border-color .15s; line-height: 1.5;
}
.tk-reply-input:focus { border-color: var(--blue); }
.btn-send-reply {
  padding: 10px 18px; background: var(--blue); color: #fff;
  border: none; border-radius: 8px; font-family: var(--font);
  font-size: 13px; font-weight: 700; cursor: pointer; white-space: nowrap;
  transition: background .15s; flex-shrink: 0;
}
.btn-send-reply:hover    { background: #132B50; }
.btn-send-reply:disabled { opacity: .5; cursor: not-allowed; }

.tk-close-ticket-row { margin-top: 10px; text-align: right; }
.btn-close-ticket {
  background: none; border: 1.5px solid #D1D5DB; border-radius: 6px;
  padding: 6px 14px; font-size: 12px; font-weight: 600; color: var(--muted);
  cursor: pointer; font-family: var(--font); transition: all .15s;
}
.btn-close-ticket:hover { border-color: #EF4444; color: #DC2626; }

/* Spinner */
.spinner { display: inline-block; width: 18px; height: 18px; border: 2px solid rgba(0,0,0,.1); border-top-color: var(--blue); border-radius: 50%; animation: spin .6s linear infinite; margin: 30px auto; display: block; }
@keyframes spin { to{transform:rotate(360deg)} }

/* Toast */
.toast-wrap { position: fixed; bottom: 24px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
.toast { padding: 11px 16px; border-radius: 8px; font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.18); display: flex; align-items: center; gap: 8px; animation: tup .25s ease; }
.ts { background: #1D8A5E; } .te { background: #DC2626; }
@keyframes tup { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
</style>

<!-- Header -->
<div class="myt-header">
  <div class="myt-header-title">My Support Tickets</div>
  <a href="tickets.php" class="btn-raise">🎫 Raise New Ticket</a>
</div>

<!-- Status filter tabs -->
<div class="myt-tabs">
  <?php
  $tabs = ['all' => 'All', 'open' => 'Open', 'in_progress' => 'In Progress', 'resolved' => 'Resolved', 'closed' => 'Closed'];
  foreach ($tabs as $val => $label):
      $cnt = $val === 'all' ? $totalCount : ($statusCounts[$val] ?? 0);
      $active = $filterStatus === $val ? 'active' : '';
  ?>
  <a href="?status=<?= $val ?>" class="myt-tab <?= $active ?>">
    <?= $label ?>
    <?php if ($cnt > 0): ?><span class="badge"><?= $cnt ?></span><?php endif; ?>
  </a>
  <?php endforeach; ?>
</div>

<!-- Ticket list -->
<?php if (empty($tickets)): ?>
<div class="myt-empty">
  <div class="myt-empty-icon">🎫</div>
  <div class="myt-empty-title">
    <?= $filterStatus === 'all' ? 'No tickets yet' : 'No ' . ($tabs[$filterStatus] ?? $filterStatus) . ' tickets' ?>
  </div>
  <div class="myt-empty-sub">
    <?= $filterStatus === 'all' ? 'Need help? Raise your first support ticket.' : 'Try viewing a different status.' ?>
  </div>
  <?php if ($filterStatus === 'all'): ?>
  <a href="tickets.php" class="btn-raise">🎫 Raise a Ticket</a>
  <?php endif; ?>
</div>
<?php else: ?>
<div class="myt-list">
  <?php foreach ($tickets as $t):
    $unread = (int)($t['unread_count'] ?? 0);
  ?>
  <div class="myt-ticket <?= $unread ? 'has-unread' : '' ?>"
       onclick="openTicket(<?= $t['ticket_id'] ?>)">
    <?php if ($unread): ?>
    <div class="myt-unread-badge">+<?= $unread ?> new</div>
    <?php endif; ?>
    <div class="myt-ticket-top">
      <div>
        <div class="myt-ticket-subject">CIJSS-TKT-<?= str_pad($t['ticket_id'], 4, '0', STR_PAD_LEFT) ?> — <?= htmlspecialchars($t['subject']) ?></div>
        <div style="margin-top:5px;display:flex;align-items:center;gap:8px">
          <?= statusBadge($t['status']) ?>
          <span style="font-size:12px;color:var(--muted)">
            <?= priorityDot($t['priority'] ?? 'low') ?><?= ucfirst($t['priority'] ?? 'low') ?>
          </span>
          <span style="font-size:12px;color:var(--muted);background:#F3F4F6;padding:2px 8px;border-radius:10px">
            <?= htmlspecialchars($t['category'] ?? 'General') ?>
          </span>
        </div>
      </div>
    </div>
    <div class="myt-ticket-meta">
      <span>📅 <?= date('d M Y, H:i', strtotime($t['created_at'])) ?></span>
      <span>💬 <?= (int)$t['msg_count'] ?> message<?= $t['msg_count'] != 1 ? 's' : '' ?></span>
      <span>🕐 Updated <?= date('d M', strtotime($t['updated_at'])) ?></span>
      <?php if (!empty($t['sub_code']) || !empty($t['sub_title'])): ?>
      <span style="color:var(--teal);font-weight:600">
        📄 <?= $t['sub_code'] ? htmlspecialchars($t['sub_code']) : '' ?>
        <?php if (!empty($t['sub_title'])): ?>
        — <?= htmlspecialchars(mb_strimwidth($t['sub_title'], 0, 55, '…')) ?>
        <?php endif; ?>
      </span>
      <?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Ticket detail modal -->
<div class="tk-modal-overlay" id="ticketModal" onclick="maybeCloseModal(event)">
  <div class="tk-modal" id="modalInner">
    <div class="tk-modal-top" id="modalTop">
      <div>
        <div class="tk-modal-title" id="modalTitle">Loading...</div>
        <div class="tk-modal-meta" id="modalMeta"></div>
      </div>
      <button class="tk-modal-close" onclick="closeModal()">✕</button>
    </div>
    <div class="tk-messages" id="modalMessages">
      <div class="spinner"></div>
    </div>
    <div class="tk-reply-area" id="replyArea"></div>
  </div>
</div>

<div class="toast-wrap" id="toastWrap"></div>

<script>
let currentTicketId   = null;
let currentTicketStatus = null;

function openTicket(ticketId) {
    currentTicketId = ticketId;
    document.getElementById('ticketModal').classList.add('open');
    document.body.style.overflow = 'hidden';
    loadTicket(ticketId);
}
function closeModal() {
    document.getElementById('ticketModal').classList.remove('open');
    document.body.style.overflow = '';
    currentTicketId = null;
    // Reload page to reflect read status / status changes
    location.reload();
}
function maybeCloseModal(e) {
    if (e.target === document.getElementById('ticketModal')) closeModal();
}

function xe(s) { return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

function fmtDate(d) {
    if (!d) return '';
    const dt = new Date(d.replace(' ','T'));
    return dt.toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'}) + ', ' + dt.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'});
}

function loadTicket(ticketId) {
    document.getElementById('modalMessages').innerHTML = '<div class="spinner"></div>';
    document.getElementById('replyArea').innerHTML = '';

    fetch('my_tickets.php?ajax=get_messages&ticket_id=' + ticketId)
    .then(r => r.json())
    .then(data => {
        if (!data.success) { showToast('❌ Failed to load ticket', 'e'); return; }

        const t = data.ticket;
        currentTicketStatus = t.status;

        document.getElementById('modalTitle').textContent = 'CIJSS-TKT-' + String(t.ticket_id).padStart(4,'0') + ' — ' + t.subject;

        const statusColors = {open:'#1D4ED8',in_progress:'#D97706',resolved:'#16A34A',closed:'#6B7280'};
        const statusBg     = {open:'#EFF6FF',in_progress:'#FFFBEB',resolved:'#F0FDF4',closed:'#F9FAFB'};
        const sc = statusColors[t.status] || '#6B7280';
        const sb = statusBg[t.status] || '#F9FAFB';
        const prioColors = {low:'#22C55E',medium:'#F59E0B',high:'#EF4444'};
        const pc = prioColors[t.priority] || '#9CA3AF';

        document.getElementById('modalMeta').innerHTML =
            `<span style="display:inline-flex;align-items:center;padding:2px 10px;border-radius:20px;font-size:11.5px;font-weight:700;color:${sc};background:${sb}">${xe(t.status.replace('_',' '))}</span>` +
            `<span style="display:inline-flex;align-items:center;font-size:12px;color:var(--muted)"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${pc};margin-right:5px"></span>${xe(t.priority||'low')}</span>` +
            `<span style="font-size:12px;color:var(--muted);background:#F3F4F6;padding:2px 8px;border-radius:10px">${xe(t.category||'General')}</span>` +
            (t.sub_code || t.sub_title
                ? `<span style="font-size:12px;color:var(--teal);font-weight:600;background:#E0F4F7;padding:2px 10px;border-radius:10px">📄 ${xe(t.sub_code||'')}${t.sub_title ? ' — ' + xe(t.sub_title.length > 55 ? t.sub_title.slice(0,55)+'…' : t.sub_title) : ''}</span>`
                : '');

        // Render messages
        const msgs = data.messages;
        if (!msgs.length) {
            document.getElementById('modalMessages').innerHTML = '<div style="text-align:center;padding:30px;color:var(--muted);font-size:13px">No messages yet</div>';
        } else {
            document.getElementById('modalMessages').innerHTML = msgs.map(m => {
                const isUser  = m.sender_type === 'user';
                const cls     = isUser ? 'user' : 'admin';
                const name    = isUser ? 'You' : ('Support Team');
                return `<div class="tk-msg ${cls}">
                    <div class="tk-msg-sender">${xe(name)}</div>
                    <div class="tk-msg-bubble">${xe(m.message)}</div>
                    <div class="tk-msg-time">${fmtDate(m.created_at)}</div>
                </div>`;
            }).join('');
            // Scroll to bottom
            const msgEl = document.getElementById('modalMessages');
            msgEl.scrollTop = msgEl.scrollHeight;
        }

        // Reply area
        if (t.status === 'closed') {
            document.getElementById('replyArea').innerHTML =
                '<div class="tk-reply-closed">🔒 This ticket is closed. <a href="tickets.php" style="color:var(--blue);font-weight:600">Raise a new ticket</a> if you need further help.</div>';
        } else {
            document.getElementById('replyArea').innerHTML = `
                <div class="tk-reply-row">
                    <textarea class="tk-reply-input" id="replyInput" placeholder="Type your reply..." rows="1"
                              oninput="autoResize(this)"
                              onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();sendReply();}"></textarea>
                    <button class="btn-send-reply" id="sendReplyBtn" onclick="sendReply()">Send</button>
                </div>
                <div class="tk-close-ticket-row">
                    <button class="btn-close-ticket" onclick="closeTicket()">✓ Mark as Resolved & Close</button>
                </div>`;
        }
    })
    .catch(() => showToast('❌ Network error', 'e'));
}

function autoResize(ta) {
    ta.style.height = 'auto';
    ta.style.height = Math.min(ta.scrollHeight, 120) + 'px';
}

function sendReply() {
    const input = document.getElementById('replyInput');
    if (!input) return;
    const msg = input.value.trim();
    if (!msg) return;

    const btn = document.getElementById('sendReplyBtn');
    btn.disabled = true; btn.textContent = '...';

    const fd = new FormData();
    fd.append('ajax_reply', '1');
    fd.append('ticket_id',  currentTicketId);
    fd.append('message',    msg);

    fetch('my_tickets.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false; btn.textContent = 'Send';
        if (data.success) {
            input.value = ''; input.style.height = '';
            loadTicket(currentTicketId);
        } else {
            showToast('❌ ' + (data.message || 'Failed to send'), 'e');
        }
    })
    .catch(() => { btn.disabled = false; btn.textContent = 'Send'; showToast('❌ Network error', 'e'); });
}

function closeTicket() {
    if (!confirm('Are you sure you want to close this ticket?')) return;
    const fd = new FormData();
    fd.append('ajax_close', '1');
    fd.append('ticket_id',  currentTicketId);
    fetch('my_tickets.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showToast('✅ Ticket closed', 's');
            setTimeout(() => loadTicket(currentTicketId), 600);
        } else showToast('❌ ' + (data.message || 'Failed'), 'e');
    })
    .catch(() => showToast('❌ Network error', 'e'));
}

function showToast(msg, t = 'i') {
    const w = document.getElementById('toastWrap');
    const d = document.createElement('div');
    d.className = 'toast t' + t; d.textContent = msg;
    w.appendChild(d); setTimeout(() => d.remove(), 3500);
}

// ESC to close modal
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
</script>

<?php layoutEnd(); ?>