import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../models/purchase_history_model.dart';
import '../constants.dart';

class PurchaseHistoryProvider with ChangeNotifier {
  List<PurchaseHistoryModel> _items = [];
  bool _isLoading = false;

  List<PurchaseHistoryModel> get items => [..._items];
  bool get isLoading => _isLoading;

  Future<void> fetchPurchaseHistory() async {
    _isLoading = true;
    notifyListeners();

    final prefs = await SharedPreferences.getInstance();
    final authToken = prefs.getString('access_token') ?? '';

    var url = '$baseUrl/api/purchase_history';

    try {
      final response = await http.get(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $authToken',
        },
      );

      final responseData = json.decode(response.body);

      if (responseData['code'] != 200) {
        throw Exception("Failed to load purchase history");
      }

      final List extractedData = responseData['data'];

      final List<PurchaseHistoryModel> loadedData = [];

      for (var purchaseData in extractedData) {
        loadedData.add(
          PurchaseHistoryModel(
            id: purchaseData['id'],
            courseTitle: purchaseData['course_title'],
            userName: purchaseData['user_name'],
            currency: purchaseData['currency']?.toString(),
            amount: (purchaseData['amount'] as num?)?.toDouble(),
            paymentType: purchaseData['payment_type'],
            createdAt: purchaseData['created_at'],
          ),
        );
      }

      _items = loadedData;
    } catch (error) {
      rethrow;
    }

    _isLoading = false;
    notifyListeners();
  }
}
