import 'package:shared_preferences/shared_preferences.dart'; import 'package:travel_mate/models/budget_category.dart'; /// Service to manage per-trip budget envelopes (multi-devise) locally. /// /// Stores envelopes in `SharedPreferences` under `budget_` so they /// remain available offline. Integration with expense data can later update /// the [spent] field. class BudgetService { /// Loads budget categories for the trip. Future> loadBudgets(String tripId) async { final prefs = await SharedPreferences.getInstance(); final raw = prefs.getString(_key(tripId)); if (raw == null) return const []; try { return BudgetCategory.decodeList(raw); } catch (_) { await prefs.remove(_key(tripId)); return const []; } } /// Persists full list. Future saveBudgets( String tripId, List categories, ) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_key(tripId), BudgetCategory.encodeList(categories)); } /// Adds an envelope. Future> addBudget( String tripId, BudgetCategory category, ) async { final current = await loadBudgets(tripId); final updated = [...current, category]; await saveBudgets(tripId, updated); return updated; } /// Deletes an envelope. Future> deleteBudget( String tripId, String categoryId, ) async { final current = await loadBudgets(tripId); final updated = current.where((c) => c.id != categoryId).toList(); await saveBudgets(tripId, updated); return updated; } /// Updates spent amount for a category (used later by expense sync). Future> updateSpent( String tripId, String categoryId, double spent, ) async { final current = await loadBudgets(tripId); final updated = current .map((c) { if (c.id != categoryId) return c; return c.copyWith(spent: spent); }) .toList(growable: false); await saveBudgets(tripId, updated); return updated; } String _key(String tripId) => 'budget_$tripId'; }