import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:supplier_new/common/preloader.dart';
import 'package:supplier_new/resources/source_loctaions_model.dart';

import '../resources/drivers_model.dart';
import '../resources/tankers_model.dart';

const Color primaryColor = Color(0XFF8270DB);
const Color secondaryColor = Color(0XFFBFE0ED);
const Color greyColor = Color(0XFF7E7F80);

TextStyle fontTextStyle(double fontSize,Color fontColor,FontWeight weight) {
  return  GoogleFonts.inter(
    textStyle: TextStyle(
      fontSize: fontSize,
      fontWeight: weight,
      color:fontColor,
    ),
  );
}

TextStyle fontTextStylewithUnderline(double fontSize,Color fontColor,FontWeight weight, Color underlineColor) {
  return  GoogleFonts.inter(
    textStyle: TextStyle(
      fontSize: fontSize,
      fontWeight: weight,
      color:fontColor,
      decoration: TextDecoration.underline,
      decorationColor: underlineColor,
      decorationThickness: 1,
    ),
  );
}

TextStyle fontTextStyleHeight(double fontSize,Color fontColor,FontWeight weight,double height) {
  return  GoogleFonts.inter(
    textStyle: TextStyle(
        fontSize: fontSize,
        fontWeight: weight,
        color:fontColor,
        height: height
    ),
  );
}

TextStyle fontTextStyleUnderline(double fontSize,Color fontColor,FontWeight weight) {
  return  GoogleFonts.inter(
    textStyle: TextStyle(
      fontSize: fontSize,
      fontWeight: weight,
      color:fontColor,
      decoration: TextDecoration.underline,
    ),
  );
}

InputDecoration textFormFieldDecoration(IconData icon,var text){
  return InputDecoration(
    counterText: '',
    filled: false,
    fillColor: Colors.white,
    /*prefixIcon: Icon(
      icon,
      color: Colors.white,
    ),*/
    border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(4.0),
        borderSide: BorderSide(color: greyColor,
          width: 1,    )),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(4.0),
      borderSide: BorderSide(color: Color(0XFF8270DB),width: 2,),
    ),

    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(4.0),
      borderSide: BorderSide(color: greyColor),
    ),
    labelText: text,
    labelStyle:fontTextStyle(14,Color(0XFF7E7F80),FontWeight.w400),
    /*  TextStyle(color: greyColor, fontWeight: FontWeight.bold //<-- SEE HERE
    ),*/
  );
}

InputDecoration textFormFieldDecorationHintText(IconData icon,var text){
  return InputDecoration(
    counterText: '',
    filled: false,
    fillColor: Colors.white,
    /*prefixIcon: Icon(
      icon,
      color: Colors.white,
    ),*/
    border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(15.0),
        borderSide: BorderSide(color: greyColor,
          width: 1,    )),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(15.0),
      borderSide: BorderSide(color: Color(0XFF8270DB),width: 2,),
    ),

    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(15.0),
      borderSide: BorderSide(color: greyColor),
    ),
    hintText: text,
    hintStyle:fontTextStyle(14,Color(0XFF7E7F80),FontWeight.w400),
    /*  TextStyle(color: greyColor, fontWeight: FontWeight.bold //<-- SEE HERE
    ),*/
  );
}

TextStyle PreloaderText() {
  return TextStyle(color:primaryColor);
}

class AppSettings{
  static SharedPreferences sharedPreferences =
  SharedPreferences.getInstance() as SharedPreferences;

  static File? updatedImage;
  static String image = '';
  static String userName = '';
  static String loginType = '';
  static String accessType = '';
  static String buildingName = '';
  static String userAddress = '';
  static String email = '';
  static String phoneNumber = '';
  static String accessToken = '';
  static String supplierId = '';
  static double supplierLatitude = 0;
  static double supplierLongitude = 0;
  static String customerIdsign = '';
  static String profileImage = '';
  static String preloadText = 'Please wait';
  static String profilePictureUrl = '';

