<?php
// /admin/chat.php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';
admin_header('Chat Control');
?>
<style>
  .wrapx{display:grid;grid-template-columns:320px 1fr;gap:12px}
  .pane{background:#fff;border:1px solid var(--border);border-radius:12px;box-shadow:var(--shadow);display:flex;flex-direction:column;min-height:640px}
  .tabs{display:flex;border-bottom:1px solid var(--border)}
  .tab{padding:10px 12px;cursor:pointer}
  .tab.active{background:#eff6ff;border-bottom:2px solid #93c5fd}
  .list{padding:10px;overflow:auto}
  .item{border:1px solid var(--border);border-radius:10px;padding:10px;margin-bottom:8px;display:flex;justify-content:space-between;gap:8px}
  .item.active{background:#f0fdf4;border-color:#86efac}
  .muted{color:#64748b;font-size:12px}
  .chat{display:flex;flex-direction:column;height:100%}
  .chat-head{padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
  .msgs{flex:1;overflow:auto;padding:12px}
  .msg{margin:8px 0}
  .msg .name{font-weight:700}
  .msg .time{color:#94a3b8;font-size:11px;margin-left:6px}
  .bubble{display:inline-block;background:#f8f9fe;border:1px solid #e5e7eb;border-radius:10px;padding:8px 10px;margin-top:3px;max-width:800px;white-space:pre-wrap}
  .me .bubble{background:#dbeafe;border-color:#bfdbfe}
  .files{display:flex;gap:8px;flex-wrap:wrap;margin-top:6px}
  .file-box{border:1px solid #e5e7eb;border-radius:8px;overflow:hidden}
  .file-box img{width:180px;height:120px;object-fit:cover;display:block}
  .file-box .act{padding:6px 8px;font-size:12px;border-top:1px solid #e5e7eb;display:flex;justify-content:space-between}
  .composer{border-top:1px solid var(--border);padding:8px;display:flex;gap:8px;align-items:flex-end}
  .composer textarea{height:68px}
  .pill{font-size:11px;border:1px solid #e5e7eb;background:#f8fafc;border-radius:999px;padding:2px 6px}
  .bar{padding:10px;border-bottom:1px solid var(--border)}
  .bar input, .bar select{height:36px}
  @media(max-width:900px){.wrapx{grid-template-columns:1fr}}
</style>

<h2 style="margin:0 0 8px">Chat Control</h2>

<div class="wrapx">
  <!-- LEFT PANE: tabs -->
  <div class="pane">
    <div class="tabs">
      <div class="tab active" data-tab="students">Students</div>
      <div class="tab" data-tab="rooms">Rooms</div>
      <div class="tab" data-tab="notices">Notices</div>
    </div>

    <!-- Students tab -->
    <div class="bar" data-panel="students">
      <input id="sQuery" placeholder="Search student by name/email/cnic..." style="width:100%">
    </div>
    <div class="list" id="studentsList" data-panel="students"></div>

    <!-- Rooms tab -->
    <div class="bar" data-panel="rooms" style="display:none">
      <form id="createRoom" style="display:flex;gap:8px">
        <input name="name" placeholder="Room name (e.g., WD-2025-A)" required style="flex:1">
        <input name="batch_id" type="number" placeholder="Batch ID" required style="width:140px">
        <button class="btn">Create</button>
      </form>
    </div>
    <div class="list" id="roomsList" data-panel="rooms" style="display:none"></div>

    <!-- Notices tab -->
    <div class="bar" data-panel="notices" style="display:none">
      <form id="noticeForm" style="display:flex;gap:8px;flex-wrap:wrap">
        <input name="title" placeholder="Notice title" required style="flex:1">
        <select name="target_type" id="nType" style="width:160px">
          <option value="ALL">All</option>
          <option value="COURSE">Course</option>
          <option value="BATCH">Batch</option>
        </select>
        <input name="target_id" id="nTarget" placeholder="Target ID (if needed)" style="width:160px">
        <textarea name="body" placeholder="Notice body..." style="width:100%;height:80px"></textarea>
        <button class="btn primary">Send Notice</button>
      </form>
    </div>
    <div class="list" id="noticesList" data-panel="notices" style="display:none"></div>
  </div>

  <!-- RIGHT PANE: conversation -->
  <div class="pane chat">
    <div class="chat-head">
      <div>
        <div class="name" id="chatTitle">Select a student/room</div>
        <div class="muted" id="chatSub"></div>
      </div>
      <div id="chatMeta"></div>
    </div>
    <div class="msgs" id="msgs"></div>
    <form class="composer" id="composer" enctype="multipart/form-data">
      <input type="hidden" id="mode" value="">
      <input type="hidden" id="thread_id" value="">
      <input type="hidden" id="room_id" value="">
      <textarea id="body" placeholder="Type a message..."></textarea>
      <label class="btn">📎 Attach
        <input type="file" id="files" multiple style="display:none">
      </label>
      <button class="btn primary">Send</button>
    </form>
  </div>
</div>

<script>
const API = '../chat_api.php';
let current = {mode:'', thread_id:0, room_id:0, since_id:0, poll:null};

function $(q){return document.querySelector(q)}
function el(html){const d=document.createElement('div'); d.innerHTML=html.trim(); return d.firstChild}
async function get(u){const r=await fetch(u); return r.json()}
async function post(u,f){const r=await fetch(u,{method:'POST',body:f}); return r.json()}
function timefmt(s){const d=new Date(s.replace(' ','T'));return d.toLocaleString()}
function scrollBottom(){const c=$("#msgs"); c.scrollTop=c.scrollHeight}
function clearChat(){ $("#msgs").innerHTML=''; $("#body").value='' }

function renderStudents(list){
  const wrap=$("#studentsList"); wrap.innerHTML='';
  if(!list || !list.length){wrap.innerHTML='<div class="muted">No students.</div>'; return;}
  list.forEach(x=>{
    const n=el(`<div class="item" data-id="${x.id}">
      <div><b>${x.name}</b><div class="muted">${x.email||''}${x.cnic?' • '+x.cnic:''}</div></div>
      <div>
        <button class="btn dmBtn">Open</button>
        <label class="btn" style="margin-left:6px">
          <input type="checkbox" class="blk" ${x.blocked?'checked':''} style="margin-right:6px"> Block
        </label>
      </div>
    </div>`);
    n.querySelector('.dmBtn').onclick=()=>openDM(x.id, x.name);
    n.querySelector('.blk').onchange=async (e)=>{
      const f=new FormData(); f.append('action','set_block'); f.append('student_id',x.id); f.append('blocked', e.target.checked?1:0);
      await post(API,f);
    };
    wrap.appendChild(n);
  });
}
function filterStudents(q){
  q=q.toLowerCase();
  document.querySelectorAll('#studentsList .item').forEach(n=>{
    n.style.display = n.textContent.toLowerCase().includes(q)?'':'none';
  });
}
function renderRooms(list){
  const wrap=$("#roomsList"); wrap.innerHTML='';
  if(!list || !list.length){wrap.innerHTML='<div class="muted">No rooms yet.</div>'; return;}
  list.forEach(r=>{
    const n=el(`<div class="item" data-id="${r.id}">
      <div><b>${r.name}</b> <span class="pill">Batch #${r.batch_id}</span></div>
      <div><button class="btn openRoom">Open</button></div>
    </div>`);
    n.querySelector('.openRoom').onclick=()=>openRoom(r.id, r.name, r.batch_id);
    wrap.appendChild(n);
  });
}
function renderNotices(list){
  const wrap=$("#noticesList"); wrap.innerHTML='';
  if(!list || !list.length){wrap.innerHTML='<div class="muted">No notices.</div>'; return;}
  list.forEach(nc=>{
    const t = nc.target_type + (nc.target_id?(' #'+nc.target_id):'');
    wrap.appendChild(el(`<div class="item">
      <div><b>${nc.title}</b><div class="muted">${t} • ${timefmt(nc.created_at)}</div></div>
      <div class="muted" style="max-width:420px">${(nc.body||'').slice(0,200)}</div>
    </div>`));
  });
}
function renderAttachments(att){
  if(!att||!att.length) return '';
  return att.map(a=>{
    const url = a.file_path.startsWith('uploads/') ? ('../'+a.file_path) : a.file_path;
    const ext = url.split('.').pop().toLowerCase();
    if(['jpg','jpeg','png','gif','webp'].includes(ext)){
      return `<div class="file-box"><a href="${url}" target="_blank"><img src="${url}"></a><div class="act"><span>Image</span><a href="${url}" target="_blank">Open</a></div></div>`;
    } else if(['mp4','webm','ogg'].includes(ext)){
      return `<div class="file-box"><video src="${url}" controls width="320" height="200"></video><div class="act"><span>Video</span><a href="${url}" target="_blank">Open</a></div></div>`;
    } else if(ext==='pdf'){
      return `<div class="file-box" style="width:180px;height:120px;display:flex;align-items:center;justify-content:center;flex-direction:column"><div>📄 PDF</div><a class="btn" href="${url}" target="_blank" style="margin-top:6px">View</a></div>`;
    } else {
      return `<div class="file-box" style="width:180px;height:120px;display:flex;align-items:center;justify-content:center;flex-direction:column"><div>📁 File</div><a class="btn" href="${url}" target="_blank" style="margin-top:6px">Download</a></div>`;
    }
  }).join('');
}
function renderMessages(payload, who='ADMIN'){
  const box=$("#msgs");
  if(!payload.ok){box.innerHTML='<div class="muted">Failed to load.</div>'; return;}
  const msgs=payload.messages||[]; const atts=payload.attachments||{};
  if(!msgs.length){ if(!box.innerHTML) box.innerHTML='<div class="muted">No messages yet.</div>'; return; }
  box.innerHTML = msgs.map(m=>{
    const mine = (m.sender_type === 'ADMIN');
    const files = atts[m.id]?`<div class="files">${renderAttachments(atts[m.id])}</div>`:'';
    return `<div class="msg ${mine?'me':''}">
      <div class="name">${m.sender_name}<span class="time">${timefmt(m.created_at)}</span></div>
      ${m.body?`<div class="bubble">${m.body.replace(/</g,'&lt;')}</div>`:''}
      ${files}
    </div>`;
  }).join('');
  scrollBottom();
  current.since_id = msgs[msgs.length-1].id;
}

// Tabs
document.querySelectorAll('.tab').forEach(t=>{
  t.onclick=()=>{
    document.querySelectorAll('.tab').forEach(a=>a.classList.remove('active'));
    t.classList.add('active');
    const k=t.dataset.tab;
    document.querySelectorAll('[data-panel]').forEach(p=>p.style.display=(p.dataset.panel===k)?'':'none');
    if(k==='students'){ loadStudents(); }
    if(k==='rooms'){ loadRooms(); }
    if(k==='notices'){ loadNotices(); }
  }
});

// Loaders
async function loadStudents(){
  const r = await get(API+'?action=list_students');
  if(r.ok) renderStudents(r.students);
}
async function loadRooms(){
  const r = await get(API+'?action=list_rooms');
  if(r.ok) renderRooms(r.rooms);
}
async function loadNotices(){
  const r = await get(API+'?action=list_notices');
  if(r.ok) renderNotices(r.notices);
}

// DM open
async function openDM(student_id, name){
  const f=new FormData(); f.append('action','open_dm'); f.append('student_id', student_id);
  const r=await post(API,f);
  if(!r.ok){alert(r.error||'Failed');return;}
  current={mode:'dm',thread_id:r.thread_id,room_id:0,since_id:0,poll:current.poll};
  $("#chatTitle").textContent=r.peer.name; $("#chatSub").textContent='Direct Message';
  clearChat(); await loadDM(true); startPoll();
}
async function loadDM(first=false){
  const url = API+`?action=dm_messages&thread_id=${current.thread_id}`+(current.since_id?`&since_id=${current.since_id}`:'');
  const r=await get(url);
  if(first) $("#msgs").innerHTML='';
  if(r.ok) renderMessages(r,'ADMIN');
}

// Room open
async function openRoom(id, name, batch){
  current={mode:'room',thread_id:0,room_id:id,since_id:0,poll:current.poll};
  $("#chatTitle").textContent = name; $("#chatSub").textContent = 'Batch #'+batch;
  clearChat(); await loadRoom(true); startPoll();
}
async function loadRoom(first=false){
  const url = API+`?action=room_messages&room_id=${current.room_id}`+(current.since_id?`&since_id=${current.since_id}`:'');
  const r=await get(url);
  if(first) $("#msgs").innerHTML='';
  if(r.ok) renderMessages(r,'ADMIN');
}

// Poller
function startPoll(){ if(current.poll) clearInterval(current.poll);
  current.poll=setInterval(()=>{ if(current.mode==='dm') loadDM(false); else if(current.mode==='room') loadRoom(false); }, 4000);
}

// Actions
$("#sQuery").addEventListener('input', e=>filterStudents(e.target.value));
$("#createRoom").addEventListener('submit', async (e)=>{
  e.preventDefault();
  const fd=new FormData(e.target);
  fd.append('action','create_room');
  const r=await post(API,fd);
  if(r.ok){ e.target.reset(); loadRooms(); } else alert(r.error||'Failed');
});
$("#noticeForm").addEventListener('submit', async (e)=>{
  e.preventDefault();
  const fd=new FormData(e.target);
  fd.append('action','create_notice');
  const r=await post(API,fd);
  if(r.ok){ e.target.reset(); loadNotices(); } else alert(r.error||'Failed');
});

// send message
$("#composer").addEventListener('submit', async (e)=>{
  e.preventDefault();
  const text=$("#body").value.trim();
  const files=$("#files").files;
  if(!text && (!files || !files.length)) return;

  const fd=new FormData();
  if(current.mode==='dm'){ fd.append('action','dm_send'); fd.append('thread_id', current.thread_id); }
  else if(current.mode==='room'){ fd.append('action','room_send'); fd.append('room_id', current.room_id); }
  else { alert('Select chat'); return; }
  fd.append('body', text);
  [...files].forEach(f=>fd.append('files[]', f));
  const r=await post(API,fd);
  if(r.ok){
    $("#body").value=''; $("#files").value='';
    if(current.mode==='dm') loadDM(false); else loadRoom(false);
  } else alert(r.error||'Failed');
});

// init default
loadStudents();
</script>
<?php admin_footer(); ?>
