import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:gen_rentals/Services/api_calling.dart';
import '../Models/CommonResponse.dart';
import '../Models/TransactionModels/PayAmountResponse.dart';

class PayAmountProvider with ChangeNotifier {
  bool _isLoading = false;
  PayAmountResponse? _payResponse;
  PaymentStatusResponse? _statusResponse;
  String? _errorMessage;

  bool get isLoading => _isLoading;
  PayAmountResponse? get payResponse => _payResponse;
  PaymentStatusResponse? get statusResponse => _statusResponse;
  String? get errorMessage => _errorMessage;

  ///  Pay Amount API
  Future<void> payAmount({
    required String sessionId,
    required String empId,
    required String amount,
    required String refType,
    required String refId,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final res = await ApiCalling.payAmountApi(
        sessionId,
        empId,
        amount,
        refType,
        refId,
      );

      if (res != null) {
        _payResponse = res;
      } else {
        _errorMessage = "No response from server";
      }
    } catch (e) {
      _errorMessage = "Error: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Get Payment Status API
  Future<void> getPaymentStatus({
    required String sessionId,
    required String empId,
    required String razorpayOrderId,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final res = await ApiCalling.getPaymentStatusApi(
        sessionId,
        empId,
        razorpayOrderId,
      );

      if (res != null) {
        _statusResponse = res;
      } else {
        _errorMessage = "No response from server";
      }
    } catch (e) {
      _errorMessage = "Error: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Reset all states
  void reset() {
    _payResponse = null;
    _statusResponse = null;
    _errorMessage = null;
    notifyListeners();
  }
}

// Payment Status Response
class PaymentStatusResponse {
  int? error;
  double? amount;
  String? date;
  String? message;
  int? sessionExists;

  PaymentStatusResponse(
      {this.error, this.amount, this.date, this.message, this.sessionExists});

  PaymentStatusResponse.fromJson(Map<String, dynamic> json) {
    error = json['error'];
    amount = json['amount'];
    date = json['date'];
    message = json['message'];
    sessionExists = json['session_exists'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['error'] = this.error;
    data['amount'] = this.amount;
    data['date'] = this.date;
    data['message'] = this.message;
    data['session_exists'] = this.sessionExists;
    return data;
  }
}