  static String host = 'http://armintaaqua.com:3000/api/';
  static String loginUrl = host + 'supplierlogin';
  static String signUpUrl = host + 'suppliers';
  static String forgotPasswordUrl = host + 'forgotpassword';
  static String sendSmsUrl = host + 'sendSmstocreatesupplier';
  static String resetTokenUrl = host + 'reset_token';
  static String verifyPhnUrl = host + 'supplierphone';
  static String uploadPicUrl = host + 'uploads_supplier_profile';
  static String getOrderRequestsFromUsersUrl = host + 'getuserRequestbookingsforsupplier';
  static String acceptOrderRequestsUrl = host + 'request-booking-with-charges';
  static String getAcceptedOrdersFromUsersUrl = host + 'getAllTankersBookingdetails';
  static String getPlanRequestsFromUsersUrl = host + 'getuserRequestbookingsforplansforsupplier';
  static String acceptPlanRequestsUrl = host + 'supplier/recurring/respond';
  static String acceptPlanRequestsUrl1 = host + 'recurringRequestedBooking';
  static String getTankersUrl = host + 'getTankers';
  static String getTankerDetailsByNameUrl = host + 'getsingledetails';
  static String addTankerUrl = host + 'addTankers';
  static String updateTankerAvailabilityUrl = host + 'updatetankerstatus';
  static String deleteTankerUrl = host + 'deleteTanker';
  static String updateTankerUrl = host + 'updateTankers';
  static String getTankerTripsUrl = host + 'tankerAccounts';
  static String getDriversUrl = host + 'getalldeliveryboys';
  static String addDriversUrl = host + 'addDeliveryboys';
  static String updateDriversUrl = host + 'updatedeliveryboy';
  static String deleteDriverUrl = host + 'deletedeliveryboy';
  static String addSourceLocationsUrl = host + 'addSource';
  static String updateSourceLocationsUrl = host + 'sources';
  static String deleteSourceUrl = host + 'sources';
  static String getSourceLoctaionsUrl = host + 'getallsourcesofsupplier';
  static String getSourceDetailsByIdUrl = host + 'sources';
  static String setRatesDailyUrl = host + 'tankers';
  static String getSupplierDetailsUrl = host + 'suppliers';
  static String updatePumpFeeUrl = host + 'suppliers';
  static String assignTankerUrl = host + 'assign-deliveryboy-tanker';
  static String getDriverDetailsByPhoneUrl = host + 'getsingledeliveryboydetails';
  static String getAcceptedRecurringBookingsUrl = host + 'supplier/recurring';
  static String getAllTransactionsUrl = host + 'supplierAccounts';
  static String getAdvanceTransactionsBySupplierUrl = host + 'advance/transactions/supplier';
  static String createAdvanceRequestUrl = host + 'advance/request';
  static String acceptAdvanceFromCustomerUrl   = host + 'advance/confirm';
  static String getAdvanceTransactionsBySupplierAndCustomerUrl   = host + 'advance/transactions';
  static String respondRecurringBookingUrl   = host + 'customer/recurring/respond';
  static String getSupplierBookingsUrl   = host + 'getuserRequestbookingsforplansforsupplier';
  static String recurringDateActionUrl   = host + 'recurring-booking/date-action';
  static String cancelTankerBookingUrl   = host + 'update-tank-cancel-status';
  static String rejectPlanRequestUrl   = host + 'rejectplans';
  static String pendingCustomersUrl = host + 'pendingCustomers';
  static String connectedCustomersUrl = host + 'connectedCustomers';
  static String acceptRequestUrl = host +"friend-request/accept";
  static String rejectRequestUrl = host +"friend-request/reject";
  static String getDriverTripsUrl = host +"getdeliveryboybookings";
  static String verifyUnloadStartOTPUrl = host + 'deliveryboystartandstop';
  static String amountpaidByCustomerUrl = host + 'amountpaidByCustomer';


  static int driverAvailableCount = 0;
  static int driverOnDeliveryCount = 0;
  static int driverOfflineCount = 0;
  static int totalDrivers = 0;

  static int tankerActiveCount = 0;
  static int tankerMaintenanceCount = 0;
  static int totalTankers = 0;

  static int resourcesInitialTab = 0;
  static List<String> existingCreditCustomerIds = [];

  static String moneyConvertion(String value) {
    var comma = NumberFormat('#,##,###.00', 'en_IN');
    return comma.format(
      double.parse(value),
    );
  }

  static String formDouble(dynamic s) {
    var comma = NumberFormat('#,##,###.##', 'en_IN');

    if (s == null) return "0.00";

    String str = s.toString().trim();
    if (str.isEmpty) return "0.00";

    try {
      return comma.format(double.parse(str));
    } catch (e) {
      return "0.00"; // fallback if it's not a valid number
    }
  }

