import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/modules/loan_module/models/loan_request_model.dart';
import 'dart:convert';

class LoanProvider extends ChangeNotifier {
  Future<bool> addLoanRequest(Map<String, dynamic> body) async {
    try {
      Response response = await ApiManager.instance.post(URLs.addLoan, body: body, showToast: false);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        String message = (jsonDecode(response.body)["data"] ?? "") + " " + (jsonDecode(response.body)["message"] ?? "");
        Fluttertoast.showToast(msg: message ?? "", toastLength: Toast.LENGTH_LONG);
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  }

  bool isLoading = false;

  Future<LoanRequestModel?> getLoanById(int id) async {
    LoanRequestModel? loanData;
    try {
      Response response = await ApiManager.instance.get(URLs.getLoanById + "?loanId=$id");
      if (response.statusCode >= 200 && response.statusCode < 300) {
        loanData = LoanRequestModel.fromJson(json.decode(response.body)["data"]);
      }
    } catch (error) {
      print(error);
    }
    return loanData;
  }

  Future<LoanRequestModel?> getLoanByWorkOrderId(int id) async {
    LoanRequestModel? loanData;
    try {
      Response response = await ApiManager.instance.get(URLs.getLoanByWorkOrderId + "?woId=$id", enableToastMessage: false);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        loanData = LoanRequestModel.fromJson(json.decode(response.body)["data"]);
      }
    } catch (error) {
      print(error);
    }
    return loanData;
  }

  Future<bool> loanWorkflowAction(Map<String, dynamic> body) async {
    try {
      Response response = await ApiManager.instance.post(URLs.loanWorkflowAction, body: body, showToast: true);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  }
}
