import 'dart:convert';

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

class LessonCourseService {
  Future<LessonCourseModel> getLessonCourse(int id) async {
    String? token = await UsersInfo().getToken();
    int? idUser = await UsersInfo().getIdUser();

    // Uri url =
    //     Uri.parse('$baseUrl/users/course/my/lesson?course=$id&user=$idUser');
    Uri url = Uri.parse('$baseUrl/users/course/my/lesson?course=$id');

    http.Response response =
        await http.get(url, headers: headerWithToken(token!));
    print(token);
    print("disiiniii les ---->" + response.body);
    if (response.statusCode == 200) {
      return LessonCourseModel.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Data Lesson Kursus Saya, Gagal Diambil');
    }
  }

  Future<SectionModel> getSectionCourse(int id) async {
    String? token = await UsersInfo().getToken();
    int? idUser = await UsersInfo().getIdUser();

    Uri url = Uri.parse(
        '$baseUrl/users/course/my/lesson?course=$id&user=$idUser&is_mobile_request=1');

    http.Response response =
        await http.get(url, headers: headerWithToken(token!));
    print("disiiniii sect ---->" + response.body);
    if (response.statusCode == 200) {
      return SectionModel.fromJson(jsonDecode(response.body));
    } else {
      print('masuk sini juga');
      throw Exception('Data Lesson Kursus Saya, Gagal Diambil');
    }
  }

  Future updateLessonCourse(lessonId, {progress = 1}) async {
    int? idUser = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();
    var body = jsonEncode({
      "id_user": idUser,
      "lesson_id": lessonId,
      "progress": progress,
    });
    Uri url = Uri.parse('$baseUrl/users/lesson/update/progress');
    http.Response response =
        await http.post(url, headers: headerWithToken(token!), body: body);
    print(response.body);
    if (response.statusCode == 200) {
      return response.statusCode;
    } else {
      print(response.statusCode);
      print('TERJADI ERROR DALAM UPDATE CEKLIS');
      // throw Exception('Gagal Update');
    }
  }
}
