import 'package:dio/dio.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/models/home/home_models.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/utils/result/result.dart';

class HomeApi {
  getTodayMeetings() async {
    Map<String, String> headers = {
      'Accept': 'application/json',
    };
    String dataToken = setting.userLocalDb.getUser().token!;
    if (dataToken != '') {
      headers['Authorization'] = "Bearer $dataToken";
    }
    final String link =
        "${config.network.baseUrl}today-meetings?lang=${setting.userLocalDb.getUser().language}";

    final response = await Dio().get(link,
        options: Options(
          headers: headers,
        ));
    TodayMeetingModel list = TodayMeetingModel.fromJson(response.data);

    return list;
  }

// log out
  Future<Result?> logOutApi() async {
    try {
      Map<String, String> headers = {"Accept": "application/json"};

      String dataToken = setting.userLocalDb.getUser().token!;
      if (dataToken != '') {
        headers['Authorization'] = "Bearer $dataToken";
      }

      final res = await Dio().post("${config.network.baseUrl}admin/logout",
          options: Options(headers: headers));

      if (res.statusCode == 200 || res.statusCode == 201) {
        setting.userLocalDb.logOut();
        return const Result(isOk: true);
      }
    } on DioException catch (e) {
      // print(e);
      // print(e.response!.data);
      return Result(
          isOk: false,
          errors: e.response!.data['errors'],
          message: e.response!.data['message']);
    }
    return const Result(isOk: false);
  }

// edit profile

  Future<Result?> editProfile({String? name, String? password}) async {
    try {
      Map<String, String> headers = {"Accept": "application/json"};

      String dataToken = setting.userLocalDb.getUser().token!;
      if (dataToken != '') {
        headers['Authorization'] = "Bearer $dataToken";
      }

      final res = await Dio().post("${config.network.baseUrl}edit-profile",
          options: Options(
            headers: headers,
          ),
          queryParameters: {'name': name, 'password': password});

      if (res.statusCode == 200 || res.statusCode == 201) {
        if (name != null) {
          setting.userLocalDb.saveUserField('name', name);
        }
        return const Result(isOk: true);
      }
    } on DioException catch (e) {
      // print(e);
      // print(e.response!.data);
      return Result(
          isOk: false,
          errors: e.response!.data['errors'],
          message: e.response!.data['message']);
    }
    return const Result(isOk: false);
  }
}
