import 'dart:convert';

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

class CategoriesService {
  Future<List<CategoriesModel>> getAllCategories() async {
    Uri url = Uri.parse('$baseUrl/homepage/categories');

    var header = {'Content-Type': 'application/json; charset=UTF-8'};
    var response = await http.get(url, headers: header);

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'][0];
      List<CategoriesModel> categories = [];
      int categoriesAdded = 0;

      for (var item in data) {
        if (item['parent_category'] == '0' && categoriesAdded < 9) {
          categories.add(CategoriesModel.fromJson(item));
          categoriesAdded++;
        }
      }

      return categories;
    } else {
      throw Exception('Gagal ambil data');
    }
  }

  Future<List<SubCategoryModel>> getSubCategories(String id) async {
    Uri url = Uri.parse('$baseUrl/homepage/subcategories/$id');
    var header = {'Content-Type': 'application/json; charset=UTF-8'};
    var response = await http.get(url, headers: header);

    if (response.statusCode == 200) {
      List<dynamic> data = jsonDecode(response.body);
      List<SubCategoryModel> subCategories = data
          .map((subCategoryJson) => SubCategoryModel.fromJson(subCategoryJson))
          .toList();
      return subCategories;
    } else {
      throw Exception('Failed to load subcategories');
    }
  }
}
