1// ── CHAT SERVICE ──
2class ChatService {
3 final _firestore = FirebaseFirestore.instance;
4 final _auth = FirebaseAuth.instance;
5
6 // Get or create a chat room between two users
7 Future<String> getOrCreateChatRoom(String otherUserId) async {
8 final currentUser = _auth.currentUser!;
9 final members = [currentUser.uid, otherUserId]..sort();
10 final roomId = members.join('_');
11
12 final roomRef = _firestore.collection('chatRooms').doc(roomId);
13 final room = await roomRef.get();
14
15 if (!room.exists) {
16 await roomRef.set({
17 'members': members,
18 'lastMessage': '',
19 'lastMessageTime': FieldValue.serverTimestamp(),
20 'isGroup': false,
21 });
22 }
23
24 return roomId;
25 }
26
27 // Send a text message
28 Future<void> sendMessage(String roomId, String text) async {
29 final user = _auth.currentUser!;
30
31 await _firestore
32 .collection('chatRooms')
33 .doc(roomId)
34 .collection('messages')
35 .add({
36 'senderId': user.uid,
37 'senderName': user.displayName ?? 'User',
38 'text': text,
39 'timestamp': FieldValue.serverTimestamp(),
40 'isRead': false,
41 });
42
43 // Update last message in chat room
44 await _firestore.collection('chatRooms').doc(roomId).update({
45 'lastMessage': text,
46 'lastMessageTime': FieldValue.serverTimestamp(),
47 });
48 }
49
50 // Real-time message stream
51 Stream<List<ChatMessage>> getMessages(String roomId) {
52 return _firestore
53 .collection('chatRooms')
54 .doc(roomId)
55 .collection('messages')
56 .orderBy('timestamp', descending: true)
57 .limit(50)
58 .snapshots()
59 .map((snapshot) => snapshot.docs
60 .map((doc) => ChatMessage.fromFirestore(doc))
61 .toList());
62 }
63
64 // Get chat rooms for current user
65 Stream<List<ChatRoom>> getChatRooms() {
66 final userId = _auth.currentUser!.uid;
67 return _firestore
68 .collection('chatRooms')
69 .where('members', arrayContains: userId)
70 .orderBy('lastMessageTime', descending: true)
71 .snapshots()
72 .map((snapshot) => snapshot.docs.map((doc) {
73 final data = doc.data();
74 return ChatRoom(
75 id: doc.id,
76 members: List<String>.from(data['members']),
77 lastMessage: data['lastMessage'],
78 lastMessageTime: data['lastMessageTime'] != null
79 ? (data['lastMessageTime'] as Timestamp).toDate()
80 : null,
81 isGroup: data['isGroup'] ?? false,
82 );
83 }).toList());
84 }
85
86 // Upload and send image
87 Future<void> sendImage(String roomId, File imageFile) async {
88 final user = _auth.currentUser!;
89 final ref = FirebaseStorage.instance
90 .ref('chat_images/${roomId}/${DateTime.now().millisecondsSinceEpoch}.jpg');
91 await ref.putFile(imageFile);
92 final url = await ref.getDownloadURL();
93
94 await _firestore
95 .collection('chatRooms')
96 .doc(roomId)
97 .collection('messages')
98 .add({
99 'senderId': user.uid,
100 'senderName': user.displayName,
101 'text': '',
102 'imageUrl': url,
103 'timestamp': FieldValue.serverTimestamp(),
104 'isRead': false,
105 });
106 }
107
108 // Update online status
109 Future<void> updateOnlineStatus(bool isOnline) async {
110 final userId = _auth.currentUser?.uid;
111 if (userId != null) {
112 await _firestore.collection('users').doc(userId).update({
113 'isOnline': isOnline,
114 'lastSeen': FieldValue.serverTimestamp(),
115 });
116 }
117 }
118}