import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:sqflite_common/sqlite_api.dart';
import 'package:trialOrderPro/data/homescreen/brand_data.dart';
import 'package:trialOrderPro/data/model/brand_data_model.dart';
import 'package:trialOrderPro/modules/brands/controllers/biotrue/biotrue_one_day_fa_controller_DACH.dart';
import 'package:trialOrderPro/modules/brands/controllers/biotrue/biotrue_one_day_fp_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/biotrue/biotrue_one_day_fp_controller_DACH.dart';
import 'package:trialOrderPro/modules/brands/controllers/biotrue/biotrue_one_day_fp_LH_controller_DACH.dart';
import 'package:trialOrderPro/modules/brands/controllers/infuse/infuse_fa_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/infuse/infuse_mf_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_fa_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_fa_controller_DACH.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_fp_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_fp_controller_DACH.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_mfa_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_one_day_mediumfit1_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_one_day_mediumfit_2_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_svs_controller.dart';
import 'package:trialOrderPro/modules/brands/controllers/ultra/ultra_one_day_smallfit_controller.dart';
import 'package:trialOrderPro/utils/config/loggers.dart';

import '../../../data/dummy_data/dummy_order_history_cart_item.dart';
import '../../../data/helper/database_helper.dart';
import '../../../data/model/customer_data_model.dart';
import '../../../utils/common/functions.dart';
import '../../../utils/constant/database_constant.dart';
import '../../brands/controllers/biotrue/biotrue_one_day_fa_controller.dart';
import '../../brands/controllers/biotrue/biotrue_one_day_svs_controller.dart';
import '../../brands/controllers/eureka/eureka_daily_controller.dart';
import '../../brands/controllers/eureka/eureka_monthly_controller.dart';
import '../../brands/controllers/infuse/infuse_svs_controller.dart';
import '../../brands/controllers/lc_oneday/lc_oneday_controller.dart';
import '../../customer/controllers/customer_list_controller.dart';
import '../../home/controllers/dashboard_controller.dart';

class CartController extends GetxController {
  var cartOpenRatio = 0.38;
  late CustomerListControllerGetX customerController;
  final box = GetStorage();
  late DashboardController dashboardController;
  late Database _database;

  @override
  void onInit() {
    super.onInit();
    customerController = Get.put(CustomerListControllerGetX());
    dashboardController = Get.put(DashboardController());
    _initDatabase();
  }

  bool isLoading = false;
  bool isDrawerOpen = false;
  bool isTileVisible = true;
  bool isExpanded = false;
  String newlyAddedDrawer = '';
  int totalItems = 0;
  int minQty = 1;
  int maxQty = 10;

  Map<String, Map<String, Map<String, Map<String, dynamic>>>> brandData = {};

  List<BasicTiles> basicTilesList = [];

  Future<void> _initDatabase() async {
    _database = await DatabaseHelper.instance.database;
    await orderHistoryTable(_database);
  }

  bool setIsDrawerOpen() {
    isDrawerOpen = !isDrawerOpen;
    update();
    return isDrawerOpen;
  }

  setLoading(value) {
    isLoading = value;
    update();
  }

  double openCartDrawerSize(BuildContext context) {
    return getScreenWidth(context) * cartOpenRatio;
  }

  //adds the lens data to local db
  void addLensValue(BrandDataModel brandDataModel) async {
    final brand = brandDataModel.brand;
    final drawer = brandDataModel.drawer;
    final indication = brandDataModel.indication;
    final lensKey = brandDataModel.lensKey;
    final lensValue = brandDataModel.lensValue.replaceAll(' ', '');
    final axis = brandDataModel.axis ?? '';
    final highAdd = brandDataModel.highAdd ?? '';
    final lowAdd = brandDataModel.lowAdd ?? '';
    final customerId = brandDataModel.customerId;
    final sku = brandDataModel.sku;
    final range = brandDataModel.range;
    String cyl = brandDataModel.cyl ?? '';

    newlyAddedDrawer = drawer;
    box.write('newlyAddedDrawer', newlyAddedDrawer);

    brandData.putIfAbsent(brand, () => {});
    brandData[brand]!.putIfAbsent(indication, () => {});
    brandData[brand]![indication]!.putIfAbsent(drawer, () => {});
    if (lensValue != 'EMPTY' && lensValue != '') {
      if (!brandData[brand]![indication]![drawer]!.containsKey(sku)) {
        brandData[brand]![indication]![drawer]![sku!] = {
          'power': lensValue,
          'qty': 1,
          'keys': [lensKey],
          'range': range
        };

        if (cyl.isNotEmpty) {
          brandData[brand]![indication]![drawer]![sku]
              .putIfAbsent('cyl', () => cyl);
        }

        if (axis.isNotEmpty) {
          brandData[brand]![indication]![drawer]![sku]
              .putIfAbsent('axis', () => axis);
        }
        if (highAdd.isNotEmpty) {
          brandData[brand]![indication]![drawer]![sku]
              .putIfAbsent('highAdd', () => true);
        }
        if (lowAdd.isNotEmpty) {
          brandData[brand]![indication]![drawer]![sku]
              .putIfAbsent('lowAdd', () => true);
        }
      } else {
        if (brandData[brand]![indication]![drawer]![sku]['keys']
            .contains(lensKey)) {
          brandData[brand]![indication]![drawer]![sku]['keys'].remove(lensKey);
          brandData[brand]![indication]![drawer]![sku]['qty'] =
              brandData[brand]![indication]![drawer]![sku]['keys'].length;

          if (brandData[brand]![indication]![drawer]![sku]['keys'].isEmpty) {
            brandData[brand]![indication]![drawer]!.remove(sku);
          }
        } else {
          if (cyl.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('cyl', () => cyl);
          }

          if (axis.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('axis', () => axis);
          }
          if (highAdd.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('highAdd', () => true);
          }
          if (lowAdd.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('lowAdd', () => true);
          }
          brandData[brand]![indication]![drawer]![sku]['keys'].add(lensKey);
          brandData[brand]![indication]![drawer]![sku]['qty'] =
              brandData[brand]![indication]![drawer]![sku]['keys'].length;
        }
      }

      //Logger.d('brandData', brandData);
      //create a brandlist in a format to store lens data
      createList();

      final db = await DatabaseHelper.instance.database;
      List<Map<String, dynamic>>? existingData = await queryCartItems(
          db,
          brand,
          indication,
          drawer,
          lensKey,
          lensValue,
          axis,
          highAdd,
          lowAdd,
          sku!,
          customerId);

      if (existingData!.isEmpty) {
        try {
          await db.insert(cart_table, brandDataModel.toMap());
        } catch (e) {
          Logger.e('Error inserting data: $e');
        }
      } else {
        await deleteCartItem(
            db, brand, indication, drawer, lensKey, lensValue, sku, customerId);
      }
    }

    // printData();
    fetchCartDataFromDatabase();
    update();
  }

