import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/models/course_model.dart';

class CourseByCategoryService {
  Future<List<CourseModel>> getCourseCategoryAndSub(categoryId, subId) async {
    print('ID kategori: $categoryId');
    print('ID SUb kategori: $subId');
    Uri url = Uri.parse(
        '$baseUrl/homepage/courses?category=$categoryId&subcategory=$subId');
    var header = {'Content-Type': 'application/json; charset=UTF-8'};
    var response = await http.get(url, headers: header);
    print(url);

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'][0];
      List<CourseModel> courseByCategory = [];
      for (var item in data) {
        courseByCategory.add(CourseModel.fromJson(item));
      }
      print("Berhasil kursus sub kategori ${response.body}");
      return courseByCategory;
    } else {
      print("Gagal kursus sub kategori ${response.body}");
      throw Exception('Gagal ambil data');
    }
  }

  Future<List<CourseModel>> getCourseOnlyCategory(categoryId) async {
    print('ID kategori: $categoryId');
    Uri url = Uri.parse('$baseUrl/homepage/courses?category=$categoryId');
    var header = {'Content-Type': 'application/json; charset=UTF-8'};
    var response = await http.get(url, headers: header);
    print(url);

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'][0];
      List<CourseModel> courseByCategory = [];
      for (var item in data) {
        courseByCategory.add(CourseModel.fromJson(item));
      }
      print("Berhasil kursus kategori ${response.body}");
      return courseByCategory;
    } else {
      print("Gagal kursus kategori ${response.body}");
      throw Exception('Gagal ambil data');
    }
  }
}
