<?php
// /chat_api.php
// Common AJAX endpoint for admin + student chat/notices/rooms.

require_once __DIR__ . '/admin/_bootstrap.php'; // <- has $conn + session_start()
header('Content-Type: application/json');

function json_out($arr){ echo json_encode($arr); exit; }
function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

// Who am I?
$is_admin   = !empty($_SESSION['admin_id']);
$admin_id   = $is_admin ? (int)$_SESSION['admin_id'] : 0;
$student_id = !$is_admin && !empty($_SESSION['student_id']) ? (int)$_SESSION['student_id'] : 0;

if (!$is_admin && !$student_id) json_out(['ok'=>false,'error'=>'Not authenticated']);

$action = $_GET['action'] ?? $_POST['action'] ?? '';

// ---------- Helpers ----------
function ensure_thread($conn, $student_id){
  $q = mysqli_query($conn, "SELECT id FROM chat_threads WHERE student_id={$student_id} LIMIT 1");
  if ($r = mysqli_fetch_assoc($q)) return (int)$r['id'];
  $st = mysqli_prepare($conn, "INSERT INTO chat_threads(student_id) VALUES (?)");
  mysqli_stmt_bind_param($st, "i", $student_id);
  mysqli_stmt_execute($st);
  $tid = mysqli_insert_id($conn);
  mysqli_stmt_close($st);
  return $tid;
}

function upload_files($files, $base='uploads/chat'){
  $saved = [];
  if (!isset($files['name'])) return $saved;
  if (!is_dir(__DIR__ . "/{$base}")) @mkdir(__DIR__ . "/{$base}", 0775, true);

  $count = is_array($files['name']) ? count($files['name']) : 0;
  for($i=0; $i<$count; $i++){
    if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;
    $tmp  = $files['tmp_name'][$i];
    $name = basename($files['name'][$i]);
    $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $safe = preg_replace('/[^a-zA-Z0-9_\.-]/','_', $name);
    $fname= time() . '_' . rand(1000,9999) . '_' . $safe;
    $dest = __DIR__ . "/{$base}/" . $fname;
    if (move_uploaded_file($tmp, $dest)) {
      $saved[] = "{$base}/{$fname}";
    }
  }
  return $saved;
}

function sender_name($conn, $type, $id){
  if ($type === 'ADMIN') {
    // adjust if you have an admins table
    return 'Admin';
  } else {
    $q = mysqli_query($conn, "SELECT full_name FROM students WHERE id={$id} LIMIT 1");
    $r = mysqli_fetch_assoc($q);
    return $r ? $r['full_name'] : 'Student';
  }
}

