// ignore_for_file: use_build_context_synchronously, unnecessary_cast

import 'dart:async';
import 'dart:convert';
import 'package:byod/bloc/view_bill.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/logger.dart';
import 'package:byod/models/bill.dart';
import 'package:byod/models/bill_detail.dart';
import 'package:byod/models/feedback_option.dart';
import 'package:byod/models/filter_menu.dart';
import 'package:byod/models/member_info.dart';
import 'package:byod/models/payment_list.dart';
import 'package:byod/models/voucher_list.dart';
import 'package:byod/ui/viewbill/view_bill.dart';
import 'package:byod/ui/viewbill/view_bill_new.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../bloc/order_bloc.dart';
import '../helper/widget/open_url.dart';
import '../main.dart';
import '../models/fav_menu.dart';
import '../models/variant_categories.dart';
import '../models/variants.dart';
// ignore: avoid_web_libraries_in_flutter

// Future<dynamic> httpPost(
//     String apiUrl, String bodies, String namaFungsi) async {
//   var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
//   if (apiResult.statusCode == 200 || apiResult.statusCode == 401) {
//     // 401 dilolosin karena mau nangkep message dari backend > show to user
//     var jsonObject = jsonDecode(apiResult.body);
//     return jsonObject;
//   } else {
//     if (debug) {
//       logd('API CLASS ON API.DART, FUNGSI: $namaFungsi, URL : $apiUrl',
//           'ERROR CONNECT TO SERVER, RESPONSE CODE : ${apiResult.statusCode}');
//     }
//     return false;
//   }
// }

