import 'dart:convert';

import 'package:siro_rider/constant/api_key.dart';
import 'package:siro_rider/constant/box_name.dart';
import 'package:siro_rider/constant/info.dart';
import 'package:siro_rider/constant/links.dart';
import 'package:siro_rider/controller/auth/login_controller.dart';
import 'package:siro_rider/env/env.dart';
import 'package:siro_rider/main.dart';
import 'package:siro_rider/views/widgets/elevated_btn.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;

import '../../print.dart';
import '../auth/register_controller.dart';
import 'crud.dart';

class SmsEgyptController extends GetxController {
  var headers = {'Content-Type': 'application/json'};
  Future<String> getSender() async {
    var res = await CRUD().get(link: AppLink.getSender, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'][0]['senderId'].toString();
      return d;
    } else {
      return "Sefer Egy";
    }
  }

  Future<dynamic> sendSmsEgypt(String phone, otp) async {
    // String sender = await getSender();
    // var body = jsonEncode({
    //   "username": 'Sefer',
    //   "password": AK.smsPasswordEgypt,
    //   "message": "${AppInformation.appName} app code is $otp\ncopy it to app",
    //   "language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
    //   "sender": sender, //"Sefer Egy",
    //   "receiver": phone
    // });

    var res = await CRUD().post(link: AppLink.sendSmsFromPHP, payload: {
      "language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
      "receiver": phone,
    });
    if (res != 'failure') {
      // var res = await http.post(
      //   Uri.parse(AppLink.sendSms),
      //   body: body,
      //   headers: headers,
      // );

      // else if (jsonDecode(res)['message'].toString() ==
      //     "Invalid Sender with Connection") {
      //
      // }
      //  else {
      Get.defaultDialog(
          title: 'You will receive a code in SMS message'.tr,
          middleText: '',
          confirm: MyElevatedButton(
              title: 'OK'.tr,
              onPressed: () {
                Get.back();
              }));
    } else {
      await CRUD().post(link: AppLink.updatePhoneInvalidSMSPassenger, payload: {
        "phone_number":
            '+2${Get.find<RegisterController>().phoneController.text}'
      });
      box.write(BoxName.phoneDriver,
          '+2${Get.find<RegisterController>().phoneController.text}');
      box.write(BoxName.isVerified, '1');

      await Get.put(LoginController()).loginUsingCredentials(
        box.read(BoxName.driverID).toString(),
        box.read(BoxName.emailDriver).toString(),
      );
    }
  }

  Future checkCredit(String phone, otp) async {
    var res = await http.post(
      Uri.parse(AppLink.checkCredit),
      body: {
        "username": AppInformation.appName,
        "password": AK.smsPasswordEgypt,
      },
      headers: headers,
    );
  }

  Future sendSmsWithValidaty(String phone, otp) async {
    var res = await http.post(
      Uri.parse(AppLink.checkCredit),
      body: {
        "username": AppInformation.appName,
        "password": AK.smsPasswordEgypt,
        "message": "This is an example SMS message.",
        "language": box.read(BoxName.lang) == 'en' ? "e" : 'r',
        "sender": "Kazumi", // todo add sefer sender name
        "receiver": "2$phone",
        "validity": "10",
        "StartTime": DateTime.now().toString() // "1/1/2024 10:00:00"
      },
      headers: headers,
    );
  }

  Future sendSmsStatus(String smsid) async {
    var res = await http.post(
      Uri.parse(AppLink.checkCredit),
      body: {
        "username": AppInformation.appName,
        "password": AK.smsPasswordEgypt,
        "smsid": smsid //"00b77dfc-5b8f-474d-9def-9f0158b70f98"
      },
      headers: headers,
    );
  }

  Future sendWhatsAppAuth(String to, String token) async {
    var headers = {
      'Authorization': 'Bearer ${Env.whatsapp}',
      'Content-Type': 'application/json'
    };
    var request = http.Request(
        'POST',
        Uri.parse(
            'https://graph.facebook.com/v20.0/${Env.whatappID}/messages'));
    request.body = json.encode({
      "messaging_product": "whatsapp",
      "to": to, //"962798583052",
      "type": "template",
      "template": {
        "name": "sefer1",
        "language": {"code": "en"},
        "components": [
          {
            "type": "body",
            "parameters": [
              {
                "type": "text",
                "text": token,
              }
            ]
          }
        ]
      }
    });
    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
      Get.defaultDialog(
          title: 'You will receive a code in WhatsApp Messenger'.tr,
          middleText: '',
          confirm: MyElevatedButton(
              title: 'OK'.tr,
              onPressed: () {
                Get.back();
              }));
    } else {
      print(response.reasonPhrase);
    }
  }
}
