import 'dart:convert';

import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/history_transaction_model.dart';
import 'package:http/http.dart' as http;

class HistoryTransactionService {
  Future<List<HistoryTransactionModel>> historyTransactions() async {
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse('$baseUrl/payment/history');

    http.Response response =
        await http.get(url, headers: headerWithToken(token!));

    List<HistoryTransactionModel> history = [];
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'][0];
      print("Data riwayat transaksi ${data}");
      int i = 0;

      for (var item in data) {
        history.add(HistoryTransactionModel.fromJson(item));
        i++;
      }
      print("Berhasil riwayat transaksi ${response.body}");
      return history;
    } else {
      print("Gagal riwayat transaksi ${response.body}");
      throw Exception('Data Transaksi Gagal Diambil');
    }
  }

  // Fungsi cek expired
  Future<bool> checkTransactionExpiration(String orderId) async {
    String? token = await UsersInfo().getToken();
    if (token == null) {
      throw Exception('Token tidak ditemukan. Silakan login kembali.');
    }

    Uri url = Uri.parse('$baseUrl/payment/check-expiration/$orderId');
    http.Response response =
        await http.post(url, headers: headerWithToken(token));

    if (response.statusCode == 210) {
        print('transaksi SUDAH KEDALUARSA');
        return false;
      } else {
        print("Error memeriksa masa berlaku transaksi: ${response.body}");
        throw Exception('Gagal memeriksa status transaksi');
      }
  }
}
