import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qpay/http/http.dart'; import 'package:qpay/models/api_response.dart'; import 'package:qpay/screens/home/home_controller.dart' as hc; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:qpay/screens/transaction_controller.dart'; part 'recipients_controller.freezed.dart'; part 'recipients_controller.g.dart'; class RecipientModel { String? creditAccount; String? errorMessage; hc.BillProvider? selectedProvider; bool isLoading = false; List recipients = []; } @freezed abstract class Recipient with _$Recipient { const factory Recipient({ @JsonKey(includeIfNull: false) String? uid, @JsonKey(includeIfNull: false) String? name, @JsonKey(includeIfNull: false) String? email, @JsonKey(includeIfNull: false) String? phoneNumber, @JsonKey(includeIfNull: false) String? address, @JsonKey(includeIfNull: false) String? account, @JsonKey(includeIfNull: false) String? initials, @JsonKey(includeIfNull: false) String? latestProviderLabel, }) = _Recipient; factory Recipient.fromJson(Map json) => _$RecipientFromJson(json); } class RecipientsController extends ChangeNotifier { final RecipientModel model = RecipientModel(); final http = Http(); BuildContext context; RecipientsController(this.context) { model.selectedProvider = Provider.of( context, listen: false, ).model.selectedProvider; } Future>> getRecipients([ Map? params, ]) async { model.errorMessage = null; model.isLoading = true; model.recipients = getDummyRecipients(); notifyListeners(); try { List response = await http.get( '/public/recipients/search?${buildQueryParameters(params ?? {})}', ); model.recipients.clear(); model.recipients.addAll(response.map((e) => Recipient.fromJson(e))); model.isLoading = false; notifyListeners(); return ApiResponse.success(List.from(model.recipients)); } catch (e) { model.errorMessage = e.toString(); model.recipients = []; logger.e(e); model.isLoading = false; notifyListeners(); return ApiResponse.failure( "Problem fetching recipients, are you connected to the internet?", ); } } String buildQueryParameters(Map params) { if (params.isEmpty) { return ''; } String query = ''; params.forEach((key, value) { query += '$key=$value&'; }); return query.substring(0, query.length - 1); } void updateCreditAccount(String account) { model.creditAccount = account; notifyListeners(); } void addRecipient(Recipient recipient) { model.recipients.add(recipient); notifyListeners(); } void removeRecipient(String uid) { model.recipients.removeWhere((recipient) => recipient.uid == uid); notifyListeners(); } List getDummyRecipients() { return [ Recipient( uid: '1', name: 'Vusumuzi Khoza', phoneNumber: '+263773591219', email: 'vusumuzi@gmail.com', address: '123 Main St, Anytown, USA', account: '1234567890', initials: 'VK', latestProviderLabel: 'MTN', ), ]; } }