import 'user.dart';

class Payment {
  final String id;
  final String groupId;
  final String userId;
  final int month;
  final int year;
  final double amount;
  final String paymentMethod;
  final String? transactionId;
  final String status;
  final DateTime? paidAt;
  final String? notes;
  final DateTime createdAt;
  final DateTime updatedAt;
  final User? user;

  Payment({
    required this.id,
    required this.groupId,
    required this.userId,
    required this.month,
    required this.year,
    required this.amount,
    required this.paymentMethod,
    this.transactionId,
    required this.status,
    this.paidAt,
    this.notes,
    required this.createdAt,
    required this.updatedAt,
    this.user,
  });

  factory Payment.fromJson(Map<String, dynamic> json) {
    return Payment(
      id: json['id'],
      groupId: json['group_id'],
      userId: json['user_id'],
      month: json['month'],
      year: json['year'],
      amount: _parseDouble(json['amount']),
      paymentMethod: json['payment_method'],
      transactionId: json['transaction_id'],
      status: json['status'],
      paidAt: json['paid_at'] != null ? DateTime.parse(json['paid_at']) : null,
      notes: json['notes'],
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: DateTime.parse(json['updated_at']),
      user: json['User'] != null ? User.fromJson(json['User']) : null,
    );
  }

  static double _parseDouble(dynamic value) {
    if (value == null) return 0.0;
    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) return double.parse(value);
    throw ArgumentError('Cannot parse $value to double');
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'group_id': groupId,
      'user_id': userId,
      'month': month,
      'year': year,
      'amount': amount,
      'payment_method': paymentMethod,
      'transaction_id': transactionId,
      'status': status,
      'paid_at': paidAt?.toIso8601String(),
      'notes': notes,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'User': user?.toJson(),
    };
  }

  // Helper methods
  bool get isPending => status == 'pending';
  bool get isSuccess => status == 'success';
  bool get isFailed => status == 'failed';
  bool get isCancelled => status == 'cancelled';
  
  String get monthYear => '$month/$year';
  String get formattedAmount => '₹${amount.toStringAsFixed(2)}';
}
