import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../models/kyc_model.dart'; import 'kyc_service.dart'; class KycController extends GetxController { var kycList = [].obs; // Using an observable list to store KYC data var isLoading = false.obs; Future fetchKycData() async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String? token = prefs.getString('token'); isLoading(true); // Call the API to get KYC data var data = await KycService().getKycData(token!); if (data != null && data.isNotEmpty) { // Parse the list of KYC objects kycList.value = KycModel.fromJsonList(data); // Convert to List } else { print("No KYC data found or API response is empty."); } print("KYC details: ${kycList}"); } finally { isLoading(false); } } // Update KYC status locally and persist the changes Future updateKycStatus(KycModel kycModel, String status, String comment) async { final index = kycList.indexOf(kycModel); if (index != -1) { kycList[index].status = status; // Update status locally saveKycToLocalStorage(); // Persist the changes locally update(); // Notify listeners about the change // Show a success message after updating Get.snackbar( "Success", "KYC status updated to $status.", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.green, colorText: Colors.white, ); } } // Save the current KYC list to SharedPreferences Future saveKycToLocalStorage() async { SharedPreferences prefs = await SharedPreferences.getInstance(); List kycListJson = kycList.map((kyc) => jsonEncode(kyc.toJson())).toList(); prefs.setStringList('kycList', kycListJson); // Save the updated list locally } // Load the KYC list from SharedPreferences Future loadKycFromLocalStorage() async { SharedPreferences prefs = await SharedPreferences.getInstance(); List? storedKycList = prefs.getStringList('kycList'); if (storedKycList != null) { // If local data is found, update the KYC list with the locally saved data List localKycList = storedKycList.map((kycJson) => KycModel.fromJson(jsonDecode(kycJson))).toList(); // Merge local data with the API data (if any exists in kycList) for (var localKyc in localKycList) { int index = kycList.indexWhere((kyc) => kyc.id == localKyc.id); if (index != -1) { // Update the status with the locally saved status kycList[index].status = localKyc.status; } } } } }