class AdvancePayment {
  final String id;
  final String title;
  final String name;
  final double amount;
  final double balance;
  final String date;

  const AdvancePayment({
    required this.id,
    required this.title,
    required this.name,
    required this.amount,
    required this.balance,
    required this.date,
  });

  factory AdvancePayment.fromJson(Map<String, dynamic> json) {
    double parseDouble(dynamic value) {
      if (value == null) return 0.0;
      if (value is num) return value.toDouble();
      if (value is String) return double.tryParse(value) ?? 0.0;
      return 0.0;
    }

    String extractProjectName(dynamic project) {
      if (project is Map && project.containsKey('name')) {
        return project['name']?.toString() ?? '';
      } else if (project is String) {
        return project;
      }
      return '';
    }

    return AdvancePayment(
      id: json['id']?.toString() ?? '',
      // 👇 Fallback for APIs using "description" instead of "title"
      title: json['title']?.toString() ?? json['description']?.toString() ?? '',
      name: extractProjectName(json['project']),
      amount: parseDouble(json['amount']),
      balance: parseDouble(json['currentBalance']),
      date: json['paidAt']?.toString() ?? json['createdAt']?.toString() ?? '',
    );
  }

  static List<AdvancePayment> listFromJson(dynamic data) {
    if (data is List) {
      return data
          .map((e) => e is Map<String, dynamic>
              ? AdvancePayment.fromJson(Map<String, dynamic>.from(e))
              : const AdvancePayment(
                  id: '',
                  title: '',
                  name: '',
                  amount: 0,
                  balance: 0,
                  date: '',
                ))
          .toList();
    }
    return [];
  }
}
