import 'dart:convert';

import 'package:get/get.dart';
import 'package:http/http.dart' as http;

import '../../../constant/links.dart';
import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../main.dart';
import '../functions/crud.dart';

class PaymobPayout extends GetxController {
  bool isLoading = false;
  String dropdownValue = 'etisalat';

  Future<String> getToken() async {
    var headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      // 'Cookie':
      //     'csrftoken=74iZJ8XYyuTm5WRq2W4tpWX5eqoJLZVK5QhuDrChWpDtzpgGA269bbCWuEcW85t4'
    };
    var body = {
      'grant_type': 'password',
      'username': AK.payMobOutUserName,
      'password': AK.payMobOutPassword,
      'client_id': AK.payMobOutClient_id,
      'client_secret': AK.payMobOutClientSecrret
    };
    var res = await http.post(
      Uri.parse('https://payouts.paymobsolutions.com/api/secure/o/token/'),
      headers: headers,
      body: body,
    );
    String token = '';
    if (res.statusCode == 200) {
      var decode = jsonDecode(res.body);
      token = decode['access_token'];
    }
    return token;
  }

  payToDriverWallet(
      String token, String amount, String issuer, String msisdn) async {
    var headers = {
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    };
    var body = json.encode({
      "amount": amount, //"10.00",
      "issuer": issuer, //"vodafone",
      "msisdn": msisdn, // "01023456789"
    });
    var res = await http.post(
      Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
      headers: headers,
      body: body,
    );
    var dec = jsonDecode(res.body);
    if (dec['disbursement_status'] == 'successful') {
      await CRUD().post(link: AppLink.addDriverpayment, payload: {
        'rideId': DateTime.now().toIso8601String(),
        'amount': ((-1) * (double.parse(dec['amount'])) + 5).toStringAsFixed(0),
        'payment_method': 'payout',
        'passengerID': 'admin',
        'driverID': box.read(BoxName.driverID).toString(),
      });
      Get.snackbar('Transaction successful'.tr,
          '${'Transaction successful'.tr} ${dec['amount']}',
          backgroundColor: AppColor.greenColor);
      // Get.find<CaptainWalletController>().getCaptainWalletFromRide();
    } else if (dec['disbursement_status'] == 'failed') {
      Get.snackbar('Transaction failed'.tr, 'Transaction failed'.tr,
          backgroundColor: AppColor.redColor);
    }
  }

  payToDriverBankAccount(String token, String amount, String bankCardNumber,
      String bankCode) async {
    var headers = {
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    };
    var body = {
      "issuer": "bank_card",
      "amount": amount, //9.0,
      "full_name":
          '${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
      "bank_card_number": bankCardNumber, //"1111-2222-3333-4444",
      "bank_code": bankCode, //"CIB",
      "bank_transaction_type": "cash_transfer"
    };
    var res = await http
        .post(
          Uri.parse('https://payouts.paymobsolutions.com/api/secure/disburse/'),
          headers: headers,
          body: body,
        )
        .then((value) {});
  }

  Future payToWalletDriverAll(
      String amount, String issuer, String msisdn) async {
    String token = await getToken();
    await payToDriverWallet(token, amount, issuer, msisdn);
  }

  Future payToBankDriverAll(
      String amount, String bankCardNumber, String bankCode) async {
    String token = await getToken();
    await payToDriverBankAccount(token, amount, bankCardNumber, bankCode);
  }
}
