
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:healthcare_pharmacy/preloader.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'dart:async';
import 'package:geolocator/geolocator.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';


const Color primaryColor = Color(0XFFA78966);
const Color secondaryColor = Color(0XFFF0E0CC);
const Color buttonColor = Color(0XFF6A3632);
const Color buttonColors = Color(0XFFFFAC1C);

const Color greyColor = Color(0XFF8F8E8E);
const Color textFieldStartColor = Colors.grey;
const Color screenBackgroundColor = Color(0XFFEAF6FF);
const Color screenBackgroundColord = Colors.black12;
const Color dashboardbackground = Color(0XFFF5F5F5);

Color AppBarGradient_1 = Color(0XFF1258F6);

TextStyle PreloaderText() {
  return TextStyle(color: Colors.blueAccent);
}

TextStyle labelTextStyle() {
  return TextStyle(color: primaryColor, fontSize: 12);
}

TextStyle haveMotorTextStyle() {
  return TextStyle(color: Colors.red, fontSize: 12,fontWeight: FontWeight.bold);
}

TextStyle textButtonStyle() {
  return TextStyle(color: primaryColor, fontSize: 15);
}

TextStyle iconBelowTextStyle() {
  return TextStyle(fontSize: 10, color: primaryColor);
}

TextStyle valuesTextStyle() {
  return TextStyle(
    fontSize: 12,
    fontWeight: FontWeight.bold,
  );
}

TextStyle startAndStopHeading() {
  return TextStyle(
    fontSize: 14,
    fontWeight: FontWeight.bold,
      color: primaryColor,
  );
}
Text capacitySuffixText() {
  return Text('in Ltrs.');
}
Text dimensionSuffixText() {
  return Text('in fts');
}

TextStyle dashboardTextStyle() {
  return TextStyle(
    color: primaryColor,
    fontSize: 12,
    fontWeight: FontWeight.bold,
  );
}

TextStyle labelTextStyleBold() {
  return TextStyle(
    color: primaryColor,
    fontWeight: FontWeight.bold,
  );
}

TextStyle serverIssueTextStyle() {
  return TextStyle(color: Colors.red, fontSize: 15);
}
TextStyle bottomSheetValuesTextStyle() {
  return TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,);
}
TextStyle wrapTextStyle() {
  return TextStyle(color:primaryColor,fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,);
}
TextStyle wrapTextStyleBlack() {
  return TextStyle(color:Colors.black,fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,);
}
TextStyle withoutWrapTextStyle() {
  return TextStyle(color:primaryColor,fontSize: 12,fontWeight: FontWeight.bold,);
}

final GlobalKey<State> preloaderWindowKey = new GlobalKey<State>();
Future<void> preloaderWindow(BuildContext context) async {
  try {
    Dialogs.showLoadingDialog(context, preloaderWindowKey);
  } catch (error) {}
}


InputDecoration textFormFieldDecoration(IconData icon,var text){
  return InputDecoration(
    filled: true,
    fillColor: Colors.white,
    prefixIcon: Icon(
      icon,
      color: greyColor,
    ),
    border: OutlineInputBorder(borderSide: BorderSide(color: primaryColor)),
    focusedBorder: OutlineInputBorder(
      borderSide: BorderSide(color: primaryColor),
    ),
    enabledBorder: OutlineInputBorder(
      borderSide: BorderSide(color: primaryColor),
    ),
    labelText: text,
    labelStyle:
    TextStyle(color: Color(0xFF7A7575), fontWeight: FontWeight.bold //<-- SEE HERE
    ),
  );
}

class AppSettings {
  static SharedPreferences sharedPreferences =
      SharedPreferences.getInstance() as SharedPreferences;
  static String pharmacyName = '';
  static String MedecineName = '';
  static String pharmacyEmail = '';
  static String pharmacyPhone = '';
  static String pharmacyDescription= '';
  static String userAddress = '';
  static String email = '';
  static String phoneNumber = '';
  static String accessToken = '';
  static String pharmacyId = '';
  static double userLatitude = 0;
  static double userLongitude = 0;
  static String healthpharmaIdsign = '';
  static String healthpharmastaticid = '123456789';
  static String profileImage = '';
  static List<String> storedPreferenceValidKeys = ['pharmacyname', 'access_token'];
  static String preloadText = 'Please wait';
  static String latitude = '';
  static String longitude = '';
  static bool servicestatus = false;
  static bool haspermission = false;
  static late LocationPermission permission;
  static late Position position;
  static String qrCode = '';

