import 'dart:convert';

import 'package:firebase_database/firebase_database.dart';
import 'package:mobile_pos/Screens/Customers/Model/customer_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../currency.dart';

class CustomerRepo {
  Future<List<CustomerModel>> getAllCustomers() async {
    List<CustomerModel> customerList = [];
    final customerRef = FirebaseDatabase.instance.ref(constUserId).child('Customers');
    await customerRef.orderByKey().get().then((value) {
      for (var element in value.children) {
        var cust = CustomerModel.fromJson(jsonDecode(
          jsonEncode(element.value),
        ));
        print('CustomerName: ${cust.customerName}');
        print('Due Balance: ${cust.dueAmount}');
        if (cust.customerName.isEmptyOrNull) {
          print(cust.customerName);
          cust.customerName = '0';
          customerList.add(cust);
        } else {
          customerList.add(cust);
        }
      }
    });

    customerRef.keepSynced(true);
    return customerList;
  }
}
// import 'dart:convert';
//
// import 'package:firebase_database/firebase_database.dart';
// import 'package:mobile_pos/Screens/Customers/Model/customer_model.dart';
// import 'package:nb_utils/nb_utils.dart';
//
// import '../currency.dart';
//
// class CustomerRepo {
//   // Replace with your actual user ID constant
//
//   Future<List<CustomerModel>> getAllCustomers() async {
//     try {
//       final DatabaseReference customerRef = FirebaseDatabase.instance.ref().child(constUserId).child('Customers');
//
//       // Enable persistence
//       customerRef.keepSynced(true);
//
//       final DataSnapshot snapshot =  await customerRef.orderByKey().get();
//
//       if (!snapshot.exists) {
//         return [];
//       }
//
//       List<CustomerModel> customerList = [];
//
//       for (DataSnapshot element in snapshot.children) {
//         try {
//           final customerData = element.value as Map<dynamic, dynamic>;
//           final customerMap = customerData.map((key, value) => MapEntry(key.toString(), value));
//
//           final CustomerModel customer = CustomerModel.fromJson(customerMap);
//
//           print('CustomerName: ${customer.customerName}');
//           print('Due Balance: ${customer.dueAmount}');
//
//           // Handle null or empty customer name more efficiently
//           customer.customerName = customer.customerName.isNotEmpty == true ? customer.customerName : 'Unknown Customer';
//
//           customerList.add(customer);
//         } catch (e) {
//           print('Error parsing customer ${element.key}: $e');
//           // Continue with next customer instead of failing entirely
//         }
//       }
//
//       return customerList;
//     } catch (e) {
//       print('Error fetching customers: $e');
//       // You might want to throw a custom exception here or return an empty list
//       return [];
//     }
//   }
// }
