import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:gen_rentals/Services/api_calling.dart';

import '../Models/TransactionsResponse.dart';

class TransactionsProvider with ChangeNotifier {
  bool _isLoading = false;
  TransactionsResponse? _transactionsResponse;

  bool get isLoading => _isLoading;
  TransactionsResponse? get transactionsResponse => _transactionsResponse;

  /// For UI convenience
  Map<String, List<TransactionItem>> get transactionsByMonth =>
      _transactionsResponse?.transactions ?? {};

  /// Fetch Rental Transactions API
  Future<void> fetchRentalTransactions(String sessionId, String accId) async {
    _isLoading = true;
    notifyListeners();

    try {
      final response =
      await ApiCalling.fetchRentalsTransactionsApi(sessionId, accId);

      if (response != null && response.error == "0") {
        _transactionsResponse = response;
        log("✅ Transactions fetched successfully: ${response.transactions?.length ?? 0} months");
      } else {
        log("⚠️ Error in API response: ${response?.message}");
        _transactionsResponse = null;
      }
    } catch (e) {
      log("❌ Exception in fetchRentalTransactions: $e");
      _transactionsResponse = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Optional: Clear data
  void clearTransactions() {
    _transactionsResponse = null;
    notifyListeners();
  }
}
