<?php
// /user/support.php
// Count unread admin replies
if (!empty($_GET['action']) && $_GET['action']==='unread_count') {
  $n = (int)mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT COUNT(*) c
    FROM ticket_messages m
    JOIN tickets t ON t.id=m.ticket_id
    WHERE t.student_id={$student_id}
      AND m.author_type IN('ADMIN','AGENT')
      AND m.id > IFNULL(t.student_last_seen_msg,0)
  "))['c'];
  echo json_encode(['ok'=>true,'count'=>$n]); exit;
}

// Recent notifications list
if (!empty($_GET['action']) && $_GET['action']==='recent_notif') {
  $rs = mysqli_query($conn,"
    SELECT t.id, t.subject AS title,
           DATE_FORMAT(MAX(m.created_at),'%d %b %H:%i') AS time
    FROM ticket_messages m
    JOIN tickets t ON t.id=m.ticket_id
    WHERE t.student_id={$student_id}
    GROUP BY t.id
    ORDER BY MAX(m.created_at) DESC LIMIT 5
  ");
  $out=[];while($r=mysqli_fetch_assoc($rs))$out[]=$r;
  echo json_encode(['ok'=>true,'items'=>$out]);exit;
}

require_once __DIR__ . '/_user_auth.php';
require_once __DIR__ . '/_user_layout.php';
header('Cache-Control: no-store');

if (!function_exists('h')) {
  function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
}

/* Helpers */
function ext_to_category($ext){
  $ext=strtolower($ext);
  $map=['image'=>['jpg','jpeg','png','gif','webp','bmp'],'video'=>['mp4','webm','ogg','mov','mkv'],'audio'=>['mp3','wav','aac','m4a','flac','oga'],'doc'=>['pdf','doc','docx','ppt','pptx','xls','xlsx','txt','csv'],'archive'=>['zip','rar','7z','tar','gz']];
  foreach($map as $k=>$a) if(in_array($ext,$a)) return $k; return 'other';
}
function ensure_dir($p){ if(!is_dir($p)) @mkdir($p,0775,true); }
function file_url_from_rel($r){ return '../'.ltrim($r,'/'); }

/* is_agent? */
$me = mysqli_fetch_assoc(mysqli_query($conn,"SELECT is_agent, full_name FROM students WHERE id={$student_id}"));
$is_agent = $me ? (int)$me['is_agent']===1 : false;

/* ---------------- AJAX API ---------------- */
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
  header('Content-Type: application/json; charset=utf-8');
  $act = $_POST['action'] ?? $_GET['action'] ?? '';

  // Create ticket
  if ($act === 'create_ticket') {
    $subject  = trim($_POST['subject'] ?? '');
    $category = $_POST['category'] ?? 'Other';
    $priority = $_POST['priority'] ?? 'Normal';
    $body     = trim($_POST['body'] ?? '');
    if ($subject===''){ echo json_encode(['ok'=>false,'error'=>'Subject required']); exit; }

    mysqli_begin_transaction($conn);
    $st = mysqli_prepare($conn,"INSERT INTO tickets(student_id,subject,category,priority,created_by,status,created_at,updated_at) VALUES (?,?,?,?, 'STUDENT','OPEN',NOW(),NOW())");
    mysqli_stmt_bind_param($st,"isss",$student_id,$subject,$category,$priority);
    if(!mysqli_stmt_execute($st)){ mysqli_rollback($conn); echo json_encode(['ok'=>false,'error'=>mysqli_stmt_error($st)]); exit; }
    $tid = mysqli_insert_id($conn);
    mysqli_stmt_close($st);

    // first message (optional body/attachments)
    if ($body!=='' || (!empty($_FILES['files']) && is_array($_FILES['files']['name']))) {
      $st2 = mysqli_prepare($conn,"INSERT INTO ticket_messages(ticket_id,author_type,author_id,body) VALUES (?,'STUDENT',?,?)");
      mysqli_stmt_bind_param($st2,"iis",$tid,$student_id,$body);
      mysqli_stmt_execute($st2);
      $mid = mysqli_insert_id($conn);
      mysqli_stmt_close($st2);

      if (!empty($_FILES['files']) && is_array($_FILES['files']['name'])) {
        $max=15*1024*1024; $count=count($_FILES['files']['name']);
        for($i=0;$i<$count;$i++){
          if($_FILES['files']['error'][$i]!==UPLOAD_ERR_OK) continue;
          if($_FILES['files']['size'][$i]>$max) continue;
          $orig=$_FILES['files']['name'][$i]; $tmp=$_FILES['files']['tmp_name'][$i];
          $ext=strtolower(pathinfo($orig, PATHINFO_EXTENSION)); if(in_array($ext,['php','phtml','phar'])) continue;
          $cat=ext_to_category($ext);
          $baseRel="uploads/tickets/$tid/$cat"; $baseFs=dirname(__DIR__).'/'.$baseRel; ensure_dir($baseFs);
          $safe=preg_replace('/[^a-zA-Z0-9_.-]/','_',$orig);
          $fname=time().'_'.mt_rand(1000,9999).'_'.$safe; $dest=$baseFs.'/'.$fname;
          if(move_uploaded_file($tmp,$dest)){
            $rel=$baseRel.'/'.$fname;
            $ia=mysqli_prepare($conn,"INSERT INTO ticket_attachments(message_id,file_path,file_type,original_name) VALUES (?,?,?,?)");
            mysqli_stmt_bind_param($ia,"isss",$mid,$rel,$cat,$orig);
            mysqli_stmt_execute($ia); mysqli_stmt_close($ia);
          }
        }
      }
    }
    mysqli_query($conn,"UPDATE tickets SET last_msg_at=NOW() WHERE id=$tid");
    mysqli_commit($conn);
    echo json_encode(['ok'=>true,'ticket_id'=>$tid]); exit;
  }

  // My tickets list
  if ($act === 'list_my_tickets') {
    $rs = mysqli_query($conn,"SELECT id,subject,status,priority,updated_at,last_msg_at FROM tickets WHERE student_id={$student_id} ORDER BY COALESCE(last_msg_at,updated_at) DESC, id DESC LIMIT 200");
    $out=[]; while($r=mysqli_fetch_assoc($rs)) $out[]=$r;
    echo json_encode(['ok'=>true,'items'=>$out]); exit;
  }

  // Agent queue (assigned to me)
  if ($act === 'list_agent_tickets') {
    if (!$is_agent){ echo json_encode(['ok'=>true,'items'=>[]]); exit; }
    $rs = mysqli_query($conn,"SELECT t.id, t.subject, t.status, t.priority, t.updated_at, s.full_name AS student
                              FROM tickets t
                              JOIN students s ON s.id=t.student_id
                              WHERE t.assigned_to_student_id={$student_id}
                              ORDER BY COALESCE(t.last_msg_at, t.updated_at) DESC
                              LIMIT 200");
    $out=[]; while($r=mysqli_fetch_assoc($rs)) $out[]=$r;
    echo json_encode(['ok'=>true,'items'=>$out]); exit;
  }

  // Get ticket + messages (access control)
  if ($act === 'get_ticket') {
    $id=(int)($_GET['id'] ?? 0);
    // ensure access: student owns OR agent (assigned) OR (for safety allow student only here)
    $t = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM tickets WHERE id=$id LIMIT 1"));
    if (!$t){ echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }
    if ($t['student_id']!=$student_id && (!$is_agent || (int)$t['assigned_to_student_id']!==$student_id)){
      echo json_encode(['ok'=>false,'error'=>'Not allowed']); exit;
    }
    $ms=[]; $mres=mysqli_query($conn,"SELECT id,author_type,author_id,body,created_at FROM ticket_messages WHERE ticket_id=$id ORDER BY id ASC");
    $ids=[];
    while($m=mysqli_fetch_assoc($mres)){ $ms[]=$m; $ids[]=(int)$m['id']; }

    $attMap=[]; if($ids){ $list=implode(',',$ids); $as=mysqli_query($conn,"SELECT message_id,file_path,file_type,original_name FROM ticket_attachments WHERE message_id IN ($list)");
      while($a=mysqli_fetch_assoc($as)){ $attMap[(int)$a['message_id']][]=$a; }
    }
    // names
    $names=[];
    // collect all authors to min queries (simple: fill when rendering on client)
    echo json_encode(['ok'=>true,'ticket'=>$t,'messages'=>$ms,'attachments'=>$attMap]); exit;
  }

  // Send message (student OR agent)
  if ($act === 'send_message') {
    $ticket_id=(int)($_POST['ticket_id'] ?? 0);
    $body=trim($_POST['body'] ?? '');
    $as_agent=(int)($_POST['as_agent'] ?? 0)===1; // only if assigned to me
    $t = mysqli_fetch_assoc(mysqli_query($conn,"SELECT assigned_to_student_id, student_id FROM tickets WHERE id=$ticket_id"));
    if (!$t){ echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }
    $atype='STUDENT'; $aid=$student_id;
    if ($as_agent && $is_agent && (int)$t['assigned_to_student_id']===$student_id){
      $atype='AGENT';
    }

    $st=mysqli_prepare($conn,"INSERT INTO ticket_messages(ticket_id,author_type,author_id,body) VALUES (?,?,?,?)");
    mysqli_stmt_bind_param($st,"isis",$ticket_id,$atype,$aid,$body);
    if(!mysqli_stmt_execute($st)){ echo json_encode(['ok'=>false,'error'=>mysqli_stmt_error($st)]); exit; }
    $mid=mysqli_insert_id($conn); mysqli_stmt_close($st);

    // files
    if (!empty($_FILES['files']) && is_array($_FILES['files']['name'])) {
      $max=15*1024*1024; $count=count($_FILES['files']['name']);
      for($i=0;$i<$count;$i++){
        if($_FILES['files']['error'][$i]!==UPLOAD_ERR_OK) continue;
        if($_FILES['files']['size'][$i]>$max) continue;
        $orig=$_FILES['files']['name'][$i]; $tmp=$_FILES['files']['tmp_name'][$i];
        $ext=strtolower(pathinfo($orig, PATHINFO_EXTENSION)); if(in_array($ext,['php','phtml','phar'])) continue;
        $cat=ext_to_category($ext);
        $baseRel="uploads/tickets/$ticket_id/$cat"; $baseFs=dirname(__DIR__).'/'.$baseRel; ensure_dir($baseFs);
        $safe=preg_replace('/[^a-zA-Z0-9_.-]/','_',$orig);
        $fname=time().'_'.mt_rand(1000,9999).'_'.$safe; $dest=$baseFs.'/'.$fname;
        if(move_uploaded_file($tmp,$dest)){
          $rel=$baseRel.'/'.$fname;
          $ia=mysqli_prepare($conn,"INSERT INTO ticket_attachments(message_id,file_path,file_type,original_name) VALUES (?,?,?,?)");
          mysqli_stmt_bind_param($ia,"isss",$mid,$rel,$cat,$orig);
          mysqli_stmt_execute($ia); mysqli_stmt_close($ia);
        }
      }
    }
    mysqli_query($conn,"UPDATE tickets SET last_msg_at=NOW(), updated_at=NOW() WHERE id=$ticket_id");
    echo json_encode(['ok'=>true,'message_id'=>$mid]); exit;
  }

  echo json_encode(['ok'=>false,'error'=>'Unknown action']); exit;
}

/* ---------------- UI ---------------- */
user_header('Support');
?>
<style>
:root {
  --primary: #2563eb;
  --primary-light: #dbeafe;
  --primary-dark: #1d4ed8;
  --secondary: #64748b;
  --success: #10b981;
  --warning: #f59e0b;
  --danger: #ef4444;
  --light: #f8fafc;
  --dark: #1e293b;
  --border: #e2e8f0;
  --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  --radius: 8px;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

body {
  background-color: #f1f5f9;
  color: #334155;
  line-height: 1.5;
}

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.card {
  background: #fff;
  border-radius: var(--radius);
  padding: 24px;
  box-shadow: var(--shadow);
  border: 1px solid var(--border);
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border);
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--dark);
  margin: 0;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--primary);
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 16px;
}