class Api {
  static Future<dynamic> getBranch(String branchCode, String brandCode,
      String role, String cashierName, String sessionId) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = '${baseUrl}romi/api/byod/get_branch';
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "role": role,
        "cashier_name": cashierName,
        "session_id": sessionId,
        "from": fromByod
      };
      var bodies = json.encode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);
      var jsonObject = await httpPost(apiUrl, bodies, 'getBranch');
      // ignore: unrelated_type_equality_checks
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          //** save sessionID and Table Mode*/
          List<String> listHistory = prefs.getStringList('list_history') ?? [];
          String tableNumber = prefs.getString('table_number') ?? '';
          String userName = prefs.getString('userName') ?? '';
          String totalOrder = prefs.getString('total_order') ?? '0';
          String dateOrder = prefs.getString('date_order') ?? '';
          String branchCode = prefs.getString("outlet") ?? '';
          String brandCode = prefs.getString("brand") ?? '';
          String token = prefs.getString("token") ?? '';
          if (sessionId != jsonObject['data']['session_id']) {
            Map historyOrder = {
              "session": sessionId,
              "table": tableNumber,
              "user_name": userName,
              "total_order": totalOrder,
              "date_order": localDate(
                dateOrder,
                isHistory: true,
              ),
              "branch_code": branchCode,
              "brand": brandCode,
              "token": token,
            };
            String historySave = jsonEncode(historyOrder);
            listHistory.add(historySave);
            await prefs.setStringList('list_history', listHistory);
          }
          await prefs.setString('sessionId', jsonObject['data']['session_id']);
          await prefs.setInt('table_mode', jsonObject['data']['table_mode']);

          await prefs.setString('logoUrl', jsonObject['data']['logo']);
          //** save sessionID and Table Mode */

          // return jsonObject['data']['name'];
          return responseByodBranchExist;
        } else if (jsonObject['status'] == 'error' &&
            (jsonObject['code'] == 'BYOD_ALWAYS_OFF' ||
                jsonObject['code'] == 'BYOD_SCHEDULE')) {
          return responseByodInActive;
        } else {
          return responseApiNoSuccess;
        }
      } else {
        return responseApiErrorServer;
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: getBranch, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return responseApiErrorServer;
    }
  }

  // static Future<List<FilterMenu>> getMenuAndFilterMenu(
  //     String branchCode,
  //     String brandCode,
  //     String role,
  //     String cashierName,
  //     String tokenUser) async {
  //   String baseUrl = prefs.getString('baseUrl') ?? '';
  //   String apiUrl = '${baseUrl}get_menu';
  //   // List<FilterMenu> filterMenu = [];
  //   List<Category> category = [];
  //   List<FilterMenu> filterMenu = [];
  //   // List<FilterMenu> filterMenuResult = [];
  //   try {
  //     Map data = {
  //       "branch_code": branchCode,
  //       "brand_code": brandCode,
  //       "role": role,
  //       "cashier_name": cashierName,
  //       "secure_token": tokenUser,
  //       "from": fromByod
  //     };
  //     var bodies = json.encode(data);
  //     // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
  //     // var jsonObject = jsonDecode(apiResult.body);
  //     var jsonObject = await httpPost(apiUrl, bodies, 'getCategory');
  //     if (jsonObject != false) {
  //       if (jsonObject['status'].toString().toLowerCase() == 'ok') {
  //         List<dynamic> dataCat =
  //             (jsonObject as Map<dynamic, dynamic>)['data']['items_categories'];
  //         for (int d = 0; d < dataCat.length; d++) {
  //           List<dynamic> menuList = dataCat[d]['items'];

  //           // // pemisahan type category
  //           List<VariantCategories> variantCategoriesEmpty = [];
  //           Map<String, dynamic> dataCatMenu = {
  //             "id": dataCat[d]['id'],
  //             "name": '',
  //             "price": '',
  //             "original_price": '',
  //             "image_medium": '',
  //             "image_thumbnail": '',
  //             "sold_in_store": false,
  //             "type": typeCategory,
  //             "category_name": dataCat[d]['name'],
  //             "description": '',
  //             "group_id": '',
  //             "group_name": '',
  //             "variant_cat": variantCategoriesEmpty
  //           };
  //           filterMenu.add(FilterMenu.createMenu(dataCatMenu));
  //           // pemisahan type category

  //           List<Menu> menu = [];
  //           String groupIdForFiltering = '';
  //           for (int i = 0; i < menuList.length; i++) {
  //             List<dynamic> variantCat = menuList[i]['variant_categories'];

  //             List<VariantCategories> variantCategories = [];

  //             for (int o = 0; o < variantCat.length; o++) {
  //               List<dynamic> variant = variantCat[o]['variants'];
  //               List<Variants> variants = [];
  //               for (int m = 0; m < variant.length; m++) {
  //                 variants.add(Variants.createVariant(variant[m]));
  //               }
  //               Map<String, dynamic> dataVariantCat = {
  //                 "id": variantCat[o]['id'],
  //                 "caption": variantCat[o]['caption'],
  //                 "type": variantCat[o]['type'],
  //                 "variants": variants
  //               };

  //               variantCategories.add(
  //                   VariantCategories.createVariantCategory(dataVariantCat));
  //             }

  //             // pemisahan type group
  //             if (menuList[i]['group_id'] != groupIdForFiltering) {
  //               groupIdForFiltering = menuList[i]['group_id'];
  //               Map<String, dynamic> dataGroupMenu = {
  //                 "id": dataCat[d]['id'],
  //                 "name": '',
  //                 "price": '',
  //                 "original_price": '',
  //                 "image_medium": '',
  //                 "image_thumbnail": '',
  //                 "sold_in_store": false,
  //                 "type": typeGroup,
  //                 "category_name": dataCat[d]['name'],
  //                 "description": '',
  //                 "group_id": menuList[i]['group_id'],
  //                 "group_name": menuList[i]['group_name'],
  //                 "variant_cat": variantCategoriesEmpty
  //               };
  //               filterMenu.add(FilterMenu.createMenu(dataGroupMenu));
  //             }

  //             // pemisahan type group

  //             //filter yang type menu
  //             Map<String, dynamic> dataMenu = {
  //               "id": menuList[i]['id'],
  //               "name": menuList[i]['name'],
  //               "price": menuList[i]['price'],
  //               "original_price": menuList[i]['original_price'],
  //               "image_medium": menuList[i]['image_medium'],
  //               "image_thumbnail": menuList[i]['image_thumbnail'],
  //               "sold_in_store": menuList[i]['sold_in_store'],
  //               "type": typeMenu,
  //               "category_name": dataCat[d]['name'],
  //               "description": menuList[i]['description'],
  //               "group_name": menuList[i]['group_name'],
  //               "group_id": menuList[i]['group_id'],
  //               "variant_cat": variantCategories
  //             };

  //             Map<String, dynamic> menuData = {
  //               "id": menuList[i]['id'],
  //               "name": menuList[i]['name'],
  //               "price": menuList[i]['price'],
  //               "original_price": menuList[i]['original_price'],
  //               "image_medium": menuList[i]['image_medium'],
  //               "image_thumbnail": menuList[i]['image_thumbnail'],
  //               "sold_in_store": menuList[i]['sold_in_store'],
  //               "variant_cat": variantCategories
  //             };

  //             menu.add(Menu.createMenu(menuData));
  //             filterMenu.add(FilterMenu.createMenu(dataMenu));
  //           }
  //           Map<String, dynamic> cat = {
  //             "id": dataCat[d]['id'],
  //             "name": dataCat[d]['name'],
  //             "menu": menu
  //           };
  //           category.add(Category.createCategory(cat));
  //           // Map<String, dynamic> catList = {
  //           //   "id": dataCat[d]['id'],
  //           //   "name": dataCat[d]['name'],
  //           // };
  //           // categoryList.add(CategoryList.createCategoryList(catList));
  //           // filterMenuResult = filterMenu;
  //         }
  //         return filterMenu;
  //       } else {
  //         FilterMenu catFailed = FilterMenu(
  //           id: '0',
  //           name: '',
  //           price: '',
  //           originalPrice: '',
  //           imageUrlMedium: '',
  //           imageUrlThumbnail: '',
  //           isSell: false,
  //           type: typeCategory,
  //           categoryName: '',
  //           description: '',
  //           groupId: '',
  //           groupName: '',
  //         );
  //         return [catFailed];
  //       }
  //     } else {
  //       return filterMenu;
  //     }
  //   } catch (e) {
  //     if (debug) {
  //       logd(
  //           'API CLASS ON API.DART, FUNGSI: getMenuAndFilterMenu, URL : $apiUrl',
  //           'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
  //     }
  //     return [];
  //   }
  // }

  static Future<List<FilterMenu>> getMenuAndFilterMenu(
      String branchCode,
      String brandCode,
      String role,
      String cashierName,
      String tokenUser) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = '${baseUrl}romi/api/v2/byod/get_menu';
    // List<FilterMenu> filterMenu = [];
    List<FilterMenu> filterMenu = [];
    // List<FilterMenu> filterMenuResult = [];
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "role": role,
        "cashier_name": cashierName,
        "secure_token": tokenUser,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);
      var jsonObject = await httpPost(apiUrl, bodies, 'getMenuAndFilterMenu');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          List<dynamic> dataCat =
              (jsonObject as Map<dynamic, dynamic>)['data']['categories'];
          List<dynamic> menuList =
              (jsonObject as Map<dynamic, dynamic>)['data']['items'];

          List<dynamic> favGroup =
              (jsonObject as Map<dynamic, dynamic>)['data']['favorite_group'];
          List<dynamic> favDetail = (jsonObject
              as Map<dynamic, dynamic>)['data']['favorite_group_detail'];

          for (int d = 0; d < dataCat.length; d++) {
            // List<dynamic> menuList = dataCat[d]['items'];

            // // pemisahan type category
            List<VariantCategories> variantCategoriesEmpty = [];
            Map<String, dynamic> dataCatMenu = {
              "id": dataCat[d]['id'],
              "name": '',
              "price": '',
              "original_price": '',
              "image_medium": '',
              "image_thumbnail": '',
              "sold_in_store": false,
              "type": typeCategory,
              "category_name": dataCat[d]['name'],
              "category_id": dataCat[d]['id'],
              "description": '',
              "group_id": '',
              "group_name": '',
              "variant_cat": variantCategoriesEmpty
            };
            filterMenu.add(FilterMenu.createMenu(dataCatMenu));
            // pemisahan type category

            // List<Menu> menu = [];
            String groupIdForFiltering = '';
            for (int i = 0; i < menuList.length; i++) {
              // cocokin category id dengan item
              if (menuList[i]['category_id'] == dataCat[d]['id']) {
                List<dynamic> variantCat = menuList[i]['variants'];

                List<VariantCategories> variantCategories = [];

                // for (int o = 0; o < variantCat.length; o++) {

                for (int j = 0; j < variantCat.length; j++) {
                  int index = variantCategories.indexWhere((varCat) =>
                      varCat.id == variantCat[j]['category_variant_id']);
                  if (index == -1) {
                    List<Variants> variants = [];
                    for (int k = 0; k < variantCat.length; k++) {
                      if (variantCat[j]['category_variant_id'] ==
                          variantCat[k]['category_variant_id']) {
                        variants.add(Variants.createVariant(variantCat[k]));
                      }
                    }
                    Map<String, dynamic> dataVariantCat = {
                      "id": variantCat[j]['category_variant_id'],
                      "caption": variantCat[j]['category_variant_caption'],
                      "type": variantCat[j]['category_variant_type'],
                      "variants": variants
                    };
                    variantCategories.add(
                        VariantCategories.createVariantCategory(
                            dataVariantCat));
                  }
                }
                // }

                // pemisahan type group
                if (menuList[i]['group_id'] != groupIdForFiltering) {
                  groupIdForFiltering = menuList[i]['group_id'];
                  Map<String, dynamic> dataGroupMenu = {
                    "id": dataCat[d]['id'],
                    "name": '',
                    "price": '',
                    "original_price": '',
                    "image_medium": '',
                    "image_thumbnail": '',
                    "sold_in_store": false,
                    "type": typeGroup,
                    "category_name": dataCat[d]['name'],
                    "category_id": dataCat[d]['id'],
                    "description": '',
                    "group_id": menuList[i]['group_id'],
                    "group_name": menuList[i]['group_name'],
                    "variant_cat": variantCategoriesEmpty
                  };
                  filterMenu.add(FilterMenu.createMenu(dataGroupMenu));
                }
                // pemisahan type group

                //filter yang type menu
                Map<String, dynamic> dataMenu = {
                  "id": menuList[i]['id'],
                  "name": menuList[i]['name'],
                  "price": menuList[i]['price'],
                  "original_price": menuList[i]['original_price'],
                  "image_medium": menuList[i]['image_medium'],
                  "image_thumbnail": menuList[i]['image_thumbnail'],
                  "sold_in_store": menuList[i]['sold_in_store'],
                  "type": typeMenu,
                  "category_name": dataCat[d]['name'],
                  "category_id": dataCat[d]['id'],
                  "description": menuList[i]['description'],
                  "group_name": menuList[i]['group_name'],
                  "group_id": menuList[i]['group_id'],
                  "variant_cat": variantCategories
                };
                filterMenu.add(FilterMenu.createMenu(dataMenu));
              }
            }
          }

          // looping for favorit group
          for (int s = 0; s < favGroup.length; s++) {
            // List<dynamic> menuList = dataCat[d]['items'];

            // // pemisahan type category, disamain dengan diatas, group dianggap category, pembeda ada di is_fav
            List<VariantCategories> variantCategoriesEmpty = [];
            Map<String, dynamic> dataFavGroup = {
              "id": favGroup[s]['id'],
              "name": '',
              "price": '',
              "original_price": '',
              "image_medium": '',
              "image_thumbnail": '',
              "sold_in_store": false,
              "type": typeCategory,
              "category_name": favGroup[s]['name'],
              "category_id": favGroup[s]['id'],
              "description": '',
              "group_id": '',
              "group_name": '',
              "variant_cat": variantCategoriesEmpty,
              "is_fav": true,
            };
            filterMenu.add(FilterMenu.createMenu(dataFavGroup));
            // end pemisahan type category

            // List<Menu> menu = [];
            String groupIdForFiltering = '';
            for (int i = 0; i < favDetail.length; i++) {
              // cocokin id
              if (favDetail[i]['favorite_group_id'] == favGroup[s]['id']) {
                // List<dynamic> variantCat = favDetail[i]['variants'];

                List<VariantCategories> variantCategories = [];

                // for (int o = 0; o < variantCat.length; o++) {
                //   List<Variants> variants = [];
                //   for (int j = 0; j < variantCat.length; j++) {
                //     if (variantCat[j]['category_variant_id'] ==
                //         variantCat[o]['category_variant_id']) {
                //       variants.add(Variants.createVariant(variantCat[j]));
                //     }
                //   }
                //   Map<String, dynamic> dataVariantCat = {
                //     "id": variantCat[o]['category_variant_id'],
                //     "caption": variantCat[o]['category_variant_caption'],
                //     "type": variantCat[o]['category_variant_type'],
                //     "variants": variants
                //   };
                //   variantCategories.add(
                //       VariantCategories.createVariantCategory(dataVariantCat));
                // }

                // pemisahan type group
                if (favDetail[i]['group_id'] != groupIdForFiltering) {
                  groupIdForFiltering = favDetail[i]['group_id'];
                  Map<String, dynamic> dataGroupMenu = {
                    "id": favGroup[s]['id'],
                    "name": '',
                    "price": '',
                    "original_price": '',
                    "image_medium": '',
                    "image_thumbnail": '',
                    "sold_in_store": false,
                    "type": typeGroup,
                    "category_name": favGroup[s]['name'],
                    "category_id": favGroup[s]['id'],
                    "description": '',
                    "group_id": favDetail[i]['group_id'],
                    "group_name": favDetail[i]['group_name'],
                    "variant_cat": variantCategoriesEmpty,
                    "is_fav": true,
                  };
                  filterMenu.add(FilterMenu.createMenu(dataGroupMenu));
                }
                // pemisahan type group

                //filter yang type menu disamain dengan di atas, menu ini dianggap sebagai fav group detail, pembeda ada di is_fav
                Map<String, dynamic> dataMenu = {
                  "id": favDetail[i]['id'],
                  "name": favDetail[i]['name'],
                  "price": favDetail[i]['price'],
                  "original_price": favDetail[i]['original_price'],
                  "image_medium": favDetail[i]['image_medium'],
                  "image_thumbnail": favDetail[i]['image_thumbnail'],
                  "sold_in_store": favDetail[i]['sold_in_store'],
                  "type": typeMenu,
                  "category_name": favGroup[s]['name'],
                  "category_id": favGroup[s]['id'],
                  "description": favDetail[i]['description'],
                  "group_name": favDetail[i]['group_name'],
                  "group_id": favDetail[i]['group_id'],
                  "variant_cat": variantCategories,
                  "favorite_group_id": favDetail[i]['favorite_group_id'],
                  "favorite_group_name": favDetail[i]['favorite_group_name'],
                  "is_fav": true,
                };
                filterMenu.add(FilterMenu.createMenu(dataMenu));
              }
            }
          }

          return filterMenu;
        } else {
          FilterMenu catFailed = FilterMenu(
            id: '0',
            name: '',
            price: '',
            originalPrice: '',
            imageUrlMedium: '',
            imageUrlThumbnail: '',
            isSell: false,
            type: typeCategory,
            categoryName: '',
            categoryId: '',
            description: '',
            groupId: '',
            groupName: '',
          );
          return [catFailed];
        }
      } else {
        return filterMenu;
      }
    } catch (e) {
      if (debug) {
        logd(
            'API CLASS ON API.DART, FUNGSI: getMenuAndFilterMenu, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return [];
    }
  }

  static Future<List<FavMenu>> getFavorite(String branchCode, String brandCode,
      String role, String cashierName, String tokenUser) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = '${baseUrl}romi/api/byod/get_menu';
    // List<FilterMenu> filterMenu = [];
    // List<Category> category = [];
    List<FavMenu> favMenu = [];
    // List<FilterMenu> filterMenuResult = [];
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "role": role,
        "cashier_name": cashierName,
        "secure_token": tokenUser,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);
      var jsonObject = await httpPost(apiUrl, bodies, 'getFavorite');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          List<dynamic> dataFav =
              (jsonObject as Map<dynamic, dynamic>)['data']['fav_group'];
          List<dynamic> menuFav =
              (jsonObject as Map<dynamic, dynamic>)['data']['fav_group_detail'];

          for (int d = 0; d < dataFav.length; d++) {
            // List<dynamic> menuList = dataCat[d]['items'];

            for (int i = 0; i < menuFav.length; i++) {
              // cocokin category id dengan item, ribet gak sih ?
              if (menuFav[i]['favorite_group_id'] == dataFav[d]['id']) {
                List<dynamic> variantCat = menuFav[i]['variants'];

                List<VariantCategories> variantCategories = [];

                for (int o = 0; o < variantCat.length; o++) {
                  List<Variants> variants = [];
                  for (int j = 0; j < variantCat.length; j++) {
                    if (variantCat[j]['category_variant_id'] ==
                        variantCat[o]['category_variant_id']) {
                      variants.add(Variants.createVariant(variantCat[j]));
                    }
                  }
                  Map<String, dynamic> dataVariantCat = {
                    "id": variantCat[o]['category_variant_id'],
                    "caption": variantCat[o]['category_variant_caption'],
                    "type": variantCat[o]['category_variant_type'],
                    "variants": variants
                  };
                  variantCategories.add(
                      VariantCategories.createVariantCategory(dataVariantCat));
                }

                //filter yang type menu
                Map<String, dynamic> dataFavorite = {
                  "id": menuFav[i]['id'],
                  "name": menuFav[i]['name'],
                  "price": menuFav[i]['price'],
                  "original_price": menuFav[i]['original_price'],
                  "image_medium": menuFav[i]['image_medium'],
                  "image_thumbnail": menuFav[i]['image_thumbnail'],
                  "sold_in_store": menuFav[i]['sold_in_store'],
                  "favorite_group_id": menuFav[i]['favorite_group_id'],
                  "description": menuFav[i]['description'],
                  "favorite_group_name": menuFav[i]['favorite_group_name'],
                  "group_id": menuFav[i]['group_id'],
                  "variant_cat": variantCategories
                };

                // Map<String, dynamic> menuData = {
                //   "id": menuList[i]['id'],
                //   "name": menuList[i]['name'],
                //   "price": menuList[i]['price'],
                //   "original_price": menuList[i]['original_price'],
                //   "image_medium": menuList[i]['image_medium'],
                //   "image_thumbnail": menuList[i]['image_thumbnail'],
                //   "sold_in_store": menuList[i]['sold_in_store'],
                //   "variant_cat": variantCategories
                // };

                // menu.add(Menu.createMenu(menuData));
                favMenu.add(FavMenu.createFav(dataFavorite));
              }
            }
            // Map<String, dynamic> cat = {
            //   "id": dataCat[d]['id'],
            //   "name": dataCat[d]['name'],
            //   "menu": menu
            // };
            // category.add(Category.createCategory(cat));
            // Map<String, dynamic> catList = {
            //   "id": dataCat[d]['id'],
            //   "name": dataCat[d]['name'],
            // };
            // categoryList.add(CategoryList.createCategoryList(catList));
            // filterMenuResult = filterMenu;
          }
          return favMenu;
        } else {
          FavMenu favMenuFailed = FavMenu(
            id: '0',
            name: '',
            price: '',
            originalPrice: '',
            imageUrlMedium: '',
            imageUrlThumbnail: '',
            isSell: false,
            favGroupId: '',
            description: '',
            favGroupName: '',
          );

          return [favMenuFailed];
        }
      } else {
        return favMenu;
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: getFavorite, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return [];
    }
  }

  static Future<List<Bill>> getBill(
    String branchCode,
    String brandCode,
    String tableNumber,
    String token, {
    String sessionIdH = '',
    String userNameH = '',
  }) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/view_bill";

    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String userName;
    String sessionId;
    if (sessionIdH == '') {
      userName = prefs.getString('userName') ?? '';
      sessionId = prefs.getString('sessionId') ?? '';
    } else {
      userName = userNameH;
      sessionId = sessionIdH;
    }

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "table_number": tableNumber,
        "role": role,
        "cashier_name": cashierName,
        "session_id": sessionId,
        "customer_name": userName,
        "from": fromByod
      };
      var bodies = json.encode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'getBill');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok' &&
            jsonObject['msg'] == 'Bill ditemukan') {
          List<Bill> bill = [];
          List<PaymentList> paymentList = [];
          // List<MemberInfo> memberInfo = [];
          List<dynamic> orderDetail =
              (jsonObject as Map<dynamic, dynamic>)['data']['order_detail'];
          List<dynamic> orderPayment =
              (jsonObject as Map<dynamic, dynamic>)['data']['order_payment'];
          for (int k = 0; k < orderPayment.length; k++) {
            paymentList.add(PaymentList.createPaymentList(orderPayment[k]));
          }
          // if (jsonObject['data']['member_info'] != null) {
          //   memberInfo.add(MemberInfo.getInfo(
          //       (jsonObject as Map<dynamic, dynamic>)['data']['member_info']));
          // }

          for (int d = 0; d < orderDetail.length; d++) {
            if (orderDetail[d]['parent_id'] == '') {
              // yang variant gak dimasukin dulu
              int index = bill.indexWhere((bill) =>
                  bill.customerName == orderDetail[d]['customer_name']);
              if (index != -1) {
                // ketemu nama yang sama
                List<String> variants = [];
                for (int z = 0; z < orderDetail[d]['variant'].length; z++) {
                  variants.add(orderDetail[d]['variant'][z]);
                }

                int totalPerCustomer =
                    amountParseToInt(orderDetail[d]['total']);

                var z = {
                  "id": orderDetail[d]['id'],
                  "customer_name": orderDetail[d]['customer_name'],
                  "name": orderDetail[d]['name'],
                  "quantity": orderDetail[d]['quantity'],
                  "price": orderDetail[d]['price'],
                  "subtotal": orderDetail[d]['subtotal'],
                  "total": orderDetail[d]['total'],
                  "service": orderDetail[d]['service'],
                  "service_tax": orderDetail[d]['service_tax'],
                  "order_status": orderDetail[d]['order_status'],
                  "notes": orderDetail[d]['notes'],
                  "image": orderDetail[d]['image_small'],
                  "variant": variants
                };
                bill[index].billDetail.add(BillDetail.createBillDetail(z));
                bill[index].totalPerCustomer += totalPerCustomer;
              } else {
                // beda orang
                List<BillDetail> billDetail = [];
                List<String> variants = [];
                for (int z = 0; z < orderDetail[d]['variant'].length; z++) {
                  variants.add(orderDetail[d]['variant'][z]);
                }
                var z = {
                  "id": orderDetail[d]['id'],
                  "customer_name": orderDetail[d]['customer_name'],
                  "name": orderDetail[d]['name'],
                  "quantity": orderDetail[d]['quantity'],
                  "price": orderDetail[d]['price'],
                  "subtotal": orderDetail[d]['subtotal'],
                  "total": orderDetail[d]['total'],
                  "service": orderDetail[d]['service'],
                  "service_tax": orderDetail[d]['service_tax'],
                  "order_status": orderDetail[d]['order_status'],
                  "notes": orderDetail[d]['notes'],
                  "image": orderDetail[d]['image_small'],
                  "variant": variants
                };
                billDetail.add(BillDetail.createBillDetail(z));
                int totalPerCustomer = amountParseToInt(z['total']);
                var i = {
                  "id": jsonObject['data']['id'],
                  "total": jsonObject['data']['total'],
                  "subtotal": jsonObject['data']['subtotal'],
                  "total_per_customer": totalPerCustomer,
                  "customer_name": orderDetail[d]['customer_name'],
                  "table_status": jsonObject['data']['table_status'],
                  "order_status": jsonObject['data']['order_status'],
                  "order_detail": billDetail,
                  "payment_list": paymentList,
                  "outstanding": jsonObject['data']['outstanding'],
                  "invoice": jsonObject['data']['code'],
                  "total_service": jsonObject['data']['service'],
                  "total_service_tax": jsonObject['data']['service_tax'],
                  "my_self_outstanding": jsonObject['data']
                      ['my_self_outstanding'],
                  "discount_total": jsonObject['data']['discount'],
                  "table_number": jsonObject['data']['table_number'],
                  "is_feedback": jsonObject['data']['is_feedback'],
                  "doku_minimum_payment": jsonObject['data']
                      ['doku_minimum_payment'],
                  "order_date": jsonObject['data']['order_date'],
                };
                bill.add(Bill.createBill(i));
                // billDetail.add(BillDetail.createBillDetail(orderDetail[d]));
              }
            }
          }
          return bill;
        } else {
          return [];
        }
      } else {
        return [];
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: getBill, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return [];
    }
  }

  static Future<List<dynamic>> checkVoucher(String codeVoucher) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/check_voucher";
    List<dynamic> voucherDetail = [];
    String token = prefs.getString('token') ?? '';
    String role = prefs.getString('role') ?? '';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String branchCode = prefs.getString('outlet') ?? '';
    String orderId = prefs.getString('sessionId') ?? '';

    await EasyLoading.show(
      status: 'Check Voucher....',
      maskType: EasyLoadingMaskType.none,
    );
    try {
      Map data = {
        "voucher_code": codeVoucher,
        "secure_token": token,
        "role": role,
        "cashier_name": cashierName,
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_id": orderId,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);
      var jsonObject = await httpPost(apiUrl, bodies, 'checkVoucher');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          await EasyLoading.dismiss();
          EasyLoading.showToast('Voucher Berhasil Diterapkan');
          voucherDetail.add(jsonObject['data']['reward']['title']);
          voucherDetail.add(jsonObject['data']['reward']['value'].toString());
          voucherDetail.add(jsonObject['data']['verification_number']);
          voucherDetail.add(false); // untuk disabled textfield
          return voucherDetail;
        } else {
          await EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          return [];
        }
      } else {
        await EasyLoading.dismiss();
        EasyLoading.showToast('Something Went Wrong');
        return [];
      }
    } catch (e) {
      await EasyLoading.dismiss();
      EasyLoading.showToast('Something Went Wrong');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: checkVoucher, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return [];
    }
  }

  static Future<List<VoucherList>> getVoucherList() async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/get_voucher_list";
    List<VoucherList> voucherList = [];
    String token = prefs.getString('token') ?? '';
    String role = prefs.getString('role') ?? '';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String branchCode = prefs.getString('outlet') ?? '';

    try {
      Map data = {
        "secure_token": token,
        "role": role,
        "cashier_name": cashierName,
        "branch_code": branchCode,
        "brand_code": brandCode,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);
      var jsonObject = await httpPost(apiUrl, bodies, 'getVoucherList');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          List<dynamic> voucherData =
              (jsonObject as Map<dynamic, dynamic>)['data'];
          for (int d = 0; d < voucherData.length; d++) {
            var mapData = {
              "id": voucherData[d]['id'],
              "expire_time": voucherData[d]['expire_time'],
              "used": voucherData[d]['used'],
              "verification_number": voucherData[d]['verification_number'],
              "title": voucherData[d]['reward']['title'],
              "subtitle": voucherData[d]['reward']['subtitle'],
              "title_image": voucherData[d]['reward']['title_image'],
              "content_image": voucherData[d]['reward']['content_image'],
              "value": voucherData[d]['reward']['value'],
              "min_transaction": voucherData[d]['reward']['min_transaction'],
            };
            voucherList.add(VoucherList.addListVoucher(mapData));
          }

          return voucherList;
        } else {
          return voucherList;
        }
      } else {
        EasyLoading.showToast('Something went wrong');
        return voucherList;
      }
    } catch (e) {
      EasyLoading.showToast('Gagal mendapatkan voucher');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: getVoucherList, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return [];
    }
  }

  static Future<bool> setWaiting(String orderId, String branchCode,
      String brandCode, String customerName) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/waiting_order";

    await EasyLoading.show(
      status: 'Harap tunggu...',
      maskType: EasyLoadingMaskType.none,
    );

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_id": orderId,
        "customer_name": customerName,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'setWaiting');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          await EasyLoading.dismiss();
          return true;
        } else {
          EasyLoading.showToast('Something went wrong..');
          return false;
        }
      } else {
        EasyLoading.showToast('Something went wrong..');
        return false;
      }
    } catch (e) {
      EasyLoading.showToast('Something went wrong..');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: setWaiting, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return false;
    }
  }

  static Future<String> addPayment(
      BuildContext context,
      String orderId,
      String branchCode,
      String brandCode,
      String customerName,
      int method,
      int paymentType,
      String codeVoucher,
      int amount) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/add_payments";
    String token = prefs.getString('token') ?? '';
    await EasyLoading.show(
      status: 'Harap tunggu...',
      maskType: EasyLoadingMaskType.none,
    );

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_id": orderId,
        "customer_name": customerName,
        "method": method,
        "payment_type": paymentType,
        "code_voucher": codeVoucher,
        "secure_token": token,
        "amount": amount,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'addPayment');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          await EasyLoading.dismiss();
          if (method == payCard) {
            if (jsonObject['url'] != null) {
              await EasyLoading.dismiss();
              // Navigator.pushReplacement(
              //     context, MaterialPageRoute(builder: (_) => const ViewBill()));
              // js.context.callMethod('open', [jsonObject['url']]);
              htmlOpenLink(jsonObject['url']);
              return jsonObject['url'];
            } else {
              await EasyLoading.dismiss();
              EasyLoading.showToast(
                  'Pembayaran berhasil, anda akan di alihkan ke halaman bill');
              Future.delayed(const Duration(milliseconds: 1000), () async {
                Navigator.push(
                    context, MaterialPageRoute(builder: (_) => ViewBill()));
              });
              return 'OK';
            }
          } else if (method == payVoucher) {
            await EasyLoading.dismiss();
            EasyLoading.showToast(
                'Pembayaran berhasil, anda akan dialihkan ke halaman bill');
            Future.delayed(const Duration(milliseconds: 1000), () async {
              Navigator.push(
                  context, MaterialPageRoute(builder: (_) => ViewBill()));
            });
            return 'OK';
          } else {
            // Navigator.push(
            //     context, MaterialPageRoute(builder: (_) => FinishOrder()));
            // EasyLoading.showToast(
            //     'Pesanan telah ditutup, silakan memanggil waiter untuk meminta bill');
            context.read<ViewBillBloc>().getBill();
            return 'OK';
          }
        } else {
          await EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          return jsonObject['msg'];
        }
      } else {
        await EasyLoading.dismiss();
        EasyLoading.showToast('Something Went Wrong');
        return '';
      }
    } catch (e) {
      await EasyLoading.dismiss();
      EasyLoading.showToast(
          'Ups.. Sepertinya terjadi kendala, silakan coba lagi');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: addPayment, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return '';
    }
  }

  static Future<bool> deletePayment(String branchCode, String brandCode,
      String paymentId, String customerName, String cashierName) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/delete_payment";

    await EasyLoading.show(
      status: 'Harap tunggu...',
      maskType: EasyLoadingMaskType.none,
    );

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "payment_id": paymentId,
        "customer_name": customerName,
        "role": 'cashier',
        "cashier_name": cashierName,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'deletePayment');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          await EasyLoading.dismiss();
          EasyLoading.showToast("Berhasil Delete Payment");
          return true;
        } else {
          await EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          return false;
        }
      } else {
        await EasyLoading.dismiss();
        EasyLoading.showToast('Something Went Wrong');
        return false;
      }
    } catch (e) {
      await EasyLoading.dismiss();
      EasyLoading.showToast('Terjadi kesalahan server');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: deletePayment, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return false;
    }
  }

  static Future<dynamic> checkOut(
      BuildContext context,
      List<dynamic> variantData,
      String branchCode,
      String brand,
      String tableNumber,
      String namaPelangganFix) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/checkout";
    String role = prefs.getString('role') ?? 'custome';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String sessionId = prefs.getString('sessionId') ?? '';
    String secureToken = prefs.getString('token') ?? '';

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brand,
        "table_number": tableNumber,
        "customer_name": namaPelangganFix,
        "role": role,
        "cashier_name": cashierName,
        "session_id": sessionId,
        "menu": variantData,
        'secure_token': secureToken,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(urlCheckout), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'checkOut');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          await EasyLoading.dismiss();
          // Navigator.pushAndRemoveUntil(
          //     context,
          //     MaterialPageRoute(
          //         builder: (_) => FinishOrder(pinOrder: jsonObject['pin'])));
          context.read<OrdersBloc>().clearOrder();
          Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (_) => const ViewBillNew()),
              (route) => false);
        } else if (jsonObject['code'] == 'ORDER_LOCK') {
          await EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          // Navigator.push(context,
          //     MaterialPageRoute(builder: (_) => FinishOrder(isLocked: true)));
        } else {
          await EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
        }
      } else {
        await EasyLoading.dismiss();
        EasyLoading.showToast('Something Went Wrong');
      }
    } catch (e) {
      await EasyLoading.dismiss();
      EasyLoading.showToast('Something Went Wrong');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: checkOut, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
    }
  }

  static Future<bool> softLockTable(
      String branchCode, String brandCode, String orderId,
      {String role = '', String cashierName = ''}) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/softlock_table";
    await EasyLoading.show(
      status: 'Harap tunggu...',
      maskType: EasyLoadingMaskType.none,
    );
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_id": orderId,
        "role": role,
        "cashier_name": cashierName,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      var jsonObject = await httpPost(apiUrl, bodies, 'softLockTable');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          EasyLoading.dismiss();
          EasyLoading.showToast('Meja telah ditandai sebagai selesai');
          return true;
        } else {
          EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          return true;
        }
      } else {
        EasyLoading.dismiss();
        EasyLoading.showToast('Something went wrong');
        return false;
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: softLockTable, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return false;
    }
  }

  static Future<bool> deleteOrderDetail(String orderIdDetail) async {
    String branchCode = prefs.getString('outlet') ?? '';
    String customerName = prefs.getString('userName') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? 'customer';
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/delete_order_detail";
    await EasyLoading.show(
      status: 'Harap tunggu...',
      maskType: EasyLoadingMaskType.none,
    );
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_detail_id": orderIdDetail,
        "customer_name": customerName,
        "role": role,
        "cashier_name": cashierName,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      var jsonObject = await httpPost(apiUrl, bodies, 'deleteOrderDetail');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          EasyLoading.dismiss();
          EasyLoading.showToast('Order berhasil didelete');
          return true;
        } else {
          EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          return false;
        }
      } else {
        EasyLoading.dismiss();
        EasyLoading.showToast('Something went wrong');
        return false;
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: deleteOrderDetail, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return false;
    }
  }

  // static Future<MemberInfo> memberInfo(String token) async {
  //   MemberInfo memberInfo = MemberInfo(
  //     id: '',
  //     name: '',
  //     cardNumber: '',
  //     expireDate: '',
  //     promotionCode: '',
  //     tier: '',
  //     balance: '',
  //   );
  //   String apiUrl = "${crmUrl}get_member_info";

  //   try {
  //     Map data = {"secure_token": token};
  //     var bodies = jsonEncode(data);
  //     var jsonObject = await httpPost(apiUrl, bodies, 'memberInfo');
  //     if (jsonObject != false) {
  //       if (jsonObject['status'].toString().toLowerCase() == 'ok') {
  //         memberInfo = MemberInfo.getInfo(
  //             (jsonObject as Map<dynamic, dynamic>)['data']['member']);
  //         await prefs.setString(
  //             'userName', jsonObject['data']['member']['name']);
  //       }
  //       return memberInfo;
  //     } else {
  //       return memberInfo;
  //     }
  //   } catch (e) {
  //     if (debug) {
  //       logd('API CLASS ON API.DART, FUNGSI: memberInfo, URL : $apiUrl',
  //           'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
  //     }
  //     return memberInfo;
  //   }
  // }

  static Future<MemberInfo> memberInfo(String token) async {
    MemberInfo memberInfo = MemberInfo(
        id: '',
        name: '',
        cardNumber: '',
        expireDate: '',
        promotionCode: '',
        tier: '',
        balance: '');
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/get_member_info";
    String branchCode = prefs.getString('outlet') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';
    try {
      Map data = {
        "secure_token": token,
        "role": role,
        "cashier_name": cashierName,
        "branch_code": branchCode,
        "brand_code": brandCode,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      var jsonObject = await httpPost(apiUrl, bodies, 'memberInfo');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          memberInfo =
              MemberInfo.getInfo((jsonObject as Map<dynamic, dynamic>)['data']);
          await prefs.setString('userName', jsonObject['data']['name']);
        }
        return memberInfo;
      } else {
        return memberInfo;
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: memberInfo, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return memberInfo;
    }
  }

  static Future<String> addPaymentBalance(
      BuildContext context,
      String orderId,
      String branchCode,
      String brandCode,
      String customerName,
      int amount) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/add_payment_balance";

    await EasyLoading.show(
      status: 'Harap tunggu...',
      maskType: EasyLoadingMaskType.none,
    );
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String token = prefs.getString('token') ?? '';
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_id": orderId,
        "customer_name": customerName,
        "role": role,
        "cashier_name": cashierName,
        "amount": amount,
        "secure_token": token,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'addPaymentBalance');
      if (jsonObject != false) {
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          await EasyLoading.dismiss();

          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (_) => const ViewBillNew()));
          return 'OK';
        } else {
          await EasyLoading.dismiss();
          EasyLoading.showToast(jsonObject['msg']);
          return jsonObject['msg'];
        }
      } else {
        await EasyLoading.dismiss();
        EasyLoading.showToast('Something Went Wrong');
        return '';
      }
    } catch (e) {
      await EasyLoading.dismiss();
      EasyLoading.showToast(
          'Ups.. Sepertinya terjadi kendala, silakan coba lagi');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: addPaymentBalance, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return '';
    }
  }

  static Future<String> checkStatusPaymentUrl(String paymentId) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/check_status";

    String branchCode = prefs.getString('outlet') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';
    await EasyLoading.show(
      status: 'Geting url...',
      maskType: EasyLoadingMaskType.none,
    );
    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "role": role,
        "cashier_name": cashierName,
        "payment_id": paymentId,
        "from": fromByod
      };
      var bodies = jsonEncode(data);
      // var apiResult = await http.post(Uri.parse(apiUrl), body: bodies);
      // var jsonObject = jsonDecode(apiResult.body);

      var jsonObject = await httpPost(apiUrl, bodies, 'checkStatusPaymentUrl');

      if (jsonObject != false) {
        await EasyLoading.dismiss();
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          return jsonObject['url'];
        } else {
          EasyLoading.showToast(jsonObject['msg']);
          return '';
        }
      } else {
        await EasyLoading.dismiss();
        EasyLoading.showToast('Something Went Wrong');
        return '';
      }
    } catch (e) {
      await EasyLoading.dismiss();
      EasyLoading.showToast(
          'Ups.. Sepertinya terjadi kendala, silakan coba lagi');
      if (debug) {
        logd(
            'API CLASS ON API.DART, FUNGSI: checkStatusPaymentUrl, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return '';
    }
  }

  static Future<bool> changeOrderDetail(BuildContext context,
      String orderDetail, int quantity, String notes) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/update_order_detail";

    String branchCode = prefs.getString('outlet') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "order_detail_id": orderDetail,
        "quantity": quantity,
        "notes": notes,
        "role": role,
        "cashier_name": cashierName,
        "from": fromByod
      };

      var bodies = jsonEncode(data);

      var jsonObject = await httpPost(apiUrl, bodies, 'changeOrderDetail');
      if (jsonObject != false) {
        await EasyLoading.dismiss();
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          return true;
        } else {
          EasyLoading.showToast(jsonObject['msg']);
          return false;
        }
      } else {
        EasyLoading.showToast('Something Went Wrong');
        return false;
      }
    } catch (e) {
      EasyLoading.showToast(
          'Ups.. Sepertinya terjadi kendala, silakan coba lagi');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: changeOrderDetail, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return false;
    }
  }

  static Future<bool> sendFeedBack(int feedBack, String message, String orderId,
      List<String> feedbackOptions) async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/feedback";

    String branchCode = prefs.getString('outlet') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String userName = prefs.getString('userName') ?? '';

    await EasyLoading.show(
      status: 'Mengirim penilaian',
      maskType: EasyLoadingMaskType.none,
    );

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "role": role,
        "cashier_name": cashierName,
        "customer_name": userName,
        "order_id": orderId,
        "feedback": feedBack,
        "message": message,
        "feedback_options": feedbackOptions,
        "from": fromByod
      };

      var bodies = jsonEncode(data);

      var jsonObject = await httpPost(apiUrl, bodies, 'sendFeedBack');
      if (jsonObject != false) {
        await EasyLoading.dismiss();
        if (jsonObject['status'].toString().toLowerCase() == 'ok') {
          EasyLoading.showToast('Penilaian anda telah dikirim');
          return true;
        } else {
          EasyLoading.showToast(jsonObject['msg']);
          return false;
        }
      } else {
        EasyLoading.showToast('Something Went Wrong');
        return false;
      }
    } catch (e) {
      EasyLoading.showToast(
          'Ups.. Sepertinya terjadi kendala, silakan coba lagi');
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: sendFeedBack, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return false;
    }
  }

  static Future<List<FeedBackOption>> getOptionFeedback() async {
    String baseUrl = prefs.getString('baseUrl') ?? '';
    String apiUrl = "${baseUrl}romi/api/byod/get_feedback_options";

    String branchCode = prefs.getString('outlet') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? 'customer';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String userName = prefs.getString('userName') ?? '';
    List<FeedBackOption> feedBack = [];

    try {
      Map data = {
        "branch_code": branchCode,
        "brand_code": brandCode,
        "role": role,
        "cashier_name": cashierName,
        "customer_name": userName,
        "from": fromByod
      };
      var bodies = jsonEncode(data);

      var jsonObject = await httpPost(apiUrl, bodies, 'getOptionFeedback');
      if (jsonObject != false) {
        List<dynamic> dataFeedback =
            (jsonObject as Map<dynamic, dynamic>)['data'];

        for (int d = 0; d < dataFeedback.length; d++) {
          List<String> feedBackAnswer = [];
          for (int i = 0;
              i < dataFeedback[d]['feedback_answer_option'].length;
              i++) {
            feedBackAnswer.add(dataFeedback[d]['feedback_answer_option'][i]);
          }
          var z = {
            "id": dataFeedback[d]['id'],
            "brand_code": dataFeedback[d]['brand_code'],
            "feedback_options": dataFeedback[d]['feedback_options'],
            "header_options": dataFeedback[d]['header_options'],
            "feedback_answer_option": feedBackAnswer
          };
          feedBack.add(FeedBackOption.getOption(z));
        }
        return feedBack;
      } else {
        return feedBack;
      }
    } catch (e) {
      if (debug) {
        logd('API CLASS ON API.DART, FUNGSI: getOptionFeedback, URL : $apiUrl',
            'ERROR CONNECT TO SERVER, ERROR CATCH : $e');
      }
      return feedBack;
    }
  }
}
