import 'package:flutter/material.dart'; import 'package:sales_chat/models/group.dart'; import 'package:sales_chat/models/invite.dart'; import 'package:sales_chat/services/api_service.dart'; class InviteProvider with ChangeNotifier { final ApiService _apiService; List _invites = []; Invite? _selectedInvite; InviteStats? _selectedInviteStats; List _availableGroups = []; bool _isLoading = false; bool _isCreating = false; String? _error; InviteProvider(this._apiService); List get invites => _invites; Invite? get selectedInvite => _selectedInvite; InviteStats? get selectedInviteStats => _selectedInviteStats; List get availableGroups => _availableGroups; bool get isLoading => _isLoading; bool get isCreating => _isCreating; String? get error => _error; Future loadInvites() async { _isLoading = true; _error = null; notifyListeners(); try { _invites = await _apiService.getMyInvites(); _isLoading = false; notifyListeners(); } catch (e) { _error = 'Failed to load invite list'; _isLoading = false; notifyListeners(); } } Future loadAvailableGroups(List groups) async { _availableGroups = groups; notifyListeners(); } Future createInvite({ required String groupId, int? expiresInDays, }) async { _isCreating = true; _error = null; notifyListeners(); try { final invite = await _apiService.createInvite( groupId: groupId, expiresInDays: expiresInDays, ); _invites.insert(0, invite); _isCreating = false; notifyListeners(); return invite; } catch (e) { _error = 'Failed to create invite'; _isCreating = false; notifyListeners(); return null; } } Future selectInvite(Invite invite) async { _selectedInvite = invite; notifyListeners(); await loadInviteStats(invite.code); } Future loadInviteStats(String code) async { try { _selectedInviteStats = await _apiService.getInviteStats(code); notifyListeners(); } catch (e) { // Handle error silently } } Future deactivateInvite(String code) async { try { await _apiService.deactivateInvite(code); final index = _invites.indexWhere((i) => i.code == code); if (index != -1) { final invite = _invites[index]; _invites[index] = Invite( id: invite.id, code: invite.code, salesId: invite.salesId, groupId: invite.groupId, link: invite.link, qrCodeUrl: invite.qrCodeUrl, createdAt: invite.createdAt, expiresAt: invite.expiresAt, clickCount: invite.clickCount, scanCount: invite.scanCount, joinCount: invite.joinCount, status: 'inactive', ); } if (_selectedInvite?.code == code) { _selectedInvite = null; _selectedInviteStats = null; } notifyListeners(); } catch (e) { _error = 'Failed to deactivate invite'; notifyListeners(); } } void clearError() { _error = null; notifyListeners(); } void clearSelection() { _selectedInvite = null; _selectedInviteStats = null; notifyListeners(); } }