label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: var(--dark);
}

input, select, textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  font-size: 14px;
  transition: all 0.2s;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

textarea {
  min-height: 100px;
  resize: vertical;
}

.btn {
  padding: 10px 16px;
  border-radius: var(--radius);
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn-primary {
  background-color: var(--primary);
  color: white;
}

.btn-primary:hover {
  background-color: var(--primary-dark);
}

.btn-outline {
  background-color: transparent;
  border: 1px solid var(--border);
  color: var(--secondary);
}

.btn-outline:hover {
  background-color: var(--light);
}

.badge {
  display: inline-flex;
  align-items: center;
  padding: 4px 10px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 600;
}

.badge-primary {
  background-color: var(--primary-light);
  color: var(--primary);
}

.badge-success {
  background-color: #dcfce7;
  color: #166534;
}

.badge-warning {
  background-color: #fef3c7;
  color: #92400e;
}

.badge-danger {
  background-color: #fee2e2;
  color: #991b1b;
}

.badge-secondary {
  background-color: #f1f5f9;
  color: #475569;
}

.ticket-list {
  display: grid;
  gap: 12px;
}

.ticket-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  cursor: pointer;
  transition: all 0.2s;
}

.ticket-item:hover {
  background-color: var(--light);
  transform: translateY(-2px);
}

