import 'package:flutter/foundation.dart'; import '../models/bar_tab.dart'; import '../models/product.dart'; import '../models/tab_item.dart'; import '../services/bar_tab_service.dart'; import 'inventory_view_model.dart'; class BarScreenViewModel extends ChangeNotifier { final BarTabService barTabService; final InventoryViewModel inventory; BarScreenViewModel({required this.barTabService, required this.inventory}); List _tabs = []; String? _selectedTabId; bool _isLoading = false; bool _hasLoaded = false; String? _errorMessage; List get tabs => _tabs; String? get selectedTabId => _selectedTabId; bool get isLoading => _isLoading; bool get hasLoaded => _hasLoaded; String? get errorMessage => _errorMessage; BarTab? get selectedTab { if (_selectedTabId == null) return null; try { return _tabs.firstWhere((tab) => tab.id == _selectedTabId); } catch (_) { return null; } } Future ensureLoaded() async { if (_hasLoaded || _isLoading) return; await load(); } Future load() async { if (_isLoading) return; _isLoading = true; _errorMessage = null; notifyListeners(); try { _tabs = await barTabService.getOpenTabs(); if (_selectedTabId == null || !_tabs.any((tab) => tab.id == _selectedTabId)) { _selectedTabId = _tabs.isEmpty ? null : _tabs.first.id; } } catch (_) { _errorMessage = 'Could not load bar screen.'; } finally { _hasLoaded = true; _isLoading = false; notifyListeners(); } } void selectTab(String tabId) { _selectedTabId = tabId; notifyListeners(); } Future createTab(String customerName) async { final tab = await barTabService.createTab(customerName: customerName); _selectedTabId = tab.id; await _reloadTabs(); } Future addProductToSelectedTab(Product product) async { final tab = selectedTab; if (tab == null) return; if (product.stockQuantity <= 0) { throw Exception('Product is out of stock.'); } await barTabService.addProductToTab( tabId: tab.id, product: product, stockAdjustment: () => inventory.decreaseStock(product.id, 1), ); await _reloadTabs(); } Future changeItemQuantity(TabItem item, int quantity) async { final difference = quantity - item.quantity; await barTabService.updateTabItemQuantity( tabItemId: item.id, quantity: quantity, stockAdjustment: () async { if (difference > 0) { await inventory.decreaseStock(item.productId, difference); } else if (difference < 0) { await inventory.increaseStock(item.productId, -difference); } }, ); await _reloadTabs(); } Future closeSelectedTab({String paymentMethod = 'cash'}) async { final tab = selectedTab; if (tab == null) return; await barTabService.closeTab(tab.id, paymentMethod: paymentMethod); await _reloadTabs(); } Future closeTab(String tabId, {String paymentMethod = 'cash'}) async { await barTabService.closeTab(tabId, paymentMethod: paymentMethod); await _reloadTabs(); } Future _reloadTabs() async { _tabs = await barTabService.getOpenTabs(); if (_selectedTabId == null || !_tabs.any((tab) => tab.id == _selectedTabId)) { _selectedTabId = _tabs.isEmpty ? null : _tabs.first.id; } notifyListeners(); } }