<?php
require_once("_guard.php");
$userId=intval($_GET['user_id']??0); $conversations=[];
$r=$conn->query("SELECT u.id,u.full_name,u.email,MAX(c.created_at) last_message,
  SUBSTRING_INDEX(GROUP_CONCAT(c.message ORDER BY c.id DESC SEPARATOR '\\n'), '\\n', 1) preview,
  SUM(CASE WHEN c.sender='user' AND c.id > COALESCE((SELECT MAX(a.id) FROM chat_messages a WHERE a.user_id=u.id AND a.sender='admin'),0) THEN 1 ELSE 0 END) unreplied
  FROM users u INNER JOIN chat_messages c ON c.user_id=u.id GROUP BY u.id ORDER BY last_message DESC"); while($r && ($x=$r->fetch_assoc())) $conversations[]=$x;
$messages=[]; if($userId>0){$s=$conn->prepare("SELECT id,user_id,sender,message,file,created_at FROM chat_messages WHERE user_id=? ORDER BY id");$s->bind_param("i",$userId);$s->execute();$r=$s->get_result();while($x=$r->fetch_assoc())$messages[]=$x;}
echo json_encode(["success"=>true,"conversations"=>$conversations,"messages"=>$messages]);
?>