.ticket-item.active {
  border-color: var(--primary);
  background-color: var(--primary-light);
}

.ticket-info {
  flex: 1;
}

.ticket-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.ticket-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--secondary);
}

.ticket-status {
  display: flex;
  gap: 8px;
}

.chat-container {
  border: 1px solid var(--border);
  border-radius: var(--radius);
  height: 380px;
  overflow: auto;
  padding: 16px;
  background-color: var(--light);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  max-width: 70%;
  border-radius: var(--radius);
  padding: 12px 16px;
  position: relative;
}

.message-header {
  font-size: 12px;
  color: var(--secondary);
  margin-bottom: 4px;
  display: flex;
  justify-content: space-between;
}

.message-user {
  font-weight: 600;
}

.message-time {
  font-size: 11px;
}

.message-body {
  margin-bottom: 6px;
}

.attachment {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 6px 10px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  background: #fff;
  font-size: 12px;
  text-decoration: none;
  color: var(--secondary);
}

.attachment:hover {
  background: var(--light);
}

.message-student {
  align-self: flex-end;
  background-color: var(--primary-light);
  border: 1px solid #bfdbfe;
}

.message-agent {
  align-self: flex-start;
  background-color: #dcfce7;
  border: 1px solid #86efac;
}

.message-admin {
  align-self: flex-start;
  background-color: #f1f5f9;
  border: 1px solid var(--border);
}

