package com.cpm.lorealbaautomation.consumeractivity;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime;
import static com.cpm.lorealbaautomation.constant.CommonFunctions.removeFirstChar;
import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerSalesHistory;
import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerTermsConditionAccept;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterAgeLimit;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetEntityItem;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetProductGroup;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSkinType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSourcesOfSale;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.retrofit.PostApi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ConsumerUserDetailsActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    String dialog_invoiceType = "Saleable", dialog_brand_Id = "", dialog_sub_brand_Id = "", dialog_reference_Id = "", product_name = "",
            product_Id = "0", product_mrp = "0", CounterId, visit_date,
            username, perchasing_tym = "", productType = "", str_termCondition = "0", response_term_condition = "", _pathforcheck = "", _path = "", tagmode = "";
    ArrayAdapter<CharSequence> dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter,
            AgeAdapter, SkinTypeAdapter, sourceofsalesAdapter;
    private SharedPreferences preferences;
    public ArrayList<ProductMaster> dialog_product_using_searchlist = new ArrayList<>();
    Lorealba_Database db;
    EditText edt_customer, edt_mobile_no;
    Button btn_scan, btn_enter_code, btn_sku_list;
    RecyclerView drawer_layout_recycle_store;
    public ArrayList<InvoiceGetterSetter> selected_list = new ArrayList<>();
    public ArrayList<ProductMaster> dialog_product_list = new ArrayList<>();
    InvoiceGetterSetter object;
    String product_scan_code = "", flag_for_consumer_Update = "", Key_For_Pos_Enable_With_Showing_Invoice = "",
            skin_genius_str = "", maybelline_vto = "", demo_given_str = "", product_sold_str = "", otp_code = "", str_img_demo_no_sale = "", str_sourceof_sales = "";
    FloatingActionButton fab, draft_fab;
    TextView qrcode_text, sku_name, stock_text_value, txt_history, current_total_stock;
    EditText edt_scan_code;
    CardView card_layout_scan, card_layout_title;
    CheckBox mobile_checkbox, no_name_checkbox;
    boolean no_name_flag = false, no_mobile_no_flag = false;
    ProgressDialog loading;
    Context context;
    int minteger = 0;
    private RadioGroup radioSexGroup;
    private RadioButton radioSexButton;
    double discount = 0.0;
    Button promotion_btn_first, promotion_btn_second, sale_btn_yes, sale_btn_no, skingn_btn_yes, skingn_btn_no, maybelline_btn_yes, maybelline_btn_no;
    double total = 0.0;
    boolean clicked_flag = false, product_add_flag = false;
    int reciept_count = 0;
    ///new changes19/08/19
    LinearLayout rl_otp, rl_actual_qty, rl_complete_layout;
    EditText edt_otp, edt_email_address;
    Spinner spin_age, spin_skin_type;
    ScrollView scroll_view;
    boolean flag_for_filter = false, flag_for_term_condition = false, flag_filter_by_edt = false;
    TextView actual_qty_dialog, rl_term_condition, text_user_nm;
    ImageView img_visble;
    ArrayList<InvoiceGetterSetter> listDataHeader = new ArrayList<>();
    HashMap<InvoiceGetterSetter, List<InvoiceGetterSetter>> listDataChild;
    JourneyPlan storeDataObject = new JourneyPlan();
    ArrayList<MasterSourcesOfSale> sourceofsaleslist = new ArrayList<>();
    ArrayList<MasterAgeLimit> ageLimits = new ArrayList<>();
    ArrayList<MasterSkinType> skinTypes = new ArrayList<>();
    ArrayList<ProductMaster> brandList, subbrandList, referenceList, productList = new ArrayList<>();
    LinearLayout rl_demo_img;
    ImageView img_only_demo;
    ArrayList<MasterPromotionSetProductGroup> selected_promoList = new ArrayList<>();
    ArrayList<InvoiceGetterSetter> added_prmo_products = new ArrayList<>();
    ArrayList<InvoiceGetterSetter> applyeid_products = new ArrayList<>();
    Spinner spinSourceof_sales;
    LinearLayout rlSalesSource;
    String from = "";

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consumer_user_details);
        from = getIntent().getStringExtra("from");
        context = this;
        ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        iduserinterface();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Consumer Details -" + username);
        perchasing_tym = CommonFunctions.getCurrentTime_only();
        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + CounterId);
    }

    @SuppressLint({"UseCompatLoadingForDrawables", "SetTextI18n"})
    private void iduserinterface() {
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        scroll_view = (ScrollView) findViewById(R.id.scroll_view);
        btn_scan = (Button) findViewById(R.id.btn_scan);
        btn_enter_code = (Button) findViewById(R.id.btn_enter_code);
        btn_sku_list = (Button) findViewById(R.id.btn_sku_list);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        draft_fab = (FloatingActionButton) findViewById(R.id.draft_fab);
        edt_customer = (EditText) findViewById(R.id.edt_customer);
        edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no);
        txt_history = (TextView) findViewById(R.id.txt_history);
        current_total_stock = (TextView) findViewById(R.id.txt_total);
        drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store);
        mobile_checkbox = (CheckBox) findViewById(R.id.mobile_checkbox);
        no_name_checkbox = (CheckBox) findViewById(R.id.no_name_checkbox);
        card_layout_scan = (CardView) findViewById(R.id.card_layout_scan);
        card_layout_title = (CardView) findViewById(R.id.card_layout_title);
        //for demo btn
        promotion_btn_first = (Button) findViewById(R.id.posm_btn_first);
        promotion_btn_second = (Button) findViewById(R.id.posm_btn_second);
        sale_btn_yes = (Button) findViewById(R.id.sale_btn_yes);
        sale_btn_no = (Button) findViewById(R.id.sale_btn_no);
        ////for skin Genius
        skingn_btn_yes = (Button) findViewById(R.id.skingn_btn_yes);
        skingn_btn_no = (Button) findViewById(R.id.skingn_btn_no);
        maybelline_btn_yes = (Button) findViewById(R.id.maybelline_btn_yes);
        maybelline_btn_no = (Button) findViewById(R.id.maybelline_btn_no);
        radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp);
        ///new changes19--08-19
        rl_term_condition = (TextView) findViewById(R.id.rl_term_condition);
        text_user_nm = (TextView) findViewById(R.id.text_user_nm);
        rl_otp = (LinearLayout) findViewById(R.id.rl_otp);
        edt_otp = (EditText) findViewById(R.id.edt_otp);
        edt_email_address = (EditText) findViewById(R.id.edt_email_address);
        spin_age = (Spinner) findViewById(R.id.spin_age);
        spin_skin_type = (Spinner) findViewById(R.id.spin_skin_type);
        /////new changwessssssssss
        rl_complete_layout = (LinearLayout) findViewById(R.id.rl_complete_layout);
        img_visble = (ImageView) findViewById(R.id.img_visble);
        rl_demo_img = (LinearLayout) findViewById(R.id.rl_demo_img);
        img_only_demo = (ImageView) findViewById(R.id.img_only_demo);
        spinSourceof_sales = (Spinner) findViewById(R.id.spinSourceof_sales);
        rlSalesSource = (LinearLayout) findViewById(R.id.rlSalesSource);
        img_visble.setVisibility(View.GONE);
        img_only_demo.setOnClickListener(this);
        btn_scan.setOnClickListener(this);
        btn_enter_code.setOnClickListener(this);
        btn_sku_list.setOnClickListener(this);
        fab.setOnClickListener(this);
        mobile_checkbox.setOnClickListener(this);
        no_name_checkbox.setOnClickListener(this);
        txt_history.setOnClickListener(this);
        draft_fab.setOnClickListener(this);
        promotion_btn_first.setOnClickListener(this);
        promotion_btn_second.setOnClickListener(this);
        sale_btn_yes.setOnClickListener(this);
        sale_btn_no.setOnClickListener(this);
        skingn_btn_yes.setOnClickListener(this);
        skingn_btn_no.setOnClickListener(this);
        maybelline_btn_yes.setOnClickListener(this);
        maybelline_btn_no.setOnClickListener(this);
        rl_otp.setOnClickListener(this);
        img_visble.setOnClickListener(this);
        rl_term_condition.setOnClickListener(this);
        if (getIntent().getStringExtra(CommonString.TAG_MODE) != null) {
            tagmode = getIntent().getStringExtra(CommonString.TAG_MODE);
        }

        db.open();
        sourceofsaleslist = db.getsourceofsales();
        db.open();
        ageLimits = db.getAgeLimitMasterData();
        db.open();
        skinTypes = db.getskinTypeMaster();
        storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, CounterId, username);
        flag_for_consumer_Update = getIntent().getStringExtra(CommonString.Key_For_Consumer_Update);
        selected_list = (ArrayList<InvoiceGetterSetter>) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        Key_For_Pos_Enable_With_Showing_Invoice = getIntent().getStringExtra(CommonString.Key_For_Pos_Enable_With_Showing_Invoice);
        adapterforAgeLimit_SkinType();
        getstatusof_termcondition();
        ///calling of age adapter
        if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) {
            edt_mobile_no.setEnabled(false);
            mobile_checkbox.setEnabled(false);
            rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            rl_term_condition.setEnabled(false);
            mobile_checkbox.setEnabled(false);
            edt_email_address.setEnabled(false);
        }

        if (selected_list != null && !selected_list.isEmpty()) {
            username = selected_list.get(0).getUserName();
            edt_customer.setText(selected_list.get(0).getCustomer_name());
            edt_mobile_no.setText(selected_list.get(0).getMobile_no());
            edt_email_address.setText(selected_list.get(0).getConsumer_email_Id());
            reciept_count = selected_list.get(0).getReccept_count();
            str_termCondition = selected_list.get(0).getStr_termcondition();
            /////for radio group
            if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Male")) {
                //radioSexButton
                radioSexGroup.check(R.id.radioM);
            } else if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Female")) {
                //radioSexButton
                radioSexGroup.check(R.id.radioF);
            } else {
                radioSexGroup.check(R.id.radio_other);
            }

            ///for source of sales
            rlSalesSource.setVisibility(View.VISIBLE);
            if (!selected_list.get(0).getSourceofSales().isEmpty()) {
                str_sourceof_sales = selected_list.get(0).getSourceofSales();
                for (int w = 0; w < sourceofsaleslist.size(); w++) {
                    if (str_sourceof_sales.equalsIgnoreCase(sourceofsaleslist.get(w).getSourcesOfSale())) {
                        spinSourceof_sales.setSelection(w + 1);
                        break;
                    }
                }
            }

            //for demo perpose button
            if (!selected_list.get(0).getDemo_given_str().isEmpty() && selected_list.get(0).getDemo_given_str().equalsIgnoreCase("Yes")) {
                promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                promotion_btn_first.setTextColor(getResources().getColor(R.color.white));
                promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));
                demo_given_str = "Yes";
            } else {
                promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                promotion_btn_second.setTextColor(getResources().getColor(R.color.white));
                promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login));
                demo_given_str = "No";
            }

            /////For Skin Genious
            if (!selected_list.get(0).getSkin_genius_str().isEmpty() && selected_list.get(0).getSkin_genius_str().equalsIgnoreCase("Yes")) {
                skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                skingn_btn_yes.setTextColor(getResources().getColor(R.color.white));
                skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                skingn_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login));
                skin_genius_str = "Yes";
            } else {
                skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                skingn_btn_no.setTextColor(getResources().getColor(R.color.white));
                skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                skingn_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));
                skin_genius_str = "No";
            }

