'Unauthorized']); exit; } $pdo = db(); // Action for admin notification count if (isset($_GET['action']) && $_GET['action'] === 'count_unread') { $unread_msgs = $pdo->query("SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0")->fetchColumn(); $pending_orders = $pdo->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn(); echo json_encode(['total' => (int)($unread_msgs + $pending_orders)]); exit; } // Support both regular user and admin polling for specific user $user_id = isset($_GET['user_id']) ? $_GET['user_id'] : $_SESSION['user_id']; // If last_id is provided, return new messages since then if (isset($_GET['last_id'])) { $last_id = (int)$_GET['last_id']; $stmt = $pdo->prepare("SELECT * FROM messages WHERE user_id = ? AND id > ? ORDER BY id ASC"); $stmt->execute([$user_id, $last_id]); $msgs = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode(['data' => $msgs]); exit; } // Default action: return count and last_id $stmt = $pdo->prepare("SELECT COUNT(*), MAX(id) FROM messages WHERE user_id = ?"); $stmt->execute([$user_id]); $res = $stmt->fetch(); $count = $res[0]; $last_id = $res[1]; echo json_encode(['count' => (int)$count, 'last_id' => (int)$last_id]);