  static String long = "", lat = "";
  late StreamSubscription<Position> positionStream;
  static String fcmId='';
  static String serverToken='AAAAA66BLaA:APA91bHcmbyiNN8hCL-t-M9oH-u7ZMOl74fcImMM2DQZLgdyY98Wu9XxME-CTPcjpjU6Yy48ouxISrOMb9lpa3PJofh8qciUKMNxV2al-bDvGvPP_VVaH0mrTHzR56hdkGy1Zl-0frDO';


  //api urls
  static String host = 'http://cloudh.in:4000/api/';
  static String loginUrl = host + 'pharmacylogin';
  static String signUpUrl = host + 'addPharmacy';
  static String updatePharmacyUrl = host + 'update/currentPharmacy';
  static String verifyPhnUrl = host + 'phone';
  static String profilePicUrl = host + 'users/profile-picture';
  static String uploadPicUrl = host + 'uploadsPharmacy';
  static String uploadOfferUrl = host + 'uploads-offerPicture';
  static String updateuploadOfferUrl = host + 'update-uploads-offerPicture';
  static String resetTokenUrl = host + 'reset_token';
  static String forgotPasswordUrl = host + 'forgotpassword';
  static String resetPasswordUrl = host + 'resetpassword';
  static String sendSmsUrl = host + 'sendSms';
  static String phoneVerificationUrl = host + 'pharmacyphone';
  static String createOffersUrl = host + 'addoffer';
  static String createCompanyOffersUrl = host + 'addcompanyoffer';
  static String getOffersActiveDataUrl = host + 'getActivePharmacyOfferdata';
  static String getApprovedOffersDataUrl = host + 'getapprovedPharmacyOfferdata';
  static String getOffersinActiveDataUrl = host + 'getInActivePharmacyOfferdata';
  static String updateOffersDataUrl = host + 'updateOffer';
  static String inactiveOffersDataUrl = host + 'inactiveOffer';
  static String reactiveOffersDataUrl = host + 'reactiveOffer';
  static String deleteOfferUrl = host + 'deleteOffer';
  static String discountOfferUrl = host + 'calculateTotalPriceWithDiscount';

  static String medecineDataUrl = host + 'medicine';
  static String getAllBiddingDataUrl = host + 'getBiddingRequests';
  static String getRequestBiddingDataUrl = host + 'statusBiddingRequest';
  static String addToCartDataUrl = host + 'cart/add';
  static String getCartDataUrl = host + 'cart/total-price';
  static String getCartFinalAmmountUrl = host + 'cart/final-price-with-gst';
  static String getPharmacyDataUrl = host + 'getAllPharmacylist';
  static String inviteFriendUrl = host + 'pharmacySendInviteLink';
  static String addDeliveryboyUrl = host + 'addDeliveryboys';
  static String getAllDeliverboyUrl = host + 'deliveryBoys';
  static String updateDeliveryboyUrl = host + 'editDeliveryBoy';
  static String deleteDeliveryboyUrl = host + 'deletedeliveryboy';
  static String getPharmacyAccountsUrl = host + 'pharmacyAccounts';
  static String generateQRCodeUrl = host + 'generate-qrcode-pharmacy';


  static File? updatedImage;
  static String image = '';
  static String profilePictureUrl = '';
  static String description = '';
  static String offerPictureUrl = '';

  static var api = {
    'signIn': host + '/login',
  };

  /*Formatter*/
  static String formNum(String s) {
    var comma = NumberFormat('#,##,###', 'en_IN');
    return comma.format(
      int.parse(s),
    );
  }

  static String formDouble(String s) {
    var comma = NumberFormat('#,##,###.##', 'en_IN');
    return comma.format(
      double.parse(s),
    );
  }
  TextStyle drawerHeaderTextStyleNew() {
    return TextStyle(color: Colors.black, fontSize: 15);
  }