// ---------- Admin: list registered students ----------
if ($action === 'list_students') {
  if (!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $q = mysqli_query($conn, "
    SELECT s.id, s.full_name, s.email, s.cnic,
           IFNULL(b.is_blocked,0) AS is_blocked
    FROM students s
    WHERE EXISTS (SELECT 1 FROM registrations r WHERE r.student_id=s.id)
    LEFT JOIN student_chat_block b ON b.student_id=s.id
    ORDER BY s.full_name
  ");
  $out=[];
  while($r=mysqli_fetch_assoc($q)){
    $out[]=['id'=>(int)$r['id'],'name'=>$r['full_name'],'email'=>$r['email'],'cnic'=>$r['cnic'],'blocked'=>(int)$r['is_blocked']];
  }
  json_out(['ok'=>true,'students'=>$out]);
}

// ---------- Admin: block/unblock ----------
if ($action === 'set_block') {
  if (!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $sid = (int)($_POST['student_id'] ?? 0);
  $blocked = (int)($_POST['blocked'] ?? 0);
  if ($sid<=0) json_out(['ok'=>false,'error'=>'Invalid student']);
  // upsert
  $q = mysqli_query($conn, "SELECT student_id FROM student_chat_block WHERE student_id={$sid} LIMIT 1");
  if ($q && mysqli_fetch_assoc($q)) {
    $st = mysqli_prepare($conn,"UPDATE student_chat_block SET is_blocked=?, updated_at=NOW() WHERE student_id=?");
    mysqli_stmt_bind_param($st,"ii",$blocked,$sid);
  } else {
    $st = mysqli_prepare($conn,"INSERT INTO student_chat_block(student_id,is_blocked) VALUES(?,?)");
    mysqli_stmt_bind_param($st,"ii",$sid,$blocked);
  }
  mysqli_stmt_execute($st); mysqli_stmt_close($st);
  json_out(['ok'=>true]);
}

// ---------- Open/Get DM thread (admin or student) ----------
if ($action === 'open_dm') {
  if ($is_admin) {
    $sid = (int)($_POST['student_id'] ?? 0);
  } else {
    // student opens their own thread with admin
    $sid = $student_id;
  }
  if ($sid<=0) json_out(['ok'=>false,'error'=>'Invalid student']);

  $tid = ensure_thread($conn, $sid);

  // peer info for header
  if ($is_admin) {
    $pq = mysqli_query($conn, "SELECT full_name, email FROM students WHERE id={$sid} LIMIT 1");
    $peer = mysqli_fetch_assoc($pq);
    json_out(['ok'=>true, 'thread_id'=>$tid, 'peer'=>['name'=>$peer['full_name']??'Student','type'=>'STUDENT','email'=>$peer['email']??'']]);
  } else {
    json_out(['ok'=>true, 'thread_id'=>$tid, 'peer'=>['name'=>'Admin','type'=>'ADMIN']]);
  }
}

// ---------- Fetch DM messages ----------
if ($action === 'dm_messages') {
  $tid = (int)($_GET['thread_id'] ?? 0);
  if ($tid<=0) json_out(['ok'=>false,'error'=>'Invalid thread']);

  // basic membership check: thread belongs to the student in question
  $q = mysqli_query($conn, "SELECT student_id FROM chat_threads WHERE id={$tid} LIMIT 1");
  $t = mysqli_fetch_assoc($q);
  if (!$t) json_out(['ok'=>false,'error'=>'Thread not found']);
  if (!$is_admin && $t['student_id'] != $student_id) json_out(['ok'=>false,'error'=>'Access denied']);

  $since = (int)($_GET['since_id'] ?? 0);
  $cond  = $since>0 ? "AND m.id>{$since}" : '';

  $rs = mysqli_query($conn, "
    SELECT m.id, m.sender_type, m.sender_id, m.body, m.created_at
    FROM chat_messages m
    WHERE m.scope='DM' AND m.thread_id={$tid} {$cond}
    ORDER BY m.id ASC
  ");
  $msgs=[]; $ids=[];
  while($r=mysqli_fetch_assoc($rs)){
    $name = sender_name($conn, $r['sender_type'], (int)$r['sender_id']);
    $msgs[]=[
      'id'=>(int)$r['id'],
      'sender_type'=>$r['sender_type'],
      'sender_id'=>(int)$r['sender_id'],
      'sender_name'=>$name,
      'body'=>$r['body'],
      'created_at'=>$r['created_at']
    ];
    $ids[]=(int)$r['id'];
  }

  // attachments map
  $atts=[];
  if (!empty($ids)) {
    $in = implode(',',$ids);
    $qa = mysqli_query($conn, "SELECT message_id, file_path FROM chat_attachments WHERE message_id IN ($in)");
    while($a=mysqli_fetch_assoc($qa)){
      $mid=(int)$a['message_id'];
      if(!isset($atts[$mid])) $atts[$mid]=[];
      $atts[$mid][]= ['file_path'=>$a['file_path']];
    }
  }

  json_out(['ok'=>true,'messages'=>$msgs,'attachments'=>$atts]);
}

// ---------- Send DM message ----------
if ($action === 'dm_send') {
  $tid = (int)($_POST['thread_id'] ?? 0);
  $body= trim($_POST['body'] ?? '');
  if ($tid<=0) json_out(['ok'=>false,'error'=>'Invalid thread']);

  // Get owning student of the thread
  $q = mysqli_query($conn, "SELECT student_id FROM chat_threads WHERE id={$tid} LIMIT 1");
  $t = mysqli_fetch_assoc($q);
  if (!$t) json_out(['ok'=>false,'error'=>'Thread not found']);
  $sid = (int)$t['student_id'];

  // Student blocked?
  if (!$is_admin) {
    $bq = mysqli_query($conn,"SELECT is_blocked FROM student_chat_block WHERE student_id={$sid} LIMIT 1");
    if ($b = mysqli_fetch_assoc($bq)) {
      if ((int)$b['is_blocked'] === 1) json_out(['ok'=>false,'error'=>'Your chat is blocked by admin.']);
    }
  }

  // Insert message
  $senderType = $is_admin ? 'ADMIN':'STUDENT';
  $senderId   = $is_admin ? $admin_id:$student_id;

  $st = mysqli_prepare($conn, "INSERT INTO chat_messages(scope,thread_id,room_id,sender_type,sender_id,body) VALUES ('DM',?,NULL,?,?,?)");
  mysqli_stmt_bind_param($st, "iiss", $tid, $senderType, $senderId, $body);
  mysqli_stmt_execute($st);
  $mid = mysqli_insert_id($conn);
  mysqli_stmt_close($st);

  // attachments
  if (!empty($_FILES['files'])) {
    $paths = upload_files($_FILES['files']);
    foreach($paths as $p){
      $ia = mysqli_prepare($conn, "INSERT INTO chat_attachments(message_id,file_path) VALUES (?,?)");
      mysqli_stmt_bind_param($ia, "is", $mid, $p);
      mysqli_stmt_execute($ia);
      mysqli_stmt_close($ia);
    }
  }

  json_out(['ok'=>true,'message_id'=>$mid]);
}

// ---------- Rooms ----------
if ($action === 'list_rooms') {
  if ($is_admin) {
    // admin sees all rooms
    $q = mysqli_query($conn, "SELECT id,name,batch_id FROM chat_rooms ORDER BY id DESC");
  } else {
    // student: only their batch rooms
    $rq = mysqli_query($conn, "
      SELECT r.batch_id FROM registrations r
      WHERE r.student_id={$student_id}
      ORDER BY r.approved_at DESC LIMIT 1
    ");
    $b = mysqli_fetch_assoc($rq);
    $bid = $b ? (int)$b['batch_id'] : 0;
    $q = mysqli_query($conn, "SELECT id,name,batch_id FROM chat_rooms WHERE batch_id={$bid} ORDER BY id DESC");
  }
  $out=[];
  while($r=mysqli_fetch_assoc($q)){
    $out[]=['id'=>(int)$r['id'],'name'=>$r['name'],'type'=>'Batch','batch_id'=>(int)$r['batch_id']];
  }
  json_out(['ok'=>true,'rooms'=>$out]);
}

if ($action === 'create_room') {
  if (!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $name = trim($_POST['name'] ?? '');
  $batch_id = (int)($_POST['batch_id'] ?? 0);
  if ($name==='' || $batch_id<=0) json_out(['ok'=>false,'error'=>'Name & batch required']);

  $st = mysqli_prepare($conn, "INSERT INTO chat_rooms(name,batch_id,created_by) VALUES (?,?,?)");
  mysqli_stmt_bind_param($st, "sii", $name, $batch_id, $admin_id);
  mysqli_stmt_execute($st);
  $rid = mysqli_insert_id($conn);
  mysqli_stmt_close($st);

  json_out(['ok'=>true,'room_id'=>$rid]);
}

if ($action === 'room_messages') {
  $rid = (int)($_GET['room_id'] ?? 0);
  if ($rid<=0) json_out(['ok'=>false,'error'=>'Invalid room']);

  // membership check for students
  if (!$is_admin) {
    $rq = mysqli_query($conn,"SELECT batch_id FROM chat_rooms WHERE id={$rid} LIMIT 1");
    $r  = mysqli_fetch_assoc($rq);
    if (!$r) json_out(['ok'=>false,'error'=>'Room not found']);
    $room_batch = (int)$r['batch_id'];
    $sq = mysqli_query($conn,"SELECT r.batch_id FROM registrations r WHERE r.student_id={$student_id} ORDER BY r.approved_at DESC LIMIT 1");
    $s  = mysqli_fetch_assoc($sq);
    $my_batch = $s ? (int)$s['batch_id'] : 0;
    if ($room_batch !== $my_batch) json_out(['ok'=>false,'error'=>'Access denied']);
  }

  $since = (int)($_GET['since_id'] ?? 0);
  $cond  = $since>0 ? "AND m.id>{$since}" : '';

  $rs = mysqli_query($conn, "
    SELECT m.id, m.sender_type, m.sender_id, m.body, m.created_at
    FROM chat_messages m
    WHERE m.scope='ROOM' AND m.room_id={$rid} {$cond}
    ORDER BY m.id ASC
  ");
  $msgs=[]; $ids=[];
  while($r=mysqli_fetch_assoc($rs)){
    $name = sender_name($conn, $r['sender_type'], (int)$r['sender_id']);
    $msgs[]=[
      'id'=>(int)$r['id'],
      'sender_type'=>$r['sender_type'],
      'sender_id'=>(int)$r['sender_id'],
      'sender_name'=>$name,
      'body'=>$r['body'],
      'created_at'=>$r['created_at']
    ];
    $ids[]=(int)$r['id'];
  }

  $atts=[];
  if (!empty($ids)) {
    $in = implode(',',$ids);
    $qa = mysqli_query($conn, "SELECT message_id, file_path FROM chat_attachments WHERE message_id IN ($in)");
    while($a=mysqli_fetch_assoc($qa)){
      $mid=(int)$a['message_id'];
      if(!isset($atts[$mid])) $atts[$mid]=[];
      $atts[$mid][]= ['file_path'=>$a['file_path']];
    }
  }

  json_out(['ok'=>true,'messages'=>$msgs,'attachments'=>$atts]);
}

if ($action === 'room_send') {
  $rid = (int)($_POST['room_id'] ?? 0);
  $body= trim($_POST['body'] ?? '');
  if ($rid<=0) json_out(['ok'=>false,'error'=>'Invalid room']);

  // membership check for students
  if (!$is_admin) {
    $rq = mysqli_query($conn,"SELECT batch_id FROM chat_rooms WHERE id={$rid} LIMIT 1");
    $r  = mysqli_fetch_assoc($rq);
    if (!$r) json_out(['ok'=>false,'error'=>'Room not found']);
    $room_batch = (int)$r['batch_id'];
    $sq = mysqli_query($conn,"SELECT r.batch_id FROM registrations r WHERE r.student_id={$student_id} ORDER BY r.approved_at DESC LIMIT 1");
    $s  = mysqli_fetch_assoc($sq);
    $my_batch = $s ? (int)$s['batch_id'] : 0;
    if ($room_batch !== $my_batch) json_out(['ok'=>false,'error'=>'Access denied']);
  }

  $senderType = $is_admin ? 'ADMIN':'STUDENT';
  $senderId   = $is_admin ? $admin_id:$student_id;

  $st = mysqli_prepare($conn, "INSERT INTO chat_messages(scope,thread_id,room_id,sender_type,sender_id,body) VALUES ('ROOM',NULL,?,?,?,?)");
  mysqli_stmt_bind_param($st, "iiss", $rid, $senderType, $senderId, $body);
  mysqli_stmt_execute($st);
  $mid = mysqli_insert_id($conn);
  mysqli_stmt_close($st);

  if (!empty($_FILES['files'])) {
    $paths = upload_files($_FILES['files']);
    foreach($paths as $p){
      $ia = mysqli_prepare($conn, "INSERT INTO chat_attachments(message_id,file_path) VALUES (?,?)");
      mysqli_stmt_bind_param($ia, "is", $mid, $p);
      mysqli_stmt_execute($ia);
      mysqli_stmt_close($ia);
    }
  }

  json_out(['ok'=>true,'message_id'=>$mid]);
}

// ---------- Notices ----------
if ($action === 'create_notice') {
  if (!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $title = trim($_POST['title'] ?? '');
  $body  = trim($_POST['body'] ?? '');
  $target_type = $_POST['target_type'] ?? 'ALL';
  $target_id   = (int)($_POST['target_id'] ?? 0);
  if ($title==='') json_out(['ok'=>false,'error'=>'Title required']);
  if (!in_array($target_type, ['ALL','COURSE','BATCH'], true)) $target_type='ALL';
  if ($target_type==='ALL') $target_id = null;

  $sql = "INSERT INTO notices(title,body,target_type,target_id,created_by) VALUES (?,?,?,?,?)";
  $st = mysqli_prepare($conn, $sql);
  mysqli_stmt_bind_param($st, "sssii", $title, $body, $target_type, $target_id, $admin_id);
  mysqli_stmt_execute($st);
  mysqli_stmt_close($st);
  json_out(['ok'=>true]);
}

if ($action === 'list_notices') {
  if ($is_admin) {
    // all
    $q = mysqli_query($conn, "
      SELECT n.*, a.id AS admin_user
      FROM notices n
      LEFT JOIN admins a ON a.id=n.created_by
      ORDER BY n.id DESC LIMIT 200
    ");
  } else {
    // student scope
    $cq = mysqli_query($conn,"SELECT r.course_id, r.batch_id FROM registrations r WHERE r.student_id={$student_id} ORDER BY r.approved_at DESC LIMIT 1");
    $r  = mysqli_fetch_assoc($cq);
    $cid= $r?(int)$r['course_id']:0;
    $bid= $r?(int)$r['batch_id']:0;

    $q = mysqli_query($conn, "
      SELECT * FROM notices n
      WHERE (n.target_type='ALL')
         OR (n.target_type='COURSE' AND n.target_id={$cid})
         OR (n.target_type='BATCH'  AND n.target_id={$bid})
      ORDER BY n.id DESC LIMIT 200
    ");
  }

  $out=[];
  while($n=mysqli_fetch_assoc($q)){
    $out[]=[
      'id'=>(int)$n['id'],
      'title'=>$n['title'],
      'body'=>$n['body'],
      'target_type'=>$n['target_type'],
      'target_id'=> isset($n['target_id']) ? (int)$n['target_id'] : null,
      'created_at'=>$n['created_at']
    ];
  }
  json_out(['ok'=>true,'notices'=>$out]);
}

json_out(['ok'=>false,'error'=>'Unknown action']);
