<?php  if (!defined('DASHBOARD_ROOT')) { http_response_code(403); exit; } $threads = Database::fetchAll( "SELECT sm.user_id, u.username, MAX(sm.created_at) as last_msg, COUNT(*) as msg_count,      SUM(CASE WHEN sm.is_read = 0 AND sm.is_admin = 0 THEN 1 ELSE 0 END) as unread_count      FROM support_messages sm LEFT JOIN users u ON u.id = sm.user_id      GROUP BY sm.user_id ORDER BY last_msg DESC LIMIT 50" ); $headers = ['Customer', 'Messages', 'Last Activity', 'Unread', 'Actions']; $rows = []; foreach ($threads as $t) { $uid = (int)($t['user_id'] ?? 0); $name = UI::e($t['username'] ?? ('User #' . $uid)); $rows[] = [ $name, (int)$t['msg_count'], $t['last_msg'] ?? '—', ($t['unread_count'] > 0) ? UI::badge((int)$t['unread_count'], 'warning') : '', '<button onclick="openThread(' . $uid . ')">Open</button>', ]; } echo '<div class="support-inbox"><h3>Support Inbox</h3>' . UI::table($headers, $rows, 'tbl-support') . '</div>'; 