  /* Preloader */
  static GlobalKey<State> preLoaderKey = new GlobalKey<State>();
  static Future<void> preLoaderDialog(BuildContext context) async {
    try {
      preLoaderKey = new GlobalKey<State>();
      Dialogs.showLoadingDialog(context, preLoaderKey);
    } catch (error) {}
  }

  ////request headers with content type
  static Future<Map<String, String>> buildRequestHeaders() async {
    Map<String, String> _headers = new Map<String, String>();
    _headers[HttpHeaders.contentTypeHeader] = 'application/json';
    _headers['Authorization'] = accessToken;
    return _headers;
  }

  //request headers without content type
  static Future<Map<String, String>> buildPutRequestHeaders() async {
    Map<String, String> _headers = new Map<String, String>();
    _headers['Authorization'] = accessToken;
    return _headers;
  }

  static Future<Map<String, String>> buildPutRequestHeadersForResetToken() async {
    Map<String, String> _headers = new Map<String, String>();
    return _headers;
  }

  // Shared preferences save,get and clear data
  static saveData(String _key, _value, type) async {
    sharedPreferences = await SharedPreferences.getInstance();

    if (type == 'STRING') {
      await sharedPreferences.setString(_key, _value.toString());
    } else if (type == 'INTEGER') {
      await sharedPreferences.setInt(_key, _value);
    } else if (type == 'BOOL') {
      await sharedPreferences.setBool(_key, _value);
    } else if (type == 'DOUBLE') {
      await sharedPreferences.setDouble(_key, _value);
    }
  }

  static getData(String _key, type) async {
    sharedPreferences = await SharedPreferences.getInstance();
    if (type == 'STRING') {
      return sharedPreferences.getString(_key) ?? '';
    } else if (type == 'INTEGER') {
      return sharedPreferences.getInt(_key) ?? -1;
    } else if (type == 'BOOL') {
      return sharedPreferences.getBool(_key) ?? -1;
    } else if (type == 'DOUBLE') {
      return sharedPreferences.getDouble(_key) ?? -1;
    }
  }


  static clearSharedPreferences() async {
    sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.clear();
  }

  /*Sign in check*/
  static Future<bool> isSigIn() async {
    bool isSignInCheck = true;
    for (var eachKey in storedPreferenceValidKeys) {
      if (await getData(eachKey, 'STRING') == '') {
        isSignInCheck = false;
      }
    }
    return isSignInCheck;
  }

