<?php
// /admin/support_tickets.php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_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=>$arr) if (in_array($ext,$arr)) return $k;
  return 'other';
}
function ensure_dir($path){ if (!is_dir($path)) @mkdir($path,0775,true); }
function file_url_from_rel($rel){ return '../' . ltrim($rel,'/'); }

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

  // 1) List tickets (filters)
  if ($act === 'list_tickets') {
    $status   = $_GET['status']   ?? '';
    $priority = $_GET['priority'] ?? '';
    $assigned = (int)($_GET['assigned_to'] ?? 0);
    $q        = trim($_GET['q'] ?? '');

    $where = " WHERE 1=1 ";
    if (in_array($status,['OPEN','PENDING','RESOLVED','CLOSED'],true)) {
      $where .= " AND t.status='".mysqli_real_escape_string($conn,$status)."' ";
    }
    if (in_array($priority,['Low','Normal','High','Urgent'],true)) {
      $where .= " AND t.priority='".mysqli_real_escape_string($conn,$priority)."' ";
    }
    if ($assigned > 0) {
      $where .= " AND t.assigned_to_student_id = " . (int)$assigned . " ";
    }
    if ($q !== '') {
      $qesc = mysqli_real_escape_string($conn,$q);
      $where .= " AND (t.subject LIKE '%$qesc%' OR s.full_name LIKE '%$qesc%' OR s.cnic LIKE '%$qesc%') ";
    }

    $sql = "SELECT t.id, t.subject, t.status, t.priority, t.updated_at, t.last_msg_at,
                   s.full_name AS student, a.full_name AS agent
            FROM tickets t
            JOIN students s ON s.id=t.student_id
            LEFT JOIN students a ON a.id=t.assigned_to_student_id
            $where
            ORDER BY COALESCE(t.last_msg_at, t.updated_at) DESC, t.id DESC
            LIMIT 200";
    $rows = mysqli_query($conn,$sql);
    $out = [];
    while($r = mysqli_fetch_assoc($rows)) $out[] = $r;
    echo json_encode(['ok'=>true,'items'=>$out]); exit;
  }

  // 2) Ticket + messages
  if ($act === 'get_ticket') {
    $id = (int)($_GET['id'] ?? 0);
    $t = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT t.*, s.full_name AS student_name, a.full_name AS agent_name
      FROM tickets t
      JOIN students s ON s.id=t.student_id
      LEFT JOIN students a ON a.id=t.assigned_to_student_id
      WHERE t.id=$id
      LIMIT 1
    "));
    if (!$t){ echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }

    $msgs = [];
    $mres = mysqli_query($conn, "
      SELECT m.id, m.author_type, m.author_id, m.body, m.created_at,
             CASE
               WHEN m.author_type IN ('STUDENT','AGENT') THEN s.full_name
               ELSE ad.name
             END AS author_name
      FROM ticket_messages m
      LEFT JOIN students s ON s.id=m.author_id AND m.author_type IN ('STUDENT','AGENT')
      LEFT JOIN admins   ad ON ad.id=m.author_id AND m.author_type='ADMIN'
      WHERE m.ticket_id=$id
      ORDER BY m.id ASC
    ");
    $ids=[]; while($m=mysqli_fetch_assoc($mres)){ $msgs[]=$m; $ids[]=(int)$m['id']; }

    $attMap=[];
    if ($ids) {
      $idList=implode(',',$ids);
      $aRes=mysqli_query($conn,"SELECT message_id,file_path,file_type,original_name FROM ticket_attachments WHERE message_id IN ($idList) ORDER BY id ASC");
      while($a=mysqli_fetch_assoc($aRes)){
        $mid=(int)$a['message_id']; if(!isset($attMap[$mid])) $attMap[$mid]=[];
        $attMap[$mid][]=$a;
      }
    }

    echo json_encode(['ok'=>true,'ticket'=>$t,'messages'=>$msgs,'attachments'=>$attMap]); exit;
  }

  // 3) Send message (ADMIN)
  if ($act === 'send_message') {
    $ticket_id = (int)($_POST['ticket_id'] ?? 0);
    $body      = trim($_POST['body'] ?? '');

    // Insert message
    $st = mysqli_prepare($conn,"INSERT INTO ticket_messages(ticket_id,author_type,author_id,body) VALUES (?,?,?,?)");
    $author_type = 'ADMIN';
    $author_id   = (int)($_SESSION['admin_id'] ?? 0);
    mysqli_stmt_bind_param($st,"isis",$ticket_id,$author_type,$author_id,$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);

    // Save attachments (multiple)
    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;
        $destFs = $baseFs.'/'.$fname;
        if (move_uploaded_file($tmp,$destFs)) {
          $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;
  }

  // 4) Assign ticket to agent (student)
  if ($act === 'assign_ticket') {
    $ticket_id = (int)($_POST['ticket_id'] ?? 0);
    $agent_id  = (int)($_POST['agent_id'] ?? 0); // 0 => Unassigned
    if ($agent_id > 0) {
      // verify is_agent
      $is = mysqli_fetch_assoc(mysqli_query($conn,"SELECT is_agent FROM students WHERE id=$agent_id"));
      if (!$is || (int)$is['is_agent']!==1){ echo json_encode(['ok'=>false,'error'=>'This student is not an agent']); exit; }
    }
    mysqli_query($conn,"UPDATE tickets SET assigned_to_student_id=".($agent_id?:'NULL').", updated_at=NOW() WHERE id=$ticket_id");
    // audit
    $aid=(int)($_SESSION['admin_id'] ?? 0);
    $meta = json_encode(['assigned_to'=>$agent_id], JSON_UNESCAPED_UNICODE);
    $ins = mysqli_prepare($conn,"INSERT INTO ticket_audit(ticket_id,action,meta,actor_type,actor_id) VALUES (?,?,?,?,?)");
    $actn='ASSIGN'; $at='ADMIN';
    mysqli_stmt_bind_param($ins,"isssi",$ticket_id,$actn,$meta,$at,$aid);
    mysqli_stmt_execute($ins); mysqli_stmt_close($ins);

    echo json_encode(['ok'=>true]); exit;
  }

  // 5) Update status
  if ($act === 'set_status') {
    $ticket_id = (int)($_POST['ticket_id'] ?? 0);
    $status    = $_POST['status'] ?? '';
    if (!in_array($status,['OPEN','PENDING','RESOLVED','CLOSED'],true)){
      echo json_encode(['ok'=>false,'error'=>'Invalid status']); exit;
    }
    mysqli_query($conn,"UPDATE tickets SET status='".mysqli_real_escape_string($conn,$status)."', updated_at=NOW() WHERE id=$ticket_id");
    // audit
    $aid=(int)($_SESSION['admin_id'] ?? 0);
    $meta = json_encode(['status'=>$status], JSON_UNESCAPED_UNICODE);
    $ins = mysqli_prepare($conn,"INSERT INTO ticket_audit(ticket_id,action,meta,actor_type,actor_id) VALUES (?,?,?,?,?)");
    $actn='STATUS_CHANGE'; $at='ADMIN';
    mysqli_stmt_bind_param($ins,"isssi",$ticket_id,$actn,$meta,$at,$aid);
    mysqli_stmt_execute($ins); mysqli_stmt_close($ins);

    echo json_encode(['ok'=>true]); exit;
  }

  // 6) Manage agents (toggle)
  if ($act === 'toggle_agent') {
    $sid = (int)($_POST['student_id'] ?? 0);
    $on  = (int)($_POST['on'] ?? 0);
    mysqli_query($conn,"UPDATE students SET is_agent=$on WHERE id=$sid");
    echo json_encode(['ok'=>true]); exit;
  }

  // 7) Search students (for assignment / agents)
  if ($act === 'search_students') {
    $q = trim($_GET['q'] ?? '');
    if ($q===''){ echo json_encode(['ok'=>true,'items'=>[]]); exit; }
    $qesc = mysqli_real_escape_string($conn,$q);
    $rs = mysqli_query($conn,"SELECT id, full_name, cnic, is_agent FROM students
                              WHERE full_name LIKE '%$qesc%' OR cnic LIKE '%$qesc%'
                              ORDER BY full_name LIMIT 50");
    $out=[]; while($r=mysqli_fetch_assoc($rs)) $out[]=$r;
    echo json_encode(['ok'=>true,'items'=>$out]); exit;
  }

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

/* -------------- UI -------------- */
admin_header('Support Tickets');
?>
<style>
  .grid{display:grid;grid-template-columns:repeat(12,1fr);gap:10px}
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:14px;box-shadow:0 1px 2px rgba(15,23,42,.04),0 8px 24px rgba(15,23,42,.06)}
  .muted{color:#64748b;font-size:12px}
  .badge{padding:3px 8px;border-radius:999px;border:1px solid #e5e7eb;font-size:11px;font-weight:700}
  .b-open{background:#dbeafe;color:#1e3a8a}.b-pending{background:#fff7ed;color:#9a3412}.b-res{background:#dcfce7;color:#166534}.b-closed{background:#e5e7eb;color:#334155}
  .ticket-item{border:1px solid #e5e7eb;border-radius:10px;padding:10px;cursor:pointer}
  .ticket-item:hover{background:#f8fafc}
  .flex{display:flex;gap:8px;align-items:center}
  .actions .btn{padding:6px 10px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;cursor:pointer}
  .btn.primary{background:#2563eb;color:#fff;border-color:#2563eb}
  .btn.small{font-size:12px;padding:5px 8px}
  .chat{border:1px solid #e5e7eb;border-radius:10px;height:420px;overflow:auto;padding:10px;background:#f8fafc}
  .bubble{max-width:70%;border-radius:12px;padding:8px 10px;margin:6px 0;background:#fff;border:1px solid #e5e7eb}
  .me{background:#dcfce7;border-color:#86efac}
  .agent{background:#dbeafe;border-color:#bfdbfe}
  .admin{background:#f1f5f9;border-color:#e5e7eb}
  .msg-head{font-size:12px;color:#475569;margin-bottom:3px}
  .att{display:inline-block;margin-top:6px;padding:4px 8px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;font-size:12px}
  .pill{padding:3px 8px;border:1px solid #e5e7eb;border-radius:999px;font-size:11px}
</style>

<div class="grid">
  <!-- Left: filters + list -->
  <div class="card" style="grid-column:span 5">
    <h3 style="margin:0 0 8px;color:#2563eb">Tickets</h3>
    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:8px;margin-bottom:8px">
      <div style="grid-column:span 4">
        <label>Status</label>
        <select id="fStatus">
          <option value="">All</option>
          <option>OPEN</option><option>PENDING</option><option>RESOLVED</option><option>CLOSED</option>
        </select>
      </div>
      <div style="grid-column:span 3">
        <label>Priority</label>
        <select id="fPriority">
          <option value="">All</option>
          <option>Low</option><option>Normal</option><option>High</option><option>Urgent</option>
        </select>
      </div>
      <div style="grid-column:span 5">
        <label>Assigned Agent</label>
        <input id="fAssigned" placeholder="Agent ID (optional)">
      </div>
      <div style="grid-column:span 12">
        <label>Search</label>
        <input id="fQ" placeholder="Subject / Student name / CNIC">
      </div>
      <div style="grid-column:span 12;display:flex;gap:8px;justify-content:flex-end">
        <button class="btn" id="btnFilter">Apply</button>
        <button class="btn" id="btnReset">Reset</button>
        <button class="btn" id="btnAgents">Manage Agents</button>
      </div>
    </div>

    <div id="ticketList" style="display:grid;gap:8px"></div>
  </div>

  <!-- Right: conversation -->
  <div class="card" style="grid-column:span 7">
    <div class="flex" style="justify-content:space-between">
      <div>
        <h3 style="margin:0" id="tSubject">Select a ticket</h3>
        <div class="muted" id="tMeta"></div>
      </div>
      <div class="flex">
        <select id="tStatus" disabled>
          <option>OPEN</option><option>PENDING</option><option>RESOLVED</option><option>CLOSED</option>
        </select>
        <button class="btn small" id="btnSaveStatus" disabled>Update</button>
      </div>
    </div>

    <div class="flex" style="margin:8px 0;justify-content:space-between">
      <div class="muted" id="tStudent"></div>
      <div class="flex">
        <input id="assignAgentId" placeholder="Assign Agent ID" style="width:140px">
        <button class="btn small" id="btnAssign" disabled>Assign</button>
      </div>
    </div>

    <div class="chat" id="chatBox"></div>

    <form id="replyForm" style="margin-top:8px">
      <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:8px">
        <div style="grid-column:span 9"><input id="msgBody" placeholder="Type reply..."></div>
        <div style="grid-column:span 3"><input type="file" id="msgFiles" multiple></div>
      </div>
      <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:8px">
        <button class="btn primary" id="btnSend" disabled>Send</button>
      </div>
    </form>
  </div>
</div>

<!-- Agents modal -->
<div id="agentsModal" style="position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;z-index:50">
  <div class="card" style="width:96%;max-width:700px">
    <div class="flex" style="justify-content:space-between">
      <h3 style="margin:0">Manage Agents</h3>
      <button class="btn" id="closeAgents">Close</button>
    </div>
    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:8px;margin-top:8px">
      <div style="grid-column:span 8">
        <input id="agentSearch" placeholder="Search student by name or CNIC">
      </div>
      <div style="grid-column:span 4">
        <button class="btn" id="btnAgentSearch">Search</button>
      </div>
      <div style="grid-column:span 12" id="agentResults"></div>
    </div>
  </div>
</div>

<script>
let selTicket = 0;
let lastPollId = 0;
let pollTimer = null;

function badgeStatus(s){
  if(s==='OPEN') return '<span class="badge b-open">OPEN</span>';
  if(s==='PENDING') return '<span class="badge b-pending">PENDING</span>';
  if(s==='RESOLVED') return '<span class="badge b-res">RESOLVED</span>';
  if(s==='CLOSED') return '<span class="badge b-closed">CLOSED</span>';
  return '';
}
function renderTicketItem(t){
  const meta = t.updated_at ? new Date(t.updated_at).toLocaleString() : '';
  const agent = t.agent ? ' • Agent: '+t.agent : '';
  return `
    <div class="ticket-item" data-id="${t.id}">
      <div style="font-weight:700">${t.subject}</div>
      <div class="muted">${badgeStatus(t.status)} • ${t.priority} • ${t.student} ${agent}</div>
      <div class="muted">Updated: ${meta}</div>
    </div>`;
}
async function loadTickets(){
  const p = new URLSearchParams();
  p.append('action','list_tickets');
  const st = document.getElementById('fStatus').value;
  const pr = document.getElementById('fPriority').value;
  const as = document.getElementById('fAssigned').value.trim();
  const q  = document.getElementById('fQ').value.trim();
  if(st) p.append('status',st);
  if(pr) p.append('priority',pr);
  if(as) p.append('assigned_to',as);
  if(q)  p.append('q',q);
  const r = await fetch('support_tickets.php?'+p.toString(), {headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  const box = document.getElementById('ticketList'); box.innerHTML='';
  if(d.ok && d.items.length){
    d.items.forEach(i=>{ box.insertAdjacentHTML('beforeend', renderTicketItem(i)); });
    document.querySelectorAll('.ticket-item').forEach(el=>{
      el.addEventListener('click', ()=> openTicket(parseInt(el.dataset.id)));
    });
  } else {
    box.innerHTML='<div class="muted">No tickets.</div>';
  }
}
async function openTicket(id){
  selTicket = id; lastPollId = 0;
  const r = await fetch('support_tickets.php?action=get_ticket&id='+id, {headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  if(!d.ok){ alert('Ticket not found'); return; }

  // Header
  document.getElementById('tSubject').textContent = d.ticket.subject;
  document.getElementById('tMeta').textContent = `#${d.ticket.id} • ${d.ticket.category} • Priority: ${d.ticket.priority}`;
  document.getElementById('tStudent').textContent = `Student: ${d.ticket.student_name} ${d.ticket.agent_name? '• Agent: '+d.ticket.agent_name:''}`;

  const stSel = document.getElementById('tStatus');
  stSel.value = d.ticket.status; stSel.disabled=false;
  document.getElementById('btnSaveStatus').disabled=false;
  document.getElementById('btnAssign').disabled=false;
  document.getElementById('btnSend').disabled=false;

  // Render messages
  const chat = document.getElementById('chatBox'); chat.innerHTML='';
  d.messages.forEach(m=>{
    lastPollId = Math.max(lastPollId, parseInt(m.id));
    const cls = (m.author_type==='ADMIN')?'admin':((m.author_type==='AGENT')?'agent':'me');
    const head = `${m.author_name||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="att" target="_blank" href="${url}">${a.original_name}</a> `;
    });
    chat.insertAdjacentHTML('beforeend', `
      <div class="bubble ${cls}">
        <div class="msg-head">${head}</div>
        ${m.body ? `<div>${m.body.replace(/</g,'&lt;')}</div>`:''}
        ${atts ? `<div style="margin-top:6px">${atts}</div>`:''}
      </div>
    `);
  });
  chat.scrollTop = chat.scrollHeight;

  // start polling
  if (pollTimer) clearInterval(pollTimer);
  pollTimer = setInterval(pollNew, 6000);
}
async function pollNew(){
  if(!selTicket) return;
  // Reuse get_ticket (simple approach)
  const r = await fetch('support_tickets.php?action=get_ticket&id='+selTicket, {headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  if(!d.ok) return;
  const chat = document.getElementById('chatBox');
  d.messages.forEach(m=>{
    const mid = parseInt(m.id);
    if (mid <= lastPollId) return;
    lastPollId = Math.max(lastPollId, mid);
    const cls = (m.author_type==='ADMIN')?'admin':((m.author_type==='AGENT')?'agent':'me');
    const head = `${m.author_name||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="att" target="_blank" href="${url}">${a.original_name}</a> `;
    });
    chat.insertAdjacentHTML('beforeend', `
      <div class="bubble ${cls}">
        <div class="msg-head">${head}</div>
        ${m.body ? `<div>${m.body.replace(/</g,'&lt;')}</div>`:''}
        ${atts ? `<div style="margin-top:6px">${atts}</div>`:''}
      </div>
    `);
    chat.scrollTop = chat.scrollHeight;
  });
}

document.getElementById('btnFilter').onclick = loadTickets;
document.getElementById('btnReset').onclick = ()=>{ 
  ['fStatus','fPriority','fAssigned','fQ'].forEach(id=>document.getElementById(id).value=''); 
  loadTickets();
};

// send
document.getElementById('replyForm').addEventListener('submit', async (e)=>{
  e.preventDefault();
  if(!selTicket) return;
  const body = document.getElementById('msgBody').value.trim();
  const files = document.getElementById('msgFiles').files;
  const fd = new FormData();
  fd.append('action','send_message');
  fd.append('ticket_id', selTicket);
  fd.append('body', body);
  for (let i=0;i<files.length;i++) fd.append('files[]', files[i]);
  const r = await fetch('support_tickets.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='';
  pollNew(); // show instantly
});

// status
document.getElementById('btnSaveStatus').onclick = async ()=>{
  const st = document.getElementById('tStatus').value;
  const fd = new FormData();
  fd.append('action','set_status');
  fd.append('ticket_id', selTicket);
  fd.append('status', st);
  const r = await fetch('support_tickets.php', {method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  if(!d.ok) alert(d.error||'Failed');
  else loadTickets();
};

// assign
document.getElementById('btnAssign').onclick = async ()=>{
  const aid = document.getElementById('assignAgentId').value.trim();
  const fd = new FormData();
  fd.append('action','assign_ticket'); fd.append('ticket_id', selTicket); fd.append('agent_id', aid?aid:0);
  const r = await fetch('support_tickets.php', {method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json();
  if(!d.ok) alert(d.error||'Failed'); else openTicket(selTicket);
};

// Agents modal
const modal = document.getElementById('agentsModal');
document.getElementById('btnAgents').onclick=()=>{ modal.style.display='flex'; };
document.getElementById('closeAgents').onclick=()=>{ modal.style.display='none'; };
document.getElementById('btnAgentSearch').onclick=async ()=>{
  const q = document.getElementById('agentSearch').value.trim(); if(!q) return;
  const r = await fetch('support_tickets.php?action=search_students&q='+encodeURIComponent(q), {headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json(); const box = document.getElementById('agentResults'); box.innerHTML='';
  if(d.ok && d.items.length){
    d.items.forEach(s=>{
      box.insertAdjacentHTML('beforeend', `
        <div class="flex" style="justify-content:space-between;border:1px solid #e5e7eb;border-radius:10px;padding:8px;margin:4px 0">
          <div>#${s.id} • ${s.full_name} • ${s.cnic} ${s.is_agent==1?'<span class="pill" style="background:#dcfce7;color:#166534">Agent</span>':''}</div>
          <div>
            <button class="btn small" onclick="toggleAgent(${s.id}, ${s.is_agent==1?0:1})">${s.is_agent==1?'Remove Agent':'Make Agent'}</button>
          </div>
        </div>`);
    });
  } else {
    box.innerHTML='<div class="muted">No results.</div>';
  }
};
async function toggleAgent(id,on){
  const fd = new FormData(); fd.append('action','toggle_agent'); fd.append('student_id',id); fd.append('on',on);
  const r = await fetch('support_tickets.php',{method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d = await r.json(); if(!d.ok) alert('Failed'); else document.getElementById('btnAgentSearch').click();
}

loadTickets();
</script>
<?php admin_footer(); ?>
