import 'dart:convert';

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

class VoucherService {
  Future<VoucherModel> radeemVoucher(int? idCourse, String voucher) async {
    int? idUser = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse(
        '$baseUrl/users/coupon-payment?voucher=$voucher&course_id=$idCourse');

    http.Response response =
        await http.get(url, headers: headerWithToken(token!));
    print("Ini API nya ${url}");
    if (response.statusCode == 200) {
      print("Berhasil kupon ${response.body}");
      return VoucherModel.fromJson(jsonDecode(response.body));
    } else {
      print("gagal kupon ${response.body}");
      throw Exception('Gagal redeem voucher');
    }
  }

  Future<VoucherModel> redeemVoucherCart(
      List<String> idCourse, String voucher) async {
    int? idUser = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse('$baseUrl/users/voucher-cart');
    var body = jsonEncode({
      // "user_id": idUser,
      "courses_id": idCourse,
      "voucher": voucher,
    });

    http.Response response =
        await http.post(url, headers: headerWithToken(token!), body: body);
    if (response.statusCode == 201) {
      print("radeem voucher cart ${response.body}");
      return VoucherModel.fromJson(jsonDecode(response.body));
    } else {
      print("gagal radeem voucher cart ${response.body}");
      throw Exception('Gagal redeem voucher');
    }
  }

  Future<VoucherModel> cancelCoupon(coupon) async {
    Uri url = Uri.parse('$baseUrl/users/cancel-redeem-voucher/$coupon');
    String? token = await UsersInfo().getToken();
    http.Response response =
        await http.delete(url, headers: headerWithToken(token!));
    print(response.body);
    if (response.statusCode == 200) {
      print("cancel coupon ${response.body}");
      return VoucherModel.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Gagal Cancel Coupon');
    }
  }
}