  //works for increment and decrement of lens data
  void updateBrandData(lensData) {
    for (final data in lensData) {
      final String brand = data['brand'];
      final String indication = data['indication'];
      final String drawer = data['drawer'];
      final String lensKey = data['lensKey'];
      final String axis = data['axis'] ?? '';
      final String highAdd = data['highAdd'] ?? '';
      final String lowAdd = data['lowAdd'] ?? '';
      final String lensValue = data['lensValue'];
      final String sku = data['sku'];
      final String cyl = data['cyl'] ?? '';
      final rangeString = data['range'].toString();
      final int qty = data['qty'];
      final str = rangeString
          .replaceAll("[", "")
          .replaceAll("]", "")
          .replaceAll(" ", "");
      List<String> range = str.split(",");

      brandData.putIfAbsent(brand, () => {});
      brandData[brand]!.putIfAbsent(indication, () => {});
      brandData[brand]![indication]!.putIfAbsent(drawer, () => {});

      if (lensValue != 'EMPTY') {
        if (!brandData[brand]![indication]![drawer]!.containsKey(sku)) {
          brandData[brand]![indication]![drawer]![sku] = {
            'power': lensValue,
            'qty': 1,
            'keys': [lensKey],
            'range': range
          };
          if (cyl.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('cyl', () => cyl);
          }
          if (axis.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('axis', () => axis);
          }
          if (highAdd.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('highAdd', () => true);
          }
          if (lowAdd.isNotEmpty) {
            brandData[brand]![indication]![drawer]![sku]
                .putIfAbsent('lowAdd', () => true);
          }
        } else {
          if (!brandData[brand]![indication]![drawer]![sku]['keys']
              .contains(lensKey)) {
            if (cyl.isNotEmpty) {
              brandData[brand]![indication]![drawer]![sku]
                  .putIfAbsent('cyl', () => cyl);
            }

            if (axis.isNotEmpty) {
              brandData[brand]![indication]![drawer]![sku]
                  .putIfAbsent('axis', () => axis);
            }
            if (highAdd.isNotEmpty) {
              brandData[brand]![indication]![drawer]![sku]
                  .putIfAbsent('highAdd', () => true);
            }
            if (lowAdd.isNotEmpty) {
              brandData[brand]![indication]![drawer]![sku]
                  .putIfAbsent('lowAdd', () => true);
            }
            brandData[brand]![indication]![drawer]![sku]['keys'].add(lensKey);
            brandData[brand]![indication]![drawer]![sku]['qty'] =
                brandData[brand]![indication]![drawer]![sku]['keys'].length;
          }
        }
      }
    }
  }

  Future<List<Map<String, dynamic>>?> queryCartItems(
    Database db,
    String brand,
    String indication,
    String drawer,
    String lensKey,
    String lensValue,
    String axis,
    String highAdd,
    String lowAdd,
    String sku,
    String customerId,
  ) async {
    try {
      final List<dynamic> whereArgs = [
        brand,
        indication,
        drawer,
        lensKey,
        lensValue,
        sku,
        customerId
      ];

      String whereClause =
          'brand = ? AND indication = ? AND drawer = ? AND lensKey = ? AND lensValue = ? AND sku = ? AND customerId = ?';

      if (axis.isNotEmpty) {
        whereArgs.add(axis);
        whereClause += ' AND axis = ?';
      }

      if (highAdd.isNotEmpty) {
        whereArgs.add(highAdd);
        whereClause += ' AND highAdd = ?';
      }
      if (lowAdd.isNotEmpty) {
        whereArgs.add(lowAdd);
        whereClause += ' AND lowAdd = ?';
      }

      final List<Map<String, dynamic>> existingData = await db.query(
        cart_table,
        where: whereClause,
        whereArgs: whereArgs,
      );

      // Return the result, which is a list of maps representing the queried data.
      return existingData;
    } catch (e) {
      // Handle errors if necessary
      // Logger.e('Error querying data: $e');
      print('Error querying data: $e');
      return null;
    }
  }

  //delete cart table function
  //it deletes cart table
  Future<void> deleteCartItem(
      Database db,
      String brand,
      String indication,
      String drawer,
      String lensKey,
      String lensValue,
      String sku,
      String customerId) async {
    try {
      await db.delete(
        cart_table,
        where:
            'brand = ? AND indication = ? AND drawer = ? AND lensKey = ? AND lensValue = ? AND sku = ? AND customerId = ?',
        whereArgs: [
          brand,
          indication,
          drawer,
          lensKey,
          lensValue,
          sku,
          customerId
        ],
      );
      createList();
    } catch (e) {
      print('Error removing data: $e');
    }
  }

  //prints customer id and lens data
  Future<void> printData() async {
    final db = await DatabaseHelper.instance.database;
    final List<Map<String, dynamic>> lensData = await db.query(cart_table);

    if (lensData.isNotEmpty) {
      for (final data in lensData) {
        print('custId: ${data['customerId']}');
        print('ID: ${data['id']}');
        print('Brand: ${data['brand']}');
        print('Indication: ${data['indication']}');
        print('Drawer: ${data['drawer']}');
        print('Lens Key: ${data['lensKey']}');
        print('Lens Value: ${data['lensValue']}');
        print('SKU no: ${data['sku']}');
        print('Axis: ${data['axis']}');
        print('High Add: ${data['highAdd']}');
        print('Low Add: ${data['lowAdd']}');
        print('Lens Qty: ${data['qty']}');
        print('-----------------------');
      }
    } else {
      print('No lens data available.');
    }
  }

