package com.cpm.lorealbaMabeline.competitionoffer;

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
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.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
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.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.databinding.CompetitionOfferBaDetailBinding;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gettersetter.BaTenureDetail;
import com.cpm.lorealbaMabeline.gettersetter.MasterCompetitionOffer;
import com.cpm.lorealbaMabeline.gettersetter.MasterCompetitionOfferSaleRange;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterCompetitionOfferGet;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterCompetitionOfferSet;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterCompetitionProductType;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterCompetitionPromoType;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterCompetitonBrandWiseNuance;

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

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class CompetitionOfferActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    Lorealba_Database db;
    Context context;
    SharedPreferences preferences;
    String counter_id, visit_date, username, _pathforcheck, _path;
    double tvapercent = 0.0;
    double avgtarget = 0.0;
    double avgofftake = 0.0;
    ArrayAdapter<CharSequence> companyAdapter, nuanceAdapter, promoTypeAdapter, comOfferSetAdapter, comOfferGetAdapter, dataForMonthAdapter, productTypeAdapter,
            compOfferSaleAdapter, spinBuyTypeAdapter, spinbuyTypeInputAdapter, spingetTypeInputAdapter;
    ArrayList<MasterCompetitonBrandWiseNuance> companies, nuances = new ArrayList<>();
    ArrayList<MasterCompetitionPromoType> competitionPromoTypes = new ArrayList<>();
    ArrayList<MasterCompetitionOfferSaleRange> competitionOfferSaleRange = new ArrayList<>();
    ArrayList<MasterCompetitionOfferSet> competitionOfferSets = new ArrayList<>();
    ArrayList<MasterCompetitionOfferGet> competitionOfferGets = new ArrayList<>();
    ArrayList<MasterCompetitionProductType> productTypes = new ArrayList<>();
    ArrayList<MasterCompetitionOffer> competitionOfferType, competitionBuyType, competitionBuyTypeInput, competitionGetTypeInput = new ArrayList<>();
    ArrayList<MasterCompetitonBrandWiseNuance> insertList = new ArrayList<>();
    ImageView img_FromDate, img_toDate, imgComoOffer, img_button_yes, img_button_no;
    Spinner spinCompany, spinNuance, spinPromoType, spinBuy, spinPromoGet, spinProductType, spinDataforMonth, spingwp;
    EditText edtPromotionDetails, edtBuyQTY, edtGetQTY, avgOfftakeET, tvapercentET, avgTargetET;
    NestedScrollView scroll_view;
    TextView tvFromDate, tvToDate;
    CompOfferAdapter compOfferAdapter;
    FloatingActionButton btn_add, fab_save;
    RecyclerView recyclCompDetails;
    LinearLayout ll_hide;

    String compofferdata = "", spinbuyTypedata = "", spinbuyTypeInputData = "", spingetTypeInputData = "", counterData = "", noOfBa = "", saleRange = "", gwpstatus = "";
    int compOfferId = 0, spinbuyTypeId = 0, spinbuyTypeInputId = 0, spingetTypeInputId = 0, saleRangeId = 0;
    EditText edtNewLaunchMrp;
    String gwpAvailable = "";


    String company = "", nounce_str = "", promoType = "", compOfferset = "", compOfferGet = "",
            present_or_not = "", img_comp_offer = "", productType = "", img_gwp = "";
    int companyId = 0, nuanceId = 0, promoTypeId = 0, compOfferSetId = 0, compOfferGetId = 0, productTypeId = 0;
    boolean ischanged = false, compOfferaddflag = false, ShowProductTypeDropdown = true;
    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    private final List<List<EditText>> allBAEditTexts = new ArrayList<>();

    //New Competition Offer Module

    String[] noofcounter = {"Select", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
    String[] noofba = {"Select", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
    String[] spngwpdata = {"Select", "Yes", "No"};
    Spinner spincounter, spinba, spinmonthlysale, spinbuyType, spinbuytypeinput, spinGetTypeInput;

    LinearLayout containerBAViews;
    ImageView gwpIV;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_competition_offer);
        context = this;
        db = new Lorealba_Database(context);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        validateUIData();
        SetSpinnerData();
        setDataToListView();
        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);
    }

    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, "");
        containerBAViews = findViewById(R.id.containerBAViews);
        gwpIV = findViewById(R.id.gwpIV);
        spingwp = findViewById(R.id.spingwp);

        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("Competition Intelligence - " + visit_date);
        scroll_view = (NestedScrollView) findViewById(R.id.scroll_view);
        img_button_yes = (ImageView) findViewById(R.id.img_button_yes);
        img_button_no = (ImageView) findViewById(R.id.img_button_no);
        imgComoOffer = (ImageView) findViewById(R.id.imgComoOffer);
        img_FromDate = (ImageView) findViewById(R.id.img_FromDate);
        img_toDate = (ImageView) findViewById(R.id.img_toDate);

        avgTargetET = findViewById(R.id.avgTargetET);
        avgOfftakeET = findViewById(R.id.avgOfftakeET);
        tvapercentET = findViewById(R.id.tvapercentET);

        spinPromoType = (Spinner) findViewById(R.id.spinPromoType);
        spinPromoGet = (Spinner) findViewById(R.id.spinPromoGet);
        spinCompany = (Spinner) findViewById(R.id.spinCompany);
        spinNuance = (Spinner) findViewById(R.id.spinNuance);
        spinBuy = (Spinner) findViewById(R.id.spinBuy);
        spinDataforMonth = (Spinner) findViewById(R.id.spinDataforMonth);
        //New Ravi
        spincounter = (Spinner) findViewById(R.id.spincounter);
        spinba = (Spinner) findViewById(R.id.spinba);
        spinmonthlysale = (Spinner) findViewById(R.id.spinmonthlysale);
        spinbuyType = (Spinner) findViewById(R.id.spinbuyType);
        spinbuytypeinput = (Spinner) findViewById(R.id.spinbuytypeinput);
        spinGetTypeInput = (Spinner) findViewById(R.id.spinGetTypeInput);
        edtNewLaunchMrp = (EditText) findViewById(R.id.edtNewLaunchMrp);
        //

        spinDataforMonth = (Spinner) findViewById(R.id.spinDataforMonth);
        spinDataforMonth = (Spinner) findViewById(R.id.spinDataforMonth);

        tvToDate = (TextView) findViewById(R.id.tvToDate);
        tvFromDate = (TextView) findViewById(R.id.tvFromDate);
        edtPromotionDetails = (EditText) findViewById(R.id.edtPromotionDetails);
        edtBuyQTY = (EditText) findViewById(R.id.edtBuyQTY);
        edtGetQTY = (EditText) findViewById(R.id.edtGetQTY);
        edtBuyQTY.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                | InputType.TYPE_NUMBER_FLAG_SIGNED);
        edtGetQTY.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                | InputType.TYPE_NUMBER_FLAG_SIGNED);
        btn_add = (FloatingActionButton) findViewById(R.id.btn_add);
        fab_save = (FloatingActionButton) findViewById(R.id.fab_save);

        recyclCompDetails = (RecyclerView) findViewById(R.id.recyclCompDetails);
        ll_hide = (LinearLayout) findViewById(R.id.ll_hide);

        img_FromDate.setOnClickListener(this);
        img_toDate.setOnClickListener(this);
        imgComoOffer.setOnClickListener(this);
        gwpIV.setOnClickListener(this);
        img_button_yes.setOnClickListener(this);
        img_button_no.setOnClickListener(this);
        fab_save.setOnClickListener(this);
        btn_add.setOnClickListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            scroll_view.setOnScrollChangeListener((View.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
                if (scrollY > oldScrollY) {
                    fab_save.hide();
                } else {
                    fab_save.show();
                }
            });
        }
    }

    public void SetSpinnerData() {
        ArrayAdapter counter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, noofcounter);
        counter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spincounter.setAdapter(counter);

        ArrayAdapter baAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, noofba);
        baAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinba.setAdapter(baAdapter);

        ArrayAdapter spingwpAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, spngwpdata);
        baAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spingwp.setAdapter(spingwpAdapter);

        spincounter.setOnItemSelectedListener(this);
        spinba.setOnItemSelectedListener(this);
        spingwp.setOnItemSelectedListener(this);

        db.open();
        companies = db.getcompanies(false, 0);
        companyAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
        companyAdapter.add("- Select -");
        for (int i = 0; i < companies.size(); i++) {
            companyAdapter.add(companies.get(i).getCompetitionBrand());
        }

        spinCompany.setAdapter(companyAdapter);
        companyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinCompany.setOnItemSelectedListener(this);

        dataForMonthAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
        dataForMonthAdapter.add("- Select -");
        for (int i = 0; i < getYearForExpiry().size(); i++) {
            dataForMonthAdapter.add(getYearForExpiry().get(i));
        }

        spinDataforMonth.setAdapter(dataForMonthAdapter);
        dataForMonthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinDataforMonth.setOnItemSelectedListener(this);

        //for Sale Range
        db.open();
        competitionOfferSaleRange = db.getCompOfferSaleRange();
        //test("salerangesize", String.valueOf(competitionOfferSaleRange.size()));
        compOfferSaleAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
        compOfferSaleAdapter.add("- Select -");
        for (int i = 0; i < competitionOfferSaleRange.size(); i++) {
            compOfferSaleAdapter.add(competitionOfferSaleRange.get(i).getSaleRange());
        }
        spinmonthlysale.setAdapter(compOfferSaleAdapter);
        compOfferSaleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinmonthlysale.setOnItemSelectedListener(this);

        ///for brand
        db.open();
        competitionOfferSets = db.getComOfferSet();
        comOfferSetAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
        comOfferSetAdapter.add("- Select -");
        for (int i = 0; i < competitionOfferSets.size(); i++) {
            comOfferSetAdapter.add(competitionOfferSets.get(i).getCompetitionOfferSet());
        }

        spinBuy.setAdapter(comOfferSetAdapter);
        comOfferSetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinBuy.setOnItemSelectedListener(this);
        //compoffer
        db.open();
        competitionOfferType = db.getCompOfferType(true, false, false, false, 0, 0, 0);
        //test("compoffersize", String.valueOf(competitionOfferType.size()));
        promoTypeAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
        promoTypeAdapter.add("- Select -");
        for (int i = 0; i < competitionOfferType.size(); i++) {
            promoTypeAdapter.add(competitionOfferType.get(i).getCompOffer());
        }
        spinPromoType.setAdapter(promoTypeAdapter);
        promoTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinPromoType.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.imgComoOffer) {
            _pathforcheck = counter_id + "-CompOfferImg-" + username + "_" + visit_date.replace("/", "") +
                    "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);

        } else if (id == R.id.gwpIV) {
            _pathforcheck = counter_id + "-Gwp_CompOfferImg-" + username + "_" + visit_date.replace("/", "") +
                    "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);

        } else if (id == R.id.img_FromDate) {
            c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
                String current_monthFromDate = (monthOfYear + 1 < 10) ? "0" + (monthOfYear + 1) : String.valueOf(monthOfYear + 1);
                String daysFromDate = (dayOfMonth < 10) ? "0" + dayOfMonth : String.valueOf(dayOfMonth);
                String dob = current_monthFromDate + "/" + daysFromDate + "/" + year;
                tvFromDate.setText(dob);
            }, mYear, mMonth, mDay);
            dpd.show();

        } else if (id == R.id.img_toDate) {
            if (tvFromDate.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select From Date");
            } else {
                c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
                    String current_month = (monthOfYear + 1 < 10) ? "0" + (monthOfYear + 1) : String.valueOf(monthOfYear + 1);
                    String days = (dayOfMonth < 10) ? "0" + dayOfMonth : String.valueOf(dayOfMonth);
                    String dob = current_month + "/" + days + "/" + year;
                    tvToDate.setText(dob);
                }, mYear, mMonth, mDay);

                try {
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                    Date d = sdf.parse(tvFromDate.getText().toString());
                    assert d != null;
                    dpd.getDatePicker().setMinDate(d.getTime());
                } catch (ParseException e) {
                    e.fillInStackTrace();
                }

                dpd.show();
            }

        } else if (id == R.id.img_button_yes) {
            db.open();
            if (db.isCompOffersFilled(visit_date, counter_id)) {
                AlertandMessages.showToastMsg(context, "Some data already uploaded,you cannot select 'Available'.");
            } else {
                if (insertList.size() > 0) {
                    if (insertList.get(0).getKeyId() == null && insertList.get(0).getPresent_str().equals("0")) {
                        insertList.clear();
                    }
                }
                ischanged = true;
                present_or_not = "1";
                img_button_yes.setImageResource(R.mipmap.available);
                img_button_no.setImageResource(R.mipmap.not_available_grey);
                ll_hide.setVisibility(View.VISIBLE);
                recyclCompDetails.setVisibility(View.VISIBLE);
            }

        } else if (id == R.id.img_button_no) {
            db.open();
            if (db.isCompOffersFilled(visit_date, counter_id)) {
                AlertandMessages.showToastMsg(context, "Some data already uploaded,you cannot select 'Not Available'.");
            } else {
                insertList.clear();
                call_not_present();
            }

        } else if (id == R.id.btn_add) {
            try {
                if (validation()) {
                    @SuppressLint("NotifyDataSetChanged") AlertDialog.Builder builder4 = new AlertDialog.Builder(context)
                            .setTitle(getString(R.string.parinaam))
                            .setMessage("Are you sure you want to add ?")
                            .setCancelable(false)
                            .setPositiveButton("Yes", (dialog, dialogId) -> {
                                compOfferaddflag = true;
                                List<BaTenureDetail> tenureDetailsnew = getBaTenureDetailList();
                                MasterCompetitonBrandWiseNuance compOffer = new MasterCompetitonBrandWiseNuance();
                                compOffer.setPresent_str("1");
                                compOffer.setDateOfMonth(spinDataforMonth.getSelectedItem().toString());
                                compOffer.setCompetitionBrandId(companyId);
                                compOffer.setCompetitionBrand(company);
                                compOffer.setCompetitionNuanceId(nuanceId);
                                compOffer.setCompetitionNuance(nounce_str);
                                compOffer.setPromoType(compofferdata);
                                compOffer.setPromoTypeId(compOfferId);
                                compOffer.setBuyType(spinbuyTypedata);
                                compOffer.setBuyTypeId(spinbuyTypeId);
                                compOffer.setBuyTypeInput(spinbuyTypeInputData);
                                compOffer.setBuyTypeInputId(spinbuyTypeInputId);
                                compOffer.setGetTypeInput(spingetTypeInputData);
                                compOffer.setGetTypeInputId(spingetTypeInputId);
                                compOffer.setCounter(counterData);
                                compOffer.setNoOfBa(noOfBa);
                                compOffer.setGwpAvailable(gwpAvailable);
                                compOffer.setSaleRange(saleRange);
                                compOffer.setFromDate(tvFromDate.getText().toString());
                                compOffer.setToDate(tvToDate.getText().toString());
                                compOffer.setCompOfferImg(img_comp_offer);
                                compOffer.setGwpImage(img_gwp);
                                compOffer.setCompPromDetail(CommonFunctions.removed_special_char(edtPromotionDetails));
                                compOffer.setNewLaunchMrp(CommonFunctions.removed_special_char(edtNewLaunchMrp));
                                compOffer.setAvgtarget(CommonFunctions.removed_special_char(avgTargetET));
                                compOffer.setAvgOfftake(CommonFunctions.removed_special_char(avgOfftakeET));
                                compOffer.setTvapercent(CommonFunctions.removed_special_char(tvapercentET));
                                compOffer.setBaTenureDetailList(tenureDetailsnew);
                                insertList.add(compOffer);

                                compOfferAdapter = new CompOfferAdapter(context, insertList);
                                recyclCompDetails.setVisibility(View.VISIBLE);
                                recyclCompDetails.setAdapter(compOfferAdapter);
                                recyclCompDetails.setLayoutManager(new LinearLayoutManager(context));
                                compOfferAdapter.notifyDataSetChanged();
                                compOfferaddflag = true;
                                clear_all_field();
                                dialog.dismiss();
                                AlertandMessages.showToastMsg(context, "Data has been added");
                            })
                            .setNegativeButton("No", (dialog, dialogId) -> dialog.dismiss());
                    AlertDialog alert = builder4.create();
                    alert.show();
                }
            } catch (Exception e) {
                e.fillInStackTrace();
            }

        } else if (id == R.id.fab_save) {
            if (compOfferaddflag && insertList.size() > 0) {
                AlertDialog.Builder builder4 = new AlertDialog.Builder(context)
                        .setTitle(getString(R.string.parinaam))
                        .setMessage(getString(R.string.alertsaveData))
                        .setCancelable(false)
                        .setPositiveButton("Yes", (dialog, dialogId) -> {
                            db.open();
                            long l = db.insertCompOffers(username, counter_id, visit_date, getfillderedList(insertList), CommonFunctions.getUUID(context));
                            if (l > 0) {
                                CommonFunctions.call_upload(context);
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                                CompetitionOfferActivity.this.finish();
                            } else {
                                AlertandMessages.showToastMsg(context, "Data Not Saved.");
                            }
                            dialog.dismiss();
                        })
                        .setNegativeButton("No", (dialog, dialogId) -> dialog.dismiss());
                builder4.show();
            } else {
                AlertandMessages.showToastMsg(context, "Please Add First");
            }
        }
    }

    private void jsondatainsert() throws JSONException {
        db.open();
        ArrayList<MasterCompetitonBrandWiseNuance> compOffers = db.getInsertedCompOffers(visit_date, counter_id, "0", false);
        JSONArray topUpArray = new JSONArray();
        if (compOffers.size() > 0) {
            topUpArray = new JSONArray();
            Gson gson = new Gson();
            db.open();
            for (int j = 0; j < compOffers.size(); j++) {
                JSONObject obj = new JSONObject();
                obj.put("MID", "0");
                obj.put("Counter_id", counter_id);
                obj.put("UserId", compOffers.get(j).get_userId());
                obj.put("TransId", "0");

                if (compOffers.get(j).getPresent_str().equals("1")) {
                    String baInfoJson = gson.toJson(compOffers.get(j).getBaTenureDetailList());
                    JSONArray baListJsonArray = new JSONArray(baInfoJson);
                    for (int i = 0; i < baListJsonArray.length(); i++) {
                        JSONObject baObj = baListJsonArray.getJSONObject(i);
                        baObj.put("KeyID", compOffers.get(j).getKeyId()); // Add keyid
                    }
                    obj.put("Present", compOffers.get(j).getPresent_str());
                    if (compOffers.get(j).getGwpAvailable().equalsIgnoreCase("1")) {
                        obj.put("GWP_Available", 1);
                    } else {
                        obj.put("GWP_Available", 0);
                    }
                    obj.put("GWP_Image", compOffers.get(j).getGwpImage());
                    obj.put("DataForMonth", compOffers.get(j).getDateOfMonth());
                    obj.put("KeyID", compOffers.get(j).getKeyId());
                    obj.put("CompBrandId", compOffers.get(j).getCompetitionBrandId());
                    obj.put("NuanceId", compOffers.get(j).getCompetitionNuanceId());
                    obj.put("CompOfferId", compOffers.get(j).getPromoTypeId());
                    obj.put("FromDate", compOffers.get(j).getFromDate());
                    obj.put("ToDate", compOffers.get(j).getToDate());
                    obj.put("CompBuyTypeId", compOffers.get(j).getBuyTypeId());
                    obj.put("CompSetId", compOffers.get(j).getBuyTypeInputId());
                    obj.put("CompGetId", compOffers.get(j).getGetTypeInputId());
                    obj.put("SaleRange", compOffers.get(j).getSaleRange());
                    obj.put("NoOfBa", compOffers.get(j).getNoOfBa());
                    obj.put("NumOfCounter", compOffers.get(j).getCounter());
                    obj.put("NewLaunchMrp", compOffers.get(j).getNewLaunchMrp());
                    obj.put("PromoDetails", compOffers.get(j).getCompPromDetail());
                    obj.put("CompOfferImg", compOffers.get(j).getCompOfferImg());
                    obj.put("AvgTarget", compOffers.get(j).getAvgtarget());
                    obj.put("AvgOfftake", compOffers.get(j).getAvgOfftake());
                    obj.put("TvaPercentage", compOffers.get(j).getTvapercent());
                    obj.put("BAListData", baListJsonArray);
                } else {
                    JSONArray balistdata = new JSONArray();
                    obj.put("Present", 0);
                    obj.put("KeyID", 0);
                    obj.put("DataForMonth", "");
                    obj.put("CompBrandId", 0);
                    obj.put("NuanceId", 0);
                    obj.put("CompOfferId", 0);
                    obj.put("FromDate", "");
                    obj.put("ToDate", "");
                    obj.put("PromoDetails", "");
                    obj.put("CompOfferImg", "");
                    obj.put("CompBuyTypeId", 0);
                    obj.put("CompSetId", 0);
                    obj.put("CompGetId", 0);
                    obj.put("SaleRange", "");
                    obj.put("NoOfBa", 0);
                    obj.put("NumOfCounter", 0);
                    obj.put("NewLaunchMrp", 0);
                    obj.put("AvgTarget", 0);
                    obj.put("AvgOfftake", 0);
                    obj.put("GWP_Image", "");
                    obj.put("GWP_Available", 0);
                    obj.put("TvaPercentage", 0);
                    obj.put("BAListData", balistdata);
                }

                topUpArray.put(obj);
            }
            String complete_json_str = topUpArray.toString();
            //test("complete_json_str",complete_json_str);
        }
    }

    private List<BaTenureDetail> getBaTenureDetailList() {
        List<BaTenureDetail> baList = new ArrayList<>();

        for (List<EditText> fields : allBAEditTexts) {
            String tenure = fields.get(0).getText().toString().trim();
            String experience = fields.get(1).getText().toString().trim();
            String ctc = fields.get(2).getText().toString().trim();
            String regular = fields.get(3).getText().toString().trim();
            String topUp = fields.get(4).getText().toString().trim();

            // You can validate here too if needed
            if (tenure.isEmpty() || experience.isEmpty() || ctc.isEmpty() || regular.isEmpty() || topUp.isEmpty()) {
                fields.get(0).requestFocus(); // optional: focus on first field of group
                //Toast.makeText(this, "Please fill all BA fields", Toast.LENGTH_SHORT).show();
                return null;
            }
            BaTenureDetail detail = new BaTenureDetail();
            detail.setTenure(tenure);
            detail.setExperience(experience);
            detail.setCtc(ctc);
            detail.setRegularIncentive(regular);
            detail.setTopUpIncentive(topUp);
            baList.add(detail);
        }
        return baList;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long _id) {
        int id = parent.getId();
        if (id == R.id.spinCompany) {
            if (position != 0) {
                companyId = companies.get(position - 1).getCompetitionBrandId();
                company = companies.get(position - 1).getCompetitionBrand();

                db.open();
                nuances = db.getcompanies(true, companyId);
                nuanceAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
                nuanceAdapter.add("- Select -");
                for (int i = 0; i < nuances.size(); i++) {
                    nuanceAdapter.add(nuances.get(i).getCompetitionNuance());
                }

                spinNuance.setAdapter(nuanceAdapter);
                nuanceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinNuance.setOnItemSelectedListener(this);
            } else {
                company = "";
                companyId = 0;
            }

        } else if (id == R.id.spinNuance) {
            if (position != 0) {
                nuanceId = nuances.get(position - 1).getCompetitionNuanceId();
                nounce_str = nuances.get(position - 1).getCompetitionNuance();
            } else {
                nounce_str = "";
                nuanceId = 0;
            }

        } else if (id == R.id.spincounter) {
            if (position != 0) {
                counterData = spincounter.getSelectedItem().toString();
            } else {
                counterData = "";
            }

        } else if (id == R.id.spinba) {
            if (position != 0) {
                noOfBa = spinba.getSelectedItem().toString();
                generateBAViews(Integer.parseInt(noOfBa));
                containerBAViews.setVisibility(View.VISIBLE);
            } else {
                noOfBa = "";
                containerBAViews.setVisibility(View.GONE);
            }

        } else if (id == R.id.spingwp) {
            if (position != 0) {
                gwpstatus = spingwp.getSelectedItem().toString();
                if (gwpstatus.equals("Yes")) {
                    gwpAvailable = "1";
                    gwpIV.setVisibility(View.VISIBLE);
                } else {
                    gwpAvailable = "0";
                    gwpIV.setVisibility(View.GONE);
                }
            } else {
                gwpstatus = "";
                gwpAvailable = "";
                gwpIV.setVisibility(View.GONE);
            }

        } else if (id == R.id.spinmonthlysale) {
            if (position != 0) {
                saleRange = competitionOfferSaleRange.get(position - 1).getSaleRange();
            } else {
                saleRange = "";
            }

        } else if (id == R.id.spinPromoType) {
            if (position != 0) {
                compofferdata = competitionOfferType.get(position - 1).getCompOffer();
                compOfferId = competitionOfferType.get(position - 1).getCompOfferId();
                db.open();
                competitionBuyType = db.getCompOfferType(false, true, false, false, compOfferId, 0, 0);
                spinBuyTypeAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
                spinBuyTypeAdapter.add("- Select -");
                for (int i = 0; i < competitionBuyType.size(); i++) {
                    spinBuyTypeAdapter.add(competitionBuyType.get(i).getCompBuyType());
                }
                spinbuyType.setAdapter(spinBuyTypeAdapter);
                spinBuyTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinbuyType.setOnItemSelectedListener(this);
            } else {
                compOfferId = 0;
                compofferdata = "";
            }

        } else if (id == R.id.spinbuyType) {
            if (position != 0) {
                spinbuyTypedata = competitionBuyType.get(position - 1).getCompBuyType();
                spinbuyTypeId = competitionBuyType.get(position - 1).getCompBuyTypeId();
                db.open();
                competitionBuyTypeInput = db.getCompOfferType(false, false, true, false, compOfferId, spinbuyTypeId, 0);
                spinbuyTypeInputAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
                spinbuyTypeInputAdapter.add("- Select -");
                for (int i = 0; i < competitionBuyTypeInput.size(); i++) {
                    spinbuyTypeInputAdapter.add(competitionBuyTypeInput.get(i).getCompSetName());
                }
                spinbuytypeinput.setAdapter(spinbuyTypeInputAdapter);
                spinbuyTypeInputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinbuytypeinput.setOnItemSelectedListener(this);
            } else {
                spinbuyTypeId = 0;
                spinbuyTypedata = "";
            }

        } else if (id == R.id.spinbuytypeinput) {
            if (position != 0) {
                spinbuyTypeInputData = competitionBuyTypeInput.get(position - 1).getCompSetName();
                spinbuyTypeInputId = competitionBuyTypeInput.get(position - 1).getCompSetId();

                db.open();
                competitionGetTypeInput = db.getCompOfferType(false, false, false, true, compOfferId, spinbuyTypeId, spinbuyTypeInputId);
                spingetTypeInputAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
                spingetTypeInputAdapter.add("- Select -");
                for (int i = 0; i < competitionGetTypeInput.size(); i++) {
                    spingetTypeInputAdapter.add(competitionGetTypeInput.get(i).getCompGetName());
                }
                spinGetTypeInput.setAdapter(spingetTypeInputAdapter);
                spingetTypeInputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinGetTypeInput.setOnItemSelectedListener(this);
            } else {
                spinbuyTypeInputId = 0;
                spinbuyTypeInputData = "";
            }

        } else if (id == R.id.spinGetTypeInput) {
            if (position != 0) {
                spingetTypeInputData = competitionGetTypeInput.get(position - 1).getCompGetName();
                spingetTypeInputId = competitionGetTypeInput.get(position - 1).getCompGetId();
            } else {
                spingetTypeInputId = 0;
                spingetTypeInputData = "";
            }

        } else if (id == R.id.spinBuy) {
            if (position != 0) {
                compOfferSetId = competitionOfferSets.get(position - 1).getCompetitionOfferSetId();
                compOfferset = competitionOfferSets.get(position - 1).getCompetitionOfferSet();
                db.open();
                competitionOfferGets = db.getComOfferGet(compOfferSetId);
                comOfferGetAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item);
                comOfferGetAdapter.add("- Select -");
                for (int i = 0; i < competitionOfferGets.size(); i++) {
                    comOfferGetAdapter.add(competitionOfferGets.get(i).getCompetitionOfferGet());
                }

                spinPromoGet.setAdapter(comOfferGetAdapter);
                spinPromoGet.setOnItemSelectedListener(this);
                comOfferGetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            } else {
                compOfferSetId = 0;
                compOfferset = "";
            }

        } else if (id == R.id.spinPromoGet) {
            if (position != 0) {
                compOfferGetId = competitionOfferGets.get(position - 1).getCometitionOfferGetId();
                compOfferGet = competitionOfferGets.get(position - 1).getCompetitionOfferGet();
                ShowProductTypeDropdown = competitionOfferGets.get(position - 1).getShowProductTypeDropdown();
                if (ShowProductTypeDropdown) {
                    spinProductType.setEnabled(true);
                    spinProductType.setClickable(true);
                    spinProductType.setBackgroundColor(getResources().getColor(R.color.white));
                } else {
                    spinProductType.setEnabled(false);
                    spinProductType.setClickable(false);
                    spinProductType.setBackgroundColor(getResources().getColor(R.color.grey_background));
                }
            } else {
                compOfferGet = "";
                compOfferGetId = 0;
                ShowProductTypeDropdown = true;
                spinProductType.setEnabled(true);
                spinProductType.setClickable(true);
                spinProductType.setBackgroundColor(getResources().getColor(R.color.white));
            }

        }


    }

    @SuppressLint("SetTextI18n")
    private void generateBAViews(int count) {
        containerBAViews.removeAllViews(); // Clear existing views
        allBAEditTexts.clear();
        for (int i = 1; i <= count; i++) {
            TextView title = new TextView(this);
            title.setText("BA-" + i);
            title.setTextSize(14);
            title.setTextColor(Color.BLACK);
            title.setTypeface(null, Typeface.BOLD);
            int padding = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
            title.setPadding(padding, padding, padding, padding);

            EditText tenure = createEditText("Tenure with the Brand");
            EditText experience = createEditText("Experience with Beauty");
            EditText ctc = createEditText("CTC");
            EditText regularIncentive = createEditText("Avg Regular Incentive/month");
            EditText topUpIncentive = createEditText("Avg Top-up Incentive/month");

            List<EditText> baFields = Arrays.asList(tenure, experience, ctc, regularIncentive, topUpIncentive);
            allBAEditTexts.add(baFields);

            containerBAViews.addView(title);
            for (EditText editText : baFields) containerBAViews.addView(editText);
        }

    }

    private EditText createEditText(String hint) {
        EditText editText = new EditText(this);
        editText.setHint(hint);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );

        editText.setBackground(ContextCompat.getDrawable(this, R.drawable.rouded_corner_edittaxt));
        // Optional: padding inside EditText
        int padding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 12, getResources().getDisplayMetrics());
        editText.setPadding(padding, padding, padding, padding);

        int margin = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 5, editText.getResources().getDisplayMetrics());
        params.setMargins(margin, margin, margin, margin);

        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        editText.setTextColor(Color.BLACK);
        editText.setHintTextColor(Color.BLACK);
        editText.setLayoutParams(params);
        return editText;
    }

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

    }

    private static ArrayList<String> getYearForExpiry() {
        ArrayList<String> years = new ArrayList<>();
        Calendar prevYear, calendar;
        try {
            prevYear = Calendar.getInstance();
            prevYear.add(Calendar.YEAR, 0);

            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, 0);
            int month = calendar.get(Calendar.MONTH);
            years.add(0, theMonth(month) + "  - " + prevYear.get(Calendar.YEAR));
            prevYear = Calendar.getInstance();
            prevYear.add(Calendar.YEAR, 0);

            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -1);
            month = calendar.get(Calendar.MONTH);
            years.add(1, theMonth(month) + "  - " + prevYear.get(Calendar.YEAR));

            prevYear = Calendar.getInstance();
            prevYear.add(Calendar.YEAR, 0);
            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -2);
            month = calendar.get(Calendar.MONTH);

            years.add(2, theMonth(month) + "  - " + prevYear.get(Calendar.YEAR));

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

        return years;
    }


    public static String theMonth(int month) {
        String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        return monthNames[month];
    }

    @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:
                    try {
                        if (_pathforcheck != null && !_pathforcheck.isEmpty()) {
                            if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                                convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                                if (_pathforcheck.contains("-CompOfferImg-")) {
                                    imgComoOffer.setImageResource(R.mipmap.camera_bsd);
                                    img_comp_offer = _pathforcheck;
                                    _pathforcheck = "";
                                } else if (_pathforcheck.contains("-Gwp_CompOfferImg-")) {
                                    gwpIV.setImageResource(R.mipmap.camera_bsd);
                                    img_gwp = _pathforcheck;
                                    _pathforcheck = "";
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }
                    break;
            }
        } else
            super.onActivityResult(requestCode, resultCode, data);
    }

    private void call_not_present() {
        try {
            present_or_not = "0";
            img_button_no.setImageResource(R.mipmap.not_available);
            img_button_yes.setImageResource(R.mipmap.available_grey);
            ll_hide.setVisibility(View.GONE);
            recyclCompDetails.setVisibility(View.GONE);

            MasterCompetitonBrandWiseNuance compOffer = new MasterCompetitonBrandWiseNuance();
            compOffer.setPresent_str("0");
            compOffer.setDateOfMonth("");
            compOffer.setCompetitionBrandId(0);
            compOffer.setCompetitionBrand("");
            compOffer.setCompetitionNuanceId(0);
            compOffer.setCompetitionNuance("");
            compOffer.setPromoType("");
            compOffer.setPromoTypeId(0);
            compOffer.setCompOfferGet("");
            compOffer.setCompOfferGetId(0);
            compOffer.setCompOfferset("");
            compOffer.setCompOffersetId(0);
            compOffer.setFromDate("");
            compOffer.setToDate("");
            compOffer.setCompOfferImg("");
            compOffer.setCompPromDetail("");
            insertList.add(compOffer);
            compOfferaddflag = true;
            clear_all_field();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private void clear_all_field() {
        tvFromDate.setText("");
        tvToDate.setText("");
        edtBuyQTY.setText("0");
        edtGetQTY.setText("0");
        spinCompany.setSelection(0);
        spinNuance.setSelection(0);
        spinPromoType.setSelection(0);
        allBAEditTexts.clear();
        containerBAViews.setVisibility(View.GONE);

        spincounter.setSelection(0);
        spingwp.setSelection(0);
        spinba.setSelection(0);
        spinmonthlysale.setSelection(0);
        spinbuyType.setSelection(0);
        spinbuytypeinput.setSelection(0);
        spinGetTypeInput.setSelection(0);
        spinDataforMonth.setSelection(0);
        edtPromotionDetails.setText("");
        edtNewLaunchMrp.setText("");
        avgTargetET.setText("");
        avgOfftakeET.setText("");
        tvapercentET.setText("0.0");
        edtPromotionDetails.setHint("Competition New Launch");
        company = "";

        counterData = "";
        noOfBa = "";
        gwpAvailable = "";
        saleRange = "";
        spinbuyTypedata = "";
        compofferdata = "";
        spinbuyTypeInputData = "";
        spingetTypeInputData = "";
        nounce_str = "";
        promoType = "";
        compOfferset = "";
        compOfferGet = "";
        companyId = 0;
        nuanceId = 0;
        promoTypeId = 0;
        compOfferSetId = 0;
        compOfferGetId = 0;
        img_comp_offer = "";
        img_gwp = "";
        compOfferId = 0;
        spinbuyTypeId = 0;
        spinbuyTypeInputId = 0;
        spingetTypeInputId = 0;
        imgComoOffer.setImageResource(R.mipmap.camera_bs);
        gwpIV.setImageResource(R.mipmap.camera_bs);
    }

    private boolean validation() {
        boolean flag;
        if (present_or_not.equals("")) {
            AlertandMessages.showToastMsg(context, "Please Select Competition Intelligence 'Available' OR 'Not Available'");
            flag = false;
        } else if (present_or_not.equals("1")) {
            List<BaTenureDetail> tenureDetails = getBaTenureDetailList();
            if (spinDataforMonth.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Data For Month");
                flag = false;
            } else if (spinCompany.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Company");
                flag = false;
            } else if (spincounter.getSelectedItemPosition() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select No. Of Counters");
                flag = false;
            } else if (spinba.getSelectedItemPosition() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select No. Of Ba's");
                flag = false;
            } else if (tenureDetails == null) {
                AlertandMessages.showToastMsg(context, "Please Fill All Ba's Field");
                flag = false;
            } else if (spinNuance.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Nuance/Sub Category");
                flag = false;
            } else if (spinmonthlysale.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Monthly Sale");
                flag = false;
            } else if (spinPromoType.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Competition Intelligence");
                flag = false;
            } else if (spinbuyType.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Competition Buy Type");
                flag = false;
            } else if (spinbuytypeinput.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Competition Buy Type Input");
                flag = false;
            } else if (spinGetTypeInput.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Competition Get Type Input");
                flag = false;
            } else if (avgTargetET.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Average Target");
                flag = false;
            } else if (avgOfftakeET.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Average Offtake");
                flag = false;
            } else if (tvFromDate.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select From Date");
                flag = false;
            } else if (tvToDate.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select To Date");
                flag = false;
            } else if (spingwp.getSelectedItemPosition() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Gwp Available Or Not");
                flag = false;
            } else if (gwpAvailable.equalsIgnoreCase("1") && img_gwp.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Capture Gwp Image");
                flag = false;
            } else if (img_comp_offer.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Capture Competition Intelligence Details");
                flag = false;
            } else {
                flag = true;
            }
        } else {
            flag = true;
        }
        return flag;
    }

    private class CompOfferAdapter extends RecyclerView.Adapter<CompOfferAdapter.MyViewHolder> {
        final LayoutInflater inflator;
        Context context;
        ArrayList<MasterCompetitonBrandWiseNuance> insertedlist_Data;

        CompOfferAdapter(Context context, ArrayList<MasterCompetitonBrandWiseNuance> insertedlist_Data) {
            inflator = LayoutInflater.from(context);
            this.context = context;
            this.insertedlist_Data = insertedlist_Data;
        }

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

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

        @SuppressLint({"NotifyDataSetChanged", "SetTextI18n"})
        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            final MasterCompetitonBrandWiseNuance current = insertedlist_Data.get(position);

            if (current.getKeyId() != null && !current.getStatus().equals("")
                    && !current.getStatus().equalsIgnoreCase(CommonString.KEY_N)) {
                holder.remove.setImageResource(R.mipmap.upload_tick);
                holder.remove.setId(position);
                holder.remove.setVisibility(View.VISIBLE);
                holder.deleteBT.setVisibility(View.GONE);
            } else {
                holder.remove.setVisibility(View.GONE);
                holder.deleteBT.setVisibility(View.VISIBLE);
            }

            holder.viewbainfoBT.setOnClickListener(v -> {
                if (current.getBaTenureDetailList() != null && !current.getBaTenureDetailList().isEmpty()) {
                    new BaDetailsDailog(context, current).show();
                } else {
                    Toast.makeText(context, getResources().getText(R.string.balist_data_not_available), Toast.LENGTH_SHORT).show();
                }
            });

            holder.deleteBT.setOnClickListener(v -> {
                if (current.getKeyId() == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(getString(R.string.parinaam));
                    builder.setMessage("Are you sure you want to Delete ?")
                            .setCancelable(false)
                            .setPositiveButton("Yes", (dialog, id) -> {
                                deleteImageIfExist(current);
                                insertedlist_Data.remove(position);
                                if (insertedlist_Data.size() > 0) {
                                    compOfferAdapter = new CompOfferAdapter(context, insertedlist_Data);
                                    recyclCompDetails.setAdapter(compOfferAdapter);
                                    compOfferAdapter.notifyDataSetChanged();
                                }
                                notifyDataSetChanged();
                            })
                            .setNegativeButton("No",
                                    (dialog, id) -> dialog.dismiss());
                    AlertDialog alert = builder.create();
                    alert.show();
                } else if (current.getStatus().equalsIgnoreCase(CommonString.KEY_N)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(getString(R.string.parinaam));
                    builder.setMessage("Are you sure you want to Delete ?")
                            .setCancelable(false)
                            .setPositiveButton("Yes", (dialog, id) -> {
                                deleteImageIfExist(current);
                                db.open();
                                db.deleteCompOffers(counter_id, visit_date, current.getKeyId());
                                insertedlist_Data.remove(position);
                                if (insertedlist_Data.size() > 0) {
                                    compOfferAdapter = new CompOfferAdapter(context, insertedlist_Data);
                                    recyclCompDetails.setAdapter(compOfferAdapter);
                                    compOfferAdapter.notifyDataSetChanged();
                                }
                                notifyDataSetChanged();
                                dialog.dismiss();
                            })
                            .setNegativeButton("No",
                                    (dialog, id) -> dialog.dismiss());
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            });

            holder.tvCompany.setText("Company > " + current.getCompetitionBrand());
            holder.tvCompany.setId(position);

            holder.tvNuance.setText("Nuance > " + current.getCompetitionNuance());
            holder.tvNuance.setId(position);

            holder.tvCounter.setText("Counter > " + current.getCounter());
            holder.tvCounter.setId(position);

            holder.tvBa.setText("No. Of Ba > " + current.getNoOfBa());
            holder.tvBa.setId(position);

            holder.tvSale.setText("SaleRange > " + current.getSaleRange());
            holder.tvSale.setId(position);

            holder.tvPromoType.setText("Type > " + current.getPromoType());
            holder.tvPromoType.setId(position);

            holder.tvBuyType.setText("BuyType > " + current.getBuyType());
            holder.tvBuyType.setId(position);

            holder.tvOfferSet.setText("Buy > " + current.getBuyTypeInput());
            holder.tvOfferSet.setId(position);

            holder.tvOfferGet.setText("Get > " + current.getGetTypeInput());
            holder.tvOfferGet.setId(position);

            holder.tvFromDatee.setText("From Date > " + current.getFromDate());
            holder.tvFromDatee.setId(position);

            holder.tvToDatee.setText("To Date > " + current.getToDate());
            holder.tvToDatee.setId(position);

            holder.avgtargetTV.setText("Avg Target > " + current.getAvgtarget());
            holder.avgtargetTV.setId(position);

            holder.avgofftakeTV.setText("Avg Offtake > " + current.getAvgOfftake());
            holder.avgofftakeTV.setId(position);

            holder.tvaperTV.setText("TVA Percent > " + current.getTvapercent());
            holder.tvaperTV.setId(position);

            if (current.getGwpAvailable().equalsIgnoreCase("0")) {
                holder.gwpavailableTV.setText("GWP Available > " + "No");
                holder.gwpavailableTV.setId(position);
            } else if (current.getGwpAvailable().equalsIgnoreCase("1")) {
                holder.gwpavailableTV.setText("GWP Available > " + "Yes");
                holder.gwpavailableTV.setId(position);
            }

            holder.remove.setId(position);
            holder.deleteBT.setId(position);
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvCompany, tvNuance, tvPromoType, tvOfferSet, tvOfferGet, tvFromDatee, tvToDatee,
                    tvCounter, tvBa, tvSale, tvBuyType, avgtargetTV, avgofftakeTV, tvaperTV, gwpavailableTV;
            Button viewbainfoBT, deleteBT;
            ImageView remove;

            public MyViewHolder(View convertView) {
                super(convertView);
                gwpavailableTV = convertView.findViewById(R.id.gwpavailableTV);
                tvCompany = (TextView) convertView.findViewById(R.id.tvCompany);
                tvNuance = (TextView) convertView.findViewById(R.id.tvNuance);
                tvPromoType = (TextView) convertView.findViewById(R.id.tvPromoType);
                tvOfferSet = (TextView) convertView.findViewById(R.id.tvOfferSet);
                tvOfferGet = (TextView) convertView.findViewById(R.id.tvOfferGet);
                tvFromDatee = (TextView) convertView.findViewById(R.id.tvFromDatee);
                tvToDatee = (TextView) convertView.findViewById(R.id.tvToDatee);
                tvCounter = (TextView) convertView.findViewById(R.id.tvCounter);
                tvBa = (TextView) convertView.findViewById(R.id.tvBa);
                tvSale = (TextView) convertView.findViewById(R.id.tvSale);
                tvBuyType = (TextView) convertView.findViewById(R.id.tvBuyType);
                avgtargetTV = (TextView) convertView.findViewById(R.id.avgtargetTV);
                avgofftakeTV = (TextView) convertView.findViewById(R.id.avgofftakeTV);
                tvaperTV = (TextView) convertView.findViewById(R.id.tvaperTV);
                remove = (ImageView) convertView.findViewById(R.id.imgDelete);
                viewbainfoBT = convertView.findViewById(R.id.viewbainfoBT);
                deleteBT = convertView.findViewById(R.id.deleteBT);

            }
        }
    }

    private void deleteImageIfExist(MasterCompetitonBrandWiseNuance obj) {
        try {
            File file = new File(CommonString.getImagesFolder(context) + obj.getCompOfferImg());
            if (file.exists()) file.delete();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setDataToListView() {
        try {
            db.open();
            insertList = db.getInsertedCompOffers(visit_date, counter_id, null, false);
            if (!insertList.isEmpty()) {
                try {
                    if (insertList.get(0).getPresent_str().equals("1")) {
                        img_button_yes.setImageResource(R.mipmap.available);
                        present_or_not = "1";
                        img_button_no.setImageResource(R.mipmap.not_available_grey);
                        recyclCompDetails.setVisibility(View.VISIBLE);
                        ll_hide.setVisibility(View.VISIBLE);
                        Collections.reverse(insertList);
                        compOfferAdapter = new CompOfferAdapter(context, insertList);
                        recyclCompDetails.setAdapter(compOfferAdapter);
                        recyclCompDetails.setLayoutManager(new LinearLayoutManager(context));
                        compOfferAdapter.notifyDataSetChanged();
                    } else if (insertList.size() > 0 && insertList.get(0).getPresent_str().equals("0")) {
                        img_button_no.setImageResource(R.mipmap.not_available);
                        img_button_yes.setImageResource(R.mipmap.available_grey);
                        present_or_not = "0";
                        recyclCompDetails.setVisibility(View.GONE);
                        ll_hide.setVisibility(View.GONE);
                    } else {
                        img_button_no.setImageResource(R.mipmap.not_available_grey_);
                        img_button_yes.setImageResource(R.mipmap.available_grey_);
                        recyclCompDetails.setVisibility(View.GONE);
                        ll_hide.setVisibility(View.GONE);
                        present_or_not = "";
                    }

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

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

    private ArrayList<MasterCompetitonBrandWiseNuance> getfillderedList(ArrayList<MasterCompetitonBrandWiseNuance> insertList) {
        ArrayList<MasterCompetitonBrandWiseNuance> filterData = new ArrayList<>();
        if (insertList.size() > 0) {
            for (int k = 0; k < insertList.size(); k++) {
                if (insertList.get(k).getKeyId() == null) {
                    filterData.add(insertList.get(k));
                }
            }
        }
        return filterData;
    }


    @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 (ischanged) {
                android.app.AlertDialog.Builder builder = new android.app.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);
                                    CompetitionOfferActivity.this.finish();
                                }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
                android.app.AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                CompetitionOfferActivity.this.finish();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (ischanged) {
            android.app.AlertDialog.Builder builder = new android.app.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);
                        CompetitionOfferActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            android.app.AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            CompetitionOfferActivity.this.finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        avgOfftakeET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int after) {
                // Only calculate percentage when both fields are not empty
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!avgTargetET.getText().toString().isEmpty() && !avgOfftakeET.getText().toString().isEmpty()) {
                    avgtarget = Double.parseDouble(avgTargetET.getText().toString());
                    avgofftake = Double.parseDouble(avgOfftakeET.getText().toString());
                    tvapercent = (avgofftake / avgtarget) * 100;
                    tvapercent = Math.round(tvapercent * 10.0) / 10.0;
                    tvapercentET.setText(String.valueOf(tvapercent));
                } else {
                    // If either field is empty, set percentage to 0
                    tvapercent = 0.0;
                    tvapercentET.setText("0.0");
                }
                // This method is called after the text has changed.
                // You can leave it empty if you don't need to do anything after the change.
            }
        });

        avgTargetET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int after) {
                // Only calculate percentage when both fields are not empty
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!avgTargetET.getText().toString().isEmpty() && !avgOfftakeET.getText().toString().isEmpty()) {
                    avgtarget = Double.parseDouble(avgTargetET.getText().toString());
                    avgofftake = Double.parseDouble(avgOfftakeET.getText().toString());
                    tvapercent = (avgofftake / avgtarget) * 100;
                    tvapercent = Math.round(tvapercent * 10.0) / 10.0;
                    tvapercentET.setText(String.valueOf(tvapercent));
                } else {
                    // If either field is empty, set percentage to 0
                    tvapercent = 0.0;
                    tvapercentET.setText("0.0");
                }
                // This method is called after the text has changed.
                // You can leave it empty if you don't need to do anything after the change.
            }
        });
    }

    private class BaDetailsDailog extends Dialog {
        Context context;
        MasterCompetitonBrandWiseNuance current;

        public BaDetailsDailog(Context context, MasterCompetitonBrandWiseNuance current) {
            super(context);
            this.context = context;
            this.current = current;
        }

        @SuppressLint({"SetTextI18n", "DefaultLocale"})
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            com.cpm.lorealbaMabeline.databinding.CompetitionOfferBaDetailBinding binding = CompetitionOfferBaDetailBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            binding.closeDialog.setOnClickListener(v -> dismiss());
            Window window = getWindow();
            if (window != null) {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                window.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                // int dialogWidthDp = 320;
               /* int dialogWidthDp = displayMetrics.widthPixels;
                float scale = context.getResources().getDisplayMetrics().density;
                int dialogWidthPx = (int) (dialogWidthDp * scale + 0.9f);*/
                int screenWidth = displayMetrics.widthPixels;
                int dialogWidth = (int) (screenWidth * 0.9);

                window.setLayout(dialogWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
                window.setGravity(Gravity.CENTER);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }


            if (current.getBaTenureDetailList() != null) {
                int i = 0;
                List<BaTenureDetail> baList = current.getBaTenureDetailList();
                int total = baList.size();
                for (BaTenureDetail detail : baList) {
                    // Create parent LinearLayout (horizontal)
                    LinearLayout horizontalLayout = new LinearLayout(context);
                    horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
                    // Optional: set padding, background, etc.
                    horizontalLayout.setPadding(10, 10, 10, 20);
                    // Set layout params for horizontal layout

                    // Create first TextView
                    TextView tv1 = new TextView(context);
                    tv1.setText(
                            "Tenure with the Brand : " + "\n" +
                                    "Experience with the beauty : " + "\n" +
                                    "CTC : " + "\n" +
                                    "Avg Regular incentive per month : " + "\n" +
                                    "Avg Top-up incentive per month : "
                    );
                    tv1.setTextSize(13);
                    tv1.setLineSpacing(10f, 1.0f);
                    tv1.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tv1.setTextColor(Color.BLACK);
                    // Set weight for equal spacing
                    LinearLayout.LayoutParams tvParams1 = new LinearLayout.LayoutParams(
                            0, ViewGroup.LayoutParams.WRAP_CONTENT, 2.5f // width=0, weight=1
                    );
                    // tvParams1.setMargins(8, 0, 8, 0);
                    tv1.setPadding(10, 0, 0, 0);
                    tv1.setLayoutParams(tvParams1);
                    // Create second TextView
                    TextView tv2 = new TextView(context);
                    tv2.setText(
                            detail.getTenure() + "\n" +
                                    detail.getExperience() + "\n" +
                                    detail.getCtc() + "\n" +
                                    detail.getRegularIncentive() + "\n" +
                                    detail.getTopUpIncentive()
                    );
                    tv2.setTextSize(13);
                    tv2.setLineSpacing(10f, 1.0f);
                    tv2.setTextColor(Color.BLACK);
                    horizontalLayout.addView(tv1);

                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT
                    );
                    horizontalLayout.setLayoutParams(layoutParams);

                    LinearLayout.LayoutParams tvParams2 = new LinearLayout.LayoutParams(
                            0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f // width=0, weight=1
                    );
                    //tvParams2.setMargins(8, 0, 8, 0);
                    // tv2.setPadding(0, 0, 8, 0);
                    tv2.setLayoutParams(tvParams2);
                    // Add TextViews to horizontal layout
                    horizontalLayout.addView(tv2);

                    // Finally add horizontal layout to your main container
                    binding.baListContainer.addView(horizontalLayout);
                    // binding.baListContainer.addView(divider);
                    if (i != total - 1) {
                        View divider = new View(context);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                ViewGroup.LayoutParams.MATCH_PARENT,
                                2
                        );
                        params.setMargins(10, 10, 10, 10); // You can reduce bottom here if needed
                        divider.setLayoutParams(params);
                        divider.setBackgroundColor(Color.LTGRAY);
                        binding.baListContainer.addView(divider);
                    }
                    i++; // Increment manually
                }
            }
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onStart() {
            super.onStart();
            setCancelable(true);
        }
    }
}