.reply-form {
  margin-top: 16px;
}

.form-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.checkbox-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.checkbox-group input {
  width: auto;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--secondary);
}

.empty-state-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

@media (max-width: 1024px) {
  .grid {
    grid-template-columns: 1fr;
  }
  
  .card {
    grid-column: span 1 !important;
  }
}
</style>

<div class="grid">
  <!-- Create Ticket Card -->
  <div class="card" style="grid-column: span 5">
    <div class="card-header">
      <h2 class="card-title">Create Support Ticket</h2>
    </div>
    <form id="createForm">
      <div class="form-group">
        <label for="subject">Subject</label>
        <input type="text" id="subject" name="subject" required placeholder="Brief description of your issue">
      </div>
      
      <div class="form-row">
        <div class="form-group" style="flex: 1;">
          <label for="category">Category</label>
          <select id="category" name="category">
            <option>Technical</option>
            <option>Fee</option>
            <option>Account</option>
            <option>Other</option>
          </select>
        </div>
        <div class="form-group" style="flex: 1;">
          <label for="priority">Priority</label>
          <select id="priority" name="priority">
            <option>Normal</option>
            <option>Low</option>
            <option>High</option>
            <option>Urgent</option>
          </select>
        </div>
      </div>
      
      <div class="form-group">
        <label for="description">Description</label>
        <textarea id="description" name="body" placeholder="Please describe your issue in detail..."></textarea>
      </div>
      
      <div class="form-group">
        <label for="files">Attach files (multiple)</label>
        <input type="file" id="files" name="files[]" multiple>
      </div>
      
      <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
        <button type="button" class="btn btn-outline" onclick="document.getElementById('createForm').reset()">Cancel</button>
        <button type="submit" class="btn btn-primary">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 2L11 13"></path>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
          Submit Ticket
        </button>
      </div>
    </form>
  </div>

  <!-- My Tickets Card -->
  <div class="card" style="grid-column: span 7">
    <div class="card-header">
      <h2 class="card-title">My Tickets</h2>
      <?php if($is_agent): ?>
        <span class="badge badge-primary">Agent Mode</span>
      <?php endif; ?>
    </div>
    <div id="myList" class="ticket-list">
      <div class="empty-state">
        <div class="empty-state-icon">📝</div>
        <p>No tickets yet. Create your first support ticket!</p>
      </div>
    </div>
  </div>

  <!-- Conversation Card -->
  <div class="card" style="grid-column: span 12">
    <div class="card-header">
      <div>
        <h2 id="tTitle" class="card-title">Select a ticket to view conversation</h2>
        <div id="tInfo" style="font-size: 14px; color: var(--secondary); margin-top: 4px;">
          Ticket details will appear here
        </div>
      </div>
      <?php if($is_agent): ?>
      <div id="agentBadge" style="display: none;">
        <span class="badge badge-success">Replying as Agent</span>
      </div>
      <?php endif; ?>
    </div>
    
    <div class="chat-container" id="chat">
      <div class="empty-state">
        <div class="empty-state-icon">💬</div>
        <p>Select a ticket to view the conversation</p>
      </div>
    </div>
    
    <form id="replyForm" class="reply-form">
      <div class="form-row">
        <div style="flex: 1;">
          <input type="text" id="msgBody" placeholder="Type your message..." disabled>
        </div>
        <div style="width: 200px;">
          <input type="file" id="msgFiles" multiple disabled>
        </div>
      </div>
      <div style="display: flex; gap: 12px; justify-content: flex-end; align-items: center;">
        <?php if($is_agent): ?>
        <div class="checkbox-group">
          <input type="checkbox" id="asAgent" style="width: auto; height: auto;">
          <label for="asAgent" style="margin: 0;">Reply as Agent</label>
        </div>
        <?php endif; ?>
        <button type="submit" class="btn btn-primary" id="btnSend" disabled>
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
          Send Message
        </button>
      </div>
    </form>
  </div>

  <?php if($is_agent): ?>
  <!-- Agent Queue Card -->
  <div class="card" style="grid-column: span 12">
    <div class="card-header">
      <h2 class="card-title">Agent Queue (Assigned to me)</h2>
    </div>
    <div id="agentList" class="ticket-list">
      <div class="empty-state">
        <div class="empty-state-icon">✅</div>
        <p>No tickets assigned to you at the moment</p>
      </div>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