/////For Maybelline VTO
            if (!selected_list.get(0).getMaybelline_vto_str().isEmpty() && selected_list.get(0).getMaybelline_vto_str().equalsIgnoreCase("Yes")) {
                maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                maybelline_btn_yes.setTextColor(getResources().getColor(R.color.white));
                maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                maybelline_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login));
                maybelline_vto = "Yes";
            } else {
                maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                maybelline_btn_no.setTextColor(getResources().getColor(R.color.white));
                maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                maybelline_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));
                maybelline_vto = "No";
            }


            if (!selected_list.get(0).getProduct_sold_str().isEmpty() && selected_list.get(0).getProduct_sold_str().equalsIgnoreCase("Yes")) {
                sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                sale_btn_yes.setTextColor(getResources().getColor(R.color.white));
                sale_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                sale_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login));
                card_layout_scan.setVisibility(View.VISIBLE);
                card_layout_title.setVisibility(View.VISIBLE);
                drawer_layout_recycle_store.setVisibility(View.VISIBLE);
                product_sold_str = "Yes";
                rl_complete_layout.setVisibility(View.GONE);
                img_visble.setVisibility(View.VISIBLE);
                text_user_nm.setText(selected_list.get(0).getCustomer_name() + "  Customer - " + CommonFunctions.removed_special_char(edt_customer));
            } else {
                sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                sale_btn_no.setTextColor(getResources().getColor(R.color.white));
                sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));
                card_layout_scan.setVisibility(View.GONE);
                card_layout_title.setVisibility(View.GONE);
                drawer_layout_recycle_store.setVisibility(View.GONE);
                ///for source of sales
                rlSalesSource.setVisibility(View.VISIBLE);
                product_sold_str = "No";
            }

            if (!selected_list.get(0).getDemo_given_str().isEmpty() && selected_list.get(0).getDemo_given_str().equalsIgnoreCase("Yes")) {
                if (selected_list.get(0).getConsumer_no_saleImg() != null && !selected_list.get(0).getConsumer_no_saleImg().isEmpty()) {
                    img_only_demo.setImageResource(R.mipmap.camera_bsd);
                    str_img_demo_no_sale = selected_list.get(0).getConsumer_no_saleImg();
                }
                rl_demo_img.setVisibility(View.VISIBLE);
            }

            db.open();
            for (int k = 0; k < ageLimits.size(); k++) {
                if (selected_list != null && !selected_list.isEmpty() && !selected_list.get(0).getConsumer_age().isEmpty()) {
                    if (ageLimits.get(k).getAgeLimit().equalsIgnoreCase(selected_list.get(0).getConsumer_age())) {
                        spin_age.setSelection(k + 1);
                        break;
                    }

                }
            }
            db.open();
            for (int k = 0; k < skinTypes.size(); k++) {
                if (selected_list != null && !selected_list.isEmpty() && !selected_list.get(0).getConsumer_skinType().isEmpty()) {
                    if (skinTypes.get(k).getSkinType().equalsIgnoreCase(selected_list.get(0).getConsumer_skinType())) {
                        spin_skin_type.setSelection(k + 1);
                        break;
                    }

                }
            }

            if (selected_list.get(0).getProduct_Id() != null)
                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
        } else {
            selected_list = new ArrayList<>();
            promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            promotion_btn_second.setTextColor(getResources().getColor(R.color.white));
            promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login));

            sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            sale_btn_no.setTextColor(getResources().getColor(R.color.white));
            sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));

            ///for Sale Genius
            skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            skingn_btn_no.setTextColor(getResources().getColor(R.color.white));
            skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            skingn_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));

            ///for Maybelline VTO
            maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            maybelline_btn_no.setTextColor(getResources().getColor(R.color.white));
            maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            maybelline_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));

            maybelline_vto = "No";
            skin_genius_str = "No";
            demo_given_str = "No";
            str_img_demo_no_sale = "";
            product_sold_str = "No";
            rl_demo_img.setVisibility(View.GONE);
            img_only_demo.setImageResource(R.mipmap.camera_bs);
            ///for source of sales
            rlSalesSource.setVisibility(View.VISIBLE);
        }
    }


    private boolean checkotp_validation() {
        boolean status = true;
        if (edt_otp.getText().toString().equals("0000")) {
            str_termCondition = "1";
        } else if (edt_otp.getText().toString().equals(otp_code)) {
            str_termCondition = "1";
        } else {
            status = false;
        }
        return status;

    }

    private void custom_dialog_for_termand_condition(final Context context) {
        minteger = 0;
        final MultiPurposeDialog multiDialog = new MultiPurposeDialog(context);
        multiDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiDialog.setContentView(R.layout.custom_dialog_for_term_condition);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiDialog.getWindow().setAttributes(lp);
        multiDialog.setCancelable(false);
        multiDialog.show();
        ///new changes 19 aug
        CheckBox checkbox_accept = (CheckBox) multiDialog.findViewById(R.id.checkbox_accept);
        CheckBox checkbox_reject = (CheckBox) multiDialog.findViewById(R.id.checkbox_reject);
        TextView txt_term_condition = (TextView) multiDialog.findViewById(R.id.txt_term_condition);
        WebView webview = (WebView) multiDialog.findViewById(R.id.webview);
        webview.loadData(db.getterm_and_condition().getTermsCondition(), "text/html; charset=utf-8", "utf-8");
        if (flag_for_term_condition) {
            checkbox_accept.setChecked(true);
        }

        db.open();
        txt_term_condition.setText(db.getterm_and_condition().getTermsCondition());
        checkbox_accept.setOnClickListener(v -> {
            try {
                flag_for_term_condition = true;
                if (multiDialog.isShowing()) {
                    multiDialog.dismiss();
                }
                rl_otp.setVisibility(View.VISIBLE);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MobileNumber", edt_mobile_no.getText().toString());
                getotp_from_mobile_no(jsonObject.toString(), multiDialog);
            } catch (JSONException e) {
                e.fillInStackTrace();
            }
        });

        checkbox_reject.setOnClickListener(v -> {
            if (multiDialog.isShowing()) {
                multiDialog.dismiss();
            }
            no_mobile_no_flag = true;
            flag_for_term_condition = false;
            edt_mobile_no.setText("0000000000");
            rl_otp.setVisibility(View.GONE);
            edt_mobile_no.setEnabled(false);
            mobile_checkbox.setChecked(true);
            mobile_checkbox.setEnabled(false);
            edt_email_address.setEnabled(false);
            edt_email_address.setText("");
            rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            rl_term_condition.setEnabled(false);

        });

        multiDialog.show();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                        (dialog, id1) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            ConsumerUserDetailsActivity.this.finish();
                        }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ConsumerUserDetailsActivity.this.finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                    (dialog, id) -> {
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        ConsumerUserDetailsActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ConsumerUserDetailsActivity.this.finish();
        }
    }


    private void calculate_invoice_added_data(ArrayList<InvoiceGetterSetter> invoice_List) {
        try {
            double cCom = 0.0, total_INR_value = 0.0;
            for (int k = 0; k < invoice_List.size(); k++) {
                if (invoice_List.get(k).getDiscount() != 0.0) {
                    int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                    double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate());
                    amount = amount * quantity;
                    invoice_List.get(k).setTotal_amount(String.valueOf(amount));
                    cCom = cCom + ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount());
                } else {
                    int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                    double amount = Double.parseDouble(invoice_List.get(k).getProduct_rate());
                    amount = amount * quantity;
                    invoice_List.get(k).setTotal_amount(String.valueOf(amount));
                }

                double amount_ofproduct = ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount());
                amount_ofproduct = (Double.parseDouble(invoice_List.get(k).getTotal_amount())) - amount_ofproduct;
                total_INR_value = total_INR_value + Double.parseDouble(invoice_List.get(k).getTotal_amount());
                String string = invoice_List.get(k).getDiscount().toString();
                if (invoice_List.get(k).getDiscount() == 0.0 || invoice_List.get(k).getDiscount() == 0) {
                    invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount())));
                    invoice_List.get(k).setDiscounted_value(0.0);
                } else {
                    invoice_List.get(k).setDiscounted_value(((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount()));
                    invoice_List.get(k).setActual_price_per_product((Double.parseDouble(invoice_List.get(k).getTotal_amount()) - ((Double.parseDouble(invoice_List.get(k).getTotal_amount())) * invoice_List.get(k).getDiscount())));
                }
            }
            total = total_INR_value - cCom;
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }
    }


    private int calculate_total_consume(ArrayList<InvoiceGetterSetter> invoice_List) {
        int total_INR_value = 0, off_worth_total = 0, worth_total = 0, OffSameProduct = 0, OffAdditionalProduct = 0, ValueOffAdditionalProduct = 0;
        try {
            if (!invoice_List.isEmpty()) {
                for (int k = 0; k < invoice_List.size(); k++) {
                    if (!invoice_List.get(k).isPromo_flag()) {
                        int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                        int amount = Integer.parseInt((invoice_List.get(k).getProduct_rate()));
                        amount = amount * quantity;
                        invoice_List.get(k).setTotal_amount(String.valueOf(amount));
                        total_INR_value = total_INR_value + Integer.parseInt(invoice_List.get(k).getTotal_amount());
                    } else {
                        if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) {
                            int quantity = Integer.parseInt(invoice_List.get(k).getQuantity());
                            int amount = Integer.parseInt((invoice_List.get(k).getProduct_rate()));
                            amount = amount * quantity;
                            invoice_List.get(k).setTotal_amount(String.valueOf(amount));
                            total_INR_value = total_INR_value + Integer.parseInt(invoice_List.get(k).getTotal_amount());
                            total_INR_value = total_INR_value - Integer.parseInt(invoice_List.get(k).getSkuType());
                        } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffWorth")
                                || invoice_List.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) {
                            off_worth_total = off_worth_total + Integer.parseInt(invoice_List.get(k).getProduct());
                        } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("Worth")) {
                            worth_total = worth_total + Integer.parseInt(invoice_List.get(k).getProduct());
                        } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) {
                            OffSameProduct = OffSameProduct + Integer.parseInt(invoice_List.get(k).getProduct());
                        } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) {
                            OffAdditionalProduct = OffAdditionalProduct + Integer.parseInt(invoice_List.get(k).getProduct());
                        } else if (invoice_List.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) {
                            ValueOffAdditionalProduct = ValueOffAdditionalProduct + Integer.parseInt(invoice_List.get(k).getProduct());
                        }
                    }
                }

                total_INR_value = total_INR_value - off_worth_total;
                total_INR_value = total_INR_value - worth_total;
                total_INR_value = total_INR_value - OffSameProduct;
                total_INR_value = total_INR_value - OffAdditionalProduct;
                total_INR_value = total_INR_value - ValueOffAdditionalProduct;
            }
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }

        return total_INR_value;
    }

    @SuppressLint({"NonConstantResourceId", "SetTextI18n", "UseCompatLoadingForDrawables"})
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.img_only_demo) {
            _pathforcheck = CounterId + "_ConsumerSimg_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
        } else if (view.getId() == R.id.img_visble) {
            if (rl_complete_layout.getVisibility() == View.VISIBLE) {
                // Its visible
                text_user_nm.setText(getString(R.string.filldetails) + "  Customer - " + CommonFunctions.removed_special_char(edt_customer));
                rl_complete_layout.setVisibility(View.GONE);
                img_visble.setImageResource(R.mipmap.invisible);
                img_visble.setVisibility(View.VISIBLE);
            } else {
                // Either gone or invisible
                rl_complete_layout.setVisibility(View.VISIBLE);
                img_visble.setImageResource(R.mipmap.visible);
                text_user_nm.setText(getString(R.string.filldetails) + "  Customer - " + CommonFunctions.removed_special_char(edt_customer));
            }

        } else if (view.getId() == R.id.rl_term_condition) {
            if (checkindex()) {
                custom_dialog_for_termand_condition(context);
            }
        } else if (view.getId() == R.id.txt_history) {
            if (edt_mobile_no.getText().toString().isEmpty()) {
                txt_history.setEnabled(true);
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number ");
            } else if (edt_mobile_no.getText().toString().length() < 10) {
                txt_history.setEnabled(true);
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (checkindex()) {
                if (CommonFunctions.checkNetIsAvailable(context)) {
                    txt_history.setEnabled(false);
                    try {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("Downloadtype", "Consumer_SalesHistory");
                        jsonObject1.put("Username", username);
                        jsonObject1.put("Param2", edt_email_address.getText().toString());
                        jsonObject1.put("Param1", edt_mobile_no.getText().toString());
                        loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true);
                        getpreviousHistory_from_mobile_no(context, loading, jsonObject1.toString());
                    } catch (JSONException e) {
                        e.fillInStackTrace();
                    }
                } else {
                    txt_history.setEnabled(true);
                    AlertandMessages.showToastMsg(context, "Unable To Connect Server. History Data Not Updated");
                }
            }

        } else if (view.getId() == R.id.mobile_checkbox) {
            clicked_flag = true;
            if (mobile_checkbox.isChecked()) {
                no_mobile_no_flag = true;
                flag_for_term_condition = false;
                edt_mobile_no.setText("0000000000");
                rl_otp.setVisibility(View.GONE);
                edt_mobile_no.setEnabled(false);
                rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            } else {
                edt_mobile_no.setText("");
                no_mobile_no_flag = false;
                edt_mobile_no.setEnabled(true);
                rl_term_condition.setTextColor(getResources().getColor(R.color.blue));
            }

        } else if (view.getId() == R.id.no_name_checkbox) {
            clicked_flag = true;
            if (no_name_checkbox.isChecked()) {
                no_name_flag = true;
                edt_customer.setText("No Name");
                edt_customer.setEnabled(false);
            } else {
                edt_customer.setText("");
                no_name_flag = false;
                edt_customer.setEnabled(true);
            }

        } else if (view.getId() == R.id.btn_scan) {
            clicked_flag = true;
            ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (demo_given_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Demo Given ");
            } else if (product_sold_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Product Sold ");
            } else if (str_sourceof_sales.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Source of visit");
            } else if (skin_genius_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Genius ");
            } else if (maybelline_vto.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO ");
            } else {
                show_proforma_dialog(context, true);
            }

        } else if (view.getId() == R.id.btn_enter_code) {
            clicked_flag = true;
            ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (demo_given_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Demo Given ");
            } else if (product_sold_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Product Sold ");
            } else if (str_sourceof_sales.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Source of visit");
            } else if (skin_genius_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Genius ");
            } else if (maybelline_vto.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO ");
            } else {
                show_proforma_dialog(context, false);
            }

        } else if (view.getId() == R.id.fab) {
            ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Check Terms & Condition");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (demo_given_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Demo Given ");
            } else if (product_sold_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Product Sold ");
            } else if (str_sourceof_sales.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Source of visit");
            } else if (skin_genius_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Genius ");
            } else if (maybelline_vto.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO ");
            } else if (product_sold_str.equalsIgnoreCase("Yes") && selected_list.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Add First ");
            } else if (!no_mobile_no_flag && flag_for_term_condition && edt_otp.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter OTP");
            } else if (!no_mobile_no_flag && flag_for_term_condition && !checkotp_validation()) {
                AlertandMessages.showToastMsg(context, "Incorrect OTP");
            } else if (checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) {
                AlertandMessages.showToastMsg(context, "You Cannot Save If 'Demo Given' and 'Skin Genius' and 'Maybelline VTO' and 'Product Sale' are 'No'.");
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData);
                builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                    try {
                        dialogInterface.dismiss();
                        if (product_sold_str.equalsIgnoreCase("No")) {
                            selected_list.clear();
                            object = new InvoiceGetterSetter();
                            object = returnobject();

                            object.setQuantity("0");
                            object.setProduct("");
                            object.setProduct_Id("0");
                            object.setProduct_rate("0");
                            object.setDiscount(0.0);
                            object.setScan_ean_code_or_enterd_ean_code("");
                            object.setSkuType("");
                            object.setStr_invoiceType("");
                            object.setPromo_flag(false);
                            object.setPromo_type("");
                            object.setPromotion_name("");
                            object.setPromotion_Id("0");
                            selected_list.add(object);
                            ////prepare products for hashmap..........
                            prepareListData();
                            long l = calculate_data_insert_data();
                            if (l > 0) {
                                CommonFunctions.call_upload(context);
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                ConsumerUserDetailsActivity.this.finish();
                            } else {
                                AlertandMessages.showToastMsg(context, "Data not Saved.Please try again.");
                            }

                        } else {
                            ///--------Check Promotion--------------
                            db.open();
                            db.insert_temp_sales_data(visit_date, CounterId, selected_list);
                            if (check_isPromo() && !product_add_flag) {
                                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                                startActivity(new Intent(context, InvoiceReportProformaActivity.class)
                                        .putExtra(CommonString.TAG_OBJECT, selected_list)
                                        .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                                        .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count))
                                        .putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                                        .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale)
                                        .putExtra("from", from));
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                added_prmo_products = new ArrayList<InvoiceGetterSetter>();
                            } else if (check_isPromo() && product_add_flag) {
                                AlertandMessages.showToastMsg(context, "Checking Promotion");
                                try {
                                    remove_added_promo_index();
                                    new LoadTask().execute(true);
                                } catch (Exception e) {
                                    remove_added_promo_index();
                                    new LoadTask().execute(true);
                                }
                            } else {
                                ////change ,,,,,,,,
                                AlertandMessages.showToastMsg(context, "Checking Promotion");
                                try {
                                    new LoadTask().execute(true);
                                } catch (Exception e) {
                                    new LoadTask().execute(true);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }
                });
                builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
                builder.show();
            }

        } else if (view.getId() == R.id.btn_sku_list) {
            clicked_flag = true;
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (demo_given_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Demo Given ");
            } else if (product_sold_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Product Sold ");
            } else if (str_sourceof_sales.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Source of visit");
            } else if (skin_genius_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Genius ");
            } else if (maybelline_vto.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO ");
            } else {
                show_dialog_forsku_categorywise(context);
            }

        } else if (view.getId() == R.id.posm_btn_first) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                promotion_btn_first.setTextColor(getResources().getColor(R.color.white));
                promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));
                demo_given_str = "Yes";
                if (response_term_condition.equals("1")) {
                    rl_demo_img.setVisibility(View.VISIBLE);
                } else if (flag_for_term_condition) {
                    rl_demo_img.setVisibility(View.VISIBLE);
                } else {
                    rl_demo_img.setVisibility(View.GONE);
                }
                //////open demo image layout
            }

        }

        ///for Skin Genius
        else if (view.getId() == R.id.skingn_btn_yes) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                skingn_btn_yes.setTextColor(getResources().getColor(R.color.white));
                skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                skingn_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login));
                skin_genius_str = "Yes";
            }

        }

        ///for Maybelline Vto yes
        else if (view.getId() == R.id.maybelline_btn_yes) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                maybelline_btn_yes.setTextColor(getResources().getColor(R.color.white));
                maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                maybelline_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login));
                maybelline_vto = "Yes";
            }

        } else if (view.getId() == R.id.skingn_btn_no) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                skingn_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                skingn_btn_no.setTextColor(getResources().getColor(R.color.white));
                skingn_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                skingn_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));
                skin_genius_str = "No";
            }

        }

        ///Maybelline VTO No
        else if (view.getId() == R.id.maybelline_btn_no) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                maybelline_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                maybelline_btn_no.setTextColor(getResources().getColor(R.color.white));
                maybelline_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                maybelline_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));
                maybelline_vto = "No";
            }

        } else if (view.getId() == R.id.posm_btn_second) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                promotion_btn_second.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                promotion_btn_second.setTextColor(getResources().getColor(R.color.white));
                promotion_btn_first.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login));

                sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                sale_btn_no.setTextColor(getResources().getColor(R.color.white));
                sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));

                demo_given_str = "No";
                str_img_demo_no_sale = "";
                rl_demo_img.setVisibility(View.GONE);
                img_only_demo.setImageResource(R.mipmap.camera_bs);
            }

        } else if (view.getId() == R.id.sale_btn_no) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                sale_btn_no.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                sale_btn_no.setTextColor(getResources().getColor(R.color.white));
                sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                sale_btn_yes.setTextColor(getResources().getColor(R.color.grayfor_login));
                card_layout_scan.setVisibility(View.GONE);
                card_layout_title.setVisibility(View.GONE);
                drawer_layout_recycle_store.setVisibility(View.GONE);
                rlSalesSource.setVisibility(View.VISIBLE);
                product_sold_str = "No";
            }

        } else if (view.getId() == R.id.sale_btn_yes) {
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else {
                if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) {
                    if (selected_list != null && !selected_list.isEmpty()) {
                        if (selected_list.get(0).getProduct_Id().equals("0")) {
                            selected_list.clear();
                        }
                    }
                }
                sale_btn_yes.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
                sale_btn_yes.setTextColor(getResources().getColor(R.color.white));
                sale_btn_no.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
                sale_btn_no.setTextColor(getResources().getColor(R.color.grayfor_login));
                card_layout_scan.setVisibility(View.VISIBLE);
                card_layout_title.setVisibility(View.VISIBLE);
                drawer_layout_recycle_store.setVisibility(View.VISIBLE);
                product_sold_str = "Yes";
                rl_complete_layout.setVisibility(View.VISIBLE);
                img_visble.setVisibility(View.VISIBLE);
                rlSalesSource.setVisibility(View.VISIBLE);

            }

        } else if (view.getId() == R.id.draft_fab) {
            ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
            } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Check Terms & Condition");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id");
            } else if (demo_given_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Demo Given");
            } else if (product_sold_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Product Sold");
            } else if (str_sourceof_sales.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Source of visit");
            } else if (skin_genius_str.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Genius ");
            } else if (maybelline_vto.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Maybelline VTO ");
            } else if (product_sold_str.equalsIgnoreCase("Yes") && selected_list.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Add First");
            } else if (flag_for_term_condition && edt_otp.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter OTP");
            } else if (flag_for_term_condition && !checkotp_validation()) {
                AlertandMessages.showToastMsg(context, "Incorrect OTP");
            } else if (checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) {
                AlertandMessages.showToastMsg(context, "You Cannot Save If 'Demo Given' and 'Skin Genius' and 'Maybelline VTO' and 'Product Sale' are 'No'.");
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.alertsaveData);
                builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                    if (product_sold_str.equalsIgnoreCase("No")) {
                        selected_list.clear();
                        object = new InvoiceGetterSetter();
                        object = returnobject();
                        object.setQuantity("0");
                        object.setProduct("");
                        object.setProduct_Id("0");
                        object.setProduct_rate("0");
                        object.setDiscount(0.0);
                        object.setScan_ean_code_or_enterd_ean_code("");
                        object.setSkuType("");
                        object.setStr_invoiceType("");
                        ////addd promo column
                        object.setPromo_flag(false);
                        object.setPromo_type("");
                        object.setPromotion_name("");
                        object.setPromotion_Id("0");
                        selected_list.add(object);
                        ////prepare products for hashmap..........
                        prepareListData();
                        long l = calculate_data_insert_data();
                        if (l > 0) {
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            ConsumerUserDetailsActivity.this.finish();
                            dialogInterface.dismiss();
                        } else {
                            AlertandMessages.showToastMsg(context, "Data not Saved.Please try again.");
                        }
                    } else {
                        calculate_invoice_added_data(selected_list);
                        prepareListData();
                        long l = calculate_data_insert_data();
                        if (l > 0) {
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            ConsumerUserDetailsActivity.this.finish();
                            dialogInterface.dismiss();
                        } else {
                            AlertandMessages.showToastMsg(context, "Data not Saved.Please try again.");
                        }
                    }
                });
                builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
                builder.show();

            }
        }
    }

    private boolean checkdemoorskinVTO() {
        boolean flag = true;
        if (!demo_given_str.isEmpty() && demo_given_str.equalsIgnoreCase("Yes") || !skin_genius_str.isEmpty() && skin_genius_str.equalsIgnoreCase("Yes") || !maybelline_vto.isEmpty() && maybelline_vto.equalsIgnoreCase("Yes")) {
            flag = false;
        }
        return flag;
    }


    private long calculate_data_insert_data() {
        long l = 0;
        if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) {
            db.open();
            db.deleteconsumersale(visit_date, (reciept_count), username);
            db.open();
            if (!checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) {
                l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total),
                        true, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader,
                        str_img_demo_no_sale, from);
            } else {
                l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total),
                        false, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader,
                        str_img_demo_no_sale, from);
            }
        } else {
            db.open();
            if (!checkdemoorskinVTO() && product_sold_str.equalsIgnoreCase("No")) {
                l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total),
                        true, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader,
                        str_img_demo_no_sale, from);
            } else {
                l = db.insert_consumer_sales_data(username, visit_date, CounterId, String.valueOf(total),
                        false, CommonFunctions.getUUID(context), str_termCondition, listDataChild, listDataHeader,
                        str_img_demo_no_sale, from);
            }
        }
        return l;
    }

    private void prepareListData() {
        listDataHeader = new ArrayList<>();
        listDataChild = new HashMap<>();
        listDataHeader.add(selected_list.get(0));
        listDataHeader.size();// Adding child data
        for (int i = 0; i < listDataHeader.size(); i++) {
            listDataChild.put(listDataHeader.get(i), selected_list); // Header, Child data
        }
    }


    @SuppressLint("SetTextI18n")
    private void show_proforma_dialog(final Context context, final boolean flag_for_rl) {
        minteger = 0;
        final MultiPurposeDialog multiPDialog = new MultiPurposeDialog(context);
        multiPDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPDialog.setContentView(R.layout.custom_bar_code_dialog);
        multiPDialog.setCancelable(false);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiPDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPDialog.getWindow().setAttributes(lp);
        multiPDialog.setCancelable(false);
        multiPDialog.show();
        //for actual Quantity form Tstock_Summery
        rl_actual_qty = (LinearLayout) multiPDialog.findViewById(R.id.rl_actual_qty);
        actual_qty_dialog = (TextView) multiPDialog.findViewById(R.id.actual_qty_dialog);


        LinearLayout rl_bar_code = (LinearLayout) multiPDialog.findViewById(R.id.rl_bar_code);
        LinearLayout RL_scan_code = (LinearLayout) multiPDialog.findViewById(R.id.RL_scan_code);
        Button check_exist_sku = (Button) multiPDialog.findViewById(R.id.check_exist_sku);
        TextView txt_bar_code = multiPDialog.findViewById(R.id.txt_bar_code);
        TextView txt_enterbar_code = multiPDialog.findViewById(R.id.txt_enterbar_code);
        LinearLayout rl_quantity = (LinearLayout) multiPDialog.findViewById(R.id.rl_quantity);
        RecyclerView recycl_mutliennter_qty = (RecyclerView) multiPDialog.findViewById(R.id.recycl_mutliennter_qty);
        recycl_mutliennter_qty.setVisibility(View.GONE);
        rl_quantity.setVisibility(View.VISIBLE);

        sku_name = multiPDialog.findViewById(R.id.sku_name);
        if (flag_for_rl) {
            RL_scan_code.setVisibility(View.GONE);
            rl_bar_code.setVisibility(View.VISIBLE);
            txt_bar_code.setVisibility(View.VISIBLE);
            txt_enterbar_code.setVisibility(View.GONE);
        } else {
            rl_bar_code.setVisibility(View.GONE);
            txt_bar_code.setVisibility(View.GONE);
            RL_scan_code.setVisibility(View.VISIBLE);
            txt_enterbar_code.setVisibility(View.VISIBLE);
        }

        qrcode_text = (TextView) multiPDialog.findViewById(R.id.qrcode_text);
        edt_scan_code = (EditText) multiPDialog.findViewById(R.id.edt_scan_code);
        final Button stock_img_minus = (Button) multiPDialog.findViewById(R.id.stock_img_minus);
        Button stock_img_plus = (Button) multiPDialog.findViewById(R.id.stock_img_plus);
        stock_text_value = (TextView) multiPDialog.findViewById(R.id.stock_text_value);

        ImageView img_bar_code = (ImageView) multiPDialog.findViewById(R.id.img_bar_code);
        ImageView cancet_btn = (ImageView) multiPDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) multiPDialog.findViewById(R.id.btn_add);
        btn_add.setVisibility(View.VISIBLE);

        stock_img_plus.setOnClickListener(v -> {
            if (!product_Id.equals("0")) {
                db.open();
                if (db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock() == 0) {
                    AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                } else {
                    minteger = minteger + 1;
                    db.open();
                    if (db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock()) {
                        minteger = minteger - 1;
                        AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                    } else {
                        stock_text_value.setText("" + minteger);
                    }
                }
            }
        });

        stock_img_minus.setOnClickListener(v -> {
            if (minteger == 0) {
                AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
            } else {
                minteger = minteger - 1;
                stock_text_value.setText("" + minteger);
            }
        });

        cancet_btn.setOnClickListener(v -> {
            if (multiPDialog.isShowing()) {
                multiPDialog.dismiss();
            }
            sku_name.setText("");
            stock_text_value.setText("");
            qrcode_text.setText("");
            product_scan_code = "";
            product_name = "";
            product_mrp = "";
            product_Id = "0";
            productType = "";
            discount = 0.0;
            sku_name.setVisibility(View.GONE);
        });

        check_exist_sku.setOnClickListener(v -> {
            if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Bar Code");
            } else {
                db.open();
                ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancode(edt_scan_code.getText().toString(), true, visit_date, CounterId, from);
                if (productList.isEmpty()) {
                    db.open();
                    productList = db.getsku_fromproductusing_eancode(removeFirstChar(edt_scan_code.getText().toString()), true, visit_date, CounterId, from);
                }
                if (productList.isEmpty()) {
                    edt_scan_code.setText("");
                    AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again");
                } else {
                    show_dialog_forsku(context, productList, rl_actual_qty, actual_qty_dialog);
                }
            }
        });


        btn_add.setOnClickListener(v -> {
            db.open();
            if (db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock() == 0) {
                AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                if (multiPDialog.isShowing()) {
                    multiPDialog.dismiss();
                }

                stock_text_value.setText("");
                qrcode_text.setText("");
                edt_scan_code.setText("");
                product_scan_code = "";
                product_name = "";
                product_mrp = "";
                product_Id = "0";
                productType = "";
                discount = 0.0;
                sku_name.setText("");
                sku_name.setVisibility(View.GONE);

            } else {
                // get selected radio button from radioGroup
                int selectedId = radioSexGroup.getCheckedRadioButtonId();
                // find the radiobutton by returned id
                radioSexButton = (RadioButton) findViewById(selectedId);
                if (flag_for_rl && qrcode_text.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Scan Bar Code");
                } else if (!flag_for_rl && edt_scan_code.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Bar Code ");
                } else if (stock_text_value.getText().toString().equals("0")) {
                    AlertandMessages.showToastMsg(context, "Please add Atleast One Product Quantity ");
                } else {
                    if (checkduplicate_entry()) {
                        if (!flag_for_rl) {
                            product_scan_code = edt_scan_code.getText().toString();
                            db.open();
                            if (db.getsku_fromproductusing_eancode(product_scan_code, true, visit_date, CounterId, from).isEmpty()) {
                                AlertandMessages.showToastMsg(context, "Product not found ");
                            } else {
                                minteger = 0;
                                if (multiPDialog.isShowing()) {
                                    multiPDialog.dismiss();
                                }
                                object = new InvoiceGetterSetter();
                                object = returnobject();
                                object.setProduct(product_name);
                                object.setProduct_Id(product_Id);
                                object.setProduct_rate(product_mrp);
                                object.setDiscount(discount);
                                object.setQuantity(stock_text_value.getText().toString());
                                object.setSkuType(productType);
                                object.setStr_invoiceType(dialog_invoiceType);
                                object.setPromo_flag(false);
                                object.setPromo_type("");
                                object.setPromotion_name("");
                                object.setPromotion_Id("0");
                                selected_list.add(object);

                                current_total_stock.setText("Total : " + calculate_total_consume(selected_list));
                                stock_text_value.setText("");
                                qrcode_text.setText("");
                                edt_scan_code.setText("");
                                product_scan_code = "";
                                product_name = "";
                                product_mrp = "";
                                product_Id = "0";
                                productType = "";
                                discount = 0.0;
                                sku_name.setText("");
                                sku_name.setVisibility(View.GONE);
                                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                                product_add_flag = true;
                            }
                        } else {
                            if (multiPDialog.isShowing()) {
                                multiPDialog.dismiss();
                            }
                            minteger = 0;
                            object = new InvoiceGetterSetter();
                            object = returnobject();
                            object.setQuantity(stock_text_value.getText().toString());
                            object.setProduct(product_name);
                            object.setProduct_Id(product_Id);
                            object.setDiscount(discount);
                            object.setProduct_rate(product_mrp);
                            object.setSkuType(productType);
                            object.setStr_invoiceType(dialog_invoiceType);
                            object.setPromo_flag(false);
                            object.setPromo_type("");
                            object.setPromotion_name("");
                            object.setPromotion_Id("0");
                            selected_list.add(object);

                            current_total_stock.setText("Total : " + calculate_total_consume(selected_list));
                            sku_name.setText("");
                            stock_text_value.setText("");
                            qrcode_text.setText("");
                            product_scan_code = "";
                            product_name = "";
                            product_mrp = "";
                            product_Id = "0";
                            productType = "";
                            discount = 0.0;
                            sku_name.setVisibility(View.GONE);
                            drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                            product_add_flag = true;
                        }
                    }
                }
            }
        });

        img_bar_code.setOnClickListener(v -> openScanner());

        multiPDialog.show();
    }


    private void openScanner() {
        IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context);
        intentIntegrator.setBeepEnabled(true);
        intentIntegrator.setOrientationLocked(false);
        intentIntegrator.setPrompt("Scan the barcode or QR code to get the data");
        intentIntegrator.initiateScan();
    }

    private void adapterforAgeLimit_SkinType() {
        ///for source of sales
        sourceofsalesAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        sourceofsalesAdapter.add("- Select Source of visit -");
        for (int i = 0; i < sourceofsaleslist.size(); i++) {
            sourceofsalesAdapter.add(sourceofsaleslist.get(i).getSourcesOfSale());
        }
        spinSourceof_sales.setAdapter(sourceofsalesAdapter);
        sourceofsalesAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spinSourceof_sales.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    try {
                        str_sourceof_sales = sourceofsaleslist.get(pos - 1).getSourcesOfSale();
                        rl_complete_layout.setVisibility(View.VISIBLE);
                        img_visble.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    str_sourceof_sales = "";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        ///for Age Adapter
        AgeAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        AgeAdapter.add("- Select Age Range -");

        for (int i = 0; i < ageLimits.size(); i++) {
            AgeAdapter.add(ageLimits.get(i).getAgeLimit());
        }

        spin_age.setAdapter(AgeAdapter);
        AgeAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spin_age.setOnItemSelectedListener(this);

        SkinTypeAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        SkinTypeAdapter.add("- Select Skin Type -");

        for (int i = 0; i < skinTypes.size(); i++) {
            SkinTypeAdapter.add(skinTypes.get(i).getSkinType());
        }

        spin_skin_type.setAdapter(SkinTypeAdapter);
        SkinTypeAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spin_skin_type.setOnItemSelectedListener(this);
        db.open();
        dialog_product_list = db.getproduct_masterlist("T_StockSummary", visit_date, CounterId, from);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    private static class MultiPurposeDialog extends Dialog {
        private MultiPurposeDialog(Context context) {
            super(context);
            // DIALOG USER_INTERFACE TEMPLATE
            WindowManager.LayoutParams wmLayoutParams = Objects.requireNonNull(getWindow()).getAttributes();
            wmLayoutParams.gravity = Gravity.CENTER;
            getWindow().setAttributes(wmLayoutParams);
            setTitle(null);
            setCancelable(false);
            setOnCancelListener(null);
            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result == null) {
            switch (resultCode) {
                case 0:
                    Log.i("MakeMachine", "User cancelled");
                    break;
                case -1:
                    if (_pathforcheck != null && !_pathforcheck.isEmpty()) {
                        if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                            convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                            img_only_demo.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                            str_img_demo_no_sale = _pathforcheck;
                            _pathforcheck = "";
                        }
                    }

                    break;
            }
        } else if (result != null) {
            if (result.getContents() == null) {
                //test("ScanActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
            } else {

                db.open();
                ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancode(result.getContents(), true, visit_date, CounterId, from);
                if (productList.isEmpty()) {
                    db.open();
                    productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), true, visit_date, CounterId, from);
                }

                if (!productList.isEmpty()) {
                    show_dialog_forsku(context, productList, rl_actual_qty, actual_qty_dialog);
                    sku_name.setText(productList.get(0).getProductName());
                    sku_name.setVisibility(View.VISIBLE);
                    stock_text_value.setText("0");
                    minteger = 0;
                } else {
                    minteger = 0;
                    product_name = "";
                    product_scan_code = "";
                    qrcode_text.setText("");
                    AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again.");
                }
            }

        } else
            super.onActivityResult(requestCode, resultCode, data);
    }


    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        private final LayoutInflater inflator;
        ArrayList<InvoiceGetterSetter> data;
        int added_value = 0;


        public ValueAdapter(Context context, ArrayList<InvoiceGetterSetter> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;
        }

        @NonNull
        @Override
        public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_adapter_proforma_sale, parent, false);
            return new ValueAdapter.MyViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            final InvoiceGetterSetter current = data.get(position);

            if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffSameProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }
            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);
                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }
            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);
                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }

            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffWorth") || current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("WorthWithProduct")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);
                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }

            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("OffProduct")) {

                holder.select_promo_productRl.setVisibility(View.GONE);
                holder.select_promo_productRl.setId(position);

                holder.select_productRl.setVisibility(View.VISIBLE);
                holder.select_productRl.setId(position);

                holder.text_item.setText("Applied Promo - " + current.getPromotion_name() + " - " + current.getProduct() + " - Discounted Rs - " + current.getSkuType());
                holder.text_item.setId(position);

                holder.text_qty.setText(current.getQuantity());
                holder.text_qty.setId(position);

                holder.txt_amount.setText(current.getProduct_rate());
                holder.txt_amount.setId(position);

            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Worth")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Discounted Rs - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }


            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Gift")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - " + "Gift - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + "Gift  - " + current.getProduct());
                    holder.txt_promo_str.setId(position);
                }

            } else if (current.isPromo_flag() && current.getPromo_type().equalsIgnoreCase("Product")) {
                holder.select_promo_productRl.setVisibility(View.VISIBLE);
                holder.select_promo_productRl.setId(position);

                holder.select_productRl.setVisibility(View.GONE);
                holder.select_productRl.setId(position);

                if (CommonFunctions.isTablet(context)) {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + " - (" + current.getProduct().toLowerCase() + ")");
                    holder.txt_promo_str.setId(position);
                } else {
                    holder.txt_promo_str.setText("Applied Promo - " + current.getPromotion_name() + "\n" + current.getProduct().toLowerCase());
                    holder.txt_promo_str.setId(position);
                }
            } else {
                holder.select_promo_productRl.setVisibility(View.GONE);
                holder.select_promo_productRl.setId(position);
                holder.select_productRl.setVisibility(View.VISIBLE);
                holder.select_productRl.setId(position);

                int quantity = Integer.parseInt(current.getQuantity());
                double amount = Double.parseDouble(current.getProduct_rate());
                amount = amount * quantity;
                double cCom = ((amount) * current.getDiscount());
                if (current.getDiscount() == 0.0 || current.getDiscount() == 0) {
                    if (!current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("Sample") ||
                            !current.getStr_invoiceType().isEmpty() && current.getStr_invoiceType().equalsIgnoreCase("GWP")) {
                        holder.text_item.setText(current.getProduct() + " - Type - " + current.getStr_invoiceType());
                        holder.text_item.setId(position);
                    } else {
                        holder.text_item.setText(current.getProduct());
                        holder.text_item.setId(position);
                    }

                } else {
                    String string = current.getDiscount().toString();
                    holder.text_item.setText(current.getProduct() + "  Discount : " + string.substring(string.length() - 1) + "0%");
                    holder.text_item.setId(position);
                }

                holder.text_qty.setText(current.getQuantity());
                holder.text_qty.setId(position);

                holder.txt_amount.setText(current.getProduct_rate());
                holder.txt_amount.setId(position);

            }


            holder.update_img.setOnClickListener(view -> {
                product_add_flag = true;
                holder.delete_added_product.setVisibility(View.GONE);
                holder.delete_added_product.setId(position);
                holder.rl_increaseqty.setVisibility(View.VISIBLE);
                holder.rl_increaseqty.setId(position);
                holder.verify_icon.setVisibility(View.VISIBLE);
                holder.verify_icon.setId(position);

            });

            holder.verify_icon.setOnClickListener(view -> {
                product_add_flag = true;
                holder.delete_added_product.setVisibility(View.VISIBLE);
                holder.delete_added_product.setId(position);
                holder.rl_increaseqty.setVisibility(View.GONE);
                holder.rl_increaseqty.setId(position);
                holder.verify_icon.setVisibility(View.GONE);
                holder.verify_icon.setId(position);
                holder.update_img.setVisibility(View.VISIBLE);
                holder.update_img.setId(position);
                current_total_stock.setText("Total : " + calculate_total_consume(selected_list));

            });

            holder.stock_img_plus.setOnClickListener(v -> {
                db.open();
                product_add_flag = true;
                if (flag_for_consumer_Update != null && flag_for_consumer_Update.equals("1")) {
                    db.open();
                    int actual_stock = db.getActualSaleableStock(current.getProduct_Id(), null, visit_date, CounterId, from).getStock();
                    if (added_value == actual_stock && actual_stock == 0) {
                        AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                    } else {
                        int minteger = Integer.parseInt(current.getQuantity());
                        minteger = minteger + 1;
                        added_value = added_value + 1;
                        db.open();
                        if (actual_stock > 0 && added_value > actual_stock) {
                            minteger = minteger - 1;
                            added_value = added_value - 1;
                            holder.text_qty.setText("" + minteger);
                            holder.text_qty.setId(position);
                            current.setQuantity("" + minteger);
                            AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                        } else {
                            holder.text_qty.setText("" + minteger);
                            holder.text_qty.setId(position);
                            current.setQuantity("" + minteger);
                        }
                    }
                } else {
                    db.open();
                    int actual_stock = db.getActualSaleableStock(current.getProduct_Id(), null, visit_date, CounterId, from).getStock();
                    if (actual_stock == 0) {
                        AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                    } else {
                        int minteger = Integer.parseInt(current.getQuantity());
                        minteger = minteger + 1;
                        db.open();
                        if (actual_stock > 0 && minteger > actual_stock) {
                            minteger = minteger - 1;
                            holder.text_qty.setText("" + minteger);
                            holder.text_qty.setId(position);
                            current.setQuantity("" + minteger);
                            AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                        } else {
                            holder.text_qty.setText("" + minteger);
                            holder.text_qty.setId(position);
                            current.setQuantity("" + minteger);
                        }
                    }
                }
            });

            holder.stock_img_minus.setOnClickListener(v -> {
                product_add_flag = true;
                int minteger = Integer.parseInt(current.getQuantity());
                if (minteger == 1) {
                    AlertandMessages.showToastMsg(context, "Product quantity should not be less than One");
                } else {
                    minteger = minteger - 1;
                    holder.text_qty.setText("" + minteger);
                    holder.text_qty.setId(position);
                    current.setQuantity("" + minteger);
                }
            });

            holder.delete_added_product.setOnClickListener(v -> {
                product_add_flag = true;
                if (tagmode != null && !tagmode.isEmpty() && tagmode.equals("1")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @SuppressLint("NotifyDataSetChanged")
                        public void onClick(DialogInterface dialog, int id) {
                            if (current.getReccept_count() != 0) {
                                db.delete_sale(visit_date, current.getReccept_count(), username);
                                data.remove(position);
                                notifyDataSetChanged();
                                if (!data.isEmpty()) {
                                    current_total_stock.setText("Total : " + calculate_total_consume(data));
                                    ValueAdapter adapter = new ValueAdapter(context, data);
                                    drawer_layout_recycle_store.setAdapter(adapter);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    current_total_stock.setText("Total : " + calculate_total_consume(data));
                                }
                                notifyDataSetChanged();
                            } else {
                                data.remove(position);
                                notifyDataSetChanged();
                                if (!data.isEmpty()) {
                                    current_total_stock.setText("Total : " + calculate_total_consume(data));
                                    ValueAdapter adapter = new ValueAdapter(context, data);
                                    drawer_layout_recycle_store.setAdapter(adapter);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    current_total_stock.setText("Total : " + calculate_total_consume(data));
                                }
                                notifyDataSetChanged();
                            }
                        }
                    }).setNegativeButton("No", (dialog, id) -> dialog.cancel());
                    AlertDialog alert = builder.create();
                    alert.show();
                } else if (tagmode.isEmpty() && calculate(data) > 0 && calculate(data) > 1) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage("Are you sure you want to Delete ?").setTitle(getString(R.string.password_rules)).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @SuppressLint("NotifyDataSetChanged")
                                public void onClick(DialogInterface dialog, int id) {
                                    if (current.getReccept_count() != 0) {
                                        db.open();
                                        db.delete_sale(visit_date, current.getReccept_count(), username);
                                        data.remove(position);
                                        notifyDataSetChanged();
                                        if (!data.isEmpty()) {
                                            current_total_stock.setText("Total : " + calculate_total_consume(data));
                                            ValueAdapter adapter = new ValueAdapter(context, data);
                                            drawer_layout_recycle_store.setAdapter(adapter);
                                            adapter.notifyDataSetChanged();
                                        }
                                        notifyDataSetChanged();

                                    } else {
                                        data.remove(position);
                                        notifyDataSetChanged();
                                        if (!data.isEmpty()) {
                                            current_total_stock.setText("Total : " + calculate_total_consume(data));
                                            ValueAdapter adapter = new ValueAdapter(context, data);
                                            drawer_layout_recycle_store.setAdapter(adapter);
                                            adapter.notifyDataSetChanged();
                                        }

                                        notifyDataSetChanged();
                                    }
                                }
                            })
                            .setNegativeButton("No",
                                    (dialog, id) -> dialog.cancel());
                    AlertDialog alert = builder.create();
                    alert.show();
                } else if (tagmode.isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Atleast One Product Has To Be Present");
                }

            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView text_item, text_qty, txt_amount, txt_promo_str;
            LinearLayout select_promo_productRl, select_productRl, rl_increaseqty, rl_edit;
            Button stock_img_minus, stock_img_plus;
            ImageView delete_added_product, verify_icon, update_img;

            public MyViewHolder(View itemView) {
                super(itemView);
                text_item = (TextView) itemView.findViewById(R.id.text_item);
                text_qty = (TextView) itemView.findViewById(R.id.text_qty);
                txt_amount = (TextView) itemView.findViewById(R.id.txt_amount);
                txt_promo_str = (TextView) itemView.findViewById(R.id.txt_promo_str);
                delete_added_product = (ImageView) itemView.findViewById(R.id.delete_added_product);
                select_promo_productRl = (LinearLayout) itemView.findViewById(R.id.select_promo_productRl);
                select_productRl = (LinearLayout) itemView.findViewById(R.id.select_productRl);
                rl_increaseqty = (LinearLayout) itemView.findViewById(R.id.rl_increaseqty);
                rl_edit = (LinearLayout) itemView.findViewById(R.id.rl_edit);
                stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus);
                stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus);
                verify_icon = (ImageView) itemView.findViewById(R.id.verify_icon);
                update_img = (ImageView) itemView.findViewById(R.id.update_img);
            }
        }
    }

    private int calculate(ArrayList<InvoiceGetterSetter> data) {
        int size = 0;
        try {
            if (!data.isEmpty()) {
                for (int k = 0; k < data.size(); k++) {
                    if (!data.get(k).isPromo_flag()) {
                        size = size + 1;

                    }
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return size;
    }

    public void getotp_from_mobile_no(String jsondata, final MultiPurposeDialog multiDialog) {
        try {
            loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true);
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(Objects.requireNonNull(MediaType.parse("application/json")), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<ResponseBody> call = api.getOTPMethod(jsonData);
            call.enqueue(new retrofit2.Callback<ResponseBody>() {
                @Override
                public void onResponse(@NonNull retrofit2.Call<ResponseBody> call, @NonNull retrofit2.Response<ResponseBody> response) {
                    ResponseBody responseBody = response.body();
                    String data = null;
                    loading.dismiss();

                    if (multiDialog != null && multiDialog.isShowing()) {
                        multiDialog.dismiss();
                    }

                    if (loading != null && loading.isShowing()) {
                        loading.dismiss();
                    }
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().string();
                            JSONObject jObject = new JSONObject(data);
                            otp_code = jObject.getString("SendOTPResult");

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    } else {
                        assert loading != null;
                        loading.dismiss();
                        if (loading != null && loading.isShowing()) {
                            loading.dismiss();
                        }
                        Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(@NonNull retrofit2.Call<ResponseBody> call, @NonNull Throwable t) {
                    loading.dismiss();
                    if (loading != null && loading.isShowing()) {
                        loading.dismiss();
                    }
                    AlertandMessages.showAlertlogin((Activity) context, getString(R.string.nonetwork));
                }
            });
        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }


    @SuppressLint("SetTextI18n")
    private void show_dialog_forsku_categorywise(final Context context) {
        minteger = 0;
        final MultiPurposeDialog multiDialog = new MultiPurposeDialog(context);
        multiDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiDialog.setContentView(R.layout.custom_sku_list_with_category);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiDialog.getWindow().setAttributes(lp);
        multiDialog.setCancelable(false);
        multiDialog.show();

        dialog_invoiceType = "Saleable";
        ///new changes 19 aug
        final Button btn_invoice_type_saleable = (Button) multiDialog.findViewById(R.id.btn_invoice_type_saleable);
        final Button btn_invoice_type_sample = (Button) multiDialog.findViewById(R.id.btn_invoice_type_sample);
        final Button btn_invoice_type_gwp = (Button) multiDialog.findViewById(R.id.btn_invoice_type_gwp);
        final LinearLayout rl_invoice_type = (LinearLayout) multiDialog.findViewById(R.id.rl_invoice_type);
        rl_invoice_type.setVisibility(View.VISIBLE);
        final Spinner dialog_brand_spin = (Spinner) multiDialog.findViewById(R.id.dialog_brand_spin);
        final Spinner dialog_subbrand_spin = (Spinner) multiDialog.findViewById(R.id.dialog_subbrand_spin);
        final Spinner dialog_reference_spin = (Spinner) multiDialog.findViewById(R.id.dialog_reference_spin);
        final Spinner dialog_product_spin = (Spinner) multiDialog.findViewById(R.id.dialog_product_spin);
        final EditText et_search = (EditText) multiDialog.findViewById(R.id.et_search);
        final TextView stock_text_value = (TextView) multiDialog.findViewById(R.id.stock_text_value);
        final Button stock_img_minus = (Button) multiDialog.findViewById(R.id.stock_img_minus);
        Button stock_img_plus = (Button) multiDialog.findViewById(R.id.stock_img_plus);
        ImageView cancet_btn = (ImageView) multiDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) multiDialog.findViewById(R.id.btn_add);
        //for actual Quantity form Tstock_Summery
        rl_actual_qty = (LinearLayout) multiDialog.findViewById(R.id.rl_actual_qty);
        actual_qty_dialog = (TextView) multiDialog.findViewById(R.id.actual_qty_dialog);
        TextView txt_current_invoice_type = (TextView) multiDialog.findViewById(R.id.txt_current_invoice_type);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = s.toString();
                if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                    setSearchFilter(db.getproduct_masterlist(dialog_invoiceType, visit_date, CounterId, from), text, dialog_product_spin);
                } else {
                    setSearchFilter(dialog_product_list, text, dialog_product_spin);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        db.open();
        validate_spin_ui_data(btn_invoice_type_saleable, btn_invoice_type_sample, btn_invoice_type_gwp, dialog_brand_spin, dialog_subbrand_spin,
                dialog_reference_spin, dialog_product_spin, stock_text_value, rl_actual_qty, actual_qty_dialog, txt_current_invoice_type);


        cancet_btn.setOnClickListener(v -> {
            multiDialog.dismiss();

            if (multiDialog.isShowing()) {
                multiDialog.dismiss();
            }
        });


        stock_img_minus.setOnClickListener(v -> {
            if (minteger == 0) {
                AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
            } else {
                minteger = minteger - 1;
                stock_text_value.setText("" + minteger);
            }
        });

        stock_img_plus.setOnClickListener(v -> {
            if (!product_Id.equals("0")) {
                db.open();
                if (!product_Id.equals("0")) {
                    rl_actual_qty.setVisibility(View.VISIBLE);
                    db.open();
                    if (dialog_invoiceType.equalsIgnoreCase("Saleable") && db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock() == 0) {
                        AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                    } else if (dialog_invoiceType.equalsIgnoreCase("Sample") && db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock() == 0) {
                        AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                    } else if (dialog_invoiceType.equalsIgnoreCase("GWP") && db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock() == 0) {
                        AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                    } else {
                        minteger = minteger + 1;
                        db.open();
                        if (dialog_invoiceType.equalsIgnoreCase("Saleable") && db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock()) {
                            minteger = minteger - 1;
                            AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                        } else if (dialog_invoiceType.equalsIgnoreCase("Sample") && db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock()) {
                            minteger = minteger - 1;
                            AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                        } else if (dialog_invoiceType.equalsIgnoreCase("GWP") && db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock() > 0 && minteger > db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock()) {
                            minteger = minteger - 1;
                            AlertandMessages.showToastMsg(context, "Stock Low. Please reduce sale quantity below or equal to the stock value");
                        } else {
                            stock_text_value.setText("" + minteger);
                        }
                    }
                }
            }
        });

        btn_add.setOnClickListener(v -> {
            ((ConsumerUserDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
            db.open();
            if (dialog_product_spin.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Product");
            } else if (stock_text_value.getText().toString().equals("0")) {
                AlertandMessages.showToastMsg(context, "Please add Atleast One Product Quantity");
            } else if (dialog_invoiceType.equalsIgnoreCase("Saleable") && db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock() == 0) {
                AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                if (multiDialog.isShowing()) {
                    multiDialog.dismiss();
                }
                minteger = 0;
                stock_text_value.setText("0");
                product_scan_code = "";
                dialog_brand_Id = "";
                dialog_sub_brand_Id = "";
                dialog_reference_Id = "";
                product_name = "";
                product_Id = "0";
                productType = "";
                discount = 0.0;
            } else if (dialog_invoiceType.equalsIgnoreCase("Sample") && db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock() == 0) {
                AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                if (multiDialog.isShowing()) {
                    multiDialog.dismiss();
                }
                minteger = 0;
                stock_text_value.setText("0");
                product_scan_code = "";
                dialog_brand_Id = "";
                dialog_sub_brand_Id = "";
                dialog_reference_Id = "";
                product_name = "";
                product_Id = "0";
                productType = "";
                discount = 0.0;
                db.open();
            } else if (dialog_invoiceType.equalsIgnoreCase("GWP") && db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock() == 0) {
                AlertandMessages.showToastMsg(context, "Stock for this Product is Zero. Cannot allow to add this Product");
                if (multiDialog.isShowing()) {
                    multiDialog.dismiss();
                }
                minteger = 0;
                stock_text_value.setText("0");
                product_scan_code = "";
                dialog_brand_Id = "";
                dialog_sub_brand_Id = "";
                dialog_reference_Id = "";
                product_name = "";
                product_Id = "0";
                productType = "";
                discount = 0.0;
            } else {
                if (checkduplicate_entry()) {
                    object = new InvoiceGetterSetter();
                    object = returnobject();

                    object.setProduct_rate(product_mrp);
                    object.setProduct(product_name);
                    object.setProduct_Id(product_Id);
                    object.setDiscount(discount);
                    object.setQuantity(stock_text_value.getText().toString());
                    object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                    object.setSkuType(productType);
                    object.setStr_invoiceType(dialog_invoiceType);
                    object.setPromo_flag(false);
                    object.setPromo_type("");
                    object.setPromotion_name("");
                    object.setPromotion_Id("0");
                    selected_list.add(object);

                    current_total_stock.setText("Total : " + calculate_total_consume(selected_list));
                    minteger = 0;
                    stock_text_value.setText("0");
                    product_scan_code = "";
                    dialog_brand_Id = "";
                    dialog_sub_brand_Id = "";
                    dialog_reference_Id = "";
                    product_name = "";
                    product_Id = "0";
                    productType = "";
                    discount = 0.0;
                    dialog_invoiceType = "Saleable";
                    drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    product_add_flag = true;
                    if (multiDialog.isShowing()) {
                        multiDialog.dismiss();
                    }

                }
            }
        });

        multiDialog.show();
    }

    ////sku scannnnnnnnnnnn
    private void show_dialog_forsku(final Context context, ArrayList<ProductMaster> skuList_with_eancode, LinearLayout rl_actual_qty, TextView actual_qty_dialog) {
        final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_adapter);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);
        multiPurposeDialog.show();

        TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name);
        sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName());
        RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku);

        recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, multiPurposeDialog, "0", rl_actual_qty, actual_qty_dialog));
        recycl_sku.setLayoutManager(new LinearLayoutManager(context));
        ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog);
        dismiss_dialog.setOnClickListener(v -> {
            if (multiPurposeDialog.isShowing()) {
                multiPurposeDialog.dismiss();
            }
        });

        multiPurposeDialog.show();
    }


    private class AdapterforSku extends RecyclerView.Adapter<AdapterforSku.MyViewHolder> {
        private final LayoutInflater inflator;
        List<ProductMaster> data;
        String show_dialog;
        MultiPurposeDialog multiPurposeDialog;
        LinearLayout rl_actual_qty;
        TextView actual_qty_dialog;

        public AdapterforSku(Context context, List<ProductMaster> data, MultiPurposeDialog multiPurposeDialog, String show_dialog
                , LinearLayout rl_actual_qty, TextView actual_qty_dialog) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.show_dialog = show_dialog;
            this.multiPurposeDialog = multiPurposeDialog;

            this.actual_qty_dialog = actual_qty_dialog;
            this.rl_actual_qty = rl_actual_qty;
        }

        @NonNull
        @Override
        public AdapterforSku.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.adapter_custom, parent, false);
            return new AdapterforSku.MyViewHolder(view);
        }


        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);
            if (show_dialog.equals("1")) {
                holder.sale_card.setVisibility(View.VISIBLE);
                holder.sale_card.setId(position);
                holder.sale_trcking_name.setText("Date : " + current.getVisit_date());
                holder.sale_trcking_name.setId(position);
                holder.consumer_recycle.setVisibility(View.VISIBLE);
                holder.consumer_recycle.setId(position);

            } else {
                holder.sale_card.setVisibility(View.VISIBLE);
                holder.sale_card.setId(position);
                holder.sale_trcking_name.setText("(MRP - " + current.getMrp().toString() + ")");
                holder.sale_trcking_name.setId(position);

                holder.consumer_recycle.setVisibility(View.GONE);
                holder.consumer_recycle.setId(position);

                holder.sale_card.setOnClickListener(v -> {
                    qrcode_text.setVisibility(View.VISIBLE);
                    qrcode_text.setText(current.getEanCode());
                    product_name = current.getProductName();
                    product_Id = current.getProductId().toString();
                    product_scan_code = current.getEanCode();
                    product_mrp = current.getMrp().toString();
                    productType = current.getProductType();
                    sku_name.setText(product_name + " Mrp - " + product_mrp);
                    sku_name.setVisibility(View.VISIBLE);
                    multiPurposeDialog.dismiss();

                    if (multiPurposeDialog != null && multiPurposeDialog.isShowing()) {
                        multiPurposeDialog.dismiss();
                    }

                    if (!product_Id.equals("0")) {
                        db.open();
                        actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, null, visit_date, CounterId, from).getStock());
                        rl_actual_qty.setVisibility(View.VISIBLE);
                    }
                });
            }
        }


        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView sale_trcking_name;
            CardView sale_card;
            RecyclerView consumer_recycle;


            public MyViewHolder(View itemView) {
                super(itemView);
                sale_card = (CardView) itemView.findViewById(R.id.sale_card);
                sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name);
                ////for consumer product
                consumer_recycle = (RecyclerView) itemView.findViewById(R.id.consumer_recycle);
            }
        }
    }

    private boolean checkduplicate_entry() {
        boolean status = true;
        try {
            if (selected_list != null && !selected_list.isEmpty()) {
                for (int k = 0; k < selected_list.size(); k++) {
                    if (selected_list.get(k).getProduct_Id().equals(product_Id) && selected_list.get(k).getProduct_rate().equals(product_mrp)) {
                        Toast.makeText(context, "This Product Already Added", Toast.LENGTH_SHORT).show();
                        status = false;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return status;
    }

    private boolean checkindex() {
        boolean status = false;
        try {
            String str = edt_mobile_no.getText().toString();
            String[] strArray = str.split(" ");
            //print elements of String array
            for (String parentMenuId : strArray) {
                if (parentMenuId.contains("1") || parentMenuId.contains("2") || parentMenuId.contains("3") || parentMenuId.contains("4") || parentMenuId.contains("5") || parentMenuId.contains("6") || parentMenuId.contains("7") || parentMenuId.contains("9") || parentMenuId.contains("8")) {
                    status = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return status;
    }

    @SuppressLint("SetTextI18n")
    private void show_consumer_previous_histry(final Context context, List<ConsumerSalesHistory> previusHistoryList) {
        final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_adapter);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(multiPurposeDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);
        TextView txt_bar_code = multiPurposeDialog.findViewById(R.id.txt_bar_code);
        txt_bar_code.setText("Consumer Purchase History");
        TextView sale_trcking_name = (TextView) multiPurposeDialog.findViewById(R.id.sale_trcking_name);
        sale_trcking_name.setVisibility(View.GONE);
        RecyclerView recycl_sku = (RecyclerView) multiPurposeDialog.findViewById(R.id.recycl_sku);

        if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Male")) {
            //radioSexButton
            radioSexGroup.check(R.id.radioM);
        } else if (previusHistoryList.get(0).getGender().equalsIgnoreCase("Female")) {
            //radioSexButton
            radioSexGroup.check(R.id.radioF);
        } else {
            radioSexGroup.check(R.id.radio_other);
        }

        for (int k = 0; k < ageLimits.size(); k++) {
            if (!previusHistoryList.get(0).getAgeGroup().isEmpty())
                db.open();
            if (ageLimits.get(k).getAgeLimit().equalsIgnoreCase(previusHistoryList.get(0).getAgeGroup())) {
                spin_age.setSelection(k + 1);
                break;
            }
        }

        for (int k = 0; k < skinTypes.size(); k++) {
            if (!previusHistoryList.get(0).getSkinType().isEmpty())
                db.open();
            if (skinTypes.get(k).getSkinType().equals(previusHistoryList.get(0).getSkinType())) {
                spin_skin_type.setSelection(k + 1);
                break;
            }
        }

        recycl_sku.setAdapter(new AdapterforHistry(context, previusHistoryList, multiPurposeDialog));
        recycl_sku.setLayoutManager(new LinearLayoutManager(context));

        ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog);
        dismiss_dialog.setOnClickListener(v -> {
            multiPurposeDialog.dismiss();
            if (multiPurposeDialog != null && multiPurposeDialog.isShowing()) {
                multiPurposeDialog.dismiss();
            }
        });

        multiPurposeDialog.show();
    }

    private class AdapterforHistry extends RecyclerView.Adapter<AdapterforHistry.MyViewHolder> {
        private final LayoutInflater inflator;
        List<ConsumerSalesHistory> data;
        MultiPurposeDialog multiPurposeDialog;

        AdapterforHistry(Context context, List<ConsumerSalesHistory> data, MultiPurposeDialog multiPurposeDialog) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.multiPurposeDialog = multiPurposeDialog;
        }

        @NonNull
        @Override
        public AdapterforHistry.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.adapter_custom_history_product, parent, false);
            return new AdapterforHistry.MyViewHolder(view);

        }


        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            final ConsumerSalesHistory current = data.get(position);

            holder.text_visit_date.setText("Date : " + current.getVisitDate());
            holder.text_visit_date.setId(position);

            holder.consume_product.setText("Product Name : " + current.getProductName());
            holder.consume_product.setId(position);

            holder.consume_product_qty_with_date.setText("MRP : " + current.getMrp().toString());
            holder.consume_product_qty_with_date.setId(position);

            holder.qty_sold_txt.setText("QTY Sold : " + current.getQtySold().toString());
            holder.qty_sold_txt.setId(position);

            holder.total_amount_txt.setText("Total Amount : " + current.getTotalAmount().toString());
            holder.total_amount_txt.setId(position);


            if (position != 0) {
                if (data.get(position - 1).getVisitDate().equalsIgnoreCase(current.getVisitDate())) {
                    holder.rl_visit_date.setVisibility(View.GONE);
                    holder.rl_visit_date.setId(position);
                } else {
                    holder.rl_visit_date.setVisibility(View.VISIBLE);
                    holder.rl_visit_date.setId(position);
                }
            }
        }


        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView consume_product, consume_product_qty_with_date, text_visit_date, qty_sold_txt, total_amount_txt;
            LinearLayout rl_visit_date;

            public MyViewHolder(View itemView) {
                super(itemView);
                rl_visit_date = (LinearLayout) itemView.findViewById(R.id.rl_visit_date);
                consume_product_qty_with_date = (TextView) itemView.findViewById(R.id.consume_product_qty_with_date);
                consume_product = (TextView) itemView.findViewById(R.id.consume_product);
                text_visit_date = (TextView) itemView.findViewById(R.id.text_visit_date);
                qty_sold_txt = (TextView) itemView.findViewById(R.id.qty_sold_txt);
                total_amount_txt = (TextView) itemView.findViewById(R.id.total_amount_txt);
            }
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void
    validate_spin_ui_data(final Button btn_invoice_type_saleable, final Button btn_invoice_type_sample, final Button btn_invoice_type_gwp, final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin,
                          final Spinner dialog_franchise_spin, final Spinner dialog_product_spin,
                          final TextView stock_text_value, final LinearLayout rl_actual_qty, final TextView actual_qty_dialog,
                          final TextView txt_current_invoice_type) {
        db.open();
        brandList = db.getproductdata_dialog("BrandName", "BrandId", false, "", visit_date, CounterId, from);
        subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", false, "", visit_date, CounterId, from);
        referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", false, "", visit_date, CounterId, from);
        productList = db.getbrand_wise_sku_fromproduct(null, null, visit_date, CounterId, from);
        ///for invoice type
        setBrandSpinnerData(brandList, dialog_brand_spin);
        setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);
        setReferenceSpinnerData(referenceList, dialog_franchise_spin);
        setProductSpinnerData(productList, dialog_product_spin);

        btn_invoice_type_saleable.setOnClickListener(view -> {
            flag_filter_by_edt = false;
            dialog_invoiceType = "Saleable";
            brandList = db.getproductdata_dialog("BrandName", "BrandId", false, "", visit_date, CounterId, from);
            subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", false, "", visit_date, CounterId, from);
            referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", false, "", visit_date, CounterId, from);
            productList = db.getbrand_wise_sku_fromproduct(null, null, visit_date, CounterId, from);
            setBrandSpinnerData(brandList, dialog_brand_spin);
            setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);
            setReferenceSpinnerData(referenceList, dialog_franchise_spin);
            setProductSpinnerData(productList, dialog_product_spin);
            db.open();
            dialog_product_list = db.getproduct_masterlist("T_StockSummary", visit_date, CounterId, from);
            btn_invoice_type_saleable.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            btn_invoice_type_saleable.setTextColor(getResources().getColor(R.color.white));
            btn_invoice_type_sample.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            btn_invoice_type_sample.setTextColor(getResources().getColor(R.color.grayfor_login));
            btn_invoice_type_gwp.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            btn_invoice_type_gwp.setTextColor(getResources().getColor(R.color.grayfor_login));
        });

        btn_invoice_type_sample.setOnClickListener(view -> {
            flag_filter_by_edt = false;
            if (!dialog_invoiceType.equalsIgnoreCase("Sample")) {
                rl_actual_qty.setVisibility(View.GONE);
            }
            dialog_invoiceType = "Sample";
            db.open();
            brandList = db.getproductdata_dialog("BrandName", "BrandId", true, "SampleBalance", visit_date, CounterId, from);
            subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", true, "SampleBalance", visit_date, CounterId, from);
            referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", true, "SampleBalance", visit_date, CounterId, from);
            productList = db.getbrand_wise_sku_fromproduct(null, "SampleBalance", visit_date, CounterId, from);
            setBrandSpinnerData(brandList, dialog_brand_spin);
            setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);
            setReferenceSpinnerData(referenceList, dialog_franchise_spin);
            setProductSpinnerData(productList, dialog_product_spin);
            btn_invoice_type_sample.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            btn_invoice_type_sample.setTextColor(getResources().getColor(R.color.white));
            btn_invoice_type_saleable.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            btn_invoice_type_saleable.setTextColor(getResources().getColor(R.color.grayfor_login));
            btn_invoice_type_gwp.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            btn_invoice_type_gwp.setTextColor(getResources().getColor(R.color.grayfor_login));
            db.open();
            dialog_product_list = db.getproduct_masterlist(dialog_invoiceType, visit_date, CounterId, from);

        });

        btn_invoice_type_gwp.setOnClickListener(view -> {
            flag_filter_by_edt = false;
            if (!dialog_invoiceType.equalsIgnoreCase("GWP")) {
                rl_actual_qty.setVisibility(View.GONE);
            }
            dialog_invoiceType = "GWP";
            db.open();
            brandList = db.getproductdata_dialog("BrandName", "BrandId", true, "GwpBalance", visit_date, CounterId, from);
            subbrandList = db.getproductdata_dialog("SubBrandName", "SubBrandId", true, "GwpBalance", visit_date, CounterId, from);
            referenceList = db.getproductdata_dialog("ReferenceName", "ReferenceId", true, "GwpBalance", visit_date, CounterId, from);
            productList = db.getbrand_wise_sku_fromproduct(null, "GwpBalance", visit_date, CounterId, from);
            setBrandSpinnerData(brandList, dialog_brand_spin);
            setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);
            setReferenceSpinnerData(referenceList, dialog_franchise_spin);
            setProductSpinnerData(productList, dialog_product_spin);
            btn_invoice_type_gwp.setBackground(getResources().getDrawable(R.drawable.rouded_corner));
            btn_invoice_type_gwp.setTextColor(getResources().getColor(R.color.white));
            btn_invoice_type_saleable.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            btn_invoice_type_saleable.setTextColor(getResources().getColor(R.color.grayfor_login));
            btn_invoice_type_sample.setBackground(getResources().getDrawable(R.drawable.round_btn_color_primary));
            btn_invoice_type_sample.setTextColor(getResources().getColor(R.color.grayfor_login));
            db.open();
            dialog_product_list = db.getproduct_masterlist(dialog_invoiceType, visit_date, CounterId, from);
        });

        dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    try {
                        flag_for_filter = true;
                        flag_filter_by_edt = false;
                        dialog_brand_Id = adapterView.getSelectedItem().toString();
                        if (dialog_invoiceType.equalsIgnoreCase("GWP") || dialog_invoiceType.equalsIgnoreCase("Sample")) {
                            setFilter(FILTER_FOR_BRAND, dialog_product_spin);
                            setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", dialog_invoiceType, visit_date, CounterId, true, from), dialog_sub_brand_spin);
                            setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", dialog_invoiceType, visit_date, CounterId, true, from), dialog_franchise_spin);
                        } else {
                            setFilter(FILTER_FOR_BRAND, dialog_product_spin);
                            setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId", "BrandName", null, visit_date, CounterId, true, from), dialog_sub_brand_spin);
                            setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId", "BrandName", null, visit_date, CounterId, true, from), dialog_franchise_spin);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    dialog_brand_Id = "";
                    if (!dialog_invoiceType.isEmpty() || dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) {
                        flag_for_filter = true;
                    } else {
                        setFilter(CLEAR_FILTER, dialog_product_spin);
                        flag_for_filter = false;
                    }
                }
            }


            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        dialog_sub_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    try {
                        flag_for_filter = true;
                        flag_filter_by_edt = false;
                        dialog_sub_brand_Id = adapterView.getSelectedItem().toString();
                        if (dialog_invoiceType.equalsIgnoreCase("GWP") || dialog_invoiceType.equalsIgnoreCase("Sample")) {
                            setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin);
                            setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", dialog_invoiceType, visit_date, CounterId, true, from), dialog_franchise_spin);
                        } else {
                            setFilter(FILTER_FOR_SUB_BRAND, dialog_product_spin);
                            setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_sub_brand_Id, "ReferenceName", "ReferenceId", "SubBrandName", null, visit_date, CounterId, true, from), dialog_franchise_spin);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    dialog_sub_brand_Id = "";
                    if (!dialog_invoiceType.isEmpty() || dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) {
                        flag_for_filter = true;
                    } else {
                        setFilter(CLEAR_FILTER, dialog_product_spin);
                        flag_for_filter = false;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        dialog_franchise_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    try {
                        flag_for_filter = true;
                        flag_filter_by_edt = false;
                        dialog_reference_Id = adapterView.getSelectedItem().toString();
                        setFilter(FILTER_FOR_REFERENCE_NAME, dialog_product_spin);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    dialog_reference_Id = "";
                    if (!dialog_invoiceType.isEmpty() || dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 ||
                            dialog_franchise_spin.getSelectedItemPosition() != 0) {
                        flag_for_filter = true;
                    } else {
                        setFilter(CLEAR_FILTER, dialog_product_spin);
                        flag_for_filter = false;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        dialog_product_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    try {
                        if (flag_filter_by_edt) {
                            product_name = dialog_product_using_searchlist.get(position - 1).getProductName();
                            product_Id = dialog_product_using_searchlist.get(position - 1).getProductId().toString();
                            product_mrp = dialog_product_using_searchlist.get(position - 1).getMrp().toString();
                            product_scan_code = dialog_product_using_searchlist.get(position - 1).getEanCode();
                            productType = dialog_product_using_searchlist.get(position - 1).getProductType();
                            if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                                product_mrp = "0";
                            }

                            stock_text_value.setText("0");
                            if (!product_Id.equals("0")) {
                                rl_actual_qty.setVisibility(View.VISIBLE);
                                if (dialog_invoiceType.equalsIgnoreCase("Saleable")) {
                                    txt_current_invoice_type.setText(R.string.current_stock_saleable);
                                    db.open();
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock());
                                } else if (dialog_invoiceType.equalsIgnoreCase("Sample")) {
                                    txt_current_invoice_type.setText(R.string.current_stock_sample);
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock());
                                } else if (dialog_invoiceType.equalsIgnoreCase("GWP")) {
                                    txt_current_invoice_type.setText(R.string.current_stock_gwp);
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock());
                                }
                            }
                            minteger = 0;
                        } else if (flag_for_filter && dialog_brand_spin.getSelectedItemPosition() != 0 || dialog_sub_brand_spin.getSelectedItemPosition() != 0 || dialog_franchise_spin.getSelectedItemPosition() != 0) {
                            product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getProductName();
                            product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getProductId().toString();
                            product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getMrp().toString();
                            product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getEanCode();
                            productType = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(position - 1).getProductType();
                            if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                                product_mrp = "0";
                            }
                            if (!product_Id.equals("0")) {
                                rl_actual_qty.setVisibility(View.VISIBLE);
                                if (dialog_invoiceType.equalsIgnoreCase("Saleable")) {
                                    txt_current_invoice_type.setText(getString(R.string.current_stock_saleable));
                                    db.open();
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock());
                                } else if (dialog_invoiceType.equalsIgnoreCase("Sample")) {
                                    txt_current_invoice_type.setText(getString(R.string.current_stock_sample));
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock());
                                } else if (dialog_invoiceType.equalsIgnoreCase("GWP")) {
                                    txt_current_invoice_type.setText(getString(R.string.current_stock_gwp));
                                    db.open();
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock());
                                }

                            }
                            stock_text_value.setText("0");
                            minteger = 0;
                        } else {
                            product_name = productList.get(position - 1).getProductName();
                            product_Id = productList.get(position - 1).getProductId().toString();
                            product_mrp = productList.get(position - 1).getMrp().toString();
                            product_scan_code = productList.get(position - 1).getEanCode();
                            productType = productList.get(position - 1).getProductType();
                            if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                                product_mrp = "0";
                            }
                            if (!product_Id.equals("0")) {
                                rl_actual_qty.setVisibility(View.VISIBLE);
                                db.open();
                                if (dialog_invoiceType.equalsIgnoreCase("Saleable")) {
                                    txt_current_invoice_type.setText(getString(R.string.current_stock_saleable));
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SaleableBalance", visit_date, CounterId, from).getStock());
                                } else if (dialog_invoiceType.equalsIgnoreCase("Sample")) {
                                    txt_current_invoice_type.setText(getString(R.string.current_stock_sample));
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "SampleBalance", visit_date, CounterId, from).getStock());
                                } else if (dialog_invoiceType.equalsIgnoreCase("GWP")) {
                                    txt_current_invoice_type.setText(getString(R.string.current_stock_gwp));
                                    actual_qty_dialog.setText("" + db.getActualSaleableStock(product_Id, "GwpBalance", visit_date, CounterId, from).getStock());
                                }
                            }
                            stock_text_value.setText("0");
                            minteger = 0;
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    stock_text_value.setText("0");
                    product_scan_code = "";
                    product_mrp = "0";
                    product_name = "";
                    product_Id = "0";
                    productType = "";
                    discount = 0.0;
                    minteger = 0;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void setBrandSpinnerData(ArrayList<ProductMaster> brandList, Spinner dialog_brand_spin) {
        try {
            dialog_brand_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
            dialog_brand_adapter.add("- Select Brand -");
            for (int i = 0; i < brandList.size(); i++) {
                dialog_brand_adapter.add(brandList.get(i).getBrandName());
            }
            dialog_brand_spin.setAdapter(dialog_brand_adapter);
            dialog_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

    }

    private void setSubBrandSpinnerData(ArrayList<ProductMaster> axeList, Spinner dialog_sub_brand_spin) {
        try {
            dialog_sub_brand_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sub_brand_adapter.add("- Select Sub Brand -");
            for (int i = 0; i < axeList.size(); i++) {
                dialog_sub_brand_adapter.add(axeList.get(i).getBrandName());
            }
            dialog_sub_brand_spin.setAdapter(dialog_sub_brand_adapter);
            dialog_sub_brand_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } catch (Exception ignored) {
        }
    }

    private void setReferenceSpinnerData(ArrayList<ProductMaster> referenceList, Spinner dialog_franchise_spin) {
        dialog_frenchise_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        dialog_frenchise_adapter.add("- Select Franchise -");
        for (int i = 0; i < referenceList.size(); i++) {
            dialog_frenchise_adapter.add(referenceList.get(i).getBrandName());
        }

        dialog_franchise_spin.setAdapter(dialog_frenchise_adapter);
        dialog_frenchise_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
    }

    private void setProductSpinnerData(ArrayList<ProductMaster> productList, Spinner dialog_product_spin) {
        try {
            dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");
            if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                for (int i = 0; i < productList.size(); i++) {
                    dialog_sku_adapter.add(productList.get(i).getProductName() + " - Type-" + dialog_invoiceType);
                }
            } else {
                for (int i = 0; i < productList.size(); i++) {
                    dialog_sku_adapter.add(productList.get(i).getProductName() + " - (MRP-" + productList.get(i).getMrp().toString() + ")");
                }
            }

            dialog_product_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        } catch (Exception ignored) {
        }
    }

    public void setFilter(int filterType, Spinner dialog_spin) {
        try {
            if (filterType == FILTER_FOR_BRAND) {
                dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
                dialog_sku_adapter.add("- Select Product -");
                if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                    for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) {
                        dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + "- Type-" + dialog_invoiceType);
                    }
                } else {
                    for (int i = 0; i < filterListForBrand(dialog_product_list, dialog_brand_Id).size(); i++) {
                        dialog_sku_adapter.add(filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getProductName() + " - (MRP-" + filterListForBrand(dialog_product_list, dialog_brand_Id).get(i).getMrp().toString() + ")");
                    }
                }

                dialog_spin.setAdapter(dialog_sku_adapter);
                dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
            } else if (filterType == FILTER_FOR_SUB_BRAND) {
                dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
                dialog_sku_adapter.add("- Select Product -");
                if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                    for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) {
                        dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - Type-" + dialog_invoiceType);
                    }
                } else {
                    for (int i = 0; i < filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).size(); i++) {
                        dialog_sku_adapter.add(filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getProductName() + " - (MRP-" +
                                filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id).get(i).getMrp().toString() + ")");
                    }
                }
                dialog_spin.setAdapter(dialog_sku_adapter);
                dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
            } else if (filterType == FILTER_FOR_REFERENCE_NAME) {
                dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
                dialog_sku_adapter.add("- Select Product -");
                if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                    for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).size(); i++) {
                        dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(i).getProductName() + " - Type-" + dialog_invoiceType);
                    }
                } else {
                    for (int i = 0; i < filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).size(); i++) {
                        dialog_sku_adapter.add(filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(i).getProductName() + " - (MRP-" + filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id, dialog_invoiceType).get(i).getMrp().toString() + ")");
                    }
                }
                dialog_spin.setAdapter(dialog_sku_adapter);
                dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
            } else {
                dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
                dialog_sku_adapter.add("- Select Product -");
                if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                    for (int i = 0; i < dialog_product_list.size(); i++) {
                        dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - Type-" + dialog_invoiceType);
                    }
                } else {
                    for (int i = 0; i < dialog_product_list.size(); i++) {
                        dialog_sku_adapter.add(dialog_product_list.get(i).getProductName() + " - (MRP-" + dialog_product_list.get(i).getMrp().toString() + ")");
                    }
                }
                dialog_spin.setAdapter(dialog_sku_adapter);
                dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
            }
            dialog_spin.invalidate();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    final int CLEAR_FILTER = 0;
    final int FILTER_FOR_BRAND = 1;
    final int FILTER_FOR_SUB_BRAND = 2;
    final int FILTER_FOR_REFERENCE_NAME = 3;

    public ArrayList<ProductMaster> filterListForBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getBrandName().equalsIgnoreCase(text)) {
                filterList.add(object);
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForSubBrand(List<ProductMaster> originalList, String sub_brand_name_id, String brand_Id) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (sub_brand_name_id.isEmpty() && object.getBrandName().equalsIgnoreCase(brand_Id)) {
                filterList.add(object);
            } else if (object.getSubBrandName().equalsIgnoreCase(sub_brand_name_id) && (brand_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brand_Id))) {
                filterList.add(object);
            }
        }

        return filterList;
    }


    public ArrayList<ProductMaster> filterListForReferencename(List<ProductMaster> originalList, String franchise_Id, String brandName_Id, String sub_brand_name_Id, String invoiceTyp_str) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (!invoiceTyp_str.isEmpty() && object.getBrandName().equalsIgnoreCase(invoiceTyp_str) && sub_brand_name_Id.isEmpty() && franchise_Id.isEmpty() && brandName_Id.isEmpty()) {
                filterList.add(object);
            } else if (sub_brand_name_Id.isEmpty() && object.getBrandName().equalsIgnoreCase(brandName_Id)) {
                filterList.add(object);
            } else if (franchise_Id.isEmpty() && object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id)) {
                filterList.add(object);
            } else if (object.getReferenceName().equalsIgnoreCase(franchise_Id) && (brandName_Id.isEmpty() || object.getBrandName().equalsIgnoreCase(brandName_Id)) && (sub_brand_name_Id.isEmpty() || object.getSubBrandName().equalsIgnoreCase(sub_brand_name_Id))) {
                filterList.add(object);
            }
        }

        return filterList;
    }


    public void setSearchFilter(ArrayList<ProductMaster> originalList, String text, Spinner dialog_product_spin) {
        try {
            flag_filter_by_edt = true;
            dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
            dialog_sku_adapter.add("- Select Product -");
            dialog_product_using_searchlist = new ArrayList<>();
            dialog_product_using_searchlist = filterListForProduct_edt(originalList, text);
            if (filterListForProduct_edt(originalList, text).isEmpty()) {
                dialog_product_using_searchlist = originalList;
            }
            if (dialog_invoiceType.equalsIgnoreCase("Sample") || dialog_invoiceType.equalsIgnoreCase("GWP")) {
                for (int i = 0; i < dialog_product_using_searchlist.size(); i++) {
                    dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - Type-" + dialog_invoiceType);
                }
            } else {
                for (int i = 0; i < dialog_product_using_searchlist.size(); i++) {
                    dialog_sku_adapter.add(dialog_product_using_searchlist.get(i).getProductName() + " - (MRP-" + dialog_product_using_searchlist.get(i).getMrp().toString() + ")");
                }

            }
            dialog_product_spin.setAdapter(dialog_sku_adapter);
            dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

            dialog_product_spin.invalidate();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public ArrayList<ProductMaster> filterListForProduct_edt(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getProductName().toLowerCase().contains(text.toLowerCase())) {
                filterList.add(object);
            }
        }

        return filterList;
    }

    public void getpreviousHistory_from_mobile_no(final Context context, final ProgressDialog loading, String jsondata) {
        try {
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(Objects.requireNonNull(MediaType.parse("application/json")), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<String> call = api.getDownloadAll(jsonData);
            call.enqueue(new retrofit2.Callback<String>() {
                @Override
                public void onResponse(@NonNull retrofit2.Call<String> call, @NonNull retrofit2.Response<String> response) {
                    String responseBody = response.body();
                    String data_for = null;
                    loading.dismiss();
                    if (responseBody != null && response.isSuccessful()) {
                        txt_history.setEnabled(true);
                        data_for = response.body();
                        assert data_for != null;
                        if (data_for.isEmpty()) {
                            txt_history.setEnabled(true);
                        } else {
                            if (!data_for.contains("No Data")) {
                                MasterBAProfileGetterSetter masterPromoOfferObject = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class);
                                if (masterPromoOfferObject != null) {
                                    List<ConsumerSalesHistory> previusHistoryList = masterPromoOfferObject.getConsumerSalesHistory();
                                    if (!previusHistoryList.isEmpty()) {
                                        show_consumer_previous_histry(context, previusHistoryList);
                                    }
                                } else {
                                    loading.dismiss();
                                }
                            } else {
                                loading.dismiss();
                                Toast.makeText(context, "No Previous History", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else {
                        loading.dismiss();
                        AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated");
                    }
                }

                @Override
                public void onFailure(@NonNull retrofit2.Call<String> call, @NonNull Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlertlogin((Activity) context, "Unable To Connect Server. History Data Not Updated");
                }
            });
        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }


    private void getstatusof_termcondition() {
        edt_mobile_no.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().isEmpty() && editable.toString().length() == 10) {
                    if (CommonFunctions.checkNetIsAvailable(context) && checkindex()) {
                        try {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("Downloadtype", "Consumer_TermsConditionAccept");
                            jsonObject1.put("Username", username);
                            jsonObject1.put("Param2", CounterId);
                            jsonObject1.put("Param1", edt_mobile_no.getText().toString());
                            getstatusoftermscondition_status(context, jsonObject1.toString());
                        } catch (JSONException e) {
                            e.fillInStackTrace();
                        }
                    } else {
                        response_term_condition = "0";
                    }
                } else {
                    rl_term_condition.setTextColor(getResources().getColor(R.color.blue));
                    rl_term_condition.setEnabled(true);
                }
            }
        });

    }

    public void getstatusoftermscondition_status(final Context context, String jsondata) {
        try {
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(Objects.requireNonNull(MediaType.parse("application/json")), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<String> call = api.getDownloadAll(jsonData);
            call.enqueue(new retrofit2.Callback<String>() {
                @Override
                public void onResponse(@NonNull retrofit2.Call<String> call, @NonNull retrofit2.Response<String> response) {
                    String responseBody = response.body();
                    String data_for = null;
                    if (responseBody != null && response.isSuccessful()) {
                        data_for = response.body();
                        assert data_for != null;
                        if (!data_for.isEmpty()) {
                            if (!data_for.contains("No Data")) {
                                MasterBAProfileGetterSetter reportbaAvailabilityGetterSetter = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class);
                                if (reportbaAvailabilityGetterSetter != null) {
                                    List<ConsumerTermsConditionAccept> dataresponce = reportbaAvailabilityGetterSetter.getConsumerTermsConditionAccept();
                                    if (dataresponce.get(0).getTermsConditionAccept()) {
                                        response_term_condition = "1";
                                        rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
                                        rl_term_condition.setEnabled(false);

                                    } else {
                                        response_term_condition = "0";
                                    }
                                } else {
                                    response_term_condition = "0";
                                }
                            } else {
                                response_term_condition = "0";
                            }
                        }
                    } else {
                        response_term_condition = "0";
                    }
                }

                @Override
                public void onFailure(@NonNull retrofit2.Call<String> call, @NonNull Throwable t) {
                    response_term_condition = "0";
                }
            });
        } catch (Exception e) {
            e.fillInStackTrace();
            response_term_condition = "0";
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        if (!response_term_condition.isEmpty() && !response_term_condition.equals("0")) {
            rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            rl_term_condition.setEnabled(false);
        }

        current_total_stock.setText("Total : " + calculate_total_consume(selected_list));
    }

    @SuppressLint("SetTextI18n")
    private void show_promotion_dialog(final Context context, final MasterPromotion promoList,
                                       final boolean flag_free_product, final String getentity_type) {
        final MultiPurposeDialog dialog = new MultiPurposeDialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.promotion_dialog_free_product);
        dialog.setCancelable(false);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(dialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialog.getWindow().setAttributes(lp);
        dialog.setCancelable(false);
        RecyclerView recycl_promotion = (RecyclerView) dialog.findViewById(R.id.recycl_promotion);
        final ImageView cancet_btn = (ImageView) dialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) dialog.findViewById(R.id.btn_add);
        TextView promo_name = (TextView) dialog.findViewById(R.id.promo_name);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle);
        if (flag_free_product) tvTitle.setText("Free Products");
        else tvTitle.setText("Additional Products");
        promo_name.setText("Promotion : " + promoList.getPromotionName());
        db.open();
        final ArrayList<MasterPromotionSetProductGroup> prodictlist_promo = db.getPromotiongetProduct(promoList.getPromoId(), getentity_type, visit_date, CounterId, from);
        recycl_promotion.setAdapter(new PromotionSkuWiseAdapter(context, dialog, prodictlist_promo, promoList, getentity_type));
        recycl_promotion.setLayoutManager(new LinearLayoutManager(context));
        cancet_btn.setOnClickListener(view -> dialog.dismiss());

        btn_add.setOnClickListener(view -> {
            dialog.dismiss();
            try {
                if (!prodictlist_promo.isEmpty()) {
                    for (int k = 0; k < prodictlist_promo.size(); k++) {
                        if (prodictlist_promo.get(k).getSelected_item_qty() > 0) {
                            selected_promoList.add(prodictlist_promo.get(k));
                        }
                    }
                    /////////////add product with setentityType--------------
                    if (getentity_type.equalsIgnoreCase("OffProduct")) {
                        for (int k = 0; k < selected_promoList.size(); k++) {
                            InvoiceGetterSetter invoiceGetterSetter;
                            invoiceGetterSetter = returnobject();
                            invoiceGetterSetter.setQuantity("1");
                            invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_promoList.get(k).getEan_code());
                            invoiceGetterSetter.setStr_invoiceType("");
                            invoiceGetterSetter.setPromo_flag(true);
                            invoiceGetterSetter.setPromo_type("OffProduct");
                            invoiceGetterSetter.setPromotion_name(promoList.getPromotionName());
                            invoiceGetterSetter.setPromotion_Id(promoList.getPromoId().toString());
                            int amount = Integer.parseInt(selected_promoList.get(k).getMrp_product());
                            int tip_per = Integer.parseInt(promoList.getPromotionGetEntityValue());
                            int tip_cal = (amount * tip_per) / 100;

                            invoiceGetterSetter.setSkuType(String.valueOf(tip_cal));
                            invoiceGetterSetter.setDiscount(0.0);
                            invoiceGetterSetter.setProduct_rate(selected_promoList.get(k).getMrp_product());
                            invoiceGetterSetter.setProduct(selected_promoList.get(k).getProductname());
                            invoiceGetterSetter.setProduct_Id(selected_promoList.get(k).getProductId().toString());
                            added_prmo_products.add(invoiceGetterSetter);
                        }
                        selected_promoList = new ArrayList<>();
                    } else if (getentity_type.equalsIgnoreCase("Gift")) {
                        ///////////for gift promo
                        if (!selected_promoList.isEmpty()) {
                            for (int k = 0; k < selected_promoList.size(); k++) {
                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();

                                invoiceGetterSetter.setQuantity(String.valueOf(selected_promoList.get(k).getSelected_item_qty()));
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_promoList.get(k).getEan_code());
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("Gift");
                                invoiceGetterSetter.setPromotion_name(promoList.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(promoList.getPromoId().toString());
                                invoiceGetterSetter.setProduct(selected_promoList.get(k).getProductname() + " - QTY - " + selected_promoList.get(k).getSelected_item_qty());
                                invoiceGetterSetter.setProduct_Id(selected_promoList.get(k).getProductId().toString());
                                added_prmo_products.add(invoiceGetterSetter);
                            }

                            selected_promoList = new ArrayList<>();
                        }

                    } else {
                        ///applyed promo for Product
                        if (!selected_promoList.isEmpty()) {
                            for (int k = 0; k < selected_promoList.size(); k++) {
                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();
                                invoiceGetterSetter.setQuantity(String.valueOf(selected_promoList.get(k).getSelected_item_qty()));
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_promoList.get(k).getEan_code());
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("Product");
                                invoiceGetterSetter.setPromotion_name(promoList.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(promoList.getPromoId().toString());
                                invoiceGetterSetter.setProduct(selected_promoList.get(k).getProductname() + " - QTY - " + selected_promoList.get(k).getSelected_item_qty());
                                invoiceGetterSetter.setProduct_Id(selected_promoList.get(k).getProductId().toString());
                                added_prmo_products.add(invoiceGetterSetter);
                            }

                            selected_promoList = new ArrayList<>();
                        }
                    }
                }
            } catch (NumberFormatException e) {
                e.fillInStackTrace();
            }
        });

        dialog.show();
    }

    @SuppressLint("SetTextI18n")
    private void show_promotion_skuwise_dialog(final Context context, ArrayList<InvoiceGetterSetter> selected_productList,
                                               final ArrayList<MasterPromotion> promoList, final boolean flag_worth) {
        final MultiPurposeDialog purposeDialog = new MultiPurposeDialog(context);
        purposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        purposeDialog.setContentView(R.layout.promotion_dialog);
        purposeDialog.setCancelable(false);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(purposeDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        purposeDialog.getWindow().setAttributes(lp);
        purposeDialog.show();

        RecyclerView recycl_promotion = (RecyclerView) purposeDialog.findViewById(R.id.recycl_promotion);
        final ImageView cancet_btn = (ImageView) purposeDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) purposeDialog.findViewById(R.id.btn_add);
        final TextView header_txt = (TextView) purposeDialog.findViewById(R.id.header_txt);
        final LinearLayout rl_changes_color = (LinearLayout) purposeDialog.findViewById(R.id.rl_changes_color);

        if (flag_worth) {
            header_txt.setText("Applicable Worth Promotions");
            rl_changes_color.setBackgroundColor(getResources().getColor(R.color.dashboard_less_ach));
        } else {
            header_txt.setText("Applicable Product Promotions");
            rl_changes_color.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        }

        ////show product selected
        recycl_promotion.setAdapter(new PromotionSpinnerAdapter(context, purposeDialog, promoList, flag_worth));
        recycl_promotion.setLayoutManager(new LinearLayoutManager(context));

        cancet_btn.setOnClickListener(view -> {
            purposeDialog.dismiss();
            added_prmo_products.clear();
            if (purposeDialog != null && purposeDialog.isShowing()) {
                purposeDialog.dismiss();
            }
        });

        btn_add.setOnClickListener(view -> {
            try {
                purposeDialog.dismiss();
                if (purposeDialog != null && purposeDialog.isShowing()) {
                    purposeDialog.dismiss();
                }

                if (flag_worth) {
                    if (!added_prmo_products.isEmpty()) {
                        selected_list.addAll(added_prmo_products);
                    }
                    drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                            putExtra(CommonString.TAG_OBJECT, selected_list)
                            .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                            .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                            putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                            .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                    added_prmo_products = new ArrayList<>();
                } else {
                    ////change for worrh promotin,,,,,,,,
                    try {
                        AlertandMessages.showToastMsg(context, "Checking Promotion");
                        db.open();
                        db.insert_temp_sales_data(visit_date, CounterId, selected_list);
                        new LoadTask().execute(false);
                    } catch (Exception e) {
                        new LoadTask().execute(false);
                    }
                }
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        });
        purposeDialog.show();
    }


    private class PromotionSkuWiseAdapter extends RecyclerView.Adapter<PromotionSkuWiseAdapter.ViewHolder> {
        ArrayList<MasterPromotionSetProductGroup> promo_product_list;
        Context context;
        MultiPurposeDialog dialog;
        private final LayoutInflater inflator;
        MasterPromotion promo_object;
        String getentity_type;
        int total_getentity_value = 0, select_product_count = 0, getentity_for_off_product = 1;

        public PromotionSkuWiseAdapter(Context context, final MultiPurposeDialog dialog, ArrayList<MasterPromotionSetProductGroup> promo_product_list,
                                       MasterPromotion promo_object, String getentity_type) {
            this.dialog = dialog;
            this.context = context;
            this.promo_object = promo_object;
            this.promo_product_list = promo_product_list;
            inflator = LayoutInflater.from(context);
            this.getentity_type = getentity_type;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_promotion, parent, false);
            return new ViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int pos) {
            ////show product selected
            final MasterPromotionSetProductGroup current = promo_product_list.get(pos);
            total_getentity_value = Integer.parseInt(promo_object.getPromotionGetEntityValue());

            if (CommonFunctions.isTablet(context)) {
                viewHolder.tvstorename.setText("Product : " + current.getProductname().trim() + " - Stock : " + current.getSallable_stock_qty());
                viewHolder.tvstorename.setId(pos);
            } else {
                viewHolder.tvstorename.setText("Product : " + current.getProductname().trim() + "\n" + "Stock : " + current.getSallable_stock_qty());
                viewHolder.tvstorename.setId(pos);
            }

            viewHolder.stock_img_plus.setOnClickListener(v -> {
                try {
                    int minteger = current.getSelected_item_qty();
                    select_product_count = select_product_count + 1;
                    minteger = minteger + 1;
                    if (getentity_type.equalsIgnoreCase("OffAdditionalProduct")) {

                    } else if (getentity_type.equalsIgnoreCase("OffProduct")) {
                        if (select_product_count > getentity_for_off_product) {
                            minteger = minteger - 1;
                            select_product_count = select_product_count - 1;
                            AlertandMessages.showToastMsg(context, "You can not add more than allowed free product");
                        } else {
                            viewHolder.stock_text_value.setText("" + minteger);
                            current.setSelected_item_qty(minteger);
                        }
                    } else {
                        if (select_product_count > total_getentity_value) {
                            minteger = minteger - 1;
                            select_product_count = select_product_count - 1;
                            AlertandMessages.showToastMsg(context, "You can not add more than allowed free product");
                        } else {
                            viewHolder.stock_text_value.setText("" + minteger);
                            current.setSelected_item_qty(minteger);
                        }
                    }
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            });

            viewHolder.stock_img_minus.setOnClickListener(v -> {
                try {
                    int minteger = current.getSelected_item_qty();
                    if (minteger == 0) {
                        AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
                    } else {
                        minteger = minteger - 1;
                        select_product_count = select_product_count - 1;
                        viewHolder.stock_text_value.setText("" + minteger);
                        current.setSelected_item_qty(minteger);
                    }
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            });

        }

        @Override
        public int getItemCount() {
            return promo_product_list.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            Button stock_img_minus, stock_img_plus;
            TextView stock_text_value;
            CardView card_view;
            TextView tvstorename;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                card_view = (CardView) itemView.findViewById(R.id.card_view);
                tvstorename = (TextView) itemView.findViewById(R.id.tvstorename);
                stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus);
                stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus);
                stock_text_value = (TextView) itemView.findViewById(R.id.stock_text_value);

            }
        }
    }

    private class PromotionSpinnerAdapter extends RecyclerView.Adapter<PromotionSpinnerAdapter.ViewHolder> {
        ArrayList<MasterPromotion> promotionList;
        Context context;
        MultiPurposeDialog dialog;
        private final LayoutInflater inflator;
        boolean flag_worth;

        public PromotionSpinnerAdapter(Context context, final MultiPurposeDialog dialog, ArrayList<MasterPromotion> list, boolean flag_worth) {
            this.dialog = dialog;
            this.context = context;
            this.promotionList = list;
            inflator = LayoutInflater.from(context);
            this.flag_worth = flag_worth;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_promotion_spin_list, parent, false);
            return new ViewHolder(view);
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onBindViewHolder(@NonNull final ViewHolder viewHolder, @SuppressLint("RecyclerView") final int pos) {
            final MasterPromotion current = promotionList.get(pos);
            StringBuilder aplyied_products = new StringBuilder();
            db.open();
            ArrayList<InvoiceGetterSetter> qualified_products = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId());
            if (!qualified_products.isEmpty()) {
                for (int k = 0; k < qualified_products.size(); k++) {
                    if (k == 0) {
                        aplyied_products = new StringBuilder(qualified_products.get(k).getProduct());
                    } else {
                        aplyied_products.append(" , ").append(qualified_products.get(k).getProduct());
                    }
                }
            }

            viewHolder.category.setText(current.getPromotionName().trim());
            viewHolder.category.setId(pos);

            if (!qualified_products.isEmpty() && !aplyied_products.toString().isEmpty()) {
                viewHolder.aplyed_products.setVisibility(View.VISIBLE);
                viewHolder.aplyed_products.setText(aplyied_products.toString());
                viewHolder.aplyed_products.setId(pos);
            } else {
                viewHolder.aplyed_products.setVisibility(View.GONE);
                viewHolder.aplyed_products.setId(pos);
            }

            viewHolder.check_promo.setOnClickListener(view -> {
                try {
                    if (viewHolder.check_promo.isChecked()) {
                        boolean valid_flag = true;
                        assert promotionList != null;
                        for (int l = 0; l < promotionList.size(); l++) {
                            if ((promotionList.get(l).getPromoId().intValue() != current.getPromoId().intValue()) && promotionList.get(l).isPromotionactive()) {
                                db.open();
                                if (db.checked_applyied_promo(promotionList.get(l).getPromoId().toString(), username, visit_date, CounterId,
                                        current.getPromoId().toString()) > 0) {
                                    AlertandMessages.showToastMsg(context, "Promotion already applied on this product");
                                    current.setPromotionactive(false);
                                    viewHolder.check_promo.setChecked(false);
                                    viewHolder.check_promo.setId(pos);
                                    notifyDataSetChanged();
                                    valid_flag = false;
                                    break;
                                }
                            }
                        }

                        if (valid_flag) {
                            current.setPromotionactive(true);
                            viewHolder.check_promo.setChecked(true);
                            viewHolder.check_promo.setId(pos);
                            //New Promotion Addede
                            if (current.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) {
                                applyeid_products = new ArrayList<>();
                                db.open();
                                ArrayList<InvoiceGetterSetter> OffSameProduct = db.getqualifiedOffSameProduct(CounterId, username, visit_date, current.getPromoId());
                                int total_off = 0, total_qty = 0, calculatetedper_values = 0, total_maxvalue = 0, previous_qty = 0;
                                int addOff = 0;
                                if (!OffSameProduct.isEmpty()) {
                                    for (int l = 0; l < OffSameProduct.size(); l++) {
                                        int rate = Integer.parseInt(OffSameProduct.get(l).getProduct_rate());
                                        int qty = Integer.parseInt(OffSameProduct.get(l).getQuantity());
                                        total_qty = total_qty + qty;
                                        total_off = total_off + rate * qty;
                                        //Updated logic for new promo------
                                        InvoiceGetterSetter invoiceGetterSetter;
                                        invoiceGetterSetter = returnobject();
                                        invoiceGetterSetter.setPromo_flag(true);
                                        invoiceGetterSetter.setPromo_type("OffSameProduct");
                                        invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                        invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                        invoiceGetterSetter.setProduct(OffSameProduct.get(l).getProduct());
                                        invoiceGetterSetter.setQuantity(OffSameProduct.get(l).getQuantity());
                                        invoiceGetterSetter.setProduct_Id(OffSameProduct.get(l).getProduct_Id());
                                        invoiceGetterSetter.setProduct_rate(OffSameProduct.get(l).getProduct_rate());
                                        ///calculate percentage
                                        double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0;
                                        try {
                                            total_valueper_productwise = rate * qty;
                                            getentityValue = Double.parseDouble(current.getPromotionGetEntityValue());
                                            if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                                if (total_qty > Integer.parseInt(current.getMaxValue()) && previous_qty <= Integer.parseInt(current.getMaxValue())) {
                                                    if (previous_qty == 0) {
                                                        addOff = rate * Integer.parseInt(current.getMaxValue());
                                                        calculate_per_productwise = (addOff * getentityValue) / 100;
                                                    } else if (previous_qty <= Integer.parseInt(current.getMaxValue())) {
                                                        addOff = (Integer.parseInt(current.getMaxValue()) - previous_qty) * rate;
                                                        calculate_per_productwise = (addOff * getentityValue) / 100;
                                                    } else {
                                                        calculate_per_productwise = 0;
                                                    }
                                                    previous_qty = total_qty;
                                                } else {
                                                    previous_qty = total_qty;
                                                    if (total_qty <= Integer.parseInt(current.getMaxValue())) {
                                                        calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100;
                                                    }
                                                }
                                            } else {
                                                calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100;
                                            }
                                        } catch (NumberFormatException e) {
                                            e.fillInStackTrace();
                                        }
                                        invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise));
                                        invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(OffSameProduct.get(l).getScan_ean_code_or_enterd_ean_code());
                                        applyeid_products.add(invoiceGetterSetter);
                                    }
                                    if (CommonFunctions.mod(total_qty, Integer.parseInt(current.getPromotionSetEntityValue())) == 0) {
                                        int totqty = 0;
                                        int prevqty = 0;
                                        int totoff = 0;
                                        int tip_per = Integer.parseInt(current.getPromotionGetEntityValue());
                                        if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                            if (total_qty > Integer.parseInt(current.getMaxValue())) {
                                                for (int l = 0; l < OffSameProduct.size(); l++) {
                                                    int rate = Integer.parseInt(OffSameProduct.get(l).getProduct_rate());
                                                    int qty = Integer.parseInt(OffSameProduct.get(l).getQuantity());
                                                    totqty = totqty + qty;
                                                    totoff = totoff + rate * qty;
                                                    if (totqty > Integer.parseInt(current.getMaxValue())) {
                                                        int totaldata = 0;
                                                        int remainqty = 0;
                                                        if (prevqty == 0) {
                                                            remainqty = Integer.parseInt(current.getMaxValue());
                                                        } else {
                                                            remainqty = Integer.parseInt(current.getMaxValue()) - prevqty;
                                                        }
                                                        totaldata = totoff - (rate * qty);
                                                        total_maxvalue = totaldata + rate * remainqty;
                                                        AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only");
                                                        break;
                                                    } else {
                                                        prevqty = prevqty + qty;
                                                    }
                                                }
                                                calculatetedper_values = (total_maxvalue * tip_per) / 100;
                                            } else {
                                                calculatetedper_values = (total_off * tip_per) / 100;
                                            }
                                        } else {
                                            calculatetedper_values = (total_off * tip_per) / 100;
                                        }
                                    } else {
                                        int tip_per = Integer.parseInt(current.getPromotionGetEntityValue());
                                        int totqty = 0;
                                        int prevqty = 0;
                                        int totoff = 0;
                                        if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                            if (total_qty > Integer.parseInt(current.getMaxValue())) {
                                                for (int l = 0; l < OffSameProduct.size(); l++) {
                                                    int rate = Integer.parseInt(OffSameProduct.get(l).getProduct_rate());
                                                    int qty = Integer.parseInt(OffSameProduct.get(l).getQuantity());
                                                    totqty = totqty + qty;
                                                    totoff = totoff + rate * qty;
                                                    if (totqty > Integer.parseInt(current.getMaxValue())) {
                                                        int totaldata = 0;
                                                        int remainqty = 0;
                                                        if (prevqty == 0) {
                                                            remainqty = Integer.parseInt(current.getMaxValue());
                                                        } else {
                                                            remainqty = Integer.parseInt(current.getMaxValue()) - prevqty;
                                                        }
                                                        totaldata = totoff - (rate * qty);
                                                        total_maxvalue = totaldata + rate * remainqty;
                                                        AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only");
                                                        break;
                                                    } else {
                                                        prevqty = prevqty + qty;
                                                    }
                                                }
                                                calculatetedper_values = (total_maxvalue * tip_per) / 100;
                                            } else {
                                                calculatetedper_values = (total_off * tip_per) / 100;
                                            }
                                        } else {
                                            calculatetedper_values = (total_off * tip_per) / 100;
                                        }
                                    }
                                }

                                MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup();
                                ob.setPromotion_name(current.getPromotionName());
                                ob.setPromotionId(current.getPromoId().toString());
                                ob.setPromotion_deducted_price(current.getPromotionGetEntityValue());
                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();

                                invoiceGetterSetter.setQuantity("0");
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code("");
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("OffSameProduct");
                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());

                                invoiceGetterSetter.setProduct(String.valueOf(calculatetedper_values));
                                invoiceGetterSetter.setProduct_Id("0");
                                //////added applyied products in list
                                invoiceGetterSetter.setApplyiedproductList(applyeid_products);
                                added_prmo_products.add(invoiceGetterSetter);
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("OffWorth")) {
                                db.open();
                                ArrayList<InvoiceGetterSetter> qualified_products1 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId());
                                int total_offworth = 0;
                                applyeid_products = new ArrayList<>();
                                if (!qualified_products1.isEmpty()) {
                                    for (int l = 0; l < qualified_products1.size(); l++) {
                                        int rate = Integer.parseInt(qualified_products1.get(l).getProduct_rate());
                                        int qty = Integer.parseInt(qualified_products1.get(l).getQuantity());
                                        total_offworth = total_offworth + rate * qty;
                                        //Updated logic for new promo------
                                        InvoiceGetterSetter invoiceGetterSetter;
                                        invoiceGetterSetter = returnobject();
                                        invoiceGetterSetter.setPromo_flag(true);
                                        invoiceGetterSetter.setPromo_type("OffWorth");
                                        invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                        invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                        invoiceGetterSetter.setProduct(qualified_products1.get(l).getProduct());
                                        invoiceGetterSetter.setQuantity(qualified_products1.get(l).getQuantity());
                                        invoiceGetterSetter.setProduct_Id(qualified_products1.get(l).getProduct_Id());
                                        invoiceGetterSetter.setProduct_rate(qualified_products1.get(l).getProduct_rate());
                                        ///calculate percentage
                                        double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0;
                                        try {
                                            total_valueper_productwise = rate * qty;
                                            getentityValue = Double.parseDouble(current.getPromotionGetEntityValue());
                                            calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100;
                                        } catch (NumberFormatException e) {
                                            e.fillInStackTrace();
                                        }
                                        invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise));
                                        invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(qualified_products1.get(l).getScan_ean_code_or_enterd_ean_code());

                                        applyeid_products.add(invoiceGetterSetter);
                                    }
                                }

                                MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup();
                                ob.setPromotion_name(current.getPromotionName());
                                ob.setPromotionId(current.getPromoId().toString());
                                ob.setPromotion_deducted_price(current.getPromotionGetEntityValue());
                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();

                                invoiceGetterSetter.setQuantity("0");
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code("");
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("OffWorth");
                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                int tip_per = Integer.parseInt(current.getPromotionGetEntityValue());
                                int tip_cal = (total_offworth * tip_per) / 100;
                                /////////calculate max value
                                if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                    int max_value = Integer.parseInt(current.getMaxValue());
                                    if (max_value != 0) {
                                        if (tip_cal > max_value) {
                                            tip_cal = max_value;
                                        }
                                    }
                                }
                                invoiceGetterSetter.setProduct("" + tip_cal);
                                invoiceGetterSetter.setProduct_Id("0");
                                //////added applyied products in list
                                invoiceGetterSetter.setApplyiedproductList(applyeid_products);
                                added_prmo_products.add(invoiceGetterSetter);
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("OffAdditionalProduct")) {
                                db.open();
                                ArrayList<InvoiceGetterSetter> qualified_products1 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId());
                                int total_offworth = 0;
                                int total_qty = 0;
                                int previous_qty = 0;
                                applyeid_products = new ArrayList<>();
                                ArrayList<MasterPromotionSetProductGroup> prodictlist_promo = db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from);
                                if (!qualified_products1.isEmpty() && !prodictlist_promo.isEmpty() && !selected_list.isEmpty()) {
                                    Collections.sort(prodictlist_promo, new Comparator() {
                                        @Override
                                        public int compare(Object o1, Object o2) {
                                            MasterPromotionSetProductGroup p1 = (MasterPromotionSetProductGroup) o1;
                                            MasterPromotionSetProductGroup p2 = (MasterPromotionSetProductGroup) o2;
                                            return p1.getMrp_product().compareToIgnoreCase(p2.getMrp_product());
                                        }
                                    });

                                    for (int k = 0; k < prodictlist_promo.size(); k++) {
                                        for (int l = 0; l < selected_list.size(); l++) {
                                            if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) {
                                                int rate = Integer.parseInt(selected_list.get(l).getProduct_rate());
                                                int qty = Integer.parseInt(selected_list.get(l).getQuantity());
                                                total_qty = total_qty + qty;
                                                total_offworth = total_offworth + rate * qty;
                                                //Updated logic for new promo------
                                                InvoiceGetterSetter invoiceGetterSetter;
                                                invoiceGetterSetter = returnobject();
                                                invoiceGetterSetter.setPromo_flag(true);
                                                invoiceGetterSetter.setPromo_type("OffAdditionalProduct");
                                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                                invoiceGetterSetter.setProduct(selected_list.get(l).getProduct());
                                                invoiceGetterSetter.setQuantity(selected_list.get(l).getQuantity());
                                                invoiceGetterSetter.setProduct_Id(selected_list.get(l).getProduct_Id());
                                                invoiceGetterSetter.setProduct_rate(selected_list.get(l).getProduct_rate());
                                                ///calculate percentage
                                                double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0, addOff = 0;
                                                try {
                                                    total_valueper_productwise = rate * qty;
                                                    getentityValue = Double.parseDouble(current.getPromotionGetEntityValue());
                                                    if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                                        if (total_qty > Integer.parseInt(current.getMaxValue()) && previous_qty <= Integer.parseInt(current.getMaxValue())) {
                                                            if (previous_qty == 0) {
                                                                addOff = rate * Integer.parseInt(current.getMaxValue());
                                                                calculate_per_productwise = (addOff * getentityValue) / 100;
                                                            } else if (previous_qty <= Integer.parseInt(current.getMaxValue())) {
                                                                addOff = (Integer.parseInt(current.getMaxValue()) - previous_qty) * rate;
                                                                calculate_per_productwise = (addOff * getentityValue) / 100;
                                                            } else {
                                                                calculate_per_productwise = 0;
                                                            }
                                                            previous_qty = total_qty;
                                                        } else {
                                                            previous_qty = total_qty;
                                                            if (total_qty <= Integer.parseInt(current.getMaxValue())) {
                                                                calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100;
                                                            }
                                                        }
                                                    } else {
                                                        calculate_per_productwise = (total_valueper_productwise * getentityValue) / 100;
                                                    }
                                                    //test("promodata", String.valueOf(calculate_per_productwise));
                                                } catch (NumberFormatException e) {
                                                    e.fillInStackTrace();
                                                }
                                                invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise));
                                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_list.get(l).getScan_ean_code_or_enterd_ean_code());
                                                applyeid_products.add(invoiceGetterSetter);
                                            }
                                        }
                                    }
                                }

                                MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup();
                                ob.setPromotion_name(current.getPromotionName());
                                ob.setPromotionId(current.getPromoId().toString());
                                ob.setPromotion_deducted_price(current.getPromotionGetEntityValue());

                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();

                                invoiceGetterSetter.setQuantity("0");
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code("");
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("OffAdditionalProduct");
                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                int tip_per = Integer.parseInt(current.getPromotionGetEntityValue());
                                int addOffProduct = 0;
                                int tip_cal = 0;
                                int prevqty = 0;
                                int remainqty = 0;
                                int totqty = 0;
                                int totoff = 0;

                                if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                    for (int k = 0; k < prodictlist_promo.size(); k++) {
                                        for (int l = 0; l < selected_list.size(); l++) {
                                            if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) {
                                                int rate = Integer.parseInt(selected_list.get(l).getProduct_rate());
                                                int qty = Integer.parseInt(selected_list.get(l).getQuantity());
                                                totqty = totqty + qty;
                                                totoff = totoff + rate * qty;
                                                addOffProduct = 0;
                                                //test("qtydata", totqty + "," + prevqty);
                                                if (totqty > Integer.parseInt(current.getMaxValue()) && prevqty <= Integer.parseInt(current.getMaxValue())) {
                                                    if (prevqty == 0) {
                                                        prevqty = prevqty + qty;
                                                        remainqty = Integer.parseInt(current.getMaxValue());
                                                    } else {
                                                        remainqty = Integer.parseInt(current.getMaxValue()) - prevqty;
                                                    }
                                                    addOffProduct = totoff - (rate * qty);
                                                    int tip = addOffProduct + rate * remainqty;
                                                    tip_cal = (tip * tip_per) / 100;
                                                    //test("discountdata", tip_cal + "," + addOffProduct + "," + total_offworth + "," + totoff + "," + tip + "," + rate * qty);
                                                    AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only");
                                                } else {
                                                    prevqty = prevqty + qty;
                                                    if (totqty > Integer.parseInt(current.getMaxValue())) {
                                                        break;
                                                    } else if (totqty < Integer.parseInt(current.getMaxValue())) {
                                                        tip_cal = (total_offworth * tip_per) / 100;
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                } else {
                                    tip_cal = (total_offworth * tip_per) / 100;
                                }

                                invoiceGetterSetter.setProduct(String.valueOf(tip_cal));
                                invoiceGetterSetter.setProduct_Id("0");
                                //////added applyied products in list
                                invoiceGetterSetter.setApplyiedproductList(applyeid_products);
                                added_prmo_products.add(invoiceGetterSetter);
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("ValueOffAdditionalProduct")) {
                                db.open();
                                ArrayList<InvoiceGetterSetter> qualified_products1 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId());
                                int total_offworth = 0;
                                int total_qty = 0;
                                int previous_qty = 0;
                                applyeid_products = new ArrayList<>();
                                ArrayList<MasterPromotionSetProductGroup> prodictlist_promo = db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from);
                                if (!qualified_products1.isEmpty() && !prodictlist_promo.isEmpty() && !selected_list.isEmpty()) {
                                    for (int k = 0; k < prodictlist_promo.size(); k++) {
                                        for (int l = 0; l < selected_list.size(); l++) {
                                            if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) {
                                                int rate = Integer.parseInt(selected_list.get(l).getProduct_rate());
                                                int qty = Integer.parseInt(selected_list.get(l).getQuantity());
                                                total_offworth = total_offworth + rate * qty;
                                                total_qty = total_qty + qty;
                                                //Updated logic for new promo------
                                                InvoiceGetterSetter invoiceGetterSetter;
                                                invoiceGetterSetter = returnobject();
                                                invoiceGetterSetter.setPromo_flag(true);
                                                invoiceGetterSetter.setPromo_type("ValueOffAdditionalProduct");
                                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                                invoiceGetterSetter.setProduct(selected_list.get(l).getProduct());
                                                invoiceGetterSetter.setQuantity(selected_list.get(l).getQuantity());
                                                invoiceGetterSetter.setProduct_Id(selected_list.get(l).getProduct_Id());
                                                invoiceGetterSetter.setProduct_rate(selected_list.get(l).getProduct_rate());
                                                ///calculate percentage
                                                double calculate_per_productwise = 0.0, getentityValue = 0.0, total_valueper_productwise = 0.0;
                                                try {
                                                    getentityValue = Double.parseDouble(current.getPromotionGetEntityValue());
                                                    if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                                        if (total_qty > Integer.parseInt(current.getMaxValue()) && previous_qty <= Integer.parseInt(current.getMaxValue())) {
                                                            if (previous_qty == 0) {
                                                                //  previous_qty = total_qty;
                                                                calculate_per_productwise = getentityValue * Integer.parseInt(current.getMaxValue());
                                                            } else if (previous_qty <= Integer.parseInt(current.getMaxValue())) {
                                                                calculate_per_productwise = (Integer.parseInt(current.getMaxValue()) - previous_qty) * getentityValue;
                                                            } else {
                                                                calculate_per_productwise = 0;
                                                            }
                                                            previous_qty = total_qty;
                                                        } else {
                                                            previous_qty = total_qty;
                                                            if (total_qty <= Integer.parseInt(current.getMaxValue())) {
                                                                calculate_per_productwise = getentityValue * qty;
                                                            }
                                                        }
                                                    } else {
                                                        calculate_per_productwise = getentityValue * qty;
                                                    }
                                                    //test("promodata", String.valueOf(calculate_per_productwise));
                                                } catch (NumberFormatException e) {
                                                    e.fillInStackTrace();
                                                }
                                                invoiceGetterSetter.setDiscounted_value_productwise(new DecimalFormat("##.##").format(calculate_per_productwise));
                                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(selected_list.get(l).getScan_ean_code_or_enterd_ean_code());
                                                applyeid_products.add(invoiceGetterSetter);
                                            }
                                        }
                                    }
                                }

                                MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup();
                                ob.setPromotion_name(current.getPromotionName());
                                ob.setPromotionId(current.getPromoId().toString());
                                ob.setPromotion_deducted_price(current.getPromotionGetEntityValue());

                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();

                                invoiceGetterSetter.setQuantity("0");
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code("");
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("ValueOffAdditionalProduct");
                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                int tip_per = Integer.parseInt(current.getPromotionGetEntityValue());

                                int addOffProduct = 0;
                                int tip_cal = 0;
                                int totqty = 0;
                                int prevqty = 0;
                                int remainqty = 0;
                                for (int k = 0; k < prodictlist_promo.size(); k++) {
                                    for (int l = 0; l < selected_list.size(); l++) {
                                        if (selected_list.get(l).getProduct_Id().equals(String.valueOf(prodictlist_promo.get(k).getProductId()))) {
                                            int rate = Integer.parseInt(selected_list.get(l).getProduct_rate());
                                            int qty = Integer.parseInt(selected_list.get(l).getQuantity());
                                            totqty = totqty + qty;
                                            if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                                if (totqty > Integer.parseInt(current.getMaxValue())) {
                                                    if (prevqty == 0) {
                                                        tip_cal = 0;
                                                        addOffProduct = tip_cal + tip_per * Integer.parseInt(current.getMaxValue());
                                                    } else {
                                                        remainqty = Integer.parseInt(current.getMaxValue()) - prevqty;
                                                        addOffProduct = tip_cal + (tip_per * remainqty);
                                                    }
                                                    tip_cal = addOffProduct;
                                                    AlertandMessages.showToastMsg(context, "Exceeds Limit, Promo will apply on" + " " + current.getMaxValue() + " " + "Quantity only");
                                                    break;
                                                } else {
                                                    prevqty = totqty;
                                                    if (totqty > Integer.parseInt(current.getMaxValue())) {
                                                        break;
                                                    } else {
                                                        tip_cal = tip_cal + (tip_per * qty);
                                                    }
                                                }
                                            } else {
                                                tip_cal = tip_per * qty;
                                            }
                                            break;
                                        }
                                    }
                                }

                                invoiceGetterSetter.setProduct(String.valueOf(tip_cal));
                                invoiceGetterSetter.setProduct_Id("0");
                                //////added applyied products in list
                                invoiceGetterSetter.setApplyiedproductList(applyeid_products);
                                added_prmo_products.add(invoiceGetterSetter);
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("OffProduct")) {
                                db.open();
                                if (!db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from).isEmpty()) {
                                    show_promotion_dialog(context, current, true, current.getPromotionGetEntityType());
                                } else {
                                    AlertandMessages.showToastMsg(context, "OffProduct not in stock");
                                }
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("Product")) {
                                db.open();
                                if (!db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from).isEmpty()) {
                                    show_promotion_dialog(context, current, true, current.getPromotionGetEntityType());
                                } else {
                                    AlertandMessages.showToastMsg(context, "Free Product not in stock");
                                }
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("Gift")) {
                                db.open();
                                if (!db.getPromotiongetProduct(current.getPromoId(), current.getPromotionGetEntityType(), visit_date, CounterId, from).isEmpty()) {
                                    show_promotion_dialog(context, current, true, current.getPromotionGetEntityType());
                                } else {
                                    AlertandMessages.showToastMsg(context, "Free Product not in stock");
                                }
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("Worth")) {
                                MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup();
                                ob.setPromotion_name(current.getPromotionName());
                                ob.setPromotionId(current.getPromoId().toString());
                                ob.setPromotion_deducted_price(current.getPromotionGetEntityValue());
                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();
                                invoiceGetterSetter.setQuantity("0");
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code("");
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("Worth");
                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                invoiceGetterSetter.setProduct(current.getPromotionGetEntityValue());
                                invoiceGetterSetter.setProduct_Id("0");
                                added_prmo_products.add(invoiceGetterSetter);
                            } else if (current.getPromotionGetEntityType().equalsIgnoreCase("WorthWithProduct")) {
                                db.open();
                                ArrayList<InvoiceGetterSetter> applyiedPromoProducts = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId());
                                int totalQty = 0, total_discount = 0;
                                applyeid_products = new ArrayList<>();
                                if (!applyiedPromoProducts.isEmpty()) {
                                    for (int l = 0; l < applyiedPromoProducts.size(); l++) {
                                        int qty = Integer.parseInt(applyiedPromoProducts.get(l).getQuantity());
                                        totalQty += qty;
                                        //Updated logic for new promo------
                                        InvoiceGetterSetter invoiceGetterSetter;
                                        invoiceGetterSetter = returnobject();
                                        invoiceGetterSetter.setPromo_flag(true);
                                        invoiceGetterSetter.setPromo_type("WorthWithProduct");
                                        invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                        invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                        invoiceGetterSetter.setProduct(applyiedPromoProducts.get(l).getProduct());
                                        invoiceGetterSetter.setQuantity(applyiedPromoProducts.get(l).getQuantity());
                                        invoiceGetterSetter.setProduct_Id(applyiedPromoProducts.get(l).getProduct_Id());
                                        invoiceGetterSetter.setProduct_rate(applyiedPromoProducts.get(l).getProduct_rate());
                                        invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code(applyiedPromoProducts.get(l).getScan_ean_code_or_enterd_ean_code());

                                        invoiceGetterSetter.setDiscounted_value_productwise("0");
                                        applyeid_products.add(invoiceGetterSetter);
                                    }
                                }

                                MasterPromotionSetProductGroup ob = new MasterPromotionSetProductGroup();
                                ob.setPromotion_name(current.getPromotionName());
                                ob.setPromotionId(current.getPromoId().toString());
                                ob.setPromotion_deducted_price(current.getPromotionGetEntityValue());
                                InvoiceGetterSetter invoiceGetterSetter;
                                invoiceGetterSetter = returnobject();

                                invoiceGetterSetter.setQuantity("0");
                                invoiceGetterSetter.setProduct_rate("0");
                                invoiceGetterSetter.setDiscount(0.0);
                                invoiceGetterSetter.setScan_ean_code_or_enterd_ean_code("");
                                invoiceGetterSetter.setSkuType("");
                                invoiceGetterSetter.setStr_invoiceType("");
                                invoiceGetterSetter.setPromo_flag(true);
                                invoiceGetterSetter.setPromo_type("WorthWithProduct");
                                invoiceGetterSetter.setPromotion_name(current.getPromotionName());
                                invoiceGetterSetter.setPromotion_Id(current.getPromoId().toString());
                                int setEntityValue = Integer.parseInt(current.getPromotionSetEntityValue());
                                /////////calculate max value
                                if (current.getMaxValue() != null && !current.getMaxValue().isEmpty()) {
                                    int max_value = Integer.parseInt(current.getMaxValue());
                                    if (max_value != 0) {
                                        if (totalQty > max_value) {
                                            totalQty = max_value;
                                        }
                                    }
                                }

                                if (totalQty >= setEntityValue) {
                                    total_discount = ((int) (totalQty / setEntityValue)) * Integer.parseInt(current.getPromotionGetEntityValue());
                                }

                                invoiceGetterSetter.setProduct(String.valueOf(total_discount));
                                invoiceGetterSetter.setProduct_Id("0");
                                //added applyied products in list
                                invoiceGetterSetter.setApplyiedproductList(applyeid_products);
                                added_prmo_products.add(invoiceGetterSetter);
                            }
                        }
                    } else {
                        current.setPromotionactive(false);
                        viewHolder.check_promo.setChecked(false);
                        remove_added_promo_fromtemp(current.getPromoId().toString());
                    }
                } catch (NumberFormatException e) {
                    e.fillInStackTrace();
                }
            });


            if (current.isPromotionactive()) {
                viewHolder.check_promo.setChecked(true);
                viewHolder.check_promo.setId(pos);
            } else {
                viewHolder.check_promo.setChecked(false);
                viewHolder.check_promo.setId(pos);
            }

            viewHolder.img_product.setOnClickListener(view -> {
                ArrayList<InvoiceGetterSetter> qualified_products12 = db.getqualified_Product_List(CounterId, username, visit_date, current.getPromoId());
                if (!qualified_products12.isEmpty()) {
                    show_qualified_products_dialog(context, qualified_products12, false, current);
                }
            });

            viewHolder.img_promo.setOnClickListener(view -> show_qualified_products_dialog(context, null, true, current));
        }

        @Override
        public int getItemCount() {
            return promotionList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView img_product, img_promo;
            CheckBox check_promo;
            CardView card_view;
            TextView category, aplyed_products;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                card_view = (CardView) itemView.findViewById(R.id.card_view);
                category = (TextView) itemView.findViewById(R.id.tvstorename);
                aplyed_products = (TextView) itemView.findViewById(R.id.aplyed_products);
                check_promo = (CheckBox) itemView.findViewById(R.id.check_promo);
                img_product = (ImageView) itemView.findViewById(R.id.img_product);
                img_promo = (ImageView) itemView.findViewById(R.id.img_promo);
            }
        }
    }

    protected boolean check_isPromo() {
        boolean status = false;
        try {
            if (!selected_list.isEmpty()) {
                for (int k = 0; k < selected_list.size(); k++) {
                    if (selected_list.get(k).isPromo_flag()) {
                        status = true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return status;
    }

    protected void remove_added_promo_index() {
        try {
            if (!selected_list.isEmpty()) {
                Iterator<InvoiceGetterSetter> it = selected_list.iterator();
                while (it.hasNext()) {
                    InvoiceGetterSetter name = it.next();
                    if (name.isPromo_flag()) {
                        it.remove();
                    }
                    // Do something
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    protected void remove_added_promo_fromtemp(String promoId) {
        try {
            if (!added_prmo_products.isEmpty()) {
                Iterator<InvoiceGetterSetter> it = added_prmo_products.iterator();
                while (it.hasNext()) {
                    InvoiceGetterSetter name = it.next();
                    if (promoId.equals(name.getPromotion_Id())) {
                        it.remove();
                    }
                    // Do something
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void show_qualified_products_dialog(final Context context, final ArrayList<InvoiceGetterSetter> qualifiedProducts, boolean
            pic_promo_flag, final MasterPromotion current) {
        final MultiPurposeDialog purposeDialog = new MultiPurposeDialog(context);
        purposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        purposeDialog.setContentView(R.layout.qualified_product);
        purposeDialog.setCancelable(false);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(purposeDialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        purposeDialog.getWindow().setAttributes(lp);
        purposeDialog.show();

        RecyclerView recycl_promotion = (RecyclerView) purposeDialog.findViewById(R.id.recycl_promotion);
        final ImageView close_white = (ImageView) purposeDialog.findViewById(R.id.img_close);
        final WebView web_view = (WebView) purposeDialog.findViewById(R.id.web_view);

        if (pic_promo_flag) {
            web_view.setVisibility(View.VISIBLE);
            recycl_promotion.setVisibility(View.GONE);
            if (CommonFunctions.checkNetIsAvailable(context)) {
                //load notice board url
                web_view.setWebViewClient(new MyWebViewClient());
                web_view.getSettings().setJavaScriptEnabled(true);
                web_view.getSettings().setBuiltInZoomControls(true);
                String url = "";
                if (CommonFunctions.isTablet(context)) {
                    url = current.getPromoPath() + current.getPromoOfferTab();
                } else {
                    url = current.getPromoPath() + current.getPromoOfferMobile();
                }
                if (url != null && !url.isEmpty()) {
                    web_view.loadUrl(url);
                }
            }
        } else {
            web_view.setVisibility(View.GONE);
            recycl_promotion.setVisibility(View.VISIBLE);
            if (qualifiedProducts != null) {
                recycl_promotion.setAdapter(new QualifiedProductsAdapter(context, purposeDialog, qualifiedProducts));
                recycl_promotion.setLayoutManager(new LinearLayoutManager(context));
            }
        }

        close_white.setOnClickListener(view -> {
            purposeDialog.dismiss();
            if (purposeDialog != null && purposeDialog.isShowing()) {
                purposeDialog.dismiss();
            }
        });

        purposeDialog.show();
    }

    private class QualifiedProductsAdapter extends RecyclerView.Adapter<QualifiedProductsAdapter.ViewHolder> {
        ArrayList<InvoiceGetterSetter> products;
        Context context;
        MultiPurposeDialog dialog;
        private final LayoutInflater inflator;

        public QualifiedProductsAdapter(Context context, final MultiPurposeDialog dialog, ArrayList<InvoiceGetterSetter> products) {
            this.dialog = dialog;
            this.context = context;
            this.products = products;
            inflator = LayoutInflater.from(context);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_qualified_products, parent, false);
            return new ViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int pos) {
            ////show product selected
            final InvoiceGetterSetter current = products.get(pos);

            viewHolder.tvstorename.setText("Product : " + current.getProduct().trim());
            viewHolder.tvstorename.setId(pos);

            viewHolder.qty_qualified.setText("QTY : " + current.getQuantity());
            viewHolder.qty_qualified.setId(pos);

            viewHolder.rate_qualified.setText("Rate : " + current.getProduct_rate());
            viewHolder.rate_qualified.setId(pos);
        }

        @Override
        public int getItemCount() {
            return products.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            CardView card_view;
            TextView tvstorename, qty_qualified, rate_qualified;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                card_view = (CardView) itemView.findViewById(R.id.card_view);
                tvstorename = (TextView) itemView.findViewById(R.id.tvstorename);
                qty_qualified = (TextView) itemView.findViewById(R.id.qty_qualified);
                rate_qualified = (TextView) itemView.findViewById(R.id.rate_qualified);
            }
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.clearCache(true);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loading != null && loading.isShowing()) {
            loading.dismiss();
        }
    }

    private Dialog dialog;
    ProgressBar pb;

    class LoadTask extends AsyncTask<Boolean, Void, Void> {
        boolean flag = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.setContentView(R.layout.circular_progress_bar);
            pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Boolean... bool) {
            flag = bool[0];
            if (flag) {
                added_check_promotion();
            } else {
                check_promotion_for_worth();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();

            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    private void deletesome_temptable_data() {
        try {
            db.open();
            db.insert_consumer_tempsales_data(username, visit_date, CounterId, selected_list);
            db.delete_table_temp();
            db.delete_table_tempforsameproduct();
            db.delete_table_tempfor_andpromo();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private void added_check_promotion() {
        try {
            db.open();
            deletesome_temptable_data();
            ///insert temp sale for checked Setentity Value promotion
            ////get promotion by jeevan
            ////for product promotion
            db.open();
            ArrayList<MasterPromotion> promoMaster = db.getPromotionMaster(true);
            // //test("promosize", String.valueOf(promoMaster.size()));

            if (!promoMaster.isEmpty()) {
                final ArrayList<MasterPromotion> validPromoList = new ArrayList<>();
                for (int x = 0; x < promoMaster.size(); x++) {
                    //if promotion set entity type is - Product
                    ///--------for AND promotion ------
                    if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) {
                        db.open();
                        ArrayList<MasterPromotionSetEntityItem> promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId());
                        if (!promoAndList.isEmpty()) {
                            boolean flag_for_and = true;
                            for (int q = 0; q < promoAndList.size(); q++) {
                                db.open();
                                int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(),
                                        promoAndList.get(q).getPromoId().toString(), true, username, visit_date, CounterId);
                                ////checking AND promo itemcount
                                if (product_countfor_and >= promoAndList.get(q).getItemCount()) {
                                    db.open();
                                    db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username,
                                            promoAndList.get(q).getPromoId(), visit_date);
                                } else {
                                    db.open();
                                    flag_for_and = false;
                                    db.delete_table_tempfor_andpromo();
                                    break;
                                }
                            }

                            if (flag_for_and) {
                                //////--------insert all AND Promo data to Apply Definition.Table...-----------
                                db.open();
                                db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x));
                                validPromoList.add(promoMaster.get(x));
                            }
                        }
                    } else {
                        db.open();
                        int product_count = db.getPromotiongetProductall(promoMaster.get(x), true, username, visit_date, CounterId);
                        //test("product_count", String.valueOf(product_count));
                        if (product_count > 0) {
                            if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) {
                                db.open();
                                db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date);
                                validPromoList.add(promoMaster.get(x));
                            }
                        }
                    }
                }

                if (!validPromoList.isEmpty()) {
                    runOnUiThread(() -> {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        show_promotion_skuwise_dialog(context, selected_list, validPromoList, false);
                    });

                } else {
                    ///finish
                    checkPromoWorth(promoMaster);
                }
            } else {
                ////get promotion by jeevan
                ////for worth promotion
                db.open();
                promoMaster = db.getPromotionMaster(false);
                //test("promosizeworth", String.valueOf(promoMaster.size()));
                if (!promoMaster.isEmpty()) {
                    final ArrayList<MasterPromotion> validPromoList = new ArrayList<>();
                    for (int x = 0; x < promoMaster.size(); x++) {
                        //if promotion set entity type is - Product
                        ///--------for AND promotion ------
                        if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) {
                            db.open();
                            ArrayList<MasterPromotionSetEntityItem> promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId());
                            if (!promoAndList.isEmpty()) {
                                boolean flag_for_and = true;
                                for (int q = 0; q < promoAndList.size(); q++) {
                                    db.open();
                                    int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), promoAndList.get(q).getPromoId().toString(), false, username, visit_date, CounterId);
                                    ////checking AND promo itemcount
                                    if (product_countfor_and >= promoAndList.get(q).getItemCount()) {
                                        db.open();
                                        db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, promoAndList.get(q).getPromoId(), visit_date);
                                    } else {
                                        db.open();
                                        flag_for_and = false;
                                        db.delete_table_tempfor_andpromo();
                                        break;
                                    }
                                }

                                if (flag_for_and) {
                                    //////--------insert all AND Promo data to Apply Definition.Table...-----------
                                    db.open();
                                    db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x));
                                    validPromoList.add(promoMaster.get(x));
                                }
                            }
                        } else {
                            db.open();
                            int product_count = db.getPromotiongetProductall(promoMaster.get(x), false, username, visit_date, CounterId);
                            //test("product_count", String.valueOf(product_count));
                            if (product_count > 0) {
                                if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) {
                                    db.open();
                                    db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date);
                                    validPromoList.add(promoMaster.get(x));
                                }
                            }
                        }
                    }

                    if (!validPromoList.isEmpty()) {
                        runOnUiThread(() -> {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }
                            show_promotion_skuwise_dialog(context, selected_list, validPromoList, true);
                        });
                    } else {
                        ///finish
                        runOnUiThread(() -> {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }
                            drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                            startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                                    putExtra(CommonString.TAG_OBJECT, selected_list)
                                    .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                                    .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                                    putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                                    .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            added_prmo_products = new ArrayList<>();
                        });
                    }

                } else {

                    runOnUiThread(() -> {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                        drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                        startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                                putExtra(CommonString.TAG_OBJECT, selected_list)
                                .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                                .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                                putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                                .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        added_prmo_products = new ArrayList<>();
                    });
                }

            }
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }
    }

    private void checkPromoWorth(ArrayList<MasterPromotion> promoMaster) {
        db.open();
        promoMaster = db.getPromotionMaster(false);
        if (!promoMaster.isEmpty()) {
            final ArrayList<MasterPromotion> validPromoList = new ArrayList<>();
            for (int x = 0; x < promoMaster.size(); x++) {
                //if promotion set entity type is - Product
                ///--------for AND promotion ------
                if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) {
                    db.open();
                    ArrayList<MasterPromotionSetEntityItem> promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId());
                    if (!promoAndList.isEmpty()) {
                        boolean flag_for_and = true;
                        for (int q = 0; q < promoAndList.size(); q++) {
                            db.open();
                            int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), promoAndList.get(q).getPromoId().toString(), false, username, visit_date, CounterId);
                            ////checking AND promo itemcount
                            if (product_countfor_and >= promoAndList.get(q).getItemCount()) {
                                db.open();
                                db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, promoAndList.get(q).getPromoId(), visit_date);
                            } else {
                                db.open();
                                flag_for_and = false;
                                db.delete_table_tempfor_andpromo();
                                break;
                            }
                        }

                        if (flag_for_and) {
                            //////--------insert all AND Promo data to Apply Definition.Table...-----------
                            db.open();
                            db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x));
                            validPromoList.add(promoMaster.get(x));
                        }
                    }
                } else {
                    db.open();
                    int product_count = db.getPromotiongetProductall(promoMaster.get(x), false, username, visit_date, CounterId);
                    if (product_count > 0) {
                        if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) {
                            db.open();
                            db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date);
                            validPromoList.add(promoMaster.get(x));
                        }
                    }
                }
            }

            if (!validPromoList.isEmpty()) {
                runOnUiThread(() -> {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    show_promotion_skuwise_dialog(context, selected_list, validPromoList, true);
                });
            } else {
                ///finish
                runOnUiThread(() -> {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                            putExtra(CommonString.TAG_OBJECT, selected_list)
                            .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                            .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                            putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                            .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                    added_prmo_products = new ArrayList<InvoiceGetterSetter>();
                });
            }

        } else {

            runOnUiThread(() -> {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                        putExtra(CommonString.TAG_OBJECT, selected_list)
                        .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                        .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                        putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                        .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                added_prmo_products = new ArrayList<>();
            });
        }
    }

    private void check_promotion_for_worth() {
        try {
            db.open();
            deletesome_temptable_data();
            db.open();
            ArrayList<MasterPromotion> promoMaster = db.getPromotionMaster(false);
            if (!promoMaster.isEmpty()) {
                final ArrayList<MasterPromotion> validPromoList = new ArrayList<>();
                for (int x = 0; x < promoMaster.size(); x++) {
                    //if promotion set entity type is - Product
                    ///--------for AND promotion ------
                    if (promoMaster.get(x).getPromoType().equalsIgnoreCase("AND")) {
                        db.open();
                        ArrayList<MasterPromotionSetEntityItem> promoAndList = db.getsetintitiytemId(promoMaster.get(x).getPromoId());
                        if (!promoAndList.isEmpty()) {
                            boolean flag_for_and = true;
                            for (int q = 0; q < promoAndList.size(); q++) {
                                db.open();
                                int product_countfor_and = db.getPromotiongetProductforAndPromo(promoAndList.get(q).getId(), promoAndList.get(q).getPromoId().toString(), false, username, visit_date, CounterId);
                                ////checking AND promo itemcount
                                if (product_countfor_and >= promoAndList.get(q).getItemCount()) {
                                    db.open();
                                    db.update_temp_promo_apply_definitionfor_andpromo(promoAndList.get(q).getId(), CounterId, username, promoAndList.get(q).getPromoId(), visit_date);
                                } else {
                                    db.open();
                                    flag_for_and = false;
                                    db.delete_table_tempfor_andpromo();
                                    break;
                                }
                            }
                            if (flag_for_and) {
                                //////--------insert all AND Promo data to Apply Definition.Table...-----------
                                db.open();
                                db.inserttemp_promo_data(CounterId, visit_date, username, promoMaster.get(x));
                                validPromoList.add(promoMaster.get(x));
                            }
                        }
                    } else {
                        db.open();
                        int product_count = db.getPromotiongetProductall(promoMaster.get(x), false, username, visit_date, CounterId);
                        //test("Productcount", String.valueOf(product_count));
                        if (product_count > 0) {
                            if (product_count >= Integer.parseInt(promoMaster.get(x).getPromotionSetEntityValue())) {
                                db.open();
                                db.update_temp_promo_apply_definition(CounterId, username, promoMaster.get(x).getPromoId().toString(), visit_date);
                                validPromoList.add(promoMaster.get(x));
                            }
                        }
                    }
                }
                if (!validPromoList.isEmpty()) {
                    runOnUiThread(() -> show_promotion_skuwise_dialog(context, selected_list, validPromoList, true));

                } else {
                    runOnUiThread(() -> {
                        if (!added_prmo_products.isEmpty()) {
                            selected_list.addAll(added_prmo_products);
                        }
                        added_prmo_products = new ArrayList<>();
                        ///finish
                        drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                        drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                        startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                                putExtra(CommonString.TAG_OBJECT, selected_list)
                                .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                                .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                                putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                                .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        added_prmo_products = new ArrayList<>();
                    });
                }
            } else {

                runOnUiThread(() -> {
                    if (!added_prmo_products.isEmpty()) {
                        selected_list.addAll(added_prmo_products);
                    }
                    added_prmo_products = new ArrayList<>();
                    drawer_layout_recycle_store.setAdapter(new ValueAdapter(context, selected_list));
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    startActivity(new Intent(context, InvoiceReportProformaActivity.class).
                            putExtra(CommonString.TAG_OBJECT, selected_list)
                            .putExtra(CommonString.Key_For_Consumer_Update, flag_for_consumer_Update)
                            .putExtra(CommonString.Key_For_Reciept_Count, String.valueOf(reciept_count)).
                            putExtra(CommonString.FLAG_FOR_TERMCONDITION, str_termCondition)
                            .putExtra(CommonString.KEY_IMAGE, str_img_demo_no_sale).putExtra("from", from));
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                    added_prmo_products = new ArrayList<>();
                });
            }
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }
    }

    private InvoiceGetterSetter returnobject() {
        InvoiceGetterSetter object = new InvoiceGetterSetter();
        try {
            object = new InvoiceGetterSetter();
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
            object.setUserName(username);
            object.setStore_name(storeDataObject.getCounterName());
            object.setStore_address(storeDataObject.getAddress() + "," + storeDataObject.getCityName());
            object.setCustomer_name(CommonFunctions.removed_special_char(edt_customer));
            object.setMobile_no(edt_mobile_no.getText().toString());
            object.setConsumer_email_Id(edt_email_address.getText().toString());
            if (spin_age.getSelectedItemId() == 0) {
                object.setConsumer_age("");
            } else {
                object.setConsumer_age(spin_age.getSelectedItem().toString());
            }
            if (spin_skin_type.getSelectedItemId() == 0) {
                object.setConsumer_skinType("");
            } else {
                object.setConsumer_skinType(spin_skin_type.getSelectedItem().toString());
            }
            object.setCustomer_gender(radioSexButton.getText().toString());
            object.setDemo_given_str(demo_given_str);
            object.setSkin_genius_str(skin_genius_str);
            object.setMaybelline_vto_str(maybelline_vto);
            object.setProduct_sold_str(product_sold_str);
            object.setPercheasing_tym(perchasing_tym);
            object.setSourceofSales(str_sourceof_sales);
            object.setConsumer_no_saleImg(str_img_demo_no_sale);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return object;
    }
}