  static Future<bool> internetConnectivity() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        return true;
      }
    } on SocketException catch (_) {
      return false;
    }
    return false;
  }

  /*Apis Starts here*/

  static Future<bool> login(payload) async {
    var response = await http.post(Uri.parse(loginUrl),
        body: json.encode(payload),
        headers: {'Content-type': 'application/json'});

    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response['simplydata']['error']);

        if (_response['simplydata']['error'] == false) {
          await saveAvailableReportAndLocationsInMemory(_response);
          //await saveProfilePic(_response);
          return true;
        } else {
          return false;
        }
      } catch (e) {
        // display error toast
        return false;
      }
    } else {
      return false;
    }
  }

  static Future<bool> signUp(payload) async {
    var response = await http.post(Uri.parse(signUpUrl),
        body: json.encode(payload),
        headers: {'Content-type': 'application/json'});

    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        healthpharmaIdsign = _response['armintahealthdata']['pharmacyId'];
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else {
      return false;
    }
  }



  static Future<String> generateQRCode() async {
    var uri = Uri.parse(generateQRCodeUrl + '/' + healthpharmaIdsign);

    var response = await http.post(uri, headers: await buildPutRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.post(uri, headers: await buildPutRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }


  static Future<bool> inviteFriend(payload) async {

    var uri = Uri.parse(inviteFriendUrl);
    uri = uri.replace(query: 'pharmacyId=$healthpharmaIdsign');
    var response = await http.post(uri,
        body: json.encode(payload), headers: await buildRequestHeaders());

    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.post(uri,
            body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  static Future<String> uploadImageHTTPNew(file) async {

    var request = http.MultipartRequest('POST', Uri.parse(uploadPicUrl + '/' + healthpharmaIdsign));
    request.files.add(await http.MultipartFile.fromPath('picture', file.path));
    var res = await request.send();
    var response = await http.Response.fromStream(res);
    return response.body;

  }


  static Future<String> offeruploadImageHTTPNew(file) async {

    var request = http.MultipartRequest('POST', Uri.parse(uploadOfferUrl + '/' + healthpharmaIdsign));
    request.files.add(await http.MultipartFile.fromPath('picture', file.path));
    var res = await request.send();
    var response = await http.Response.fromStream(res);
    return response.body;
  }

  static Future<bool> updatePharmaData(payload) async {
    try {
      var response = await http.put(
          Uri.parse(updatePharmacyUrl + '/' + healthpharmaIdsign),
          body: json.encode(payload),
          headers: await buildRequestHeaders());

      if (response.statusCode == 200) {
        var _response = json.decode(response.body);
        pharmacyName = _response['pharmacyname'];
        phoneNumber = _response['phone'];
        email = _response['emails'][0]['email'];
        pharmacyDescription = _response['description'];
        await saveData('pharmacyname', _response['simplydata']['pharmacyname'], 'STRING');
        await saveData('phone', _response['simplydata']['phone'], 'STRING');
        await saveData('description', _response['simplydata']['description'], 'STRING');
        await saveData('email', _response['simplydata']['email'][0]['email'], 'STRING');
        await loadDataFromMemory();
        return true;
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }

  static Future<bool> createOffers(payload) async {
    var uri = Uri.parse(createOffersUrl + '/' + healthpharmaIdsign);
    var response = await http.post(uri,
        body: json.encode(payload), headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.post(uri,
            body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  static Future<bool> deleteInActiveOffer(offerCode) async {
    var uri = Uri.parse(deleteOfferUrl + '/' + healthpharmaIdsign);
    uri = uri.replace(query: 'offer_code=$offerCode');

    try {
      var response =
      await http.put(uri, headers: await buildPutRequestHeaders());

      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response =
          await http.put(uri, headers: await buildPutRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }
  static Future<bool> createCompanyOffers(payload) async {
    var uri = Uri.parse('http://35.200.129.165:4000/api/addcompanyoffer/1234');
    var response = await http.post(uri,
        body: json.encode(payload), headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.post(uri,
            body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  static Future<String> getOffers() async {
    //path parameter
    var uri = Uri.parse(getOffersActiveDataUrl + '/' + healthpharmaIdsign);
    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  static Future<String> getApprovedOffers() async {
    //path parameter
    var uri = Uri.parse(getApprovedOffersDataUrl + '/' + healthpharmaIdsign);
    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }

  static Future<String> getCartDetails(bookingId) async {
    //path parameter
    var uri = Uri.parse(getCartDataUrl + '/' + bookingId);
   // uri = uri.replace(query: 'pharmacyId=$healthpharmaIdsign');
    var response = await http.get(uri, headers: await buildRequestHeaders());
    var responcedatatemp=jsonDecode(response.body);
    print("responcedata$responcedatatemp");
    print("responcedata$bookingId");
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  static Future<http.Response> addToCart(String orderId, String quantity, String price,String mName,String mtimings) async {
    var headers = {
      'Content-Type': 'application/json'
    };
    var body=json.encode({
      "bookingId": orderId,
      "items": [
        {
          "medicinename": mName,
          "quantity": quantity,
          "price": price,
          "medicine_timings":[
            {
              "medicine_timings":mtimings
            }
          ]
        }
      ]
    });
    print("Timintgs"+body.toString());
    var uri = Uri.parse(addToCartDataUrl);
    uri = uri.replace(query: 'pharmacyId=$healthpharmaIdsign');
    var response = await http.post(
      uri,
      headers: headers,
      body: body,
    );

    return response;
  }

  static Future<http.Response> cartFinalAmmount(String bookingId,String totalPrice, String priceGst, String additionalDiscont,) async {
    var headers = {
      'Content-Type': 'application/json'
    };
    var body=json.encode({
      "totalPrice": totalPrice,
      "gst": priceGst,
      "additional_discount": additionalDiscont
    });
    print("cartResponce"+body.toString());
    var uri = Uri.parse(getCartFinalAmmountUrl+ '/' + bookingId);
    var response = await http.post(
      uri,
      headers: headers,
      body: body,
    );

    return response;
  }





  static Future<String> getPharmacyData() async {
    var uri = Uri.parse(getPharmacyDataUrl);
    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  static Future<String> getAllBiddingRecords() async {
    //path parameter
    var uri = Uri.parse(getAllBiddingDataUrl + '/' + healthpharmaIdsign);
    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  static Future<bool> getRequestBiddingDetails(var bookingId,payload) async {
    var response = await http.put(Uri.parse(getRequestBiddingDataUrl + '/' + bookingId),
        body: json.encode(payload), headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.put(Uri.parse(getRequestBiddingDataUrl + '/' + bookingId),
            body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  static Future<String> getinactiveOffers() async {
    //path parameter
    var uri = Uri.parse(getOffersinActiveDataUrl + '/' + healthpharmaIdsign);
    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  static Future<String> offerupdateuploadImageHTTPNew(file, var offerCode) async {
    var request = http.MultipartRequest('POST', Uri.parse(updateuploadOfferUrl + '/' + healthpharmaIdsign+"/"+offerCode));
    request.files.add(await http.MultipartFile.fromPath('picture', file.path));
    var res = await request.send();
    var response = await http.Response.fromStream(res);
    if(response.statusCode==200){
      return response.body;
    }
    else{
      return 'error';
    }

  }
  static Future<bool> updateOffers(offer_code, payload) async {
    var uri = Uri.parse(updateOffersDataUrl + '/' + healthpharmaIdsign);
    uri = uri.replace(query: 'offer_code=$offer_code');
    try {
      var response = await http.put(uri,
          body: json.encode(payload), headers: await buildRequestHeaders());
      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response = await http.put(uri,
              body: json.encode(payload), headers: await buildRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }



  static Future<bool> discountOffer(String offerCode, String bookidID) async {
    try {
      // Construct the URL with offerCode as path parameter and bookidID as query parameter
      var uri = Uri.parse('$discountOfferUrl/$offerCode').replace(query: 'bookingId=$bookidID');

      // Make the HTTP request
      var response = await http.get(uri, headers: await buildPutRequestHeaders());

      // Check the response status
      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        // Handle 401 Unauthorized status if needed
        bool status = await AppSettings.resetToken();
        if (status) {
          // Retry the request after resetting the token
          response = await http.put(uri, headers: await buildPutRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        // Handle other status codes if needed
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }

  static Future<bool> deleteOffers(offer_code) async {
    var uri = Uri.parse(inactiveOffersDataUrl + '/' + healthpharmaIdsign);
    uri = uri.replace(query: 'offer_code=$offer_code');

    try {
      var response =
      await http.put(uri, headers: await buildPutRequestHeaders());

      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response =
          await http.put(uri, headers: await buildPutRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }
  static Future<bool> reactiveOffers(offer_code) async {
    var uri = Uri.parse(reactiveOffersDataUrl + '/' + healthpharmaIdsign);
    uri = uri.replace(query: 'offer_code=$offer_code');

    try {
      var response =
      await http.put(uri, headers: await buildPutRequestHeaders());

      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response =
          await http.put(uri, headers: await buildPutRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }
  static Future<bool> sendSms(payload) async{
    var response=await http.post(Uri.parse(sendSmsUrl),body: json.encode(payload), headers: {'Content-type': 'application/json'});
    if(response.statusCode==200){
      return true;
    }
    else{
      return false;
    }
  }
  static Future<String> getAllMedecines(var medicine) async {
    var uri = Uri.parse(medecineDataUrl + '/' + medicine);
    //uri = uri.replace(query: 'customerId=$customerId');

    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
  static Future<bool> phoneVerification(payload) async{
    var response=await http.post(Uri.parse(phoneVerificationUrl),body: json.encode(payload), headers: {'Content-type': 'application/json'});
    if(response.statusCode==200){
      return true;
    }
    else{
      return false;
    }
  }
  static Future<bool> resetToken() async {
    var uri = Uri.parse(resetTokenUrl + '/' + pharmacyId);

    try {
      // var response = await http.get(uri, headers: await buildPutRequestHeaders());
      var response = await http.get(uri,
          headers: await buildPutRequestHeadersForResetToken());
      if (response.statusCode == 200) {
        print(response.body);
        var res = jsonDecode(response.body);
        print(res);

        accessToken = res['access_token'];
        return true;
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }
  static Future<bool> verifyPhn(payload) async {
    var response = await http.post(Uri.parse(verifyPhnUrl),
        body: json.encode(payload),
        headers: {'Content-type': 'application/json'});

    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        if (_response['armintahealthdata']['error'] == false) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        // display error toast
        return false;
      }
    } else {
      return false;
    }
  }
  static Future<bool> updateProfilePicture(payload) async {
    var uri = Uri.parse(profilePicUrl + '/' + pharmacyId);
    var response = await http.post(uri,
        body: json.encode(payload), headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    }

    else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.post(uri,
            body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    }

    else {
      return false;
    }
  }


  static Future<bool> addDeliverboy(payload) async {
    var response = await http.post(Uri.parse(addDeliveryboyUrl + '/' + healthpharmaIdsign),
        body: json.encode(payload), headers: await buildRequestHeaders());

    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.post(Uri.parse(addDeliveryboyUrl + '/' + healthpharmaIdsign),
            body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }



  static Future<String> getAllDeliverboy() async {
    var response = await http.get(Uri.parse(getAllDeliverboyUrl + '/' + healthpharmaIdsign),
        headers: await buildRequestHeaders());

    if (response.statusCode == 200) {
      try {
        var _response = json.decode(response.body);
        print(_response);
        return response.body;
      } catch (e) {
        // display error toast
        return '';
      }
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(Uri.parse(getAllDeliverboyUrl + '/' + healthpharmaIdsign),
            headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return "";
        }
      } else {
        return "";
      }
    } else {
      return "";
    }
  }

  static Future<bool> updateDeliveryboy(phone, payload) async {
    var uri = Uri.parse(updateDeliveryboyUrl + '/' + healthpharmaIdsign);
    uri = uri.replace(query: 'phone=$phone');
    try {
      var response = await http.put(uri,
          body: json.encode(payload), headers: await buildRequestHeaders());
      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response = await http.put(uri,
              body: json.encode(payload), headers: await buildRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }
  static Future<bool> deleteDeliveryboy(phone) async {
    var uri = Uri.parse(deleteDeliveryboyUrl + '/' + healthpharmaIdsign);
    uri = uri.replace(query: 'phone=$phone');

    try {
      var response =
      await http.put(uri, headers: await buildPutRequestHeaders());

      if (response.statusCode == 200) {
        return true;
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response =
          await http.put(uri, headers: await buildPutRequestHeaders());
          if (response.statusCode == 200) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }


  static Future<String> getPharmacyAccounts() async {
    var uri = Uri.parse(getPharmacyAccountsUrl + '/' + healthpharmaIdsign);
    var response = await http.get(uri, headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await http.get(uri, headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }

  /*Apis ends here*/

  //save data local
  static Future<void> saveAvailableReportAndLocationsInMemory(
      dynamic input) async {
    // save login name information
    await saveData('pharmacyname', input['simplydata']['pharmacyname'], 'STRING');
    await saveData('phone', input['simplydata']['phone'], 'STRING');
    await saveData('email', input['simplydata']['email'][0]['email'], 'STRING');
    await saveData('description', input['simplydata']['description'], 'STRING');

    await saveData(
        'access_token', input['simplydata']['access_token'], 'STRING');
    await saveData('pharmacyId', input['simplydata']['pharmacyId'], 'STRING');
   // await saveData('customerId', input['simplydata']['customerId'], 'STRING');
    await saveData('profile', input['simplydata']['picture'], 'STRING');
    await saveData('pharmacy_address', input['simplydata']['pharmacy_address'], 'STRING');
    await saveData('latitude', input['simplydata']['latitude'], 'DOUBLE');
    await saveData('longitude', input['simplydata']['longitude'], 'DOUBLE');
   // await saveData('fcmId', input['simplydata']['fcmId'], 'STRING');
    //latitude,longitude
    await loadDataFromMemory();
  }
  
  static Future<void> saveProfile(dynamic image) async {
    // save login name information
    await saveData('profile', image.toString(), 'STRING');
    await saveData('description', image.toString(), 'STRING');
    await saveData('offer', image.toString(), 'STRING');

    //await loadDataFromMemory();
  }

  static Uint8List convertBase64Image(String base64String) {
    return Base64Decoder().convert(base64String.split(',').last);
  }

  static Future<void> loadDataFromMemory() async {
    pharmacyName = await getData('pharmacyname', 'STRING');
    accessToken = await getData('access_token', 'STRING');
    email = await getData('email', 'STRING');
    pharmacyName = await getData('description', 'STRING');
    userAddress = await getData('user_address', 'STRING');
    phoneNumber = await getData('phone', 'STRING');
    healthpharmaIdsign = await getData('pharmacyId', 'STRING');
    userLatitude = await getData('latitude', 'DOUBLE');
    profilePictureUrl=await getData('profile', 'STRING');
    profilePictureUrl=await getData('profile', 'STRING');
    offerPictureUrl=await getData('offer', 'STRING');
    userLongitude =await getData('longitude', 'DOUBLE');
    fcmId =await getData('fcmId', 'STRING');
  }

  /*static void longFailedToast(String message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }*/

  static void longFailedStyledToast(String message, context) {
    showToast(
      message,
      context: context,
      animation: StyledToastAnimation.scale,
      reverseAnimation: StyledToastAnimation.fade,
      position: StyledToastPosition.bottom,
      animDuration: Duration(seconds: 1),
      duration: Duration(seconds: 6),
      curve: Curves.elasticOut,
      reverseCurve: Curves.linear,
      backgroundColor: Colors.red,
    );
  }
  static void longFailedToast(String message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }
  static void longSuccessToast(String message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0);
  }


 /* static void longSuccessToast(String message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0);
  }*/


  static Widget noDataUI(String _tabName) {
    _tabName = _tabName ?? '';
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image(
            image: AssetImage('images/no_data.png'),
            width: 200,
          ),
          SizedBox(
            height: 8,
          ),
          Text(
            'There is no data to show you right now.',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
              fontFamily: 'Swis2',
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Text(
            _tabName,
            style: TextStyle(fontSize: 15, fontFamily: 'Swis1'),
          ),
        ],
      ),
    );
  }

  static appBar(String title) {
    title = title ?? '';
    return AppBar(
      backgroundColor: primaryColor,
      title: Text(title),
    );
  }

  /*location*/
  static checkGps() async {
    servicestatus = await Geolocator.isLocationServiceEnabled();
    if (servicestatus) {
      permission = await Geolocator.checkPermission();

      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
        if (permission == LocationPermission.denied) {
          print('Location permissions are denied');
        } else if (permission == LocationPermission.deniedForever) {
          print("'Location permissions are permanently denied");
        } else {
          haspermission = true;
        }
      } else {
        haspermission = true;
      }

      if (haspermission) {
        /*setState(() {
          //refresh the UI
        });*/

        await getLocation();
      }
    } else {
      print("GPS Service is not enabled, turn on GPS location");
    }
  }

  static getLocation() async {
    position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    /*print(position.longitude); //Output: 80.24599079
    print(position.latitude);*/ //Output: 29.6593457

    long = await position.longitude.toString();
    lat = await position.latitude.toString();

    /*setState(() {
      //refresh UI
    });*/

    LocationSettings locationSettings = LocationSettings(
      accuracy: LocationAccuracy.high, //accuracy of the location data
      distanceFilter: 100, //minimum distance (measured in meters) a
      //device must move horizontally before an update event is generated;
    );

    StreamSubscription<Position> positionStream =
        Geolocator.getPositionStream(locationSettings: locationSettings)
            .listen((Position position) {
      print(position.longitude); //Output: 80.24599079
      print(position.latitude); //Output: 29.6593457

      long = position.longitude.toString();
      lat = position.latitude.toString();

      /*setState(() {
        //refresh UI on update
      });*/
    });
  }
}
