import 'package:flutter/foundation.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:em2rp/models/alert_model.dart'; class AlertProvider extends ChangeNotifier { final FirebaseFirestore _firestore = FirebaseFirestore.instance; List _alerts = []; // Getters List get alerts => _alerts; /// Nombre d'alertes non lues int get unreadCount => _alerts.where((alert) => !alert.isRead).length; /// Alertes non lues uniquement List get unreadAlerts => _alerts.where((alert) => !alert.isRead).toList(); /// Alertes de stock critique List get lowStockAlerts => _alerts.where((alert) => alert.type == AlertType.lowStock).toList(); /// Alertes de maintenance List get maintenanceAlerts => _alerts.where((alert) => alert.type == AlertType.maintenanceDue).toList(); /// Alertes de conflit List get conflictAlerts => _alerts.where((alert) => alert.type == AlertType.conflict).toList(); /// Stream des alertes Stream> get alertsStream { return _firestore .collection('alerts') .orderBy('createdAt', descending: true) .snapshots() .map((snapshot) { _alerts = snapshot.docs .map((doc) => AlertModel.fromMap(doc.data(), doc.id)) .toList(); return _alerts; }); } /// Marquer une alerte comme lue Future markAsRead(String alertId) async { try { await _firestore.collection('alerts').doc(alertId).update({ 'isRead': true, }); notifyListeners(); } catch (e) { print('Error marking alert as read: $e'); rethrow; } } /// Marquer toutes les alertes comme lues Future markAllAsRead() async { try { final batch = _firestore.batch(); for (var alert in _alerts.where((a) => !a.isRead)) { batch.update( _firestore.collection('alerts').doc(alert.id), {'isRead': true}, ); } await batch.commit(); notifyListeners(); } catch (e) { print('Error marking all alerts as read: $e'); rethrow; } } /// Supprimer une alerte Future deleteAlert(String alertId) async { try { await _firestore.collection('alerts').doc(alertId).delete(); notifyListeners(); } catch (e) { print('Error deleting alert: $e'); rethrow; } } /// Supprimer toutes les alertes lues Future deleteReadAlerts() async { try { final batch = _firestore.batch(); for (var alert in _alerts.where((a) => a.isRead)) { batch.delete(_firestore.collection('alerts').doc(alert.id)); } await batch.commit(); notifyListeners(); } catch (e) { print('Error deleting read alerts: $e'); rethrow; } } /// Créer une alerte (utilisé principalement par les services) Future createAlert(AlertModel alert) async { try { await _firestore.collection('alerts').doc(alert.id).set(alert.toMap()); notifyListeners(); } catch (e) { print('Error creating alert: $e'); rethrow; } } /// Récupérer les alertes pour un équipement spécifique Stream> getAlertsForEquipment(String equipmentId) { return _firestore .collection('alerts') .where('equipmentId', isEqualTo: equipmentId) .orderBy('createdAt', descending: true) .snapshots() .map((snapshot) { return snapshot.docs .map((doc) => AlertModel.fromMap(doc.data(), doc.id)) .toList(); }); } }