package com.cpm.lorealbaautomation.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

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

import android.text.Editable;
import android.text.InputFilter;
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.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.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
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.adapter.InvoiceTypeSpinnerAdapter;
import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter;
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.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice;
import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

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

public class ManualInWardStockActivity extends AppCompatActivity implements View.OnClickListener {
    Lorealba_Database db;
    Context context;
    private SharedPreferences preferences;
    String counter_id, visit_date, username, _pathforcheck = "", _path = "", str_img_invoice = "";
    RecyclerView invoiceListView;
    ValueAdapter adapter;
    FloatingActionButton draftBtn, saveBtn;
    TextView invoice_date;
    Spinner invoice_type_spin;
    EditText invoice_number;
    ImageView date_img;
    TCounterInvoice tCounterInvoiceObj = new TCounterInvoice();
    ArrayList<MasterInvoiceType> invoiceTypeList = new ArrayList<>();
    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    Button btn_scan, btn_enter_code, btn_sku_list;
    TextView qrcode_text, stock_text_value;
    EditText edt_scan_code;
    int minteger = 0;
    RecyclerView drawer_layout_recycle_store;
    InvoiceGetterSetter object;
    String product_scan_code = "", demo_given_str = "", product_sold_str = "";
    public ArrayList<InvoiceGetterSetter> selected_list = new ArrayList<>();
    public ArrayList<InvoiceGetterSetter> selected_list2 = new ArrayList<>();
    public ArrayList<ProductMaster> dialog_product_list = new ArrayList<>();
    ArrayAdapter<CharSequence> dialog_brand_adapter, dialog_sub_brand_adapter, dialog_frenchise_adapter, dialog_sku_adapter;
    ArrayList<MasterNonStockReason> reasonList = new ArrayList<>();
    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;
    boolean flag_for_filter = false;
    String invoiceNo = "", invDate = "", invType = "";
    TCounterInvoice tCounterInvoice;
    boolean flag_filter_by_edt = false;
    boolean flag = true;
    int itemPos = 0;
    public ArrayList<ProductMaster> dialog_product_using_searchlist = new ArrayList<>();
    String dialog_brand_Id = "", dialog_sub_brand_Id = "", dialog_reference_Id = "", product_name = "", product_Id = "0", product_mrp = "0",
            dialog_reference = "", dialog_sub_brand = "", dialog_brand = "", store_name, store_address, Error_Msg = "";
    String value = "";
    ArrayList<TCounterInvoice> manualInwardStockList = new ArrayList<>();
    String month = "", dd = "", yy = "";
    MultiPurposeDialog dialog_final = null;
    ImageView invoice_img;
    TextView txt_invoice_qty, txt_actual_qty;
    boolean isDataAdded = false;
    String blockCharacterSet = "[';:-+{('}<!>,@=#$%^&*?)\"]";
    InputFilter filter = (source, start, end, dest, dstart, dend) -> {
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manual_in_ward_stock);
        context = this;
        ((ManualInWardStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();
        invoiceTypeList = db.getInvoiceTypeList();
        reasonList = db.getReasonData(false);
        db.open();
        dialog_product_list = db.getproduct_masterlist(null, visit_date, counter_id, null);
        validateUIData();
        setDataToListView();
        invoice_number.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(30)});
        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 - " + counter_id);
        txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty());
        txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty());
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void validateUIData() {
        preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        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);
        invoiceListView = (RecyclerView) findViewById(R.id.invoice_list);
        draftBtn = (FloatingActionButton) findViewById(R.id.draft_btn);
        saveBtn = (FloatingActionButton) findViewById(R.id.save_btn);
        invoice_date = (TextView) findViewById(R.id.invoice_date);
        date_img = (ImageView) findViewById(R.id.date_img);
        invoice_type_spin = (Spinner) findViewById(R.id.invoice_type);
        invoice_number = (EditText) findViewById(R.id.invoice_no);
        drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store);
        invoice_img = (ImageView) findViewById(R.id.manualinvoice_img);
        ///added actual and invoice qty
        txt_invoice_qty = (TextView) findViewById(R.id.txt_invoice_qty);
        txt_actual_qty = (TextView) findViewById(R.id.txt_actual_qty);

        btn_enter_code.setOnClickListener(this);
        btn_sku_list.setOnClickListener(this);
        date_img.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        draftBtn.setOnClickListener(this);
        btn_scan.setOnClickListener(this);
        invoice_img.setOnClickListener(this);

        value = getIntent().getStringExtra(CommonString.KEY_VALUE);

        invoice_type_spin.setAdapter(new InvoiceTypeSpinnerAdapter(context, R.layout.spinner_text_view, invoiceTypeList));

        invoice_type_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos == 0) {
                    tCounterInvoiceObj.setInvoiceType("");
                } else {
                    tCounterInvoiceObj.setInvoiceType(invoiceTypeList.get(pos).getInvoiceType());
                }
            }

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

            }
        });


        if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) {
            tCounterInvoice = (TCounterInvoice) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
            assert tCounterInvoice != null;
            invoiceNo = tCounterInvoice.getInvoiceNo();
            invType = tCounterInvoice.getInvoiceType();
            invDate = tCounterInvoice.getInvoiceDate();

            if (tCounterInvoice.getUpload_status().equalsIgnoreCase(CommonString.KEY_U) || !tCounterInvoice.getTransactionId().equals("")) {
                btn_scan.setEnabled(false);
                draftBtn.setEnabled(false);
                saveBtn.setEnabled(false);
                date_img.setEnabled(false);
                invoice_img.setEnabled(false);
                btn_enter_code.setEnabled(false);
                btn_sku_list.setEnabled(false);
                invoice_number.setEnabled(false);
                invoice_type_spin.setEnabled(false);
                btn_scan.setBackground(getResources().getDrawable(R.drawable.rouded_corner_gray));
                btn_scan.setTextColor(getResources().getColor(R.color.list_odd));

                btn_enter_code.setBackground(getResources().getDrawable(R.drawable.rouded_corner_gray));
                btn_enter_code.setTextColor(getResources().getColor(R.color.list_odd));

                btn_sku_list.setBackground(getResources().getDrawable(R.drawable.rouded_corner_gray));
                btn_sku_list.setTextColor(getResources().getColor(R.color.list_odd));
            }
        }

        for (int i = 0; i < invoiceTypeList.size(); i++) {
            if (invType.equalsIgnoreCase(invoiceTypeList.get(i).getInvoiceType())) {
                itemPos = i;
            }
        }
        if (!invoiceNo.isEmpty()) {
            invoice_number.setText(invoiceNo);
            invoice_number.setEnabled(false);
        }
        if (!invDate.isEmpty()) {
            invoice_date.setText(invDate);
            date_img.setClickable(false);
        } else {
            date_img.setClickable(true);
        }

        if (!invType.isEmpty()) {
            invoice_type_spin.setEnabled(false);
            invoice_type_spin.setSelection(itemPos);
        }

        drawer_layout_recycle_store.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0) {
                    saveBtn.hide();
                } else if (dy < 0) {
                    saveBtn.show();
                }

            }
        });

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        setTitle("Manual Stock - " + visit_date);
    }


    @SuppressLint("UseCompatLoadingForDrawables")
    public void setDataToListView() {
        try {
            db.open();
            selected_list = db.getInsertedManualStockData(invoiceNo, invType, visit_date);
            selected_list2 = db.getInsertedManualStockData(invoiceNo, invType, visit_date);
            Collections.reverse(selected_list2);
            Collections.reverse(selected_list);
            if (!selected_list.isEmpty()) {
                str_img_invoice = selected_list.get(0).getInvoice_img();
                if (!str_img_invoice.isEmpty()) {
                    invoice_img.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                }
                adapter = new ValueAdapter(context, selected_list);
                drawer_layout_recycle_store.setAdapter(adapter);
                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(e);
            //test("Exception when fetching", e.toString());
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.manualinvoice_img) {
            isDataAdded = true;
            _pathforcheck = counter_id + "_minwordsimg_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
        } else if (v.getId() == R.id.btn_scan) {
            isDataAdded = true;
            show_proforma_dialog(context, true);
        } else if (v.getId() == R.id.btn_enter_code) {
            isDataAdded = true;
            show_proforma_dialog(context, false);
        } else if (v.getId() == R.id.btn_sku_list) {
            isDataAdded = true;
            show_dialog_forsku_categorywise(context);
        } else if (v.getId() == R.id.draft_btn) {
            if (validateData()) {
                saveDataInDraft();
            } else {
                AlertandMessages.showToastMsg(context, Error_Msg);
            }

        } else if (v.getId() == R.id.save_btn) {
            if (validateData()) {
                saveUpdateAndUploadData();
            } else {
                AlertandMessages.showToastMsg(context, Error_Msg);
            }

        } else if (v.getId() == R.id.date_img) {
            c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            c.add(Calendar.DAY_OF_MONTH, -6);
            Date result = c.getTime();

            // Launch Date Picker Dialog
            dpd = new DatePickerDialog(ManualInWardStockActivity.this, (view, year, monthOfYear, dayOfMonth) -> {
                if (monthOfYear + 1 < 10) {
                    month = "0" + (monthOfYear + 1);
                } else {
                    month = String.valueOf(monthOfYear + 1);
                }

                if (dayOfMonth < 10) {
                    dd = "0" + dayOfMonth;
                } else {
                    dd = String.valueOf(dayOfMonth);
                }

                String dob = month + "-" + dd + "-" + year;
                invoice_date.setText(dob);
            }, mYear, mMonth, mDay);

            // TODO Hide Future Date Here
            //  dpd.getDatePicker().setMaxDate(System.currentTimeMillis());
            // TODO Hide Past Date Here
            dpd.getDatePicker().setMaxDate(System.currentTimeMillis());
            dpd.getDatePicker().setMinDate(result.getTime());
            dpd.show();

        }
    }

    public class MultiPurposeDialog extends Dialog {
        public 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);
        }
    }

    private void show_dialog_for_final_submit(final Context context) {
        final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context);
        final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        final_save_dialog.setContentView(R.layout.custom_dialog_final_save);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(final_save_dialog.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        final_save_dialog.getWindow().setAttributes(lp);
        final_save_dialog.setCancelable(false);
        final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes);
        Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel);
        Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay);
        btn_okay.setOnClickListener(v -> {
            if (txt_hint_yes.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Text");
            } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) {
                AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text");
            } else {
                new InsertAsync().execute();
                final_save_dialog.dismiss();
            }
        });


        btn_cancel.setOnClickListener(v -> final_save_dialog.dismiss());

        final_save_dialog.show();
    }


    @SuppressLint("StaticFieldLeak")
    class InsertAsync extends AsyncTask<Boolean, Void, Void> {
        private Dialog dialog = null;
        private ProgressBar pb = null;

        @Override
        protected void 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();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Boolean... bool) {
            savedManualInward();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.cancel();
            AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_saved_msg));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            if (CommonFunctions.checkNetIsAvailable(context)) CommonFunctions.call_upload(context);
            ManualInWardStockActivity.this.finish();
        }
    }

    private void savedManualInward() {
        ////final submit
        // invoice id is 0 for manual entry
        // counter confirm will zero in draft mode
        // invoice status is maintain to 0 till he/she save data as draft
        // here user can save data and data is synced with server
        String TransactionId = CommonFunctions.getUUID(context);
        String counterType = tCounterInvoiceObj.getInvoiceType();
        ///for new Manual inward Products list for insert
        boolean Newproduct = true;
        ArrayList<InvoiceGetterSetter> newproducts;
        ArrayList<InvoiceGetterSetter> existingproducts;
        newproducts = newinwardproduct_Checked(selected_list, Newproduct);
        Newproduct = false;
        existingproducts = newinwardproduct_Checked(selected_list, Newproduct);
        db.open();
        ////deleted record perticular invoice no..................
        db.deletemanualinwardbyInvoiceid(counter_id, visit_date, CommonFunctions.removed_special_char(invoice_number), counterType);
        if (!newproducts.isEmpty()) {
            db.open();
            Newproduct = true;
            db.insertManualInwardStockData(newproducts, counter_id, username,
                    CommonFunctions.removed_special_char(invoice_number), counterType,
                    invoice_date.getText().toString(), visit_date, str_img_invoice, TransactionId, Newproduct);
        }

        ///inserting for exsting product manual inward for interting
        TransactionId = CommonFunctions.getUUID(context);
        Newproduct = false;
        if (!existingproducts.isEmpty()) {
            db.open();
            db.insertManualInwardStockData(existingproducts, counter_id, username,
                    CommonFunctions.removed_special_char(invoice_number), counterType,
                    invoice_date.getText().toString(), visit_date, str_img_invoice, TransactionId, Newproduct);
        }
    }

    private ArrayList<InvoiceGetterSetter> newinwardproduct_Checked(ArrayList<InvoiceGetterSetter> selected_list, boolean flagfornewproduct) {
        ArrayList<InvoiceGetterSetter> nwproductlist = new ArrayList<>();
        if (!selected_list.isEmpty()) {
            for (int k = 0; k < selected_list.size(); k++) {
                db.open();
                TStockSummary stockObj = db.getTStockSummaryProductDetails(Integer.parseInt(selected_list.get(k).getProduct_Id()));
                if (flagfornewproduct) {
                    if (stockObj == null) {
                        nwproductlist.add(selected_list.get(k));
                    }
                } else {
                    if (stockObj != null && stockObj.getProductId() != null) {
                        nwproductlist.add(selected_list.get(k));
                    }
                }
            }
        }
        return nwproductlist;
    }


    private void saveUpdateAndUploadData() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context);
        builder.setCancelable(false).setTitle(R.string.dialog_title);
        builder.setMessage(R.string.save_data_msg_new).setCancelable(false)
                .setPositiveButton("OK", (dialog, id) -> {
                    show_dialog_for_final_submit(context);
                    dialog.dismiss();
                })
                .setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
        androidx.appcompat.app.AlertDialog alert = builder.create();
        alert.show();

    }

    private void saveDataInDraft() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context);
        builder.setCancelable(false).setTitle(R.string.dialog_title);
        builder.setMessage(R.string.save_draft_data_msg).setCancelable(false)
                .setPositiveButton("OK", (dialog, id) -> {
                    String counterType = tCounterInvoiceObj.getInvoiceType();
                    db.open();
                    // invoice id is 0 for manual entry
                    // counter confirm will zero in draft mode
                    // invoice status is maintain to 0 till he/she save data as draft
                    // here user can save data as draft but data is not synced with server
                    String invoice_status = "0", invoiceId = "0", counter_confirm = "0", draft_status = "1", source = "Manual";
                    long val = db.insertmanualinwardinDraft(selected_list, invoice_status, invoiceId, counter_confirm, draft_status, counter_id,
                            username, CommonFunctions.removed_special_char(invoice_number), counterType,
                            invoice_date.getText().toString(), source, visit_date, str_img_invoice);
                    if (val > 0) {
                        AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_saved_msg));
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        ManualInWardStockActivity.this.finish();
                    } else {
                        AlertandMessages.showToastMsg(context, getResources().getString(R.string.data_not_saved_msg));
                    }
                    dialog.dismiss();
                }).setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());

        androidx.appcompat.app.AlertDialog alert = builder.create();
        alert.show();
    }


    private boolean validateData() {
        boolean entryFlag = false;
        db.open();
        manualInwardStockList = db.getInsertedManualInwardStockData(counter_id, CommonFunctions.removed_special_char(invoice_number));
        if (invoice_number.getText().toString().isEmpty()) {
            Error_Msg = getResources().getString(R.string.invoice_number_error_msg);
        } else if (value.equalsIgnoreCase("add")) {
            if (!manualInwardStockList.isEmpty()) {
                Error_Msg = getResources().getString(R.string.duplicate_invoice_error_msg);
            } else {
                entryFlag = checkRestDataValidation();
            }
        } else {
            entryFlag = checkRestDataValidation();
        }
        return entryFlag;
    }

    private boolean checkRestDataValidation() {
        boolean flag = false;
        if (tCounterInvoiceObj.getInvoiceType().isEmpty()) {
            Error_Msg = getResources().getString(R.string.invoice_type_error_msg);
        } else if (invoice_date.getText().toString().isEmpty()) {
            Error_Msg = getResources().getString(R.string.invoice_date_error_msg);
        } else if (str_img_invoice.isEmpty()) {
            Error_Msg = getResources().getString(R.string.invoice_img_error_msg);
        } else if (selected_list.isEmpty()) {
            Error_Msg = getResources().getString(R.string.sku_error_msg);
        } else if (validateListData(selected_list)) {
            flag = true;
        } else {
            flag = false;
        }

        return flag;
    }

    private boolean validateListData(ArrayList<InvoiceGetterSetter> selected_list) {
        flag = true;
        for (int i = 0; i < selected_list.size(); i++) {
            if (selected_list.get(i).getViewMode().equals("1")) {
                if (!selected_list.get(i).isConfirmChecked()) {
                    Error_Msg = getResources().getString(R.string.edit_confirmation);
                    flag = false;
                    break;
                } else {
                    if (Integer.parseInt(selected_list.get(i).getActualQty()) < Integer.parseInt(selected_list.get(i).getQuantity())) {
                        if (selected_list.get(i).getReasonId() == 0) {
                            Error_Msg = getResources().getString(R.string.error_reason);
                            flag = false;
                            break;
                        } else {
                            flag = true;
                        }
                    } else {
                        flag = true;
                    }
                }
            } else {
                if (Integer.parseInt(selected_list.get(i).getActualQty()) < Integer.parseInt(selected_list.get(i).getQuantity())) {
                    if (selected_list.get(i).getReasonId() == 0) {
                        Error_Msg = getResources().getString(R.string.error_reason);
                        flag = false;
                        break;
                    } else {
                        flag = true;
                    }
                } else {
                    flag = true;
                }
            }
        }

        return flag;
    }


    @SuppressLint("SetTextI18n")
    private void show_dialog_forsku_categorywise(final Context context) {
        minteger = 0;
        final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.custom_sku_list_with_category);
        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);
        ///new changes 19 aug
        final Spinner dialog_brand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_brand_spin);
        final Spinner dialog_subbrand_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_subbrand_spin);
        final Spinner dialog_reference_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_reference_spin);
        final Spinner dialog_product_spin = (Spinner) multiPurposeDialog.findViewById(R.id.dialog_product_spin);
        final EditText et_search = (EditText) multiPurposeDialog.findViewById(R.id.et_search);
        final TextView stock_text_value = (TextView) multiPurposeDialog.findViewById(R.id.stock_text_value);
        final Button stock_img_minus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_minus);
        Button stock_img_plus = (Button) multiPurposeDialog.findViewById(R.id.stock_img_plus);
        ImageView cancet_btn = (ImageView) multiPurposeDialog.findViewById(R.id.cancet_btn);
        final ImageView btn_add = (ImageView) multiPurposeDialog.findViewById(R.id.btn_add);
        final LinearLayout rl_return_reason = (LinearLayout) multiPurposeDialog.findViewById(R.id.rl_return_reason);
        rl_return_reason.setVisibility(View.GONE);
        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();
                setSearchFilter(dialog_product_list, text, dialog_product_spin);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
            }
        });
        db.open();
        validate_spin_ui_data(dialog_brand_spin, dialog_subbrand_spin, dialog_reference_spin, dialog_product_spin,
                db.getproductdata_formanual_inwarddialog("BrandName", "BrandId"),
                db.getproductdata_formanual_inwarddialog("SubBrandName", "SubBrandId"),
                db.getproductdata_formanual_inwarddialog("ReferenceName", "ReferenceId"),
                db.getbrand_wise_sku_fromproductformanual(), stock_text_value);
        cancet_btn.setOnClickListener(v -> multiPurposeDialog.dismiss());
        stock_img_plus.setOnClickListener(v -> {
            minteger = minteger + 1;
            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);
            }
        });

        btn_add.setOnClickListener(v -> {
            ((ManualInWardStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (dialog_product_spin.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Product");
            } else if (stock_text_value.getText().toString().equals("0")) {
                AlertandMessages.showToastMsg(context, "Quantity must be greater than zero");
            } else {
                // get selected radio button from radioGroup
                // find the radiobutton by returned id
                object = new InvoiceGetterSetter();
                if (checkduplicate_entry(product_Id, product_mrp)) {
                    object.setProduct_rate(product_mrp);
                    object.setProduct(product_name);
                    object.setProduct_Id(product_Id);
                    object.setScan_ean_code_or_enterd_ean_code(product_scan_code);
                    object.setQuantity(stock_text_value.getText().toString());
                    object.setActualQty(stock_text_value.getText().toString());
                    object.setDraft_status("0");
                    object.setViewMode(CommonString.ADD_NEW_ITEM_FROM_OPTION);
                    selected_list.add(object);
                    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";
                    adapter = new ValueAdapter(context, selected_list);
                    drawer_layout_recycle_store.setAdapter(adapter);
                    drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                    multiPurposeDialog.dismiss();
                    txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty());
                    txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty());
                }
            }
        });
        multiPurposeDialog.show();
    }


    private void
    validate_spin_ui_data(final Spinner dialog_brand_spin, final Spinner dialog_sub_brand_spin,
                          final Spinner dialog_franchise_spin, final Spinner dialog_product_spin, final ArrayList<ProductMaster> brandList,
                          final ArrayList<ProductMaster> subbrandList,
                          final ArrayList<ProductMaster> referenceList,
                          final ArrayList<ProductMaster> productList, final TextView stock_text_value) {

        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);
        setSubBrandSpinnerData(subbrandList, dialog_sub_brand_spin);
        setReferenceSpinnerData(referenceList, dialog_franchise_spin);
        setProductSpinnerData(productList, dialog_product_spin);
        dialog_brand_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos != 0) {
                    db.open();
                    flag_for_filter = true;
                    flag_filter_by_edt = false;
                    try {
                        dialog_brand_Id = adapterView.getSelectedItem().toString();
                        Log.d("spinner_error", dialog_brand_Id);
                        setFilter(FILTER_FOR_BRAND, dialog_product_spin);
                        setSubBrandSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "SubBrandName", "SubBrandId",
                                "BrandName", null, visit_date, counter_id, false, null), dialog_sub_brand_spin);
                        setReferenceSpinnerData(db.getsub_brand_using_brand_Id(dialog_brand_Id, "ReferenceName", "ReferenceId",
                                "BrandName", null, visit_date, counter_id, false, null), dialog_franchise_spin);
                    } catch (Exception e) {
                        Log.d("spinner_ex", e.getMessage());
                        throw new RuntimeException(e);
                    }
                } else {
                    dialog_brand_Id = "";
                    if (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) {
                    db.open();
                    flag_for_filter = true;
                    flag_filter_by_edt = false;
                    try {
                        dialog_sub_brand_Id = adapterView.getSelectedItem().toString();
                        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, counter_id, false, null), dialog_franchise_spin);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    dialog_sub_brand_Id = "";
                    if (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) {
                    flag_for_filter = true;
                    flag_filter_by_edt = false;
                    try {
                        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_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() {
            @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();
                            stock_text_value.setText("1");
                            minteger = 1;
                        } else if (flag_for_filter) {
                            product_name = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductName();
                            product_Id = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getProductId().toString();
                            product_mrp = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getMrp().toString();
                            product_scan_code = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id).get(position - 1).getEanCode();
                            stock_text_value.setText("1");
                            minteger = 1;
                        } 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();
                            stock_text_value.setText("1");
                            minteger = 1;
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    stock_text_value.setText("0");
                    product_scan_code = "";
                    product_mrp = "0";
                    product_name = "";
                    product_Id = "0";
                    minteger = 0;
                }
            }

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

            }
        });

    }


    private void setSubBrandSpinnerData(ArrayList<ProductMaster> axeList, Spinner dialog_sub_brand_spin) {
        dialog_sub_brand_adapter = new ArrayAdapter<>(this, 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);
    }


    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) {
        dialog_sku_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        dialog_sku_adapter.add("- Select Product -");

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


    public void setFilter(int filterType, Spinner dialog_spin) {
        List<ProductMaster> filteredList = new ArrayList<>();

        // Filter only once based on type
        switch (filterType) {
            case FILTER_FOR_BRAND:
                filteredList = filterListForBrand(dialog_product_list, dialog_brand_Id);
                break;
            case FILTER_FOR_SUB_BRAND:
                filteredList = filterListForSubBrand(dialog_product_list, dialog_sub_brand_Id, dialog_brand_Id);
                break;
            case FILTER_FOR_REFERENCE_NAME:
                filteredList = filterListForReferencename(dialog_product_list, dialog_reference_Id, dialog_brand_Id, dialog_sub_brand_Id);
                break;
            default:
                filteredList = dialog_product_list;
                break;
        }

        // Prepare display strings
        List<String> displayList = new ArrayList<>();
        displayList.add("- Select Product -"); // default item
        for (ProductMaster product : filteredList) {
            displayList.add(product.getProductName() + " - (MRP-" + product.getMrp() + ")");
        }

        // Set adapter
        dialog_sku_adapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        dialog_sku_adapter.addAll(displayList);
        dialog_sku_adapter.setDropDownViewResource(R.layout.spinner_custom_item);
        dialog_spin.setAdapter(dialog_sku_adapter);
    }


    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) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            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;
    }

    private void show_proforma_dialog(final Context context, final boolean flag_for_rl) {
        minteger = 0;
        dialog_final = new MultiPurposeDialog(context);
        dialog_final.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog_final.setContentView(R.layout.custom_bar_code_dialog);
        dialog_final.setCancelable(false);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(dialog_final.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialog_final.getWindow().setAttributes(lp);
        dialog_final.setCancelable(false);

        LinearLayout rl_bar_code = (LinearLayout) dialog_final.findViewById(R.id.rl_bar_code);
        LinearLayout RL_scan_code = (LinearLayout) dialog_final.findViewById(R.id.RL_scan_code);
        Button check_exist_sku = (Button) dialog_final.findViewById(R.id.check_exist_sku);
        TextView txt_bar_code = dialog_final.findViewById(R.id.txt_bar_code);
        TextView txt_enterbar_code = dialog_final.findViewById(R.id.txt_enterbar_code);

        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) dialog_final.findViewById(R.id.qrcode_text);
        edt_scan_code = (EditText) dialog_final.findViewById(R.id.edt_scan_code);
        stock_text_value = (TextView) dialog_final.findViewById(R.id.stock_text_value);
        ImageView img_bar_code = (ImageView) dialog_final.findViewById(R.id.img_bar_code);
        ImageView cancet_btn = (ImageView) dialog_final.findViewById(R.id.cancet_btn);

        cancet_btn.setOnClickListener(v -> dialog_final.dismiss());

        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(), false, visit_date, counter_id, null);
                if (productList.isEmpty()) {
                    db.open();
                    productList = db.getsku_fromproductusing_eancode(removeFirstChar(edt_scan_code.getText().toString()), false, visit_date, counter_id, null);
                }
                if (productList.isEmpty()) {
                    edt_scan_code.setText("");
                    AlertandMessages.showToastMsg(context, "Invalid Bar Code.Please try again");
                } else {
                    show_dialog_forsku(context, productList);
                }
            }
        });

        img_bar_code.setOnClickListener(v -> openScanner());
        dialog_final.show();
    }

    private class AdapterforSku extends RecyclerView.Adapter<AdapterforSku.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;
        MultiPurposeDialog multiPurposeDialog;

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

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

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final AdapterforSku.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            final ProductMaster current = data.get(position);
            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.stock_img_plus.setId(position);
            holder.stock_img_plus.setOnClickListener(v -> {
                if (checkduplicate_entry(current.getProductId().toString(), current.getMrp().toString())) {
                    int value = 0;
                    if (!current.getActualQty().isEmpty()) {
                        value = Integer.parseInt(current.getActualQty());
                    }
                    value = value + 1;
                    holder.edt_stock_text_value.setText("" + value);
                    holder.edt_stock_text_value.setId(position);
                    current.setActualQty("" + value);
                }
            });
            holder.stock_img_minus.setId(position);
            holder.stock_img_minus.setOnClickListener(v -> {
                int value = 0;
                if (!current.getActualQty().isEmpty()) {
                    value = Integer.parseInt(current.getActualQty());
                }
                if (value == 0) {
                    AlertandMessages.showToastMsg(context, "Product quantity should not be less than Zero");
                } else {
                    value = value - 1;
                    holder.edt_stock_text_value.setText("" + value);
                    holder.edt_stock_text_value.setId(position);
                    current.setActualQty("" + value);
                }
            });


            holder.edt_stock_text_value.setOnFocusChangeListener((view, b) -> {
                final EditText Caption = (EditText) view;
                String value = Caption.getText().toString().replaceFirst("^0+(?!$)", "");
                if (value.isEmpty()) {
                    current.setActualQty("0");
                    holder.edt_stock_text_value.setText("0");
                    holder.edt_stock_text_value.setId(position);
                } else {
                    current.setActualQty(value);
                    holder.edt_stock_text_value.setText(value);
                    holder.edt_stock_text_value.setId(position);
                }
            });
            if (current.getActualQty().isEmpty()) {
                holder.edt_stock_text_value.setText("0");
                holder.edt_stock_text_value.setId(position);
            } else {
                holder.edt_stock_text_value.setText(current.getActualQty());
                holder.edt_stock_text_value.setId(position);
            }
        }


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

        class MyViewHolder extends RecyclerView.ViewHolder {
            CardView sale_card;
            LinearLayout rl_quantity;
            // CheckBox check_inword_item;
            Button stock_img_minus, stock_img_plus;
            TextView sale_trcking_name;
            EditText edt_stock_text_value;


            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
                edt_stock_text_value = (EditText) itemView.findViewById(R.id.edt_stock_text_value);
                stock_img_plus = (Button) itemView.findViewById(R.id.stock_img_plus);
                stock_img_minus = (Button) itemView.findViewById(R.id.stock_img_minus);
                rl_quantity = (LinearLayout) itemView.findViewById(R.id.rl_quantity);
            }
        }
    }


    private boolean checkduplicate_entry(String product_Id, String product_mrp) {
        boolean status = true;
        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)) {
                    AlertandMessages.showToastMsg(context, "This Product Already Exists In The Current Invoice");
                    status = false;
                    break;
                }
            }
        }

        return status;
    }


    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 class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<InvoiceGetterSetter> selected_list;

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

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

        @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
        @Override
        public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            final int quantity = Integer.parseInt(selected_list.get(position).getQuantity());
            holder.text_item.setText(selected_list.get(position).getProduct() + "( MRP - ₹ " + selected_list.get(position).getProduct_rate() + ")");
            holder.invoice_qty.setText(selected_list.get(position).getQuantity());
            holder.actual_qty.setText(selected_list.get(position).getActualQty());

            if (!selected_list.get(position).getInvoice_status().equals("1")) {
                if (value.equalsIgnoreCase("add")) {
                    defaultElementVisibility(holder);
                } else {
                    if (selected_list.get(position).getViewMode().equalsIgnoreCase(CommonString.ADD_NEW_ITEM_FROM_OPTION)) {
                        defaultElementVisibility(holder);
                    } else if (selected_list.get(position).getViewMode().equalsIgnoreCase(CommonString.KEY_DISABLE_EDIT_MODE)) {
                        holder.edit_existing_product.setVisibility(View.GONE);
                        holder.delete_added_product.setVisibility(View.GONE);
                        holder.cancel_product.setVisibility(View.VISIBLE);
                        holder.confirmation_check.setVisibility(View.VISIBLE);
                        if (!value.isEmpty() && value.equalsIgnoreCase("edit")) {
                            holder.delete_added_product.setVisibility(View.VISIBLE);
                        }

                        enableElement(holder);
                    } else if (selected_list.get(position).getViewMode().equalsIgnoreCase(CommonString.KEY_ENABLE_EDIT_MODE)) {
                        holder.confirmation_check.setChecked(false);
                        selected_list.get(position).setConfirmChecked(false);
                        holder.delete_added_product.setVisibility(View.GONE);
                        holder.cancel_product.setVisibility(View.GONE);
                        holder.confirmation_check.setVisibility(View.GONE);
                        holder.edit_existing_product.setVisibility(View.VISIBLE);
                        if (!value.isEmpty() && value.equalsIgnoreCase("edit")) {
                            holder.delete_added_product.setVisibility(View.VISIBLE);
                        }
                        disablElement(holder);
                    } else {
                        holder.delete_added_product.setVisibility(View.VISIBLE);
                        holder.edit_existing_product.setVisibility(View.VISIBLE);
                        disablElement(holder);
                    }
                }
            } else {
                holder.confirmation_check.setChecked(false);
                selected_list.get(position).setConfirmChecked(false);
                holder.delete_added_product.setVisibility(View.GONE);
                holder.cancel_product.setVisibility(View.GONE);
                holder.confirmation_check.setVisibility(View.GONE);
                holder.edit_existing_product.setVisibility(View.VISIBLE);
                if (!value.isEmpty() && value.equalsIgnoreCase("edit")) {
                    holder.delete_added_product.setVisibility(View.VISIBLE);
                }
                disablElement(holder);
            }

            holder.edit_existing_product.setOnClickListener(view -> {
                selected_list.get(position).setViewMode(CommonString.KEY_DISABLE_EDIT_MODE);
                if (!value.isEmpty() && value.equalsIgnoreCase("edit")) {
                    holder.delete_added_product.setVisibility(View.VISIBLE);
                }
                holder.edit_existing_product.setVisibility(View.GONE);
                holder.confirmation_check.setVisibility(View.VISIBLE);
                holder.cancel_product.setVisibility(View.VISIBLE);
                notifyDataSetChanged();
            });

            holder.cancel_product.setOnClickListener(view -> {
                selected_list.get(position).setViewMode(CommonString.KEY_ENABLE_EDIT_MODE);
                holder.cancel_product.setVisibility(View.GONE);
                holder.confirmation_check.setVisibility(View.GONE);
                if (!value.isEmpty() && value.equalsIgnoreCase("edit")) {
                    holder.delete_added_product.setVisibility(View.VISIBLE);
                }
                selected_list.get(position).setActualQty(selected_list2.get(position).getActualQty());
                selected_list.get(position).setReasonId(selected_list2.get(position).getReasonId());
                notifyDataSetChanged();

            });

            holder.stock_img_plus.setOnClickListener(v -> {
                notifyDataSetChanged();
                int minteger = Integer.parseInt(selected_list.get(position).getActualQty());
                ++minteger;
                if (minteger < quantity) {
                    selected_list.get(position).setActualQty(String.valueOf(minteger));
                } else if (minteger == quantity) {
                    selected_list.get(position).setActualQty(String.valueOf(minteger));
                    holder.reasonSpinner.setSelection(0);
                    selected_list.get(position).setReasonId(0);
                    holder.reasonLayout.setVisibility(View.GONE);
                } else {
                    AlertandMessages.showToastMsg(context, "Actual quantity cannot be greater than invoice quantity.");
                }
            });

            reasonList = new ArrayList<>();
            db.open();
            reasonList = db.getReasonData(false);
            holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(context, R.layout.spinner_text_view, reasonList));
            holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                    if (pos == 0) {
                        selected_list.get(position).setReasonId(0);
                    } else {
                        if (pos < reasonList.size())
                            selected_list.get(position).setReasonId(reasonList.get(pos).getReasonId());
                    }
                }

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


            if (Integer.parseInt(selected_list.get(position).getActualQty()) < quantity) {
                if (selected_list.get(position).getReasonId() == 0) {
                    holder.reasonSpinner.setSelection(0);
                } else {
                    if (!reasonList.isEmpty()) {
                        for (int k = 0; k < reasonList.size(); k++) {
                            if (selected_list.get(position).getReasonId() == reasonList.get(k).getReasonId()) {
                                holder.reasonSpinner.setSelection(k);
                                break;
                            }
                        }
                    }
                }
                holder.reasonLayout.setVisibility(View.VISIBLE);
            } else {
                holder.reasonLayout.setVisibility(View.GONE);
            }

            holder.stock_img_minus.setOnClickListener(v -> {
                notifyDataSetChanged();
                int minteger = Integer.parseInt(selected_list.get(position).getActualQty());
                --minteger;
                if (minteger >= 0) {
                    holder.reasonLayout.setVisibility(View.VISIBLE);
                    selected_list.get(position).setActualQty(String.valueOf(minteger));
                } else {
                    AlertandMessages.showToastMsg(context, "Actual quantity cannot be less than 0");
                }
            });


            if (Integer.parseInt(selected_list.get(position).getActualQty()) < Integer.parseInt(selected_list.get(position).getQuantity())) {
                holder.actual_qty.setTextColor(Color.RED);
            } else {
                holder.actual_qty.setTextColor(Color.BLACK);
            }

            holder.actual_qty.setText(selected_list.get(position).getActualQty());

            holder.invoice_qty.setText(selected_list.get(position).getQuantity());

            holder.confirmation_check.setOnCheckedChangeListener((compoundButton, b) -> {
                if (compoundButton.isPressed()) {
                    selected_list.get(position).setConfirmChecked(compoundButton.isChecked());
                    adapter.notifyDataSetChanged();
                }
            });

            holder.delete_added_product.setOnClickListener(v -> {
                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",
                                (dialog, id) -> {
                                    if (value.equalsIgnoreCase("edit")) {
                                        if (selected_list.get(position).getKeyId() != null) {
                                            db.open();
                                            db.deleteManualStockWithKeyIdData(counter_id, visit_date, selected_list.get(position).getKeyId());
                                            selected_list2.remove(position);
                                        }
                                    }

                                    selected_list.remove(position);
                                    if (!selected_list.isEmpty()) {
                                        adapter = new ValueAdapter(context, selected_list);
                                        drawer_layout_recycle_store.setAdapter(adapter);
                                        notifyDataSetChanged();
                                    }

                                    txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty());
                                    txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty());

                                    notifyDataSetChanged();
                                })
                        .setNegativeButton("No",
                                (dialog, id) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            });

            if (tCounterInvoice != null && tCounterInvoice.getUpload_status() != null && !tCounterInvoice.getUpload_status().isEmpty() &&
                    tCounterInvoice.getUpload_status().equalsIgnoreCase(CommonString.KEY_U) || tCounterInvoice != null && tCounterInvoice.getTransactionId() != null
                    && !tCounterInvoice.getTransactionId().isEmpty()) {
                holder.edit_existing_product.setVisibility(View.GONE);
                holder.edit_existing_product.setId(position);
                holder.confirmation_check.setVisibility(View.GONE);
                holder.confirmation_check.setId(position);
                holder.cancel_product.setVisibility(View.GONE);
                holder.cancel_product.setId(position);
                holder.delete_added_product.setVisibility(View.GONE);
                holder.delete_added_product.setId(position);
            }

        }

        private void disablElement(MyViewHolder holder) {
            holder.stock_img_plus.setEnabled(false);
            holder.reasonSpinner.setEnabled(false);
            holder.stock_img_minus.setEnabled(false);
        }

        private void enableElement(MyViewHolder holder) {
            holder.stock_img_plus.setEnabled(true);
            holder.reasonSpinner.setEnabled(true);
            holder.stock_img_minus.setEnabled(true);
        }

        private void defaultElementVisibility(MyViewHolder holder) {
            holder.delete_added_product.setVisibility(View.VISIBLE);
            holder.edit_existing_product.setVisibility(View.GONE);
            holder.cancel_product.setVisibility(View.GONE);
            holder.confirmation_check.setVisibility(View.GONE);
            holder.stock_img_plus.setEnabled(true);
            holder.reasonSpinner.setEnabled(true);
            holder.stock_img_minus.setEnabled(true);
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView text_item;
            TextView actual_qty, invoice_qty;
            Button stock_img_plus, stock_img_minus;
            Spinner reasonSpinner;
            LinearLayout reasonLayout;
            CheckBox confirmation_check;
            CardView card_view;
            ImageView delete_added_product, edit_existing_product, cancel_product;

            public MyViewHolder(View itemView) {
                super(itemView);
                text_item = (TextView) itemView.findViewById(R.id.manual_brand_name);
                actual_qty = (TextView) itemView.findViewById(R.id.manual_actual_qty);
                stock_img_plus = (Button) itemView.findViewById(R.id.manual_stock_img_plus);
                stock_img_minus = (Button) itemView.findViewById(R.id.manual_stock_img_minus);
                invoice_qty = (TextView) itemView.findViewById(R.id.manual_invoice_qty);
                reasonSpinner = (Spinner) itemView.findViewById(R.id.manual_reason_spinner);
                reasonLayout = (LinearLayout) itemView.findViewById(R.id.manual_reason_layout);
                delete_added_product = (ImageView) itemView.findViewById(R.id.manual_delete_added_product);
                edit_existing_product = (ImageView) itemView.findViewById(R.id.manual_edit_product);
                cancel_product = (ImageView) itemView.findViewById(R.id.manual_cancel_product);
                confirmation_check = (CheckBox) itemView.findViewById(R.id.confirm_check);
                card_view = (CardView) itemView.findViewById(R.id.card_view);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result == null) {
            switch (resultCode) {
                case 0:
                    Log.i("MakeMachine", "User cancelled");
                    break;
                case -1:
                    try {
                        if (_pathforcheck != null && !_pathforcheck.isEmpty()) {
                            if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                                convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                                invoice_img.setImageResource(R.mipmap.camera_bsd);
                                str_img_invoice = _pathforcheck;
                                _pathforcheck = "";
                            }
                        }
                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }
                    break;
            }
        } else {
            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(), false, visit_date, counter_id, null);
                if (productList.isEmpty()) {
                    db.open();
                    productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null);
                }
                if (!productList.isEmpty()) {
                    show_dialog_forsku(context, productList);
                } else {
                    product_name = "";
                    product_scan_code = "";
                    qrcode_text.setText("");
                    AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again.");
                }
            }

        }
    }

    void isChanged() {
        if (isDataAdded) {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
            builder.setTitle(getString(R.string.parinaam));
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
                        dialog.dismiss();
                    });
            android.app.AlertDialog alert = builder.create();
            alert.show();
        } else {
            super.onBackPressed();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    @Override
    public void onBackPressed() {
        isChanged();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            isChanged();
        }
        return super.onOptionsItemSelected(item);
    }


    ////sku scannnnnnnnnnnn
    @SuppressLint("SetTextI18n")
    private void show_dialog_forsku(final Context context, final ArrayList<ProductMaster> skuList_with_eancode) {
        final MultiPurposeDialog dialog_custom = new MultiPurposeDialog(context);
        dialog_custom.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog_custom.setContentView(R.layout.custom_sku_adapter);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(Objects.requireNonNull(dialog_custom.getWindow()).getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialog_custom.getWindow().setAttributes(lp);
        dialog_custom.setCancelable(false);
        ((ManualInWardStockActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        TextView sale_trcking_name = (TextView) dialog_custom.findViewById(R.id.sale_trcking_name);
        sale_trcking_name.setText(skuList_with_eancode.get(0).getProductName());
        RecyclerView recycl_sku = (RecyclerView) dialog_custom.findViewById(R.id.recycl_sku);
        recycl_sku.setAdapter(new AdapterforSku(context, skuList_with_eancode, dialog_custom));
        recycl_sku.setLayoutManager(new LinearLayoutManager(context));
        ImageView dismiss_dialog = (ImageView) dialog_custom.findViewById(R.id.dismiss_dialog);
        Button btn_submit = (Button) dialog_custom.findViewById(R.id.btn_submit);
        btn_submit.setVisibility(View.VISIBLE);

        dismiss_dialog.setOnClickListener(v -> dialog_custom.dismiss());

        btn_submit.setOnClickListener(view -> {
            if (validate_entered_data(skuList_with_eancode)) {
                for (int k = 0; k < skuList_with_eancode.size(); k++) {
                    if (!skuList_with_eancode.get(k).getActualQty().isEmpty() && !skuList_with_eancode.get(k).getActualQty().equals("0")) {
                        object = new InvoiceGetterSetter();
                        object.setDraft_status("0");
                        object.setStore_name(store_name);
                        object.setBrandName(dialog_brand);
                        object.setStore_address(store_address);
                        object.setSubBrandName(dialog_sub_brand);
                        object.setReferenceName(dialog_reference);
                        object.setDemo_given_str(demo_given_str);
                        object.setProduct_sold_str(product_sold_str);
                        object.setViewMode(CommonString.ADD_NEW_ITEM_FROM_OPTION);

                        object.setQuantity(skuList_with_eancode.get(k).getActualQty());
                        object.setActualQty(skuList_with_eancode.get(k).getActualQty());
                        object.setProduct(skuList_with_eancode.get(k).getProductName());
                        object.setProduct_Id(skuList_with_eancode.get(k).getProductId().toString());
                        object.setProduct_rate(skuList_with_eancode.get(k).getMrp().toString());
                        object.setScan_ean_code_or_enterd_ean_code(skuList_with_eancode.get(k).getEanCode());
                        selected_list.add(object);
                    }
                }

                adapter = new ValueAdapter(context, selected_list);
                drawer_layout_recycle_store.setAdapter(adapter);
                drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
                dialog_final.cancel();
                dialog_custom.cancel();
                txt_invoice_qty.setText("Invoice QTY : " + calculate_invoice_qty());
                txt_actual_qty.setText("Actual QTY : " + calculate_actual_qty());
            } else {
                AlertandMessages.showToastMsg(context, "Please Add Atleast One Product, And Please Increase Quantity Of Product");
            }
        });
        dialog_custom.show();
    }


    public void setSearchFilter(ArrayList<ProductMaster> originalList, String text, Spinner dialog_product_spin) {
        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;
        }
        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();
    }

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


    private boolean validate_entered_data(ArrayList<ProductMaster> skuList_with_eancode) {
        boolean status = false;
        for (int k = 0; k < skuList_with_eancode.size(); k++) {
            if (!skuList_with_eancode.get(k).getActualQty().isEmpty() && !skuList_with_eancode.get(k).getActualQty().equals("0")) {
                status = true;
                break;
            }
        }

        return status;
    }

    private int calculate_invoice_qty() {
        int total_invoice_qty = 0;
        if (!selected_list.isEmpty()) {
            for (int i = 0; i < selected_list.size(); i++) {
                if (selected_list.get(i).getActualQty() != null && !selected_list.get(i).getActualQty().isEmpty()) {
                    total_invoice_qty = total_invoice_qty + Integer.parseInt(selected_list.get(i).getActualQty());
                }
            }
        }

        return total_invoice_qty;
    }

    private int calculate_actual_qty() {
        int total_actual_qty = 0;
        if (!selected_list.isEmpty()) {
            for (int i = 0; i < selected_list.size(); i++) {
                if (selected_list.get(i).getQuantity() != null && !selected_list.get(i).getQuantity().isEmpty()) {
                    total_actual_qty = total_actual_qty + Integer.parseInt(selected_list.get(i).getQuantity());
                }
            }
        }

        return total_actual_qty;
    }

}