  void updateLensValueCount(
      {required String brand,
      required String indication,
      required String drawer,
      required String lensKey,
      required String sku,
      required String lensValue,
      required int increment,
      List<dynamic>? range,
      String? add,
      String? cyl,
      String? axis,
      List<String>? keys,
      int? maxQty = 10}) async {
    bool doIncrement = increment == 1 ? true : false;

    if (brandData.containsKey(brand) &&
        brandData[brand]!.containsKey(indication) &&
        brandData[brand]![indication]!.containsKey(drawer) &&
        brandData[brand]![indication]![drawer]!.containsKey(sku) &&
        brandData[brand]![indication]![drawer]![sku]!.containsKey('qty')) {
      int addedQtry = brandData[brand]![indication]![drawer]![sku]!['qty'] =
          (brandData[brand]![indication]![drawer]![sku]!['qty'] ?? 0) +
              increment;
      if (brand == brands[0].name) {
        if (indication == brands[0].indications[2].name) {
          /// BTOD FP Dach
          if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) {
            Get.find<BtodFPLHDrawerControllerDach>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                add: add,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[0].indications[1].name) {
          /// Biotru OneDay Dach
          if (Get.isRegistered<BtodFADachDrawerController>()) {
            Get.find<BtodFADachDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                cyl: cyl,
                axis: axis,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[0].indications[0].name) {
          /// Biotru FA
          if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
            Get.find<BtodFPDrawerControllerDach>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } //else if (indication == brands[0].indications[3].name) {
        /// Biotru OneDay DACH
        // if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
        //   Get.find<BtodFPDrawerControllerDach>().updateLensCount(
        //       brand: brand,
        //       indication: indication,
        //       drawer: drawer,
        //       lensKey: lensKey,
        //       lensValue: lensValue,
        //       sku: sku,
        //       doIncrement: doIncrement,
        //       keys: keys!,
        //       range: range,
        //       addedQty: addedQtry,
        //       maxQty: maxQty!);
        // }
        // }
      } else if (brand == brands[1].name) {
        if (indication == brands[1].indications[1].name) {
          /// Ultra SVS
          if (Get.isRegistered<UltraSVSDrawerController>()) {
            Get.find<UltraSVSDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[3].name) {
          /// Ultra FP DACH
          if (Get.isRegistered<UltraFPDachDrawerController>()) {
            Get.find<UltraFPDachDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                addedQty: addedQtry,
                //cyl: cyl,
                range: range,
                //axis: axis,
                add:add,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[2].name) {
          /// Ultra FA DACH
          if (Get.isRegistered<UltraFADachDrawerController>()) {
            Get.find<UltraFADachDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                cyl: cyl,
                axis: axis,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[0].name) {
          /// Ultra OneDay
          if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
            Get.find<ULTRAOneDayDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
          if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>()) {
            Get.find<ULTRAOneDayMediumfit1DrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
           if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>()) {
            Get.find<ULTRAOneDayMediumfit2DrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[4].name) {
          /// Ultra MFA
          if (Get.isRegistered<UltraMFADrawerController>()) {
            Get.find<UltraMFADrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                cyl: cyl,
                axis: axis,
                add: add,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } //else if (indication == brands[1].indications[4].name) {
        /// Ultra OneDay
        // if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
        //   Get.find<ULTRAOneDayDrawerController>().updateLensCount(
        //       brand: brand,
        //       indication: indication,
        //       drawer: drawer,
        //       lensKey: lensKey,
        //       lensValue: lensValue,
        //       sku: sku,
        //       doIncrement: doIncrement,
        //       keys: keys!,
        //       range: range,
        //       addedQty: addedQtry,
        //       maxQty: maxQty!);
        // }
        // }
      } else if (brand == brands[2].name) {
        if (indication == brands[2].indications[0].name) {
          /// Infuse SVS
          if (Get.isRegistered<InfuseSvsDrawerController>()) {
            Get.find<InfuseSvsDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[2].indications[1].name) {
          /// Infuse MF
          if (Get.isRegistered<InfuseMfDrawerController>()) {
            Get.find<InfuseMfDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                add: add,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[2].indications[2].name) {
          /// Infuse FA
          if (Get.isRegistered<InfuseFaDrawerController>()) {
            Get.find<InfuseFaDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                axis: axis,
                cyl: cyl,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        }
      } else if (brand == brands[3].name) {
        if (indication == brands[3].indications[0].name) {
          /// Eureka Daily
          if (Get.isRegistered<EurekaDailyDrawerController>()) {
            Get.find<EurekaDailyDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[3].indications[1].name) {
          /// Eureka Monthly
          if (Get.isRegistered<EurekaMonthlyDrawerController>()) {
            Get.find<EurekaMonthlyDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        }
      } else if (brand == brands[4].name) {
        if (indication == brands[4].indications[0].name) {
          /// LC Oneday
          if (Get.isRegistered<Lc_Oneday_DrawerController>()) {
            Get.find<Lc_Oneday_DrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        }
      }

      createList();

      update();
    }
  }

  //update the count of lens value on checkout page
  // void updateLensValueCountCheckOut(
  //     {required String brand,
  //     required String indication,
  //     required String drawer,
  //     required String lensKey,
  //     required String sku,
  //     required String lensValue,
  //     required int increment,
  //     List<dynamic>? range,
  //     String? add,
  //     String? cyl,
  //     String? axis,
  //     String? customer_id,
  //     List<String>? keys,
  //     int? maxQty = 10}) async {
  //   bool doIncrement = increment == 1 ? true : false;

  //   if (brandData.containsKey(brand) &&
  //       brandData[brand]!.containsKey(indication) &&
  //       brandData[brand]![indication]!.containsKey(drawer) &&
  //       brandData[brand]![indication]![drawer]!.containsKey(sku) &&
  //       brandData[brand]![indication]![drawer]![sku]!.containsKey('qty')) {
  //     int addedQty = brandData[brand]![indication]![drawer]![sku]!['qty'] =
  //         (brandData[brand]![indication]![drawer]![sku]!['qty'] ?? 0) +
  //             increment;
  //     int totalQty = range!.length;
  //     int remQty = totalQty - addedQty;

  //     String highAdd = '';
  //     String lowAdd = '';

  //     if (add == 'High' || add == 'HIGH ADD') {
  //       highAdd = 'High';
  //     } else if (add == 'Low' || add == 'LOW ADD') {
  //       lowAdd = 'Low';
  //     }

  //     final db = await DatabaseHelper.instance.database;
  //     CustomerData? customerData = CustomerData.getCustomerDataFromStorage();
  //     String? customerId =
  //         customer_id ?? customerData?.Id_From_LocalDB.toString();
  //     if (doIncrement) {
  //       if (addedQty > totalQty && remQty < 1) {
  //         brandData[brand]![indication]![drawer]![sku]['keys']
  //             .add((1000 + addedQty - totalQty).toString());
  //         brandData[brand]![indication]![drawer]![sku]['qty'] =
  //             brandData[brand]![indication]![drawer]![sku]['keys'].length;
  //         BrandDataModel brandDataModel = BrandDataModel(
  //             brand: brand,
  //             indication: indication,
  //             drawer: drawer,
  //             lensKey: (1000 + addedQty - totalQty).toString(),
  //             lensValue: lensValue,
  //             sku: sku,
  //             axis: axis,
  //             cyl: cyl,
  //             range: range,
  //             highAdd: highAdd,
  //             lowAdd: lowAdd,
  //             customerId: customerId!);

  //         await db.insert(cart_table, brandDataModel.toMap());
  //       } else {
  //         for (int i = 0; i < range.length; i++) {
  //           if (!keys!.contains(range[i])) {
  //             brandData[brand]![indication]![drawer]![sku]['keys']
  //                 .add(range[i].toString());
  //             brandData[brand]![indication]![drawer]![sku]['qty'] =
  //                 brandData[brand]![indication]![drawer]![sku]['keys']
  //                     .length; // Replace with your list

  //             BrandDataModel brandDataModel = BrandDataModel(
  //                 brand: brand,
  //                 indication: indication,
  //                 drawer: drawer,
  //                 lensKey: range[i].toString(),
  //                 lensValue: lensValue,
  //                 sku: sku,
  //                 axis: axis,
  //                 cyl: cyl,
  //                 range: range,
  //                 highAdd: highAdd,
  //                 lowAdd: lowAdd,
  //                 customerId: customerId!);

  //             await db.insert(cart_table, brandDataModel.toMap());

  //             update();
  //             break;
  //           }
  //         }
  //       }
  //     } else {
  //       if (addedQty > totalQty || addedQty == totalQty) {
  //         brandData[brand]![indication]![drawer]![sku]['keys']
  //             .remove(((1000 + (addedQty + 1) - totalQty)).toString());
  //         brandData[brand]![indication]![drawer]![sku]['qty'] =
  //             brandData[brand]![indication]![drawer]![sku]['keys'].length;
  //         await db.delete(
  //           cart_table,
  //           where:
  //               'brand = ? AND indication = ? AND drawer = ? AND lensKey = ? AND lensValue = ? AND sku = ? AND customerId = ?',
  //           whereArgs: [
  //             brand,
  //             indication,
  //             drawer,
  //             ((1000 + (addedQty + 1) - totalQty)).toString(),
  //             lensValue,
  //             sku,
  //             customerId
  //           ],
  //         );
  //       } else {
  //         for (int i = range.length - 1; i > 0; i--) {
  //           if (keys!.contains(range[i])) {
  //             brandData[brand]![indication]![drawer]![sku]['keys']
  //                 .remove(range[i].toString());
  //             brandData[brand]![indication]![drawer]![sku]['qty'] =
  //                 brandData[brand]![indication]![drawer]![sku]['keys'].length;

  //             await db.delete(
  //               cart_table,
  //               where:
  //                   'brand = ? AND indication = ? AND drawer = ? AND lensKey = ? AND lensValue = ? AND sku = ? AND customerId = ?',
  //               whereArgs: [
  //                 brand,
  //                 indication,
  //                 drawer,
  //                 range[i].toString(),
  //                 lensValue,
  //                 sku,
  //                 customerId
  //               ],
  //             );
  //             update();
  //             break;
  //           }
  //         }
  //       }
  //     }
  //     createList();
  //     update();
  //   }
  // }
  void updateLensValueCountCheckOut(
      {required String brand,
      required String indication,
      required String drawer,
      required String lensKey,
      required String sku,
      required String lensValue,
      required int increment,
      List<dynamic>? range,
      String? add,
      String? cyl,
      String? axis,
      List<String>? keys,
      int? maxQty = 10}) async {
    bool doIncrement = increment == 1 ? true : false;

    if (brandData.containsKey(brand) &&
        brandData[brand]!.containsKey(indication) &&
        brandData[brand]![indication]!.containsKey(drawer) &&
        brandData[brand]![indication]![drawer]!.containsKey(sku) &&
        brandData[brand]![indication]![drawer]![sku]!.containsKey('qty')) {
      int addedQtry = brandData[brand]![indication]![drawer]![sku]!['qty'] =
          (brandData[brand]![indication]![drawer]![sku]!['qty'] ?? 0) +
              increment;
      if (brand == brands[0].name) {
        if (indication == brands[0].indications[2].name) {
          /// BTOD FP Dach
          if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) {
            Get.find<BtodFPLHDrawerControllerDach>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                add: add,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[0].indications[1].name) {
          /// Biotru OneDay Dach
          if (Get.isRegistered<BtodFADachDrawerController>()) {
            Get.find<BtodFADachDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                axis: axis,
                cyl: cyl,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[0].indications[0].name) {
          /// Biotru FA
          if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
            Get.find<BtodFPDrawerControllerDach>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } 
      } else if (brand == brands[1].name) {
        if (indication == brands[1].indications[1].name) {
          /// Ultra SVS
          if (Get.isRegistered<UltraSVSDrawerController>()) {
            Get.find<UltraSVSDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[3].name) {
          /// Ultra FP DACH
          if (Get.isRegistered<UltraFPDachDrawerController>()) {
            Get.find<UltraFPDachDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                addedQty: addedQtry,
                //cyl: cyl,
                range: range,
                //axis: axis,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[2].name) {
          /// Ultra FA DACH
          if (Get.isRegistered<UltraFADachDrawerController>()) {
            Get.find<UltraFADachDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                cyl: cyl,
                axis: axis,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[0].name) {
          /// Ultra OneDay
          if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
            Get.find<ULTRAOneDayDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
          if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>()) {
            Get.find<ULTRAOneDayMediumfit1DrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
           if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>()) {
            Get.find<ULTRAOneDayMediumfit2DrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[1].indications[4].name) {
          /// Ultra MFA
          if (Get.isRegistered<UltraMFADrawerController>()) {
            Get.find<UltraMFADrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                cyl: cyl,
                axis: axis,
                add: add,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } //else if (indication == brands[1].indications[4].name) {
        /// Ultra OneDay
        // if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
        //   Get.find<ULTRAOneDayDrawerController>().updateLensCount(
        //       brand: brand,
        //       indication: indication,
        //       drawer: drawer,
        //       lensKey: lensKey,
        //       lensValue: lensValue,
        //       sku: sku,
        //       doIncrement: doIncrement,
        //       keys: keys!,
        //       range: range,
        //       addedQty: addedQtry,
        //       maxQty: maxQty!);
        // }
        // }
      } else if (brand == brands[2].name) {
        if (indication == brands[2].indications[0].name) {
          /// Infuse SVS
          if (Get.isRegistered<InfuseSvsDrawerController>()) {
            Get.find<InfuseSvsDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[2].indications[1].name) {
          /// Infuse MF
          if (Get.isRegistered<InfuseMfDrawerController>()) {
            Get.find<InfuseMfDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                add: add,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[2].indications[2].name) {
          /// Infuse FA
          if (Get.isRegistered<InfuseFaDrawerController>()) {
            Get.find<InfuseFaDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                axis: axis,
                cyl: cyl,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        }
      } else if (brand == brands[3].name) {
        if (indication == brands[3].indications[0].name) {
          /// Eureka Daily
          if (Get.isRegistered<EurekaDailyDrawerController>()) {
            Get.find<EurekaDailyDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        } else if (indication == brands[3].indications[1].name) {
          /// Eureka Monthly
          if (Get.isRegistered<EurekaMonthlyDrawerController>()) {
            Get.find<EurekaMonthlyDrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        }
      } else if (brand == brands[4].name) {
        if (indication == brands[4].indications[0].name) {
          /// LC Oneday
          if (Get.isRegistered<Lc_Oneday_DrawerController>()) {
            Get.find<Lc_Oneday_DrawerController>().updateLensCount(
                brand: brand,
                indication: indication,
                drawer: drawer,
                lensKey: lensKey,
                lensValue: lensValue,
                sku: sku,
                doIncrement: doIncrement,
                keys: keys!,
                range: range,
                addedQty: addedQtry,
                maxQty: maxQty!);
          }
        }
      }

      createList();

      update();
    }
  }
  
  void getLensValueAll() {
    if (Get.isRegistered<BtodSVSDrawerController>()) {
      Get.find<BtodSVSDrawerController>().clearRows();
      Get.find<BtodSVSDrawerController>().getLensValues();
    }

    if (Get.isRegistered<BtodFPDrawerController>()) {
      Get.find<BtodFPDrawerController>().clearRows();
      Get.find<BtodFPDrawerController>().getLensValues();
    }
    //BTOD OneDay DACH
    if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
      Get.find<BtodFPDrawerControllerDach>().clearRows();
      Get.find<BtodFPDrawerControllerDach>().getLensValues();
    }

    if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) {
      Get.find<BtodFPLHDrawerControllerDach>().clearRows();
      Get.find<BtodFPLHDrawerControllerDach>().getLensValues();
    }

    if (Get.isRegistered<BtodFADachDrawerController>()) {
      Get.find<BtodFADachDrawerController>().clearRows();
      Get.find<BtodFADachDrawerController>().getLensValues();
    }

    if (Get.isRegistered<BtodFADrawerController>()) {
      Get.find<BtodFADrawerController>().clearRows();
      Get.find<BtodFADrawerController>().getLensValues();
    }

    if (Get.isRegistered<UltraSVSDrawerController>()) {
      Get.find<UltraSVSDrawerController>().clearRows();
      Get.find<UltraSVSDrawerController>().getLensValues();
    }

    if (Get.isRegistered<UltraFPDrawerController>()) {
      Get.find<UltraFPDrawerController>().clearRows();
      Get.find<UltraFPDrawerController>().getLensValues();
    }

    if (Get.isRegistered<UltraFPDachDrawerController>()) {
      Get.find<UltraFPDachDrawerController>().clearRows();
      Get.find<UltraFPDachDrawerController>().getLensValues();
    }

    if (Get.isRegistered<UltraFADrawerController>()) {
      Get.find<UltraFADrawerController>().clearRows();
      Get.find<UltraFADrawerController>().getLensValues();
    }
    //ULTRA FA DACH
    if (Get.isRegistered<UltraFADachDrawerController>()) {
      Get.find<UltraFADachDrawerController>().clearRows();
      Get.find<UltraFADachDrawerController>().getLensValues();
    }

    if (Get.isRegistered<UltraMFADrawerController>()) {
      Get.find<UltraMFADrawerController>().clearRows();
      Get.find<UltraMFADrawerController>().getLensValues();
    }

    if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
      Get.find<ULTRAOneDayDrawerController>().clearRows();
      Get.find<ULTRAOneDayDrawerController>().getLensValues();
    }
    if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>()) {
      Get.find<ULTRAOneDayMediumfit1DrawerController>().clearRows();
      Get.find<ULTRAOneDayMediumfit1DrawerController>().getLensValues();
    }
    if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>()) {
      Get.find<ULTRAOneDayMediumfit2DrawerController>().clearRows();
      Get.find<ULTRAOneDayMediumfit2DrawerController>().getLensValues();
    }

    if (Get.isRegistered<InfuseSvsDrawerController>()) {
      Get.find<InfuseSvsDrawerController>().clearRows();
      Get.find<InfuseSvsDrawerController>().getLensValues();
    }

    if (Get.isRegistered<InfuseMfDrawerController>()) {
      Get.find<InfuseMfDrawerController>().clearRows();
      Get.find<InfuseMfDrawerController>().getLensValues();
    }
    //Infuse Fa
    if (Get.isRegistered<InfuseFaDrawerController>()) {
      Get.find<InfuseFaDrawerController>().clearRows();
      Get.find<InfuseFaDrawerController>().getLensValues();
    }

    if (Get.isRegistered<EurekaDailyDrawerController>()) {
      Get.find<EurekaDailyDrawerController>().clearRows();
      Get.find<EurekaDailyDrawerController>().getLensValues();
    }

    if (Get.isRegistered<EurekaMonthlyDrawerController>()) {
      Get.find<EurekaMonthlyDrawerController>().clearRows();
      Get.find<EurekaMonthlyDrawerController>().getLensValues();
    }

    if (Get.isRegistered<Lc_Oneday_DrawerController>()) {
      Get.find<Lc_Oneday_DrawerController>().clearRows();
      Get.find<Lc_Oneday_DrawerController>().getLensValues();
    }
    update();
  }

  //remove cart item
  void removeCartItem(
      {required String brand,
      required String indication,
      required String drawer,
      required String lensValue,
      List<String>? keys,
      String? sku,
      String? add,
      String? customerId,
      String? axis}) async {
    String highAdd = '';
    String lowAdd = '';
    if (add == 'High') {
      highAdd = 'High';
    } else if (add == 'Low') {
      lowAdd = 'Low';
    }
    if (axis == '-') {
      axis = '';
    }

    if (brandData[brand]![indication]![drawer]![sku].containsKey('axis')) {
    } else if (brandData[brand]![indication]![drawer]![sku]
            .containsKey('highAdd') ||
        brandData[brand]![indication]![drawer]![sku].containsKey('lowAdd')) {
    } else {
      brandData[brand]![indication]![drawer]!.remove(sku);
    }

    await deleteFromCart(brand, indication, drawer, sku!, customerId!);
    await fetchCartDataFromDatabase(customerId: customerId);
    String andAxisQuery = '';

    if (brand == brands[0].name) {
      if (indication == brands[0].indications[2].name) {
        /// BTOD OneDay DACH
         if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) {
          Get.find<BtodFPLHDrawerControllerDach>().updateRows(sku,lensValue);
        }
      } if (indication == brands[0].indications[1].name) {
        /// BTOD OneDay DACH
         if (Get.isRegistered<BtodFADachDrawerController>()) {
          Get.find<BtodFADachDrawerController>().updateRows(sku,lensValue);
        }
      }  else if (indication == brands[0].indications[0].name) {
        /// Biotru FP
        if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
          Get.find<BtodFPDrawerControllerDach>().updateRows(sku, lensValue);
        }
      }  
    } else if (brand == brands[1].name) {
      if (indication == brands[1].indications[1].name) {
        /// Ultra SVS
        if (Get.isRegistered<UltraSVSDrawerController>()) {
          Get.find<UltraSVSDrawerController>().updateRows(lensValue);
        }
      } else if (indication == brands[1].indications[3].name) {
        /// Ultra FP DACH
        if (Get.isRegistered<UltraFPDachDrawerController>()) {
          Get.find<UltraFPDachDrawerController>().updateRows(sku, lensValue);
        }
      } else if (indication == brands[1].indications[2].name) {
        /// Ultra FA DACH
        if (Get.isRegistered<UltraFADachDrawerController>()) {
          Get.find<UltraFADachDrawerController>().updateRows(sku, lensValue);
        }
      } else if (indication == brands[1].indications[0].name) {
        /// Ultra OneDay
        if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
          Get.find<ULTRAOneDayDrawerController>().updateRows(lensValue);
        }
        if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>()) {
          Get.find<ULTRAOneDayMediumfit1DrawerController>()
              .updateRows(lensValue);
        }
         if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>()) {
          Get.find<ULTRAOneDayMediumfit2DrawerController>()
              .updateRows(lensValue);
        }
      } else if (indication == brands[1].indications[4].name) {
        /// Ultra MFA
        if (Get.isRegistered<UltraMFADrawerController>()) {
          Get.find<UltraMFADrawerController>().updateRows(sku);
        }
      }
    } else if (brand == brands[2].name) {
      /// Infuse SVS
      if (indication == brands[2].indications[0].name) {
        if (Get.isRegistered<InfuseSvsDrawerController>()) {
          Get.find<InfuseSvsDrawerController>().updateRows(lensValue);
        }

        /// Infuse MF
      } else if (indication == brands[2].indications[1].name) {
        if (Get.isRegistered<InfuseMfDrawerController>()) {
          Get.find<InfuseMfDrawerController>().updateRows(lensValue);
        }
      }

      /// Infuse FA
      else if (indication == brands[2].indications[2].name) {
        if (Get.isRegistered<InfuseFaDrawerController>()) {
          Get.find<InfuseFaDrawerController>().updateRows(sku, lensValue);
        }
      }
    } else if (brand == brands[3].name) {
      /// Eureka Daily
      if (indication == brands[3].indications[0].name) {
        if (Get.isRegistered<EurekaDailyDrawerController>()) {
          Get.find<EurekaDailyDrawerController>().updateRows(lensValue);
        }

        /// Eureka Daily
      } else if (indication == brands[3].indications[1].name) {
        if (Get.isRegistered<EurekaMonthlyDrawerController>()) {
          Get.find<EurekaMonthlyDrawerController>().updateRows(lensValue);
        }
      }
    } else if (brand == brands[4].name) {
      /// LC OneDay
      if (indication == brands[4].indications[0].name) {
        if (Get.isRegistered<Lc_Oneday_DrawerController>()) {
          Get.find<Lc_Oneday_DrawerController>().updateRows(lensValue);
        }
      }
    }
    update();
  }

  //delete function to erase the brand data from cart table
  Future<void> deleteFromCart(String brand, String indication, String drawer,
      String sku, String customerId) async {
    final db = await DatabaseHelper.instance.database;

    final whereArgs = [brand, indication, drawer, sku, customerId];

    String whereClause =
        'brand = ? AND indication = ? AND drawer = ? AND sku = ? AND customerId = ?';

    await db.rawDelete('''
    DELETE FROM cart_table
    WHERE $whereClause  
  ''', whereArgs);
  }

//fetch active cart function to fetch all the lensdata and map it to form active customer page
  Future<List<CustomerData>> fetchActiveCarts(
      {CustomerData? updatedCustomer}) async {
    print("fetchActiveCarts");
    List<CustomerData> activeCartCustomerList = [];
    await customerController.getDataFromDatabase();
    final db = await DatabaseHelper.instance.database;
    final List<Map<String, dynamic>> lensData = await db.query(cart_table);

    num getTotalQuantityForCustomer(String customerId) {
      num totalQuantity = 0;
      for (var data in lensData) {
        if (data['customerId'].toString() == customerId) {
          totalQuantity += data['qty'];
        }
      }
      return totalQuantity;
    }

    // Create and populate a Set of unique customer IDs who have selected lenses
    final Set<String> customerIds = Set<String>();
    bool isUpdatePerformed =
        false; // A flag to check if the update has been performed

    if (updatedCustomer != null) {
      String newCustomerId = updatedCustomer.Id_From_LocalDB.toString();

      for (int i = 0; i < lensData.length; i++) {
        final data = lensData[i];
        final String customerId = data['customerId'].toString();

        if (i == 0 && !isUpdatePerformed && customerId != newCustomerId) {
          // Perform the database update only at the first index and only if it hasn't been done before
          await _database.update(cart_table, {'customerId': newCustomerId},
              where: 'customerId = ?', whereArgs: [customerId]);

          isUpdatePerformed = true; // Mark that the update has been performed
          customerIds
              .add(newCustomerId); // Add new customer ID since it's updated
          continue; // Skip further processing in this iteration
        }

        // Add existing customerId for all data points
        customerIds.add(customerId);
      }
    } else {
      // If updatedCustomer is null, just add all existing customerIds
      final List<Map<String, dynamic>> newlensData = await db.query(cart_table);
      for (final data in newlensData) {
        final String customerId = data['customerId'].toString();
        customerIds
            .add(customerId); // Add each customerId from the data to the set
      }
      print(
          "Updated customer is null, adding existing customer IDs without updates.");
    }

    final Set<String> uniqueCustomerIds = Set<String>();
    for (var customer in customerController.filterMappingList) {
      if (customerIds.contains(customer.Id_From_LocalDB.toString())) {
        uniqueCustomerIds.add(customer.Id_From_LocalDB.toString());
      }
    }

    CustomerData? customerData = CustomerData.getCustomerDataFromStorage();
    String? customerId = customerData?.Id_From_LocalDB.toString();

    // Insert updatedCustomer at index 0 if provided and valid

    // Check if the list already has an updatedCustomer at index 0 before adding others
    // bool hasUpdatedCustomerAtTop = !activeCartCustomerList.isEmpty && activeCartCustomerList[0].Id_From_LocalDB == updatedCustomer?.Id_From_LocalDB;
    // Populate the activeCartCustomerList with unique customers
    for (var customer in customerController.filterMappingList) {
      if (uniqueCustomerIds.contains(customer.Id_From_LocalDB.toString())) {
        if (customerId == customer.Id_From_LocalDB.toString()) {
          activeCartCustomerList.insert(0, customer);
        } else {
          activeCartCustomerList.add(customer);
        }
      }
    }

    // Assign quantities and update dashboard
    for (var customer in activeCartCustomerList) {
      customer.totalQuantity =
          getTotalQuantityForCustomer(customer.Id_From_LocalDB.toString())
              .toString();
    }
    dashboardController.updateActiveCartCount(activeCartCustomerList.length);
    return activeCartCustomerList;
  }

  //fetch cart function
  Future<void> fetchCartDataFromDatabase({String? customerId}) async {
    brandData.clear();
    basicTilesList.clear();
    final db = await DatabaseHelper.instance.database;
    CustomerData? customerData = CustomerData.getCustomerDataFromStorage();
    String? customerIdFromController =
        customerId ?? customerData?.Id_From_LocalDB.toString();

    final List<Map<String, dynamic>> lensData = await db.query(
      cart_table,
      where: 'customerId = ?', // Add WHERE clause to filter by customerId
      whereArgs: [customerIdFromController], // Provide the customerId value
    );

    updateBrandData(lensData);

    createList();
    // printData();
  }

  Future<void> fetchCartDataFromDatabaseBasesOnUserId(
      customerIdFromController) async {
    brandData.clear();
    basicTilesList.clear();
    final db = await DatabaseHelper.instance.database;

    final List<Map<String, dynamic>> lensData = await db.query(
      cart_table,
      where: 'customerId = ?', // Add WHERE clause to filter by customerId
      whereArgs: [customerIdFromController], // Provide the customerId value
    );

    updateBrandData(lensData);

    createList();
    // printData();
  }

//erase cart function
  Future<void> eraseDataFromCart(String? customerId) async {
    // Get the current active customer's ID from the customer controller
    // Only proceed if a valid customer ID is available
    if (customerId != null) {
      final db = await DatabaseHelper.instance.database;

      try {
        await db.delete(
          cart_table,
          where: 'customerId = ?',
          whereArgs: [customerId],
        );
        brandData.clear();
        eraseDatafromDrawer();
        // Recalculate the total items and update the listbrandData.clear();
        basicTilesList.clear();
        totalItems = 0;
        //Logger.d("BrandData in dart", brandData);
        update();
        Logger.d('', 'Data in cart_table erased successfully');
      } catch (e) {
        Logger.e('Error erasing data from cart_table: $e');
      }
    }
  }

  //erase customer data
  Future<void> eraseAllCustomerData() async {
    final db = await DatabaseHelper.instance.database;

    try {
      await db.delete(cart_table);
      brandData.clear();
      eraseDatafromDrawer();
      // Recalculate the total items and update the listbrandData.clear();
      basicTilesList.clear();
      totalItems = 0;
      //Logger.d("BrandData in dart", brandData);
      update();
      Logger.d('', 'Data in cart_table erased successfully');
    } catch (e) {
      Logger.e('Error erasing data from cart_table: $e');
    }
  }

  eraseDatafromDrawer() {
    if (Get.isRegistered<BtodSVSDrawerController>())
      Get.find<BtodSVSDrawerController>().clearRows();
    if (Get.isRegistered<BtodFPDrawerController>())
      Get.find<BtodFPDrawerController>().clearRows();
    if (Get.isRegistered<BtodFPDrawerControllerDach>()) //BTOD OneDay DACH
      Get.find<BtodFPDrawerControllerDach>().clearRows();
    if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) //BTOD FP DACH
      Get.find<BtodFPLHDrawerControllerDach>().clearRows();  
    if (Get.isRegistered<BtodFADrawerController>())
      Get.find<BtodFADrawerController>().clearRows();
    if (Get.isRegistered<BtodFADachDrawerController>()) //BTOD FA DACH
      Get.find<BtodFADachDrawerController>().clearRows();
    if (Get.isRegistered<UltraSVSDrawerController>())
      Get.find<UltraSVSDrawerController>().clearRows();
    if (Get.isRegistered<UltraFPDrawerController>())
      Get.find<UltraFPDrawerController>().clearRows();
    if (Get.isRegistered<UltraFPDachDrawerController>()) // Ultra FP DACH
      Get.find<UltraFPDachDrawerController>().clearRows();
    if (Get.isRegistered<UltraFADrawerController>())
      Get.find<UltraFADrawerController>().clearRows();
    if (Get.isRegistered<UltraFADachDrawerController>()) //Ultra FA DACH
      Get.find<UltraFADachDrawerController>().clearRows();
    if (Get.isRegistered<UltraMFADrawerController>())
      Get.find<UltraMFADrawerController>().clearRows();
    if (Get.isRegistered<ULTRAOneDayDrawerController>())
      Get.find<ULTRAOneDayDrawerController>().clearRows();
    if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>())
      Get.find<ULTRAOneDayMediumfit1DrawerController>().clearRows();
    if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>())
      Get.find<ULTRAOneDayMediumfit2DrawerController>().clearRows();
    if (Get.isRegistered<InfuseSvsDrawerController>())
      Get.find<InfuseSvsDrawerController>().clearRows();
    if (Get.isRegistered<InfuseMfDrawerController>())
      Get.find<InfuseMfDrawerController>().clearRows();
    if (Get.isRegistered<InfuseFaDrawerController>()) // Infuse FA
      Get.find<InfuseFaDrawerController>().clearRows();
    if (Get.isRegistered<EurekaDailyDrawerController>())
      Get.find<EurekaDailyDrawerController>().clearRows();
    if (Get.isRegistered<EurekaMonthlyDrawerController>())
      Get.find<EurekaMonthlyDrawerController>().clearRows();
    if (Get.isRegistered<Lc_Oneday_DrawerController>())
      Get.find<Lc_Oneday_DrawerController>().clearRows();
  }

  createList() {
    basicTilesList = createBasicTilesList(
        brandData, (int totalCount) => {totalItems = totalCount});
    update();
  }

  updateDrawerValue() {
    var controller;
    if (Get.isRegistered<BtodSVSDrawerController>()) {
      controller = Get.find<BtodSVSDrawerController>();
    } else if (Get.isRegistered<BtodFPDrawerController>()) {
      controller = Get.find<BtodFPDrawerController>();
    } else if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
      // BTOD OneDay DACH
      controller = Get.find<BtodFPDrawerControllerDach>();
    } else if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) {
      // BTOD FP DACH
      controller = Get.find<BtodFPLHDrawerControllerDach>();
    } else if (Get.isRegistered<BtodFADrawerController>()) {
      controller = Get.find<BtodFADrawerController>();
    } else if (Get.isRegistered<BtodFADachDrawerController>()) {
      controller = Get.find<BtodFADachDrawerController>();
    } else if (Get.isRegistered<UltraSVSDrawerController>()) {
      controller = Get.find<UltraSVSDrawerController>();
    } else if (Get.isRegistered<UltraFPDrawerController>()) {
      controller = Get.find<UltraFPDrawerController>();
    } else if (Get.isRegistered<UltraFPDachDrawerController>()) {
      controller = Get.find<UltraFPDachDrawerController>();
    } else if (Get.isRegistered<UltraFADrawerController>()) {
      controller = Get.find<UltraFADrawerController>();
    } else if (Get.isRegistered<UltraFADachDrawerController>()) {
      // Ultra FA DACH
      controller = Get.find<UltraFADachDrawerController>();
    } else if (Get.isRegistered<UltraMFADrawerController>()) {
      controller = Get.find<UltraMFADrawerController>();
    } else if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
      controller = Get.find<ULTRAOneDayDrawerController>();
    } else if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>()) {
      controller = Get.find<ULTRAOneDayMediumfit1DrawerController>();
    } else if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>()) {
      controller = Get.find<ULTRAOneDayMediumfit2DrawerController>();
    } else if (Get.isRegistered<InfuseSvsDrawerController>()) {
      controller = Get.find<InfuseSvsDrawerController>();
    } else if (Get.isRegistered<InfuseMfDrawerController>()) {
      controller = Get.find<InfuseMfDrawerController>();
    } else if (Get.isRegistered<InfuseFaDrawerController>()) {
      // Infuse FA
      controller = Get.find<InfuseFaDrawerController>();
    } else if (Get.isRegistered<EurekaDailyDrawerController>()) {
      controller = Get.find<EurekaDailyDrawerController>();
    } else if (Get.isRegistered<EurekaMonthlyDrawerController>()) {
      controller = Get.find<EurekaMonthlyDrawerController>();
    } else if (Get.isRegistered<Lc_Oneday_DrawerController>()) {
      controller = Get.find<Lc_Oneday_DrawerController>();
    }
    controller.toggleCartDrawer();
  }

  bool isShowBadgeDot(int totalCountValue) {
    return totalCountValue > 0 ? true : false;
  }

  //create a structure of cart by using lens data
  List<BasicTiles> createBasicTilesList(
      Map<String, Map<String, Map<String, Map<String, dynamic>>>> brandData,
      getTotalCount) {
    List<BasicTiles> result = [];
    late BasicTiles cartTile;
    late BasicTiles drawerTile;
    BasicTiles indicationTile;
    BasicTiles brandTile;
    var totalCountValue = 0;
    setLoading(true);
    brandData.forEach((brand, indications) {
      List<BasicTiles> brandTiles = [];

      indications.forEach((indication, drawers) {
        List<BasicTiles> indicationTiles = [];

        drawers.forEach((drawer, skus) {
          //Logger.d('drawer', drawer);
          List<BasicTiles> drawerTiles = [];
          List<CartItem> cartItemList = [];

          skus.forEach((sku, cartItems) {
            cartItems.forEach((key, value) async {
              if (key == 'power') {
                final power = cartItems['power'] ?? '';
                final cyl = cartItems['cyl'] ?? '-';
                var axis = cartItems['axis'] ?? '-';
                var add = cartItems['add'] ?? '-';
                final qty = cartItems['qty'] ?? 1;
                List<dynamic> range = cartItems['range']
                    .map((element) => element.toString())
                    .toList();

                if (cartItems.containsKey('axis')) {
                  axis = cartItems['axis']
                      .replaceAll("Axis", "")
                      .toString()
                      .trim();
                }
                if (cartItems.containsKey('highAdd')) {
                  add = 'High';
                } else if (cartItems.containsKey('lowAdd')) {
                  add = 'Low';
                }

                cartItemList.insert(
                    0,
                    CartItem(
                        sku: sku,
                        power: power,
                        cylinder: cyl,
                        axis: axis,
                        add: add,
                        quantity: qty,
                        brand: brand,
                        indication: indication,
                        drawer: drawer,
                        lensValue: power,
                        keys: cartItems['keys'],
                        range: range,
                        lensKey: sku));
              }
            });
          });

          if (cartItemList.length > 0) {
            int drawerCount = 0;
            for (var cartItem in cartItemList) {
              drawerCount = drawerCount + cartItem.quantity;
            }
            String newlyAddedDrawer = box.read('newlyAddedDrawer') ?? '';

            isExpanded = false; // Default to false
            if (drawer == newlyAddedDrawer) {
              isExpanded = true; // Set to true for the newly added Drawer
            }
            // Create the Drawer tile with cart items
            cartTile = BasicTiles(
                //title: drawer,
                cartItem: cartItemList,
                cartItemLength: cartItemList.length,
                count: cartItemList.length);

            drawerTiles.insert(0, cartTile);

            drawerTile = BasicTiles(
              isExpanded: isExpanded,
              title: drawer,
              count: drawerCount,
              showCard: true,
              tiles: drawerTiles,
            );
            indicationTiles.insert(0, drawerTile);
          } else {
            drawerTiles.clear();
          }
        });

        if (indicationTiles.length > 0) {
          int indicationCount = 0;
          for (var indication in indicationTiles) {
            indicationCount = indicationCount + indication.count;
          }
          // Create the Indication tile without the Lens Value title
          indicationTile = BasicTiles(
            isExpanded: isExpanded,
            title: indication,
            count: indicationCount,
            divider: true,
            tiles: indicationTiles,
          );

          brandTiles.insert(0, indicationTile);
        } else {
          indicationTiles.clear();
        }
      });

      if (brandTiles.length > 0) {
        int brandCount = 0;
        for (var brand in brandTiles) {
          brandCount = brandCount + brand.count;
        }
        totalCountValue = totalCountValue + brandCount;

        brandTile = BasicTiles(
          isExpanded: isExpanded,
          title: brand,
          count: brandCount,
          tiles: brandTiles,
        );
        if (brandTile != null) {
          result.insert(0, brandTile);
        }
      } else {
        brandTiles.clear();
      }
    });

    getTotalCount(totalCountValue);
    var isShowBadge = isShowBadgeDot(totalCountValue);
    dashboardController.getRedDotValue();
    var controller = getDrawerController();
    if (controller != null) {
      controller.updateBadgeValue(isShowBadge);
    }

    setLoading(false);
    return result;
  }

  dynamic getDrawerController() {
    var controller;

    if (Get.isRegistered<BtodSVSDrawerController>()) {
      controller = Get.find<BtodSVSDrawerController>();
    } else if (Get.isRegistered<BtodFPDrawerController>()) {
      controller = Get.find<BtodFPDrawerController>();
    } else if (Get.isRegistered<BtodFPDrawerControllerDach>()) {
      //BTOD OneDay DACH
      controller = Get.find<BtodFPDrawerControllerDach>();
    } else if (Get.isRegistered<BtodFPLHDrawerControllerDach>()) {  //BTOD FP DACH 
      controller = Get.find<BtodFPLHDrawerControllerDach>();
    } else if (Get.isRegistered<BtodFADrawerController>()) {
      controller = Get.find<BtodFADrawerController>();
    } else if (Get.isRegistered<BtodFADachDrawerController>()) { //BTOD FA DACH 
      controller = Get.find<BtodFADachDrawerController>();
    } else if (Get.isRegistered<UltraSVSDrawerController>()) {
      controller = Get.find<UltraSVSDrawerController>();
    } else if (Get.isRegistered<UltraFPDrawerController>()) {
      controller = Get.find<UltraFPDrawerController>();
    } else if (Get.isRegistered<UltraFPDachDrawerController>()) { //Ultra FP DACH
      controller = Get.find<UltraFPDachDrawerController>();
    } else if (Get.isRegistered<UltraFADrawerController>()) {
      controller = Get.find<UltraFADrawerController>();
    } else if (Get.isRegistered<UltraFADachDrawerController>()) { //Ultra FA DACH
      controller = Get.find<UltraFADachDrawerController>();
    } else if (Get.isRegistered<UltraMFADrawerController>()) {
      controller = Get.find<UltraMFADrawerController>();
    } else if (Get.isRegistered<ULTRAOneDayDrawerController>()) {
      controller = Get.find<ULTRAOneDayDrawerController>();
    } else if (Get.isRegistered<ULTRAOneDayMediumfit1DrawerController>()) {
      controller = Get.find<ULTRAOneDayMediumfit1DrawerController>();
    } else if (Get.isRegistered<ULTRAOneDayMediumfit2DrawerController>()) {
      controller = Get.find<ULTRAOneDayMediumfit2DrawerController>();
    } else if (Get.isRegistered<InfuseSvsDrawerController>()) {
      controller = Get.find<InfuseSvsDrawerController>();
    } else if (Get.isRegistered<InfuseMfDrawerController>()) {
      controller = Get.find<InfuseMfDrawerController>();
    } else if (Get.isRegistered<InfuseFaDrawerController>()) {
      //Infuse FA
      controller = Get.find<InfuseFaDrawerController>();
    } else if (Get.isRegistered<EurekaDailyDrawerController>()) {
      controller = Get.find<EurekaDailyDrawerController>();
    } else if (Get.isRegistered<EurekaMonthlyDrawerController>()) {
      controller = Get.find<EurekaMonthlyDrawerController>();
    } else if (Get.isRegistered<Lc_Oneday_DrawerController>()) {
      controller = Get.find<Lc_Oneday_DrawerController>();
    }

    return controller;
  }
}


my requirement is i want it is working and going inside of updateLensValueCount(... 
but not for updateLensValueCountCheckOut(.. , it is not even register or finding it