  // 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();
  }

  /* 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) {}
  }


  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;
  }

  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;
  }

  static Future<Map<String, String>>
  buildPutRequestHeadersForResetToken() async {
    Map<String, String> _headers = new Map<String, String>();
    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;
  }

  /*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);
        return true;
      } catch (e) {
        // display error toast
        return false;
      }
    } else {
      return false;
    }
  }

  static Future<bool> resetToken() async {
    var uri = Uri.parse(resetTokenUrl + '/' + supplierId);

    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> getOtp(payload) async {
    var uri = Uri.parse(sendSmsUrl);
    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> 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['armintatankdata']['error'] == false) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        // display error toast
        return false;
      }
    } else {
      return false;
    }
  }

  static Future<String> uploadrofileImageHTTPNew(file) async {
    var request = http.MultipartRequest(
        'POST', Uri.parse(uploadPicUrl + '/' + supplierId));
    request.files.add(await http.MultipartFile.fromPath('file', file.path));
    var res = await request.send();
    var response = await http.Response.fromStream(res);
    return response.body;
  }

  static Future<String> getOrderRequestsFromUsers() async {
    var uri = Uri.parse(getOrderRequestsFromUsersUrl+'/'+supplierId);
    //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> acceptOrderRequests(payload,dbId) async {

    var uri = Uri.parse(acceptOrderRequestsUrl+'/'+dbId+'/supplier/quote');

    var response = await http.post(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.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> getAcceptedOrdersFromUsers() async {
    var uri = Uri.parse(getAcceptedOrdersFromUsersUrl+'/'+supplierId);
    //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<String> getPlanRequestsFromUsers() async {
    var uri = Uri.parse(getPlanRequestsFromUsersUrl+'/'+supplierId);
    //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> acceptPlanRequests(payload,dbId) async {

    var uri = Uri.parse(acceptPlanRequestsUrl1+'/'+dbId+'/action');

    var response = await http.post(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.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> getTankers() async {
    var uri = Uri.parse(getTankersUrl);
    uri = uri.replace(query: 'supplierId=$supplierId');

    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<TankersModel?> getTankerDetailsByName(String tankerName) async {
    try {
      var uri = Uri.parse("$getTankerDetailsByNameUrl/$supplierId");
      uri = uri.replace(query: 'tankerName=$tankerName');

      var response = await http.get(uri, headers: await buildRequestHeaders());

      if (response.statusCode == 200) {
        final decoded = jsonDecode(response.body);

        if (decoded['data'] != null &&
            decoded['data'] is List &&
            decoded['data'].isNotEmpty) {
          return TankersModel.fromJson(decoded['data'][0]); // ✅ return model
        } else {
          debugPrint("⚠️ No tanker data found in response");
          return null;
        }
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response = await http.get(uri, headers: await buildRequestHeaders());
          if (response.statusCode == 200) {
            final decoded = jsonDecode(response.body);
            if (decoded['data'] != null &&
                decoded['data'] is List &&
                decoded['data'].isNotEmpty) {
              return TankersModel.fromJson(decoded['data'][0]); // ✅ model again
            }
          }
        }
        return null;
      } else {
        debugPrint("❌ Failed: ${response.statusCode}");
        return null;
      }
    } catch (e) {
      debugPrint("⚠️ getTankerDetailsByName() error: $e");
      return null;
    }
  }

  static Future<bool> addTankers(payload) async {

    var uri = Uri.parse(addTankerUrl + '/' + supplierId);

    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 == 2083) {
      AppSettings.longFailedToast('Tanker name already exists');
      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<Map?> addTankersWithResponse(payload) async {

    var uri = Uri.parse(addTankerUrl + '/' + supplierId);

    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 FULL DATA
        return _response;

      }
      catch (e) {

        return null;

      }

    }

    else if (response.statusCode == 2083) {

      AppSettings.longFailedToast(
          'Tanker name already exists'
      );

      return null;

    }

    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) {

          var _response =
          json.decode(response.body);

          return _response["data"];

        }

        else {

          return null;

        }

      }

      else {

        return null;

      }

    }

    else {

      return null;

    }

  }


  static Future<bool> updateTanker(payload,tankerName) async {
    var uri = Uri.parse(updateTankerUrl+'/'+supplierId);
    uri = uri.replace(query: 'tankerName=$tankerName');

    var response = await http.put(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.put(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> updateTankerAvailability(payload) async {

    var uri = Uri.parse(updateTankerAvailabilityUrl + '/' + supplierId);
    var response = await http.put(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.put(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> deleteTanker(tankerName) async {

    var uri = Uri.parse(deleteTankerUrl + '/' + supplierId);
    uri = uri.replace(query: 'tankerName=$tankerName');
    var response = await http.put(uri, headers: await buildPutRequestHeaders());

    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, headers: await buildPutRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  static Future<String> getTankerTrips(payload) async {
    var uri = Uri.parse(getTankerTripsUrl+ '/' + supplierId);

    var response = await http.put(uri, body: json.encode(payload), 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.put(uri, body: json.encode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }

  static Future<DriversModel?> getDriverDetailsByPhone(String phone) async {
    try {
      var uri = Uri.parse("$getDriverDetailsByPhoneUrl/$phone");

      var response = await http.get(uri, headers: await buildRequestHeaders());

      if (response.statusCode == 200) {
        final decoded = jsonDecode(response.body);

        if (decoded['data'] != null &&
            decoded['data'] is List &&
            decoded['data'].isNotEmpty) {
          return DriversModel.fromJson(decoded['data'][0]); // ✅ Correct model
        } else {
          debugPrint("⚠️ No driver data found in response");
          return null;
        }
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response = await http.get(uri, headers: await buildRequestHeaders());
          if (response.statusCode == 200) {
            final decoded = jsonDecode(response.body);
            if (decoded['data'] != null &&
                decoded['data'] is List &&
                decoded['data'].isNotEmpty) {
              return DriversModel.fromJson(decoded['data'][0]); // ✅ again
            }
          }
        }
        return null;
      } else {
        debugPrint("❌ Failed: ${response.statusCode}");
        return null;
      }
    } catch (e) {
      debugPrint("⚠️ getDriverDetailsByPhone() error: $e");
      return null;
    }
  }

  static Future<String> getDrivers() async {
    var uri = Uri.parse(getDriversUrl+'/'+supplierId);
    //uri = uri.replace(query: 'supplierId=$supplierId');

    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> addDrivers(payload) async {

    var uri =Uri.parse(addDriversUrl + '/' + supplierId);
    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> updateDrivers(payload,phone) async {

    var uri =Uri.parse(updateDriversUrl + '/' + supplierId);
    uri = uri.replace(query: 'phone=$phone');

    var response = await http.put (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.put (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> deleteDriver(driverPhone) async {

    var uri = Uri.parse(deleteDriverUrl + '/' + supplierId);
    uri = uri.replace(query: 'phone=$driverPhone');
    var response = await http.put(uri, headers: await buildPutRequestHeaders());

    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, headers: await buildPutRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  static Future<String> getSourceLoctaions() async {
    var uri = Uri.parse(getSourceLoctaionsUrl+'/'+supplierId);
    //uri = uri.replace(query: 'supplierId=$supplierId');

    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<SourceLocationsModel?> getSourceDetailsById(String dbId) async {
    try {
      var uri = Uri.parse("$getSourceDetailsByIdUrl/$dbId");
      var response = await http.get(uri, headers: await buildRequestHeaders());

      if (response.statusCode == 200) {
        final decoded = jsonDecode(response.body);

        if (decoded['data'] != null) {
          return SourceLocationsModel.fromJson(decoded['data']); // ✅ correct
        } else {
          debugPrint("⚠️ No source data found in response");
          return null;
        }
      } else if (response.statusCode == 401) {
        bool status = await AppSettings.resetToken();
        if (status) {
          response = await http.get(uri, headers: await buildRequestHeaders());
          if (response.statusCode == 200) {
            final decoded = jsonDecode(response.body);
            if (decoded['data'] != null) {
              return SourceLocationsModel.fromJson(decoded['data']); // ✅ again
            }
          }
        }
        return null;
      } else {
        debugPrint("❌ Failed: ${response.statusCode}");
        return null;
      }
    } catch (e) {
      debugPrint("⚠️ getSourceDetailsById() error: $e");
      return null;
    }
  }

  static Future<bool> addSourceLocations(payload) async {

    var uri = Uri.parse(addSourceLocationsUrl + '/' + supplierId);
    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> updateSourceLocations(payload,dbId) async {

    var uri =Uri.parse(updateSourceLocationsUrl + '/' + dbId);

    var response = await http.put (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.put (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> deleteSource(dbId) async {

    var uri = Uri.parse(deleteSourceUrl + '/' + dbId);
    var response = await http.delete (uri, headers: await buildPutRequestHeaders());

    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.delete (uri, headers: await buildPutRequestHeaders());
        if (response.statusCode == 200) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  static Future<bool> setRatesDaily(payload) async {
    var uri = Uri.parse(setRatesDailyUrl + '/' + supplierId+'/update-prices');

    var response = await http.put(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.put(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> getSupplierDetails() async {
    var uri = Uri.parse(getSupplierDetailsUrl+'/'+supplierId);
    //uri = uri.replace(query: 'supplierId=$supplierId');

    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> updatePumpFee(payload) async {

    var uri =Uri.parse(updatePumpFeeUrl + '/' + supplierId+'/pumping-fee');
    var response = await http.put(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.put(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> assignTanker(payload,dbId) async {

    var uri = Uri.parse(assignTankerUrl+'/'+dbId+'/supplier/assigntanker');

    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;
    }
  }

  static Future<String> getAcceptedRecurringBookings() async {
    var uri = Uri.parse("$getAcceptedRecurringBookingsUrl/${AppSettings.supplierId}/accepted");
    //uri = uri.replace(query: 'supplierId=$supplierId');

    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> getSupplierTransactions() async {
    var uri = Uri.parse("$getAllTransactionsUrl/${AppSettings.supplierId}");
    //uri = uri.replace(query: 'supplierId=$supplierId');

    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> getAdvanceTransactionsBySupplier() async {
    var uri = Uri.parse("$getAdvanceTransactionsBySupplierUrl/${AppSettings.supplierId}");
    //uri = uri.replace(query: 'supplierId=$supplierId');

    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> createAdvanceRequest(Map<String, dynamic> payload,) async {
    var uri = Uri.parse("$createAdvanceRequestUrl");

    var response = await http.post(
      uri,
      body: json.encode(payload),
      headers: await buildRequestHeaders(),
    );

    if (response.statusCode == 200) {
      return true;
    }

    // 🔁 Token expired → retry
    if (response.statusCode == 401) {
      final status = await AppSettings.resetToken();

      if (status) {
        response = await http.post(
          uri,
          body: json.encode(payload),
          headers: await buildRequestHeaders(),
        );

        return response.statusCode == 200;
      }
    }

    return false;
  }

  static Future<bool> acceptAdvanceFromCustomer(Map<String, dynamic> payload,) async {
    var uri = Uri.parse("$acceptAdvanceFromCustomerUrl");

    var response = await http.post(
      uri,
      body: json.encode(payload),
      headers: await buildRequestHeaders(),
    );

    if (response.statusCode == 200) {
      return true;
    }

    // 🔁 Token expired → retry
    if (response.statusCode == 401) {
      final status = await AppSettings.resetToken();

      if (status) {
        response = await http.post(
          uri,
          body: json.encode(payload),
          headers: await buildRequestHeaders(),
        );

        return response.statusCode == 200;
      }
    }

    return false;
  }

  static Future<bool> confirmAdvanceReceived(String transactionId, String action,) async {
    try {
      var uri = Uri.parse("$acceptAdvanceFromCustomerUrl/$transactionId");

      var payload = json.encode({
        "action": action, // "accept"
      });

      var response = await http.put(uri, body: payload, headers: await buildRequestHeaders(),);

      if (response.statusCode == 200) {
        return true;
      }

      // 🔁 Token expired → retry
      if (response.statusCode == 401) {
        bool refreshed = await resetToken();
        if (!refreshed) return false;

        response = await http.put(
          uri,
          body: payload,
          headers: await buildRequestHeaders(),
        );

        return response.statusCode == 200;
      }

      return false;
    } catch (e) {
      debugPrint("❌ confirmAdvanceReceived error: $e");
      return false;
    }
  }

  static Future<String> getAdvanceTransactionsBySupplierAndCustomer(
      String supplierId,
      String customerId,
      ) async {
    var uri = Uri.parse("$getAdvanceTransactionsBySupplierAndCustomerUrl/$supplierId/$customerId");


    final response = await http.get(
      uri,
      headers: await buildRequestHeaders(),
    );

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception("Failed to fetch transactions");
    }
  }

  static Future<Map<String, dynamic>> respondRecurringBooking({
    required String bookingId,
    required String supplierId,
    required String action, // "accept" | "reject"
  }) async {

    var uri = Uri.parse("$respondRecurringBookingUrl/$bookingId");

    final response = await http.post(
      uri,
      headers: await buildRequestHeaders(),
      body: jsonEncode({
        "supplierId": supplierId,
        "action": action,
      }),
    );

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception("Failed to respond booking");
    }
  }

  static Future<String> getSupplierBookings() async {
    var uri = Uri.parse("$getSupplierBookingsUrl/${AppSettings.supplierId}");


    final response = await http.get(
      uri,
      headers: await buildRequestHeaders(),
    );

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception("Failed to fetch transactions");
    }
  }

  static Future<void> recurringDateAction(
      String bookingId,
      Map<String, dynamic> payload,
      ) async {

    final url = Uri.parse("$recurringDateActionUrl/${bookingId}");


    final response = await http.post(
      url,
      headers: await buildRequestHeaders(),
      body: jsonEncode(payload),
    );

    if (response.statusCode != 200) {
      throw Exception(
        "Recurring date action failed: ${response.body}",
      );
    }
  }

  static Future<bool> cancelTankerBooking(
      String bookingId,
      String status,
      String reason,
      ) async {
    try {
      var uri = Uri.parse("$cancelTankerBookingUrl/$bookingId");

      var payload = json.encode({
        "status": status,      // "cancelled"
        "reason": reason,
      });

      var response = await http.put(
        uri,
        body: payload,
        headers: await buildRequestHeaders(),
      );

      if (response.statusCode == 200) {
        return true;
      }

      // 🔁 Token expired → retry
      if (response.statusCode == 401) {
        bool refreshed = await resetToken();
        if (!refreshed) return false;

        response = await http.put(
          uri,
          body: payload,
          headers: await buildRequestHeaders(),
        );

        return response.statusCode == 200;
      }

      return false;
    } catch (e) {
      debugPrint("❌ cancelTankerBooking error: $e");
      return false;
    }
  }

  static Future<Map<String, dynamic>> rejectPlan({
    required String planId,
    required String reason,
  }) async {

    final uri = Uri.parse("$rejectPlanRequestUrl/$planId/reject");

    final response = await http.put(
      uri,
      headers: {
        ...(await buildRequestHeaders()),
        "Content-Type": "application/json",
      },
      body: jsonEncode({
        "action": "reject",
        "reason": reason,
      }),
    );

    print("Reject StatusCode: ${response.statusCode}");
    print("Reject Body: ${response.body}");

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception("Failed API call: ${response.body}");
    }
  }


  static Future<String> getPendingSuppliers() async {
    var response = await http.get(Uri.parse(pendingCustomersUrl + '/' + supplierId),
        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(pendingCustomersUrl + '/' + supplierId),
            headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return "";
        }
      } else {
        return "";
      }
    } else {
      return "";
    }
  }

  static Future<String> getConnectedCustomers() async {
    var response = await http.get(Uri.parse(connectedCustomersUrl + '/' + supplierId),
        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(connectedCustomersUrl + '/' + supplierId),
            headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return "";
        }
      } else {
        return "";
      }
    } else {
      return "";
    }
  }


  static Future<bool> acceptRequest( payload) async {
    var uri = Uri.parse(acceptRequestUrl );
    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> rejectRequest( payload) async {
    var uri = Uri.parse(rejectRequestUrl );
    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<String> getDriverTrips(
      String mobile) async {
    var uri = Uri.parse(getDriverTripsUrl+'/'+mobile );


    var response =
    await http.get(
        uri,
        headers:
        await buildRequestHeaders()
    );

    return response.body;

  }

  static Future<bool> deleteTankerImage(

      String tankerId,
      String imageUrl

      ) async {

    try{

      var response = await http.delete(

        Uri.parse(

            AppSettings.host+
                "delete_tanker_image/$tankerId"

        ),

        headers:{

          'Content-Type':'application/json'

        },

        body: jsonEncode({

          "imageUrl": imageUrl

        }),

      );

      print(response.body);

      return response.statusCode==200;

    }
    catch(e){

      print(e);

      return false;

    }

  }

  static Future<String> verifyUnloadStartOTP(String bookingId, payload) async {
    final uri = Uri.parse(verifyUnloadStartOTPUrl+'/'+bookingId);
    var response = await http.put(uri, body: jsonEncode(payload), headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await await http.put(uri, body: jsonEncode(payload), headers: await buildRequestHeaders());
        if (response.statusCode == 200) {
          return response.body;
        } else {
          return '';
        }
      } else {
        return '';
      }
    } else {
      return '';
    }
  }

  static Future<String> amountpaidByCustomer(String bookingId, payload) async {
    final uri = Uri.parse(amountpaidByCustomerUrl+'/'+bookingId);
    var response = await http.put(uri, body: jsonEncode(payload), headers: await buildRequestHeaders());
    if (response.statusCode == 200) {
      return response.body;
    } else if (response.statusCode == 401) {
      bool status = await AppSettings.resetToken();
      if (status) {
        response = await await http.put(uri, body: jsonEncode(payload), 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('username', input['simplydata']['suppliername'], 'STRING');
    await saveData('logintype', input['simplydata']['loginType'], 'STRING');
    await saveData('all_motor_access', input['simplydata']['all_motor_access'], 'STRING');
    await saveData('buildingname', input['simplydata']['buildingName'], 'STRING');
    await saveData(
        'access_token', input['simplydata']['access_token'], 'STRING');
    await saveData('phone', input['simplydata']['phone'], 'STRING');
    await saveData('email', input['simplydata']['email'][0]['email'], 'STRING');
    await saveData('supplierId', input['simplydata']['supplierId'], 'STRING');
    await saveData('profile', input['simplydata']['picture'], 'STRING');
    await saveData('user_address', input['simplydata']['office_address'], 'STRING');
    if(input['simplydata']['latitude']==0){
      input['simplydata']['latitude']=0.0;
    }
    if(input['simplydata']['longitude']==0){
      input['simplydata']['longitude']=0.0;
    }
    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 loadDataFromMemory();
  }

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

  static Future<void> loadDataFromMemory() async {
    userName = await getData('username', 'STRING');
    loginType = await getData('logintype', 'STRING');
    accessType = await getData('all_motor_access', 'STRING');
    buildingName = await getData('buildingname', 'STRING');
    accessToken = await getData('access_token', 'STRING');
    email = await getData('email', 'STRING');
    userAddress = await getData('user_address', 'STRING');
    phoneNumber = await getData('phone', 'STRING');
    supplierId = await getData('supplierId', 'STRING');
    supplierLatitude = await getData('latitude', 'DOUBLE');
    supplierLongitude = await getData('longitude', 'DOUBLE');
    profilePictureUrl = await getData('profile', 'STRING');
   // fcmId = await getData('fcmId', 'STRING');
    //profileImage=await getData('profile', 'STRING');
    getProfile();
  }

  static String getStringFromBytes(var data) {
    final buffer = data.buffer;
    var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    var bufferdata = utf8.decode(list);
    String bs4str = base64.encode(list);
    Uint8List decodedbytes = base64.decode(bs4str);
//OR
    // String bs4str1 = base64Encode(imgbytes);
    String s = new String.fromCharCodes(list);
    var outputAsUint8List = new Uint8List.fromList(s.codeUnits);
    return bufferdata;
  }

  static Uint8List image1(dynamicList) {
    List<int> intList =
    dynamicList.cast<int>().toList(); //This is the magical line.
    Uint8List data = Uint8List.fromList(intList);
    return data;
  }

  static Future<void> getProfile() async {
    final image1 = await getData('profile', 'STRING');

    //Io.File.fromUri(imageFile.uri)

    var x = image1;

    if (image1 == null) return;

    if (image1 == '') {
      updatedImage = null;
    } else if (image1 == 'null') {
      updatedImage = null;
    } else {
      final imageTemp = File(image1);
      updatedImage = imageTemp;
    }

    print(updatedImage);
  }

  //assign saved values to variables
  static Future<void> saveProfilePic(dynamic input) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

// your custom int list
    List<dynamic> mList = input['simplydata']['picture']['data'];

    print(mList.length);
    //input['simplydata']['picture']['data'];[0,1,2,3]

// convert your custom list to string list
    List<String> stringsList = mList.map((i) => i.toString()).toList();

// store your string list in shared prefs
    prefs.setStringList("stringList", stringsList);

    // String bar = utf8.decode(bytes);

    //String convertedValue = utf8.decode(mList);
  }

  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 appBar(String title) {
    title = title ?? '';
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0,
      titleSpacing: 0,
      title: Text(title,style: fontTextStyle(14,Color(0XFF2A2A2A),FontWeight.w500),),
      iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
      actions: [
        Row(
          children: [
            Padding(padding: EdgeInsets.fromLTRB(10,10,0,10),
              child: IconButton(
                icon: Image(
                    image:  AssetImage('images/customercare_appbar.png')

                ),
                onPressed: (){

                },
              ),
            ),

            Padding(padding: EdgeInsets.fromLTRB(0,10,10,10),
              child: IconButton(
                icon:  Image.asset(
                  'images/notification_appbar.png', // Example URL image
                ),
                onPressed: (){

                },
              ),
            )
          ],
        )
      ],
    );
  }

  static SupplierAppBarWithHelpAction(String title,context) {
    title = title ?? '';
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0,
      titleSpacing: 0,
      title: Text(
        title,
        style: fontTextStyle(16, Color(0XFF2A2A2A), FontWeight.w600),
      ),
      iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
      leading: GestureDetector(
        onTap: () {
          Navigator.pop(context);
        },
        child: Padding(
          padding:
          const EdgeInsets.fromLTRB(8, 8, 8, 8), // Add padding if needed
          child: Image.asset(
            'images/backbutton_appbar.png', // Replace with your image path
            fit: BoxFit.contain,
            color: Color(0XFF2A2A2A),
            height: 24,
            width: 24,
          ),
        ),
      ),
      actions: [
        Row(
          children: [
            Padding(
              padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
              child: IconButton(
                icon: Image.asset(
                  'images/help_appbar.png',
                  height: 20,
                  width: 20,// Example URL image
                ),
                onPressed: () {},
              ),
            )
          ],
        )
      ],

    );
  }

  static supplierAppBarWithActionsText(

      String title,

      BuildContext context,

      {dynamic result}

      ){

    title = title ?? '';

    return AppBar(

      backgroundColor: Colors.white,

      elevation: 0,

      scrolledUnderElevation: 0,

      titleSpacing: 0,

      title: Text(

        title,

        style: fontTextStyle(
            16,
            Color(0XFF2A2A2A),
            FontWeight.w600),

      ),

      iconTheme:
      IconThemeData(
          color: Color(0XFF2A2A2A)),

      leading: GestureDetector(

        onTap: () {

          Navigator.pop(
              context,
              result   // ⭐ IMPORTANT
          );

        },

        child: Padding(

          padding:
          EdgeInsets.fromLTRB(
              8,8,8,8),

          child: Image.asset(

            'images/backbutton_appbar.png',

            fit: BoxFit.contain,

            color: Color(0XFF2A2A2A),

            height: 24,

            width: 24,

          ),

        ),

      ),

      actions: [

        Padding(

          padding: EdgeInsets.all(8),

          child: TextButton(

            onPressed: (){},

            child: Text(

              'HELP',

              style: fontTextStyle(
                  14,
                  primaryColor,
                  FontWeight.w600),

            ),

          ),

        )

      ],

    );

  }

  static appBarWithoutActions(String title) {
    title = title ?? '';
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0,
      titleSpacing: 0,
      title: Text(
        title,
        style: fontTextStyle(14, Color(0XFF2A2A2A), FontWeight.w500),
      ),
      iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
    );
  }

  static appBarWithNotificationIcon(String buildingName,String typeOfWater,String capacity,context){
    buildingName = buildingName ?? '';
    typeOfWater = typeOfWater ?? '';
    capacity = capacity ?? '';

    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0,
      titleSpacing: 0,
      title: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(buildingName,
              style: fontTextStyle(16, const Color(0XFF2A2A2A), FontWeight.w600)),
          const SizedBox(height: 2),
          Text('$typeOfWater | $capacity',
              style: fontTextStyle(12, const Color(0XFF2A2A2A), FontWeight.w400)),
        ],
      ),
      iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
      leading: GestureDetector(
        onTap: () {
          Navigator.pop(context);
        },
        child: Padding(
          padding:
          const EdgeInsets.fromLTRB(8, 8, 8, 8), // Add padding if needed
          child: Image.asset(
            'images/backbutton_appbar.png', // Replace with your image path
            fit: BoxFit.contain,
            color: Color(0XFF2A2A2A),
            height: 24,
            width: 24,
          ),
        ),
      ),
      actions: [
        Row(
          children: [
            Padding(
              padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
              child: IconButton(
                icon: Image.asset(
                  'images/notification_appbar.png',
                  height: 20,
                  width: 20,// Example URL image
                ),
                onPressed: () {},
              ),
            )
          ],
        )
      ],
    );
  }

}