let currentTicket = 0, lastMsgId = 0, timer = null;

function badge(s){
  if(s==='OPEN') return '<span class="badge badge-success">OPEN</span>';
  if(s==='PENDING') return '<span class="badge badge-warning">PENDING</span>';
  if(s==='RESOLVED') return '<span class="badge badge-primary">RESOLVED</span>';
  if(s==='CLOSED') return '<span class="badge badge-secondary">CLOSED</span>';
  return '';
}

function priorityBadge(p){
  if(p==='Urgent') return '<span class="badge badge-danger">URGENT</span>';
  if(p==='High') return '<span class="badge badge-warning">HIGH</span>';
  if(p==='Normal') return '<span class="badge badge-primary">NORMAL</span>';
  if(p==='Low') return '<span class="badge badge-secondary">LOW</span>';
  return '';
}

function row(t){
  const when = t.last_msg_at || t.updated_at || '';
  return `<div class="ticket-item" data-id="${t.id}">
    <div class="ticket-info">
      <div class="ticket-title">${t.subject}</div>
      <div class="ticket-meta">
        <span>${badge(t.status)}</span>
        <span>${priorityBadge(t.priority)}</span>
        <span>${when}</span>
      </div>
    </div>
  </div>`;
}

async function loadMy(){
  const r = await fetch('support.php?action=list_my_tickets', {headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json(); 
  const box = document.getElementById('myList'); 
  box.innerHTML='';
  
  if(d.ok && d.items.length){ 
    d.items.forEach(t=>box.insertAdjacentHTML('beforeend',row(t))); 
  } else {
    box.innerHTML='<div class="empty-state"><div class="empty-state-icon">📝</div><p>No tickets yet. Create your first support ticket!</p></div>';
  }
  
  document.querySelectorAll('#myList .ticket-item').forEach(el=> {
    el.onclick = ()=>openTicket(parseInt(el.dataset.id), false);
  });
}

async function loadAgent(){
  const r = await fetch('support.php?action=list_agent_tickets',{headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json(); 
  const box = document.getElementById('agentList'); 
  if(!box) return;
  
  box.innerHTML=''; 
  if(d.ok && d.items.length){ 
    d.items.forEach(t=>box.insertAdjacentHTML('beforeend',`
      <div class="ticket-item" data-id="${t.id}">
        <div class="ticket-info">
          <div class="ticket-title">${t.subject}</div>
          <div class="ticket-meta">
            <span>${badge(t.status)}</span>
            <span>${priorityBadge(t.priority)}</span>
            <span>Student: ${t.student}</span>
            <span>${t.updated_at}</span>
          </div>
        </div>
      </div>`));
  } else {
    box.innerHTML='<div class="empty-state"><div class="empty-state-icon">✅</div><p>No tickets assigned to you at the moment</p></div>';
  }
  
  document.querySelectorAll('#agentList .ticket-item').forEach(el=> {
    el.onclick = ()=>openTicket(parseInt(el.dataset.id), true);
  });
}

async function openTicket(id, asAgent){
  currentTicket = id; 
  lastMsgId = 0;
  
  // Update active state
  document.querySelectorAll('.ticket-item').forEach(el => {
    el.classList.remove('active');
    if(parseInt(el.dataset.id) === id) {
      el.classList.add('active');
    }
  });
  
  const r = await fetch('support.php?action=get_ticket&id='+id, {headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json(); 
  if(!d.ok){ alert(d.error||'Not found'); return; }
  
  document.getElementById('tTitle').textContent = d.ticket.subject + ' (#'+d.ticket.id+')';
  document.getElementById('tInfo').innerHTML = `
    <span>${d.ticket.category}</span> • 
    <span>Priority: ${priorityBadge(d.ticket.priority)}</span> • 
    <span>Status: ${badge(d.ticket.status)}</span>
  `;
  
  const chat = document.getElementById('chat'); 
  chat.innerHTML='';
  
  if(d.messages.length === 0) {
    chat.innerHTML = '<div class="empty-state"><div class="empty-state-icon">💬</div><p>No messages yet. Start the conversation!</p></div>';
  } else {
    d.messages.forEach(m=>{
      lastMsgId = Math.max(lastMsgId, parseInt(m.id));
      let cls='message-student'; 
      if(m.author_type==='AGENT') cls='message-agent'; 
      else if(m.author_type==='ADMIN') cls='message-admin';
      
      const head = m.author_type + ' • ' + new Date(m.created_at).toLocaleString();
      let atts=''; 
      const A = d.attachments[m.id]||[];
      A.forEach(a=>{
        const url = '../'+a.file_path.replace(/^\/+/,'');
        atts += `<a class="attachment" target="_blank" href="${url}">📎 ${a.original_name}</a> `;
      });
      
      chat.insertAdjacentHTML('beforeend', `
        <div class="message ${cls}">
          <div class="message-header">
            <span class="message-user">${m.author_type}</span>
            <span class="message-time">${new Date(m.created_at).toLocaleString()}</span>
          </div>
          <div class="message-body">${m.body?m.body.replace(/</g,'&lt;'):''}</div>
          ${atts?'<div>'+atts+'</div>':''}
        </div>
      `);
    });
  }
  
  chat.scrollTop = chat.scrollHeight;

  document.getElementById('msgBody').disabled=false;
  document.getElementById('msgFiles').disabled=false;
  document.getElementById('btnSend').disabled=false;

  // Show "reply as agent" checkbox only if asAgent true
  const agentWrap = document.getElementById('asAgentWrap');
  const agentBadge = document.getElementById('agentBadge');
  if (agentWrap){ 
    agentWrap.style.display = asAgent ? 'flex' : 'none'; 
  }
  if (agentBadge){ 
    agentBadge.style.display = asAgent ? 'block' : 'none'; 
  }
  if (agentWrap && !asAgent) {
    document.getElementById('asAgent').checked=false;
  }

  if (timer) clearInterval(timer);
  timer = setInterval(async ()=>{
    const r = await fetch('support.php?action=get_ticket&id='+currentTicket,{headers:{'X-Requested-With':'XMLHttpRequest'}});
    const d = await r.json(); 
    if(!d.ok) return;
    
    const chat = document.getElementById('chat');
    d.messages.forEach(m=>{
      const mid = parseInt(m.id);
      if(mid <= lastMsgId) return;
      lastMsgId = Math.max(lastMsgId, mid);
      
      let cls='message-student'; 
      if(m.author_type==='AGENT') cls='message-agent'; 
      else if(m.author_type==='ADMIN') cls='message-admin';
      
      const head = m.author_type + ' • ' + new Date(m.created_at).toLocaleString();
      let atts=''; 
      const A = d.attachments[m.id]||[];
      A.forEach(a=>{
        const url = '../'+a.file_path.replace(/^\/+/,'');
        atts += `<a class="attachment" target="_blank" href="${url}">📎 ${a.original_name}</a> `;
      });
      
      chat.insertAdjacentHTML('beforeend', `
        <div class="message ${cls}">
          <div class="message-header">
            <span class="message-user">${m.author_type}</span>
            <span class="message-time">${new Date(m.created_at).toLocaleString()}</span>
          </div>
          <div class="message-body">${m.body?m.body.replace(/</g,'&lt;'):''}</div>
          ${atts?'<div>'+atts+'</div>':''}
        </div>
      `);
      chat.scrollTop = chat.scrollHeight;
    });
  }, 6000);
}

// Create ticket submit
document.getElementById('createForm').addEventListener('submit', async (e)=>{
  e.preventDefault();
  const fd = new FormData(e.target);
  fd.append('action','create_ticket');
  const r = await fetch('support.php', {method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  if(!d.ok){ alert(d.error||'Failed'); return; }
  e.target.reset();
  loadMy();
  alert('Ticket created successfully!');
});

// Send message
document.getElementById('replyForm').addEventListener('submit', async (e)=>{
  e.preventDefault(); 
  if(!currentTicket) return;
  
  const fd = new FormData();
  fd.append('action','send_message');
  fd.append('ticket_id', currentTicket);
  fd.append('body', document.getElementById('msgBody').value.trim());
  
  const files = document.getElementById('msgFiles').files;
  for(let i=0;i<files.length;i++) fd.append('files[]', files[i]);
  
  const asAgent = document.getElementById('asAgent') ? (document.getElementById('asAgent').checked?1:0) : 0;
  fd.append('as_agent', asAgent);
  
  const r = await fetch('support.php', {method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  if(!d.ok){ alert(d.error||'Failed'); return; }
  
  document.getElementById('msgBody').value='';
  document.getElementById('msgFiles').value='';
  
  // Refresh the conversation
  openTicket(currentTicket, asAgent===1);
});

// Initialize
loadMy();
<?php if($is_agent): ?>loadAgent();<?php endif; ?>
</script>
<?php user_footer(); ?>