package com.cpm.lorealbaautomation.upload;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.cpm.lorealbaautomation.BuildConfig;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.UserLoginActivity;
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.gettersetter.AuditDataGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitonBrandWiseNuance;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.retrofit.PostApiForUpload;
import com.cpm.lorealbaautomation.retrofit.StringConverterFactory;
import com.squareup.okhttp.MultipartBuilder;

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.saveBitmapToFile;
import static com.cpm.lorealbaautomation.dailyactivity.ServiceActivity.uploadBackup;
import static com.cpm.lorealbaautomation.download.Downloader.convertTym;
import static com.cpm.lorealbaautomation.download.Downloader.getFileNames;

public class ManualUploadActivity extends AppCompatActivity implements View.OnClickListener {
    ArrayList<MasterProfile> baProfile_ImageList = new ArrayList<>();
    ArrayList<JourneyPlan> counterprofile_imgList = new ArrayList<>();
    ArrayList<MEMEAuditQuestion> meQuizList = new ArrayList<>();
    ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList = new ArrayList<>();
    ArrayList<ProductMaster> productMasterArrayList = new ArrayList<>();
    ArrayList<GroomingGetterSetter> groomingList = new ArrayList<>();
    ArrayList<JourneyPlan> counterList = new ArrayList<>();
    ImageView img_manual_dataupload, img_manual_imageupload;
    ArrayList<ProductMaster> masterList = new ArrayList<>();
    private SharedPreferences.Editor editor = null;
    public static int uploadedFiles = 0;
    public static int totalFiles = 0;
    ProductMaster obj = new ProductMaster();
    String counter_Id, visit_date, username;
    boolean clicked_flag = false;
    Lorealba_Database db;
    ProgressDialog pd;
    Context context;
    int value = -1;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manual_upload);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        SharedPreferences preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        img_manual_dataupload = (ImageView) findViewById(R.id.img_manual_dataupload);
        img_manual_imageupload = (ImageView) findViewById(R.id.img_manual_imageupload);
        img_manual_imageupload.setVisibility(View.GONE);
        setTitle("Manual Upload - " + username);
        value = getIntent().getIntExtra(CommonString.TAG_OBJECT, -1);
        db.open();
        masterList = db.getmasterTransaction(visit_date, counter_Id, true);
        if (!masterList.isEmpty()) {
            clicked_flag = true;
            pd = new ProgressDialog(context);
            pd.setCancelable(false);
            pd.setMessage("Uploading Data" + "(" + "0/" + ")");
            pd.show();
            handleuploaddata_withcase(masterList, 0, pd);
        } else if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) {
            pd = new ProgressDialog(context);
            pd.setCancelable(false);
            pd.setMessage("Uploading Data" + "(" + "0/" + ")");
            pd.show();
            CommonUploadwithrecursive(db, true, pd);
        }

        ////...............call interface..................
        img_manual_dataupload.setOnClickListener(this);
        img_manual_imageupload.setOnClickListener(this);

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

    @SuppressLint("LongLogTag")
    private void handleuploaddata_withcase(ArrayList<ProductMaster> masterList, int masterfinalindex, ProgressDialog pd) {
        if (!masterList.isEmpty()) {
            obj = new ProductMaster();
            obj = masterList.get(masterfinalindex);
            pd.setMessage("Uploading (" + masterfinalindex + "/" + masterList.size() + ") \n" + obj.getStock_type() + "");
            switch (obj.getStock_type()) {
                case CommonString.SALEABLE:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.SALEABLE, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    } else {
                        db.open();
                        ArrayList<ProductMaster> saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id());
                        int endIndex = 0;
                        int startIndex = endIndex;
                        if (startIndex + 200 < saleableCompstockList.size()) {
                            endIndex = startIndex + 200;
                        } else {
                            endIndex = saleableCompstockList.size();
                        }

                        UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd);
                    }

                    break;

                case CommonString.TESTER:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.TESTER, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    } else {
                        db.open();
                        ArrayList<ProductMaster> saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id());
                        int endIndex = 0;
                        int startIndex = endIndex;
                        if (startIndex + 200 < saleableCompstockList.size()) {
                            endIndex = startIndex + 200;
                        } else {
                            endIndex = saleableCompstockList.size();
                        }
                        UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd);
                    }

                    break;

                case CommonString.SAMPLE:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.SAMPLE, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    } else {
                        db.open();
                        ArrayList<ProductMaster> saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id());
                        int endIndex = 0;
                        int startIndex = endIndex;
                        if (startIndex + 200 < saleableCompstockList.size()) {
                            endIndex = startIndex + 200;
                        } else {
                            endIndex = saleableCompstockList.size();
                        }

                        UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd);
                    }

                    break;

                case CommonString.GWP:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT) || obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.GWP, final_saleable_str);
                        }
                    } else {
                        db.open();
                        ArrayList<ProductMaster> saleableCompstockList = db.gettransaction_date(obj.getMaster_transaction_id());
                        int endIndex = 0;
                        int startIndex = endIndex;
                        if (startIndex + 200 < saleableCompstockList.size()) {
                            endIndex = startIndex + 200;
                        } else {
                            endIndex = saleableCompstockList.size();
                        }
                        UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, saleableCompstockList, masterList, masterfinalindex, pd);
                    }

                    break;

                case CommonString.DAMAGE:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.DAMAGE, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.RETURNTO_DB:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.RETURNTO_DB, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.INWARD_DMS_NEW_SKU:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.INWARD_DMS_NEW_SKU, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.INWARD_DMS:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.isEmpty()) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.INWARD_DMS, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.MANUALINWARD_DMS_NEWPRODUCT:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.MANUALINWARD_DMS_NEWPRODUCT, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.MANUALINWARD_DMS:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.MANUALINWARD_DMS, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.CONSUMERSALE:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.CONSUMERSALE, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.CONSUMERRETURN:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.CONSUMERRETURN, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.LEAVE_MANAGEMENT:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.LEAVE_MANAGEMENT, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.BREAK_MANAGEMENT:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.BREAK_MANAGEMENT, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.VISIBILITY:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.VISIBILITY, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.MAKEOVER_CAPTURE:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.MAKEOVER_CAPTURE, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.SKINGENIUS:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.SKINGENIUS, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.OPEN_SKINGENIUS:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.OPEN_SKINGENIUS, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.OPEN_MAYBELLINE:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.OPEN_MAYBELLINE, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;

                case CommonString.COMP_OFFERS:
                    if (obj.getEntry_type().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        String final_saleable_str = saleablejsonstr(counter_Id, obj);
                        if (final_saleable_str != null && !final_saleable_str.equals("")) {
                            upload_recursive_Data(final_saleable_str, masterfinalindex, masterList, pd);
                            //test(CommonString.KEY_JSON + "," + CommonString.COMP_OFFERS, final_saleable_str);
                        } else {
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
                        }
                    }

                    break;


                default:
                    pd.dismiss();
                    AlertandMessages.showToastMsg(context, "Error in uploading");
                    break;
            }
        }
    }

    private String saleablejsonstr(String counter_id, ProductMaster objectcurrent) {
        String saleablejson_str = "";
        db.open();
        JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_id);
        db.open();
        ArrayList<ProductMaster> saleablestockList = db.gettransaction_date(objectcurrent.getMaster_transaction_id());
        try {

            String key = "", complete_json_str = "";
            JSONArray topUpArray = null;
            if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SALEABLE)) {
                if (saleablestockList.size() > 0) {
                    key = "SaleableFData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    for (int j = 0; j < saleablestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", saleablestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("REASON_ID", saleablestockList.get(j).getReasonId());
                        obj.put("TranId", saleablestockList.get(j).getTransaction_Id());
                        obj.put("UserId", saleablestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        //header image
                        String img = saleablestockList.get(j).getImagePath();
                        if (img == null) {
                            img = "";
                        }

                        obj.put("Image", img);
                        int stk = saleablestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);
                        if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) {
                            obj.put("Status", saleablestockList.get(j).getEntry_type());
                        } else {
                            key = "SaleableData";
                        }

                        topUpArray.put(obj);
                    }
                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.TESTER)) {
                if (saleablestockList.size() > 0) {
                    key = "TesterFData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < saleablestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", saleablestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", saleablestockList.get(j).getTransaction_Id());
                        obj.put("UserId", saleablestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        int stk = saleablestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);

                        if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) {
                            obj.put("Status", saleablestockList.get(j).getEntry_type());
                        } else {
                            key = "TesterData";
                        }

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }

            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SAMPLE)) {
                if (saleablestockList.size() > 0) {
                    key = "SampleFData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < saleablestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", saleablestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", saleablestockList.get(j).getTransaction_Id());
                        obj.put("UserId", saleablestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        int stk = saleablestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);

                        if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) {
                            obj.put("Status", saleablestockList.get(j).getEntry_type());
                        } else {
                            key = "SampleData";
                        }

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }

            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.GWP)) {
                if (saleablestockList.size() > 0) {
                    key = "GWPFData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < saleablestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", saleablestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", saleablestockList.get(j).getTransaction_Id());
                        obj.put("UserId", saleablestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        int stk = saleablestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }
                        obj.put("STOCK", stk);
                        if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) {
                            obj.put("Status", saleablestockList.get(j).getEntry_type());
                        } else {
                            key = "GWPData";
                        }
                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.ME_SALE)) {
                if (saleablestockList.size() > 0) {
                    key = "ME_SaleFData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < saleablestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", saleablestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", saleablestockList.get(j).getTransaction_Id());
                        obj.put("UserId", saleablestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        int stk = saleablestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);

                        if (objectcurrent.getEntry_type().equalsIgnoreCase(CommonString.KEY_DRAFT)) {
                            obj.put("Status", saleablestockList.get(j).getEntry_type());
                        } else {
                            key = "ME_SaleData";
                        }

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.DAMAGE)) {
                if (saleablestockList.size() > 0) {
                    key = "DamageData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < saleablestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", saleablestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", saleablestockList.get(j).getTransaction_Id());
                        obj.put("UserId", saleablestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        //header image
                        String img = saleablestockList.get(j).getImagePath();
                        if (img == null) {
                            img = "";
                        }

                        obj.put("Image", img);
                        int stk = saleablestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }
                        obj.put("STOCK", stk);
                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.RETURNTO_DB)) {
                db.open();
                ArrayList<ProductMaster> damagestockList = db.getreturntodistributor_byUUID(objectcurrent.getTransaction_Id());
                if (damagestockList.size() > 0) {
                    complete_json_str = "";
                    key = "DamageReturnToDistributor";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < damagestockList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", damagestockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", damagestockList.get(j).getTransaction_Id());
                        obj.put("UserId", damagestockList.get(j).getUser_id());
                        obj.put("CounterId", counter_id);
                        int stk = damagestockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }
                        obj.put("STOCK", stk);

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS_NEW_SKU)) {
                db.open();
                ArrayList<ProductMaster> dmsList = db.getInwardStockTransactionData(objectcurrent.getTransaction_Id());
                if (dmsList.size() > 0) {
                    key = "Inward_NewProduct_Stock";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < dmsList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("UserId", dmsList.get(j).getUser_id());
                        obj.put(CommonString.KEY_VISIT_DATE, dmsList.get(j).getVisit_date());
                        obj.put("TranId", dmsList.get(j).getTransaction_Id());
                        obj.put(CommonString.KEY_ProductId, dmsList.get(j).getProductId());
                        obj.put(CommonString.KEY_INVOICE_ID, dmsList.get(j).getInvId());
                        obj.put(CommonString.KEY_INVOICE_STATUS, dmsList.get(j).getInvoice_Status());
                        obj.put(CommonString.KEY_INVOICE_NUMBER, dmsList.get(j).getInvoice_number());
                        obj.put(CommonString.KEY_INVOICE_TYPE, dmsList.get(j).getInvoice_type());
                        obj.put(CommonString.KEY_INVOICE_DATE, dmsList.get(j).getInvoice_date());
                        obj.put(CommonString.KEY_INVOICE_QTY, dmsList.get(j).getConsumer_qty());
                        obj.put(CommonString.KEY_ACTUAL_QTY, dmsList.get(j).getActualQty());
                        obj.put(CommonString.KEY_COUNTER_ID, dmsList.get(j).getCounter_id());
                        if (dmsList.get(j).isConfirmChecked()) {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "1");
                        } else {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "0");
                        }
                        obj.put(CommonString.KEY_REASON_ID, dmsList.get(j).getReasonId());
                        obj.put(CommonString.KEY_SOURCE, dmsList.get(j).getSource());

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS)) {
                db.open();
                ArrayList<ProductMaster> dmsList = db.getInwardStockTransactionData(objectcurrent.getTransaction_Id());
                if (dmsList.size() > 0) {
                    key = "Inward_ExistingProduct_Stock";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < dmsList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("UserId", dmsList.get(j).getUser_id());
                        obj.put(CommonString.KEY_VISIT_DATE, dmsList.get(j).getVisit_date());
                        obj.put("TranId", dmsList.get(j).getTransaction_Id());
                        obj.put(CommonString.KEY_ProductId, dmsList.get(j).getProductId());
                        obj.put(CommonString.KEY_INVOICE_ID, dmsList.get(j).getInvId());
                        obj.put(CommonString.KEY_INVOICE_STATUS, dmsList.get(j).getInvoice_Status());
                        obj.put(CommonString.KEY_INVOICE_NUMBER, dmsList.get(j).getInvoice_number());
                        obj.put(CommonString.KEY_INVOICE_TYPE, dmsList.get(j).getInvoice_type());
                        obj.put(CommonString.KEY_INVOICE_DATE, dmsList.get(j).getInvoice_date());
                        obj.put(CommonString.KEY_INVOICE_QTY, dmsList.get(j).getConsumer_qty());
                        obj.put(CommonString.KEY_ACTUAL_QTY, dmsList.get(j).getActualQty());
                        obj.put(CommonString.KEY_COUNTER_ID, dmsList.get(j).getCounter_id());
                        if (dmsList.get(j).isConfirmChecked()) {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "1");
                        } else {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "0");
                        }
                        obj.put(CommonString.KEY_REASON_ID, dmsList.get(j).getReasonId());
                        obj.put(CommonString.KEY_SOURCE, dmsList.get(j).getSource());

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }

            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS_NEWPRODUCT)) {
                db.open();
                ArrayList<ProductMaster> manualIList = db.getManualInwardStock(objectcurrent.getTransaction_Id());
                if (manualIList.size() > 0) {
                    topUpArray = new JSONArray();
                    complete_json_str = "";
                    key = "Manual_Inward_NewProduct";
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < manualIList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("UserId", manualIList.get(j).getUser_id());
                        obj.put(CommonString.KEY_VISIT_DATE, manualIList.get(j).getVisit_date());
                        obj.put("TranId", manualIList.get(j).getTransaction_Id());
                        obj.put(CommonString.KEY_ProductId, manualIList.get(j).getProductId());
                        obj.put(CommonString.KEY_INVOICE_ID, manualIList.get(j).getInvId());
                        obj.put(CommonString.KEY_INVOICE_STATUS, manualIList.get(j).getInvoice_Status());
                        obj.put(CommonString.KEY_INVOICE_NUMBER, manualIList.get(j).getInvoice_number());
                        obj.put(CommonString.KEY_INVOICE_TYPE, manualIList.get(j).getInvoice_type());
                        obj.put(CommonString.KEY_INVOICE_DATE, manualIList.get(j).getInvoice_date());
                        obj.put(CommonString.KEY_INVOICE_QTY, manualIList.get(j).getConsumer_qty());
                        obj.put(CommonString.KEY_ACTUAL_QTY, manualIList.get(j).getActualQty());
                        obj.put(CommonString.KEY_COUNTER_ID, manualIList.get(j).getCounter_id());
                        obj.put(CommonString.KEY_INVOICE_IMG, manualIList.get(j).getInvoice_img());
                        if (manualIList.get(j).isConfirmChecked()) {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "1");
                        } else {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "0");
                        }

                        obj.put(CommonString.KEY_REASON_ID, manualIList.get(j).getReasonId());
                        obj.put(CommonString.KEY_SOURCE, manualIList.get(j).getSource());
                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }

            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS)) {
                db.open();
                ArrayList<ProductMaster> manualIList = db.getManualInwardStock(objectcurrent.getTransaction_Id());
                if (manualIList.size() > 0) {
                    topUpArray = new JSONArray();
                    complete_json_str = "";
                    key = "Manual_Inward_ExistProduct";
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < manualIList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("UserId", manualIList.get(j).getUser_id());
                        obj.put(CommonString.KEY_VISIT_DATE, manualIList.get(j).getVisit_date());
                        obj.put("TranId", manualIList.get(j).getTransaction_Id());
                        obj.put(CommonString.KEY_ProductId, manualIList.get(j).getProductId());
                        obj.put(CommonString.KEY_INVOICE_ID, manualIList.get(j).getInvId());
                        obj.put(CommonString.KEY_INVOICE_STATUS, manualIList.get(j).getInvoice_Status());
                        obj.put(CommonString.KEY_INVOICE_NUMBER, manualIList.get(j).getInvoice_number());
                        obj.put(CommonString.KEY_INVOICE_TYPE, manualIList.get(j).getInvoice_type());
                        obj.put(CommonString.KEY_INVOICE_DATE, manualIList.get(j).getInvoice_date());
                        obj.put(CommonString.KEY_INVOICE_QTY, manualIList.get(j).getConsumer_qty());
                        obj.put(CommonString.KEY_ACTUAL_QTY, manualIList.get(j).getActualQty());
                        obj.put(CommonString.KEY_COUNTER_ID, manualIList.get(j).getCounter_id());
                        obj.put(CommonString.KEY_INVOICE_IMG, manualIList.get(j).getInvoice_img());

                        if (manualIList.get(j).isConfirmChecked()) {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "1");
                        } else {
                            obj.put(CommonString.KEY_COUNTER_CONFIRM, "0");
                        }

                        obj.put(CommonString.KEY_REASON_ID, manualIList.get(j).getReasonId());
                        obj.put(CommonString.KEY_SOURCE, manualIList.get(j).getSource());
                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.CONSUMERSALE)) {
                db.open();
                ArrayList<InvoiceGetterSetter> consumerSalesList = db.getsaleTrackingHeaderData(visit_date, counter_id, null, false, true, objectcurrent.getTransaction_Id());
                if (!consumerSalesList.isEmpty()) {
                    complete_json_str = "";
                    int consumerIndex = 0;
                    topUpArray = new JSONArray();
                    if (consumerSalesList.get(consumerIndex).getUserType().equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                        key = "ConsumerSalesWithapplyiedProductFromME";
                    } else {
                        key = "ConsumerSalesWithapplyiedProduct";
                    }
                    db.open();
                    jcp_Object = db.getBIDfromJCP(consumerSalesList.get(consumerIndex).getStrUserId(), counter_id);
                    JSONArray consumerUserInfoArray = new JSONArray();
                    JSONArray consumerGivenProductArray = new JSONArray();
                    JSONArray consumerpromotionArray = new JSONArray();
                    JSONObject obj = new JSONObject();
                    obj.put("MID", jcp_Object.getMID());
                    obj.put("BID", jcp_Object.getBID());
                    obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                    obj.put("VisiteDate", visit_date);
                    obj.put("POS_Sale", "1");
                    obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                    obj.put("ConsumerName", consumerSalesList.get(consumerIndex).getCustomer_name());
                    obj.put("MobileNumber", consumerSalesList.get(consumerIndex).getMobile_no());
                    obj.put("EmailId", consumerSalesList.get(consumerIndex).getConsumer_email_Id());
                    obj.put("Age", consumerSalesList.get(consumerIndex).getConsumer_age());
                    obj.put("SkinType", consumerSalesList.get(consumerIndex).getConsumer_skinType());
                    obj.put("Gender", consumerSalesList.get(consumerIndex).getCustomer_gender());
                    obj.put("DemoGiven", consumerSalesList.get(consumerIndex).getDemo_given_str());
                    obj.put("ProductSold", consumerSalesList.get(consumerIndex).getProduct_sold_str());
                    obj.put("SkinGenius", consumerSalesList.get(consumerIndex).getSkin_genius_str());
                    obj.put("MaybellineVTO", consumerSalesList.get(consumerIndex).getMaybelline_vto_str());
                    obj.put("ReceiptNumber", consumerSalesList.get(consumerIndex).getReccept_count());
                    obj.put("ConsumerTime", consumerSalesList.get(consumerIndex).getPercheasing_tym());
                    obj.put("TermConditions", consumerSalesList.get(consumerIndex).getStr_termcondition());
                    obj.put("ConsumerNoSaleImg", consumerSalesList.get(consumerIndex).getConsumer_no_saleImg());
                    obj.put("SourceofSales", consumerSalesList.get(consumerIndex).getSourceofSales());
                    consumerUserInfoArray.put(obj);
                    db.open();
                    ArrayList<InvoiceGetterSetter> childList = db.getsalesTrackingByUserMobile(consumerSalesList.get(consumerIndex).getReccept_count(), consumerSalesList.get(consumerIndex).getMobile_no(), consumerSalesList.get(consumerIndex).getVisit_date(), counter_id, consumerSalesList.get(consumerIndex).getStrUserId());
                    if (!childList.isEmpty()) {
                        for (int k = 0; k < childList.size(); k++) {
                            if (!childList.get(k).getProduct_Id().equals("0") && !childList.get(k).isPromo_flag()) {
                                obj = new JSONObject();
                                obj.put("MID", jcp_Object.getMID());
                                obj.put("BID", jcp_Object.getBID());
                                obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                obj.put("ProductId", childList.get(k).getProduct_Id());
                                obj.put("Quantity", childList.get(k).getQuantity());
                                obj.put("ProductMRP", childList.get(k).getProduct_rate());
                                obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code());
                                obj.put("Invoice_Type", childList.get(k).getStr_invoiceType());
                                consumerGivenProductArray.put(obj);

                            } else if (childList.get(k).isPromo_flag() && childList.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) {
                                obj = new JSONObject();
                                obj.put("MID", jcp_Object.getMID());
                                obj.put("BID", jcp_Object.getBID());
                                obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                obj.put("ProductId", childList.get(k).getProduct_Id());
                                obj.put("Quantity", childList.get(k).getQuantity());
                                obj.put("ProductMRP", childList.get(k).getProduct_rate());
                                obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code());
                                obj.put("Invoice_Type", "Saleable");
                                consumerGivenProductArray.put(obj);
                            }
                        }
                    }
                    ///get promo product
                    db.open();
                    ArrayList<InvoiceGetterSetter> promotionList = db.getapplyeid_promotion(consumerSalesList.get(consumerIndex).getReccept_count(), consumerSalesList.get(consumerIndex).getMobile_no(), consumerSalesList.get(consumerIndex).getVisit_date(), counter_id, consumerSalesList.get(consumerIndex).getStrUserId());
                    if (!promotionList.isEmpty()) {
                        for (int k = 0; k < promotionList.size(); k++) {
                            obj = new JSONObject();
                            obj.put("MID", jcp_Object.getMID());
                            obj.put("BID", jcp_Object.getBID());
                            obj.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                            obj.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                            obj.put("PromoType", promotionList.get(k).getPromo_type());

                            ArrayList<InvoiceGetterSetter> applyedProducts = new ArrayList<>();
                            JSONArray jsonArrayPromoApplyiedOnProductId = new JSONArray();
                            if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffSameProduct")) {
                                applyedProducts = promotionList.get(k).getApplyiedproductList();
                                if (!applyedProducts.isEmpty()) {
                                    jsonArrayPromoApplyiedOnProductId = new JSONArray();
                                    for (int h = 0; h < applyedProducts.size(); h++) {
                                        JSONObject obj7 = new JSONObject();
                                        obj7.put("MID", jcp_Object.getMID());
                                        obj7.put("BID", jcp_Object.getBID());
                                        obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                        obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                        obj7.put("PromoType", promotionList.get(k).getPromo_type());
                                        obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id());
                                        obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id());
                                        obj7.put("Rate", applyedProducts.get(h).getProduct_rate());
                                        obj7.put("MRP", applyedProducts.get(h).getMrp());
                                        obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code());
                                        obj7.put("QTY", applyedProducts.get(h).getQuantity());
                                        obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise());
                                        jsonArrayPromoApplyiedOnProductId.put(obj7);
                                    }
                                }
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", "0");
                                obj.put("ProductId", 0);
                                obj.put("Quantity", 0);
                                if (!applyedProducts.isEmpty()) {
                                    obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId);
                                } else {
                                    obj.put("PromoApplyiedOnProducts", "");
                                }
                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffAdditionalProduct")) {
                                applyedProducts = promotionList.get(k).getApplyiedproductList();
                                if (!applyedProducts.isEmpty()) {
                                    jsonArrayPromoApplyiedOnProductId = new JSONArray();
                                    for (int h = 0; h < applyedProducts.size(); h++) {
                                        JSONObject obj7 = new JSONObject();
                                        obj7.put("MID", jcp_Object.getMID());
                                        obj7.put("BID", jcp_Object.getBID());
                                        obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                        obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                        obj7.put("PromoType", promotionList.get(k).getPromo_type());
                                        obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id());
                                        obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id());
                                        obj7.put("Rate", applyedProducts.get(h).getProduct_rate());
                                        obj7.put("MRP", applyedProducts.get(h).getMrp());
                                        obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code());
                                        obj7.put("QTY", applyedProducts.get(h).getQuantity());
                                        obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise());
                                        jsonArrayPromoApplyiedOnProductId.put(obj7);
                                    }
                                }
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", "0");
                                obj.put("ProductId", 0);
                                obj.put("Quantity", 0);
                                if (!applyedProducts.isEmpty()) {
                                    obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId);
                                } else {
                                    obj.put("PromoApplyiedOnProducts", "");
                                }
                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("ValueOffAdditionalProduct")) {
                                applyedProducts = promotionList.get(k).getApplyiedproductList();
                                if (!applyedProducts.isEmpty()) {
                                    jsonArrayPromoApplyiedOnProductId = new JSONArray();
                                    for (int h = 0; h < applyedProducts.size(); h++) {
                                        JSONObject obj7 = new JSONObject();
                                        obj7.put("MID", jcp_Object.getMID());
                                        obj7.put("BID", jcp_Object.getBID());
                                        obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                        obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                        obj7.put("PromoType", promotionList.get(k).getPromo_type());
                                        obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id());
                                        obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id());
                                        obj7.put("Rate", applyedProducts.get(h).getProduct_rate());
                                        obj7.put("MRP", applyedProducts.get(h).getMrp());
                                        obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code());
                                        obj7.put("QTY", applyedProducts.get(h).getQuantity());
                                        obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise());
                                        jsonArrayPromoApplyiedOnProductId.put(obj7);
                                    }
                                }
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", "0");
                                obj.put("ProductId", 0);
                                obj.put("Quantity", 0);
                                if (!applyedProducts.isEmpty()) {
                                    obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId);
                                } else {
                                    obj.put("PromoApplyiedOnProducts", "");
                                }
                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffWorth")) {
                                applyedProducts = promotionList.get(k).getApplyiedproductList();
                                if (!applyedProducts.isEmpty()) {
                                    jsonArrayPromoApplyiedOnProductId = new JSONArray();
                                    for (int h = 0; h < applyedProducts.size(); h++) {
                                        JSONObject obj7 = new JSONObject();
                                        obj7.put("MID", jcp_Object.getMID());
                                        obj7.put("BID", jcp_Object.getBID());
                                        obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                        obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                        obj7.put("PromoType", promotionList.get(k).getPromo_type());
                                        obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id());
                                        obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id());
                                        obj7.put("Rate", applyedProducts.get(h).getProduct_rate());
                                        obj7.put("MRP", applyedProducts.get(h).getMrp());
                                        obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code());
                                        obj7.put("QTY", applyedProducts.get(h).getQuantity());
                                        obj7.put("DISCOUNT", applyedProducts.get(h).getDiscounted_value_productwise());
                                        jsonArrayPromoApplyiedOnProductId.put(obj7);
                                    }
                                }
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", "0");
                                obj.put("ProductId", 0);
                                obj.put("Quantity", 0);
                                if (!applyedProducts.isEmpty()) {
                                    obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId);
                                } else {
                                    obj.put("PromoApplyiedOnProducts", "");
                                }


                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Worth")) {
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", "0");
                                obj.put("ProductId", 0);
                                obj.put("Quantity", 0);
                                obj.put("PromoApplyiedOnProducts", "");

                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("OffProduct")) {
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", promotionList.get(k).getProduct_rate());
                                obj.put("ProductId", promotionList.get(k).getProduct_Id());
                                obj.put("Quantity", promotionList.get(k).getQuantity());
                                obj.put("PromoApplyiedOnProducts", "");

                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Gift")) {
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", 0);
                                obj.put("Rate", 0);
                                obj.put("ProductId", promotionList.get(k).getProduct_Id());
                                obj.put("Quantity", promotionList.get(k).getQuantity());
                                obj.put("PromoApplyiedOnProducts", "");

                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("Product")) {
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", 0);
                                obj.put("Rate", 0);
                                obj.put("ProductId", promotionList.get(k).getProduct_Id());
                                obj.put("Quantity", promotionList.get(k).getQuantity());
                                obj.put("PromoApplyiedOnProducts", "");
                            } else if (promotionList.get(k).getPromo_type().equalsIgnoreCase("WorthWithProduct")) {
                                applyedProducts = promotionList.get(k).getApplyiedproductList();
                                if (!applyedProducts.isEmpty()) {
                                    jsonArrayPromoApplyiedOnProductId = new JSONArray();
                                    for (int h = 0; h < applyedProducts.size(); h++) {
                                        JSONObject obj7 = new JSONObject();
                                        obj7.put("MID", jcp_Object.getMID());
                                        obj7.put("BID", jcp_Object.getBID());
                                        obj7.put("UserId", consumerSalesList.get(consumerIndex).getStrUserId());
                                        obj7.put("TranId", consumerSalesList.get(consumerIndex).getUnique_code());
                                        obj7.put("PromoType", promotionList.get(k).getPromo_type());
                                        obj7.put("PromoId", applyedProducts.get(h).getPromotion_Id());
                                        obj7.put("PromoApplyiedOnProductId", applyedProducts.get(h).getProduct_Id());
                                        obj7.put("Rate", applyedProducts.get(h).getProduct_rate());
                                        obj7.put("MRP", applyedProducts.get(h).getMrp());
                                        obj7.put("EanCode", applyedProducts.get(h).getScan_ean_code_or_enterd_ean_code());
                                        obj7.put("QTY", applyedProducts.get(h).getQuantity());
                                        obj7.put("DISCOUNT", 0);
                                        jsonArrayPromoApplyiedOnProductId.put(obj7);
                                    }
                                }
                                obj.put("PromoId", promotionList.get(k).getPromotion_Id());
                                obj.put("Discounted_Rs", promotionList.get(k).getDiscounted_value());
                                obj.put("Rate", "0");
                                obj.put("ProductId", 0);
                                obj.put("Quantity", 0);
                                if (!applyedProducts.isEmpty()) {
                                    obj.put("PromoApplyiedOnProducts", jsonArrayPromoApplyiedOnProductId);
                                } else {
                                    obj.put("PromoApplyiedOnProducts", "");
                                }
                            }
                            ///adding promotion Data--------------
                            consumerpromotionArray.put(obj);
                        }
                    }

                    JSONObject jsonObject4 = null;
                    if (!childList.isEmpty()) {
                        jsonObject4 = new JSONObject();
                        jsonObject4.put("Consumer_User_Info", consumerUserInfoArray);
                        jsonObject4.put("Consumer_Product_Sold", consumerGivenProductArray);
                        jsonObject4.put("Consumer_Applied_Promo", consumerpromotionArray);
                    } else {
                        jsonObject4 = new JSONObject();
                        jsonObject4.put("Consumer_User_Info", consumerUserInfoArray);
                        jsonObject4.put("Consumer_Product_Sold", "");
                        jsonObject4.put("Consumer_Applied_Promo", "");
                    }
                    //test("promojsondata", jsonObject4.toString());
                    complete_json_str = jsonObject4.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.CONSUMERRETURN)) {
                db.open();
                ArrayList<InvoiceGetterSetter> consumerreturnList = db.getsaleReturnHeaderData(jcp_Object.getVisitDate(), counter_id, username, true, true, objectcurrent.getTransaction_Id());
                if (!consumerreturnList.isEmpty()) {
                    int consumerIndex = 0;
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    key = "Consumer_Return_Data";
                    db.open();
                    jcp_Object = db.getBIDfromJCP(consumerreturnList.get(consumerIndex).getStrUserId(), counter_id);
                    JSONArray consumerReturnUserInfoArray = new JSONArray();
                    JSONArray consumerReturnProductArray = new JSONArray();
                    JSONArray replaceProductArray = new JSONArray();
                    JSONObject obj = new JSONObject();
                    obj.put("MID", jcp_Object.getMID());
                    obj.put("BID", jcp_Object.getBID());
                    obj.put("UserId", consumerreturnList.get(consumerIndex).getStrUserId());
                    obj.put("Counter_Id", counter_id);
                    obj.put("VisiteDate", jcp_Object.getVisitDate());
                    obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code());
                    obj.put("ConsumerName", consumerreturnList.get(consumerIndex).getCustomer_name());
                    obj.put("BillNo", consumerreturnList.get(consumerIndex).getConsumer_return_bill_no());
                    obj.put("MobileNo", consumerreturnList.get(consumerIndex).getMobile_no());
                    obj.put("Gender", consumerreturnList.get(consumerIndex).getCustomer_gender());
                    obj.put("KeyId", consumerreturnList.get(consumerIndex).getReccept_count()).toString();
                    consumerReturnUserInfoArray.put(obj);

                    db.open();
                    ArrayList<InvoiceGetterSetter> childList = db.getsalesReturnChildData(consumerreturnList.get(consumerIndex).getReccept_count(), jcp_Object.getVisitDate(), counter_id, username, true);
                    for (int k = 0; k < childList.size(); k++) {
                        obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("BID", jcp_Object.getBID());
                        obj.put("UserId", childList.get(k).getUserName());
                        obj.put("Counter_Id", counter_id);
                        obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code());
                        obj.put("ProductId", childList.get(k).getProduct_Id());
                        obj.put("Quantity", childList.get(k).getQuantity());
                        obj.put("ProductMRP", childList.get(k).getProduct_rate());
                        obj.put("EANCode", childList.get(k).getScan_ean_code_or_enterd_ean_code());
                        obj.put("Reason_Id", childList.get(k).getCon_return_reason_Id());
                        consumerReturnProductArray.put(obj);

                    }

                    db.open();
                    ArrayList<InvoiceGetterSetter> replaceProductList = db.getsalesReturnReplaceProduct(consumerreturnList.get(consumerIndex).getReccept_count(), jcp_Object.getVisitDate(), counter_id, username, true);
                    for (int k = 0; k < replaceProductList.size(); k++) {
                        obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("BID", jcp_Object.getBID());
                        obj.put("UserId", consumerreturnList.get(consumerIndex).getStrUserId());
                        obj.put("Counter_Id", counter_id);
                        obj.put("TranId", consumerreturnList.get(consumerIndex).getUnique_code());
                        obj.put("ProductId", replaceProductList.get(k).getProduct_Id());
                        obj.put("Quantity", replaceProductList.get(k).getQuantity());
                        obj.put("ProductMRP", replaceProductList.get(k).getProduct_rate());
                        obj.put("EANCode", replaceProductList.get(k).getScan_ean_code_or_enterd_ean_code());
                        replaceProductArray.put(obj);

                    }


                    JSONObject jsonObject4 = new JSONObject();
                    jsonObject4.put("Consumer_Return_User_Info", consumerReturnUserInfoArray);
                    jsonObject4.put("Consumer_Return_Product", consumerReturnProductArray);
                    jsonObject4.put("Consumer_Return_Replace_Product", replaceProductArray);

                    complete_json_str = jsonObject4.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.LEAVE_MANAGEMENT)) {
                db.open();
                T_LeaveRequest leaveRequestObject = db.getinserted_leave_request_data(counter_id, username, jcp_Object.getVisitDate(), objectcurrent.getTransaction_Id(), true);
                if (leaveRequestObject.getTransId() != null && !leaveRequestObject.getTransId().equals("")) {
                    key = "RequestFor_Leave_Approval";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    JourneyPlan jcpfor_bid = db.getBIDfromJCP(leaveRequestObject.getUserId(), counter_id);
                    JSONObject obj = getJsonObject(jcpfor_bid, leaveRequestObject);
                    topUpArray.put(obj);

                    complete_json_str = topUpArray.toString();
                }

            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.BREAK_MANAGEMENT)) {
                db.open();
                MasterBreak breakManagementObject = db.getBreakManagementforuploadList(counter_id, jcp_Object.getVisitDate(), username, objectcurrent.getTransaction_Id(), true);
                if (breakManagementObject.getBreakId() != null && !breakManagementObject.getEndTym().equals("")) {
                    key = "Break_Management_Data";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    JourneyPlan jcpfor_bid = db.getBIDfromJCP(breakManagementObject.getUserId(), counter_id);
                    JSONObject obj = new JSONObject();
                    obj.put("MID", jcpfor_bid.getMID());
                    obj.put("BID", jcpfor_bid.getBID());
                    obj.put("UserId", breakManagementObject.getUserId());
                    obj.put("VisitDate", jcpfor_bid.getVisitDate());
                    obj.put("TranId", breakManagementObject.getTransId());
                    obj.put("BreakId", breakManagementObject.getBreakId().toString());
                    obj.put("StartTym", convertTym(breakManagementObject.getStartTym()));
                    obj.put("EndTym", convertTym(breakManagementObject.getEndTym()));
                    obj.put("TotalDuration", breakManagementObject.getTotalDuration().toString());
                    topUpArray.put(obj);

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.VISIBILITY)) {
                db.open();
                ArrayList<MasterPosm> visibilityList = db.getVisibility_inserted_data(counter_id, jcp_Object.getVisitDate(), objectcurrent.getTransaction_Id(), true);
                if (!visibilityList.isEmpty()) {
                    key = "VisibiliElementData";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < visibilityList.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("UserId", visibilityList.get(j).getUserId());
                        obj.put("PosmId", visibilityList.get(j).getPosmId());
                        obj.put("PosmTypeId", visibilityList.get(j).getPosmTypeId());
                        obj.put("Counter_id", counter_id);
                        if (visibilityList.get(j).getPromotion_exists_state().equalsIgnoreCase("Yes")) {
                            obj.put("Promotion_Exists", "1");
                            obj.put("Promo_Img", visibilityList.get(j).getPromotion_img());
                            obj.put("PReason_Id", "0");
                        } else {
                            obj.put("Promotion_Exists", "0");
                            obj.put("Promo_Img", "");
                            obj.put("PReason_Id", visibilityList.get(j).getPromotion_currect_ans_Id());
                        }

                        topUpArray.put(obj);
                    }

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.MAKEOVER_CAPTURE)) {
                db.open();
                ArrayList<InvoiceGetterSetter> memakeoverList = db.getMakeover(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true);
                if (!memakeoverList.isEmpty()) {
                    key = "ME_Makeover_Capture";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    int consumerIndex = 0;
                    db.open();
                    JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id);
                    JSONObject obj = getJsonObject(jcp, memakeoverList, consumerIndex);

                    topUpArray.put(obj);

                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.SKINGENIUS)) {
                db.open();
                ArrayList<InvoiceGetterSetter> memakeoverList = db.getskinGeniusData(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true);
                if (!memakeoverList.isEmpty()) {
                    key = "Skin_Genius";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    int consumerIndex = 0;
                    db.open();
                    JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id);
                    JSONObject obj = new JSONObject();
                    obj.put("MID", jcp.getMID());
                    obj.put("BID", jcp.getBID());
                    obj.put("VisiteDate", jcp.getVisitDate());
                    obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId());
                    obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code());
                    obj.put("SkinGeniusImg", memakeoverList.get(consumerIndex).getInvoice_img());
                    topUpArray.put(obj);
                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.OPEN_SKINGENIUS)) {
                db.open();
                ArrayList<InvoiceGetterSetter> memakeoverList = db.getOpenskinGeniusData(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true);
                if (!memakeoverList.isEmpty()) {
                    key = "Open_Skin_Genius_Count";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    int consumerIndex = 0;
                    db.open();
                    JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id);
                    JSONObject obj = new JSONObject();
                    obj.put("MID", jcp.getMID());
                    obj.put("BID", jcp.getBID());
                    obj.put("VisiteDate", memakeoverList.get(consumerIndex).getVisit_date());
                    obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId());
                    obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code());
                    obj.put("OpenSkinGeniusCount", memakeoverList.get(consumerIndex).getMaybellineorskingenius_count());
                    topUpArray.put(obj);
                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.OPEN_MAYBELLINE)) {
                db.open();
                ArrayList<InvoiceGetterSetter> memakeoverList = db.getOpenMaybellineData(jcp_Object.getVisitDate(), counter_id, username, objectcurrent.getTransaction_Id(), true);
                if (!memakeoverList.isEmpty()) {
                    key = "Open_Maybelline_Count";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    int consumerIndex = 0;
                    db.open();
                    JourneyPlan jcp = db.getBIDfromJCP(memakeoverList.get(consumerIndex).getStrUserId(), counter_id);
                    JSONObject obj = new JSONObject();
                    obj.put("MID", jcp.getMID());
                    obj.put("BID", jcp.getBID());
                    obj.put("VisiteDate", jcp.getVisitDate());
                    obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId());
                    obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code());
                    obj.put("OpenMaybellineCount", memakeoverList.get(consumerIndex).getMaybellineorskingenius_count());
                    topUpArray.put(obj);
                    complete_json_str = topUpArray.toString();
                }
            } else if (objectcurrent.getStock_type().equalsIgnoreCase(CommonString.COMP_OFFERS)) {
                db.open();
                ArrayList<MasterCompetitonBrandWiseNuance> compOffers = db.getInsertedCompOffers(visit_date, counter_id, objectcurrent.getTransaction_Id(), true);
                if (compOffers.size() > 0) {
                    key = "CompOffers_TVA_New";
                    complete_json_str = "";
                    topUpArray = new JSONArray();
                    Gson gson = new Gson();
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_id);
                    for (int j = 0; j < compOffers.size(); j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("Counter_id", counter_id);
                        obj.put("UserId", compOffers.get(j).get_userId());
                        obj.put("TransId", objectcurrent.getTransaction_Id());

                        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());
                            }
                            obj.put("Present", 1);
                            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("KeyID", compOffers.get(j).getKeyId());
                            obj.put("DataForMonth", compOffers.get(j).getDateOfMonth());
                            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("KeyID", 0);
                            obj.put("Present", 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("GWP_Available", 0);
                            obj.put("GWP_Image", "");
                            obj.put("NoOfBa", 0);
                            obj.put("NumOfCounter", 0);
                            obj.put("NewLaunchMrp", 0);
                            obj.put("AvgTarget", 0);
                            obj.put("AvgOfftake", 0);
                            obj.put("TvaPercentage", 0);
                            obj.put("BAListData", balistdata);
                        }
                        topUpArray.put(obj);
                    }
                    complete_json_str = topUpArray.toString();
                }
            }

            if (!complete_json_str.isEmpty()) {
                db.open();
                jcp_Object = db.getBIDfromJCP(null, counter_id);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", key);
                jsonObject.put("JsonData", complete_json_str);
                jsonObject.put("UserId", username);
                saleablejson_str = jsonObject.toString();
                //test("compjsondata", saleablejson_str);
            }
        } catch (JSONException e) {
            e.fillInStackTrace();
            pd.dismiss();
            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
        }

        return saleablejson_str;
    }

    private static @NonNull JSONObject getJsonObject(JourneyPlan jcp, ArrayList<InvoiceGetterSetter> memakeoverList, int consumerIndex) throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("MID", jcp.getMID());
        obj.put("BID", jcp.getBID());
        obj.put("VisiteDate", jcp.getVisitDate());
        obj.put("UserId", memakeoverList.get(consumerIndex).getStrUserId());
        obj.put("TranId", memakeoverList.get(consumerIndex).getUnique_code());
        obj.put("ConsumerName", memakeoverList.get(consumerIndex).getCustomer_name());
        obj.put("MobileNumber", memakeoverList.get(consumerIndex).getMobile_no());
        obj.put("EmailId", memakeoverList.get(consumerIndex).getConsumer_email_Id());
        obj.put("Age", memakeoverList.get(consumerIndex).getConsumer_age());
        obj.put("SkinType", memakeoverList.get(consumerIndex).getConsumer_skinType());
        obj.put("Look", memakeoverList.get(consumerIndex).getLook_creater_str());
        obj.put("Gender", memakeoverList.get(consumerIndex).getCustomer_gender());
        obj.put("BeforeMakeoverImg", memakeoverList.get(consumerIndex).getBefore_makeover_img());
        obj.put("AfterMakeoverImg", memakeoverList.get(consumerIndex).getAfter_makeover_img());
        obj.put("Feedback", memakeoverList.get(consumerIndex).getCst_feed_back_value());
        obj.put("TermConditions", memakeoverList.get(consumerIndex).getStr_termcondition());
        return obj;
    }

    private static @NonNull JSONObject getJsonObject(JourneyPlan jcpfor_bid, T_LeaveRequest leaveRequestObject) throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("MID", jcpfor_bid.getMID());
        obj.put("BID", jcpfor_bid.getBID());
        obj.put("UserId", leaveRequestObject.getUserId());
        obj.put("TranId", leaveRequestObject.getTransId());
        obj.put("Applied_Date", leaveRequestObject.getUpload_request_date());
        obj.put("From_Date", leaveRequestObject.getUpload_start_date_str());
        obj.put("End_Date", leaveRequestObject.getUpload_end_date_str());
        obj.put("Leave_Type", leaveRequestObject.getOne_day_leave_str());
        obj.put("Leave_TypeId", leaveRequestObject.getStr_leaveTypeId());
        obj.put("Reason", leaveRequestObject.getLeave_reason());
        return obj;
    }

    private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final ArrayList<ProductMaster> stockList, final ArrayList<ProductMaster> masterfinalList, final int masterfinal_index, final ProgressDialog pd) {
        try {
            db.open();
            JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_Id);
            JSONArray topUpArray = new JSONArray();
            String key = "";
            if (!stockList.isEmpty()) {
                if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.SALEABLE)) {
                    key = "SaleableFData";
                    for (int j = startIndex; j < endIndex; j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", stockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("REASON_ID", stockList.get(j).getReasonId());
                        obj.put("TranId", stockList.get(j).getTransaction_Id());
                        obj.put("UserId", username);
                        obj.put("CounterId", counter_Id);
                        //header image
                        String img = stockList.get(j).getImagePath();
                        if (img == null) {
                            img = "";
                        }

                        obj.put("Image", img);
                        ////for uploaded first time data if status is not null
                        int stk = stockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }
                        obj.put("STOCK", stk);
                        obj.put("Status", status);
                        topUpArray.put(obj);
                    }


                } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.TESTER)) {
                    key = "TesterFData";
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_Id);
                    for (int j = startIndex; j < endIndex; j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", stockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", stockList.get(j).getTransaction_Id());
                        obj.put("UserId", username);
                        obj.put("CounterId", counter_Id);
                        ////for uploaded first time data if status is not null
                        int stk = stockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);
                        obj.put("Status", status);
                        topUpArray.put(obj);
                    }

                } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.SAMPLE)) {
                    key = "SampleFData";
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_Id);
                    for (int j = startIndex; j < endIndex; j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", stockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", stockList.get(j).getTransaction_Id());
                        obj.put("UserId", username);
                        obj.put("CounterId", counter_Id);
                        ////for uploaded first time data if status is not null
                        int stk = stockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);
                        obj.put("Status", status);
                        topUpArray.put(obj);
                    }

                } else if (stockList.get(0).getStock_type().equalsIgnoreCase(CommonString.GWP)) {
                    key = "GWPFData";
                    db.open();
                    jcp_Object = db.getBIDfromJCP(null, counter_Id);
                    for (int j = startIndex; j < endIndex; j++) {
                        JSONObject obj = new JSONObject();
                        obj.put("ProductId", stockList.get(j).getProductId());
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("TranId", stockList.get(j).getTransaction_Id());
                        obj.put("UserId", username);
                        obj.put("CounterId", counter_Id);
                        ////for uploaded first time data if status is not null
                        int stk = stockList.get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);
                        obj.put("Status", status);
                        topUpArray.put(obj);
                    }
                }
            }

            db.open();
            jcp_Object = db.getBIDfromJCP(null, counter_Id);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcp_Object.getMID());
            jsonObject.put("Keys", key);
            jsonObject.put("JsonData", topUpArray.toString());
            jsonObject.put("UserId", username);

            String jsonString = jsonObject.toString();
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.isEmpty()) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    if (endIndex < stockList.size()) {
                                        int startIndex1 = endIndex;
                                        int endIndex1 = 0;
                                        if (startIndex1 + 200 < stockList.size()) {
                                            endIndex1 = startIndex1 + 200;
                                        } else {
                                            endIndex1 = stockList.size();
                                        }
                                        UploadStockRecursive(status, startIndex1, endIndex1, stockList, masterfinalList, masterfinal_index, pd);
                                    } else {
                                        ///-------------update status..........////----------
                                        db.open();
                                        update_upload_status(counter_Id, masterfinalList.get(masterfinal_index));
                                        //-------------------//upload recursive.........method..............
                                        final int[] finalJsonIndex = {masterfinal_index};
                                        finalJsonIndex[0]++;
                                        if (finalJsonIndex[0] != masterfinalList.size()) {
                                            handleuploaddata_withcase(masterfinalList, finalJsonIndex[0], pd);
                                        } else {
                                            //////show masage......data upload .... success......
                                            pd.dismiss();
                                            if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) {
                                                ProgressDialog pd = new ProgressDialog(context);
                                                pd.setCancelable(false);
                                                pd.setMessage("Uploading Data" + "(" + "0/" + ")");
                                                pd.show();
                                                CommonUploadwithrecursive(db, true, pd);
                                            } else {
                                                ///finish activity........
                                                pd.dismiss();
                                                calling_method();
                                            }
                                        }
                                    }
                                } else {
                                    pd.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false);
                                }
                            }
                        } catch (Exception e) {
                            db.open();
                            pd.dismiss();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again");
                        }
                    } else {
                        pd.dismiss();
                        AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    pd.dismiss();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again");
                }
            });
        } catch (JSONException e) {
            e.fillInStackTrace();
            pd.dismiss();
            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again");
        }
    }


    public void upload_recursive_Data(String jsondata, final int index, final ArrayList<ProductMaster> final_list, final ProgressDialog pd) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    update_upload_status(counter_Id, final_list.get(index));
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != final_list.size()) {
                                        handleuploaddata_withcase(final_list, finalJsonIndex[0], pd);
                                    } else {
                                        //////show masage......data upload .... success......
                                        pd.dismiss();
                                        if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) {
                                            ProgressDialog pd = new ProgressDialog(context);
                                            pd.setCancelable(false);
                                            pd.setMessage("Uploading Data" + "(" + "0/" + ")");
                                            pd.show();
                                            CommonUploadwithrecursive(db, true, pd);
                                        } else {
                                            ////////////finish activty............
                                            pd.dismiss();
                                            calling_method();
                                        }
                                    }
                                } else {
                                    pd.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            pd.dismiss();
                        }
                    } else {
                        pd.dismiss();
                        AlertandMessages.showAlert((Activity) context, "Server Not Responding. Please upload again", false);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    pd.dismiss();
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please upload again", false);
                }
            });

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


    private void update_upload_status(String counter_Id, ProductMaster currentobj) {
        if (currentobj != null) {
            /////............update status.....................................
            db.open();
            db.updateMasterTransactionDataStatus(currentobj.getTransaction_Id());
            if (currentobj.getStock_type().equalsIgnoreCase(CommonString.RETURNTO_DB)) {
                db.open();
                db.updatereturntodistributor(counter_Id, currentobj.getTransaction_Id());
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS) || currentobj.getStock_type().equalsIgnoreCase(CommonString.INWARD_DMS_NEW_SKU)) {
                db.open();
                db.updateinwarddms(counter_Id, currentobj.getTransaction_Id());
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS) || currentobj.getStock_type().equalsIgnoreCase(CommonString.MANUALINWARD_DMS_NEWPRODUCT)) {
                db.open();
                db.updatemanualinward(counter_Id, currentobj.getTransaction_Id());
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.CONSUMERSALE)) {
                db.open();
                db.update_SalesTRacking(counter_Id, currentobj.getTransaction_Id());
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.CONSUMERRETURN)) {
                db.open();
                db.update_ConsumersReturn(counter_Id, currentobj.getTransaction_Id());
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.LEAVE_MANAGEMENT)) {
                db.open();
                db.update_leave_management_status(counter_Id, visit_date, username, currentobj.getTransaction_Id(), true);
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.BREAK_MANAGEMENT)) {
                db.open();
                db.update_break_management_status(counter_Id, visit_date, username, currentobj.getTransaction_Id(), true);
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.VISIBILITY)) {
                db.open();
                db.update_visibility(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_visibilisty);
                db.updateStockTransactionDataStatus(currentobj.getTransaction_Id());
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.MAKEOVER_CAPTURE)) {
                db.open();
                db.update_makeover(counter_Id, username, currentobj.getTransaction_Id(), true);
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.SKINGENIUS)) {
                db.open();
                db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Skin_Genius_Table);
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.OPEN_SKINGENIUS)) {
                db.open();
                db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Open_Skin_Genius_Table);
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.OPEN_MAYBELLINE)) {
                db.open();
                db.update_skinGenius_Category(counter_Id, username, currentobj.getTransaction_Id(), CommonString.Table_Open_Maybelline_Table);
            } else if (currentobj.getStock_type().equalsIgnoreCase(CommonString.COMP_OFFERS)) {
                db.open();
                db.update_visibility(counter_Id, username, currentobj.getTransaction_Id(), CommonString.COMP_OFFERS);
                db.updateStockTransactionDataStatus(currentobj.getTransaction_Id());
            } else {
                db.open();
                db.updateStockTransactionDataStatus(currentobj.getTransaction_Id());
            }
        }
    }

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

        if (view.getId() == R.id.img_manual_dataupload) {
            if (CommonFunctions.checkNetIsAvailable(context)) {
                masterList = db.getmasterTransaction(visit_date, counter_Id, true);
                if (masterList.size() > 0) {
                    clicked_flag = true;
                    pd = new ProgressDialog(context);
                    pd.setCancelable(false);
                    pd.setMessage("Uploading Data" + "(" + "0/" + ")");
                    pd.show();
                    handleuploaddata_withcase(masterList, 0, pd);
                } else if (!CommonFunctions.checkincomplete_upload_data(visit_date, counter_Id, db, true)) {
                    pd = new ProgressDialog(context);
                    pd.setCancelable(false);
                    pd.setMessage("Uploading Data" + "(" + "0/" + ")");
                    pd.show();
                    CommonUploadwithrecursive(db, true, pd);
                } else {
                    AlertandMessages.showToastMsg(context, "No data for upload");
                }
            } else {
                AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
            }


        } else if (view.getId() == R.id.img_manual_imageupload) {
            if (CommonFunctions.checkNetIsAvailable(context)) {
                upload_imagewithfolder();
            } else {
                AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
            }

        }
    }


    private void upload_imagewithfolder() {
        try {
            File f = new File(CommonString.getImagesFolder(context));
            ArrayList<String> finalList = new ArrayList<>();
            if (!getFileNames(f.listFiles()).isEmpty()) {
                for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) {
                    if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) {
                        finalList.add(getFileNames(f.listFiles()).get(k));
                    }
                }
            }
            if (!finalList.isEmpty()) {
                clicked_flag = true;
                pd = new ProgressDialog(context);
                pd.setCancelable(false);
                pd.setMessage("Uploading Images");
                pd.show();
                totalFiles = finalList.size();
                uploadedFiles = 0;
                UploadImageRecursive(pd);
            } else {
                AlertandMessages.showToastMsg(context, "No images for upload");
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }


    public void UploadImageRecursive(final ProgressDialog pd) {
        try {
            final int[] uploadedFiles = {0};
            final int[] statusforimage = {0};
            statusforimage[0] = 0;
            String filename = null, foldername = null;
            File f = new File(CommonString.getImagesFolder(context));
            ArrayList<String> finalList = new ArrayList<>();
            if (!getFileNames(f.listFiles()).isEmpty()) {
                for (int k = 0; k < getFileNames(f.listFiles()).size(); k++) {
                    if (!db.ischeck_uploaded_image(visit_date, getFileNames(f.listFiles()).get(k))) {
                        finalList.add(getFileNames(f.listFiles()).get(k));
                    }
                }
            }

            if (!finalList.isEmpty()) {
                filename = "";
                for (int i = 0; i < finalList.size(); i++) {
                    pd.setMessage("Uploading images" + "(" + uploadedFiles[0] + "/" + totalFiles + ")");
                    if (new File(CommonString.getImagesFolder(context) + finalList.get(i)).exists()) {
                        if (finalList.get(i).contains("_Counter_Selfie_img_")) {
                            foldername = "BACoverageImages";
                        } else if (finalList.get(i).contains("_cp_img_one_") || finalList.get(i).contains("_cp_img_two_")) {
                            foldername = "CounterProfileImages";
                        } else if (finalList.get(i).contains("_counter_img_one_") || finalList.get(i).contains("_counter_img_two_")) {
                            foldername = "CounterImages";
                        } else if (finalList.get(i).contains("_ba_AuditPic_") || finalList.get(i).contains("_ba_profile_img_")) {
                            foldername = "BAProfileImages";
                        } else if (finalList.get(i).contains("_Damaged_stock_img_") || finalList.get(i).contains("_Damage_header_img_")) {
                            foldername = "DamageStockImages";
                        } else if (finalList.get(i).contains("_groomed_img_mrng_") || finalList.get(i).contains("_groomed_img_noon_") || finalList.get(i).contains("_groomed_img_evning_")) {
                            foldername = "GroomingImages";
                        } else if (finalList.get(i).contains("_stock_check_img_") || finalList.get(i).contains("_tester_stock_img_") || finalList.get(i).contains("_suggested_stk_img") || finalList.get(i).contains("_Sample_stock_img")) {
                            foldername = "SaleableStockImages";
                        } else if (finalList.get(i).contains("_visibility_img_")) {
                            foldername = "VisibilityImages";
                        } else if (finalList.get(i).contains("_ConsumerSimg_")) {
                            foldername = "ConsumerInteractionImages";
                        } else if (finalList.get(i).contains("_QuizPic-")) {
                            foldername = "MEAuditImages";
                        } else if (finalList.get(i).contains("_before_makeo_img_") || finalList.get(i).contains("_after_makeo_img_")) {
                            foldername = "MeMakeoverImages";
                        } else if (finalList.get(i).contains("SurveyPic-")) {
                            foldername = "SurveyImages";
                        } else if (finalList.get(i).contains("_invoiceimg_")) {
                            foldername = "ConsumerReturnImages";
                        } else if (finalList.get(i).contains("_minwordsimg_")) {
                            foldername = "InwardImages";
                        } else if (finalList.get(i).contains("-SkinGenius-")) {
                            foldername = "SkinGeniusImages";
                        } else if (finalList.get(i).contains("-CompOfferImg-") || finalList.get(i).contains("-Gwp_CompOfferImg-")) {
                            foldername = "CompetitionOffersImages";
                        } else if (finalList.get(i).contains("_GeoTag-")) {
                            foldername = "GeoTagImages";
                        } else {
                            foldername = "BulkUpload";
                        }

                        filename = finalList.get(i);
                    }
                    break;
                }

                File originalFile = new File(CommonString.getImagesFolder(context) + filename);
                File finalFile = saveBitmapToFile(originalFile);
                if (finalFile == null) {
                    finalFile = originalFile;
                }

                String date = visit_date.replace("/", "");

                com.squareup.okhttp.OkHttpClient okHttpClient = new com.squareup.okhttp.OkHttpClient();
                okHttpClient.setConnectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS);
                okHttpClient.setWriteTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS);
                okHttpClient.setReadTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS);
                com.squareup.okhttp.RequestBody photo = com.squareup.okhttp.RequestBody.create(com.squareup
                        .okhttp.MediaType.parse("application/octet-stream"), finalFile);
                com.squareup.okhttp.RequestBody body1 = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file",
                        finalFile.getName(), photo).addFormDataPart("FolderName", foldername).addFormDataPart("Path", date).build();

                retrofit.Retrofit adapter = new retrofit.Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).client(okHttpClient)
                        .addConverterFactory(new StringConverterFactory()).build();
                PostApiForUpload api = adapter.create(PostApiForUpload.class);
                retrofit.Call<String> call = api.getUploadImageRetrofitOne(body1);
                final File finalFile1 = finalFile;
                final String finalFilename = filename;
                call.enqueue(new retrofit.Callback<String>() {
                    @Override
                    public void onResponse(retrofit.Response<String> response) {
                        try {
                            if (response.code() == 200 && response.message().equalsIgnoreCase("OK") && response.isSuccess() && response.body().contains("Success")) {
                                if (finalFilename.contains("_counter_img_two_") || finalFilename.contains("_counter_img_one_") || finalFilename.contains("_cp_img_one_") || finalFilename.contains("_cp_img_two_") || finalFilename.contains("_groomed_img_mrng_") || finalFilename.contains("_groomed_img_noon_") || finalFilename.contains("_groomed_img_evning_")) {
                                    db.open();
                                    db.insert_temp_image(finalFilename, visit_date);
                                } else {
                                    finalFile1.delete();
                                }

                                statusforimage[0] = 1;
                                uploadedFiles[0]++;
                            } else {
                                statusforimage[0] = 0;
                            }
                            if (statusforimage[0] == 0) {
                                pd.dismiss();
                                AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles);

                            } else {
                                if (totalFiles == uploadedFiles[0]) {
                                    pd.dismiss();
                                    AlertandMessages.showAlertlogin((Activity) context, "All images upload successfully");

                                } else {
                                    UploadImageRecursive(pd);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            statusforimage[0] = -1;
                            pd.dismiss();
                            AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles);

                        } catch (OutOfMemoryError error) {
                            statusforimage[0] = -1;
                            error.fillInStackTrace();
                            pd.dismiss();
                            AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) {
                            statusforimage[0] = -1;
                            pd.dismiss();
                            AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles);

                        }
                    }
                });
            }
        } catch (JsonSyntaxException e) {
            pd.dismiss();
            e.fillInStackTrace();
            AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles);
        } catch (Exception e) {
            pd.dismiss();
            e.fillInStackTrace();
            AlertandMessages.showAlertlogin((Activity) context, "Image not uploaded.Please try again." + "\n" + uploadedFiles + " images uploaded out of " + totalFiles);

        }
    }

    public void CommonUploadwithrecursive(Lorealba_Database db, boolean previous_date, ProgressDialog pd) {
        pd.setMessage("Uploading Data");
        db.open();
        baProfile_ImageList = db.getBaProfileListData(visit_date, counter_Id, previous_date);
        counterprofile_imgList = db.getCounterProfileListData(visit_date, counter_Id, previous_date);
        meQuizList = db.getme_quiz_from(visit_date, counter_Id, previous_date);
        masterRetailExcellenceArrayList = db.getRetailExcellence_from(visit_date, counter_Id, previous_date);
        productMasterArrayList = db.getProductMasterMeSale_from(visit_date, counter_Id, previous_date);
        groomingList = db.getgroomingdata(counter_Id, visit_date, previous_date);
        db.open();
        counterList = db.getba_counterimgList(counter_Id, visit_date, previous_date);
        if (baProfile_ImageList.size() > 0) {
            UploadBaProfile(pd, db, baProfile_ImageList, 0);
        } else if (counterprofile_imgList.size() > 0) {
            UploadCounterProfile(pd, db, counterprofile_imgList, 0);
        } else if (meQuizList.size() > 0) {
            UploadMeQuiz(pd, db, meQuizList, 0);
        } else if (groomingList.size() > 0) {
            UploadGrooming(pd, db, groomingList, 0);
        } else if (counterList.size() > 0) {
            UploadCounter(pd, db, counterList, 0);
        } else if (masterRetailExcellenceArrayList.size() > 0) {
            UploadRetailExcellence(pd, db, masterRetailExcellenceArrayList, 0);
        } else if (productMasterArrayList.size() > 0) {
            UploadMeSaleData(pd, db, productMasterArrayList, 0);
        }
    }


    private void UploadBaProfile(ProgressDialog loading, Lorealba_Database db, ArrayList<MasterProfile> baProfile_ImageList, int consumerIndex) {
        try {
            JSONArray topUpArray = new JSONArray();
            JSONArray storeDetail = new JSONArray();
            db.open();
            ArrayList<AuditDataGetterSetter> ba_profile_auditList = db.getAfterSaveAuditQuestionAnswerData(baProfile_ImageList.get(consumerIndex).getUserId(), null);
            if (ba_profile_auditList.size() > 0) {
                for (int j = 0; j < ba_profile_auditList.size(); j++) {
                    JSONObject obj = new JSONObject();
                    obj.put("Category_Id", ba_profile_auditList.get(j).getCATEGORY_ID());
                    obj.put("Question_Id", ba_profile_auditList.get(j).getQUESTION_ID());
                    obj.put("Question", ba_profile_auditList.get(j).getQUESTION());
                    obj.put("Answer_type", ba_profile_auditList.get(j).getANSWER_TYPE());
                    obj.put("Answer_Id", ba_profile_auditList.get(j).getANSWER_ID());
                    obj.put("Answer", ba_profile_auditList.get(j).getANSWER());
                    obj.put("Visit_Date", baProfile_ImageList.get(consumerIndex).getViisitDate());
                    db.open();
                    obj.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_Id).getMID());
                    obj.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId());
                    obj.put("Counter_id", counter_Id);
                    topUpArray.put(obj);
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Address", baProfile_ImageList.get(consumerIndex).getAddress());
            jsonObject.put("Dob", baProfile_ImageList.get(consumerIndex).getDob());
            jsonObject.put("Mobile_no", baProfile_ImageList.get(consumerIndex).getMobile());
            jsonObject.put("Email_Address", baProfile_ImageList.get(consumerIndex).getEmail());
            jsonObject.put("Instagram_Address", baProfile_ImageList.get(consumerIndex).getInstragramAddress());
            jsonObject.put("Profile_pic", baProfile_ImageList.get(consumerIndex).getProfilePic());
            jsonObject.put("Location", baProfile_ImageList.get(consumerIndex).getLocation());
            jsonObject.put("Landmark", baProfile_ImageList.get(consumerIndex).getLandmark());
            db.open();
            jsonObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_Id).getMID());
            jsonObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId());
            jsonObject.put("Counter_id", counter_Id);
            if (ba_profile_auditList.size() > 0) {
                jsonObject.put("BA_PROFILE_DATA", topUpArray);
            } else {
                jsonObject.put("BA_PROFILE_DATA", "");
            }
            storeDetail.put(jsonObject);

            JSONObject jsonFinalObject = new JSONObject();
            db.open();
            jsonFinalObject.put("MID", db.getBIDfromJCP(baProfile_ImageList.get(consumerIndex).getUserId(), counter_Id).getMID());
            jsonFinalObject.put("Keys", "BaProfileData");
            jsonFinalObject.put("JsonData", storeDetail.toString());
            jsonFinalObject.put("UserId", baProfile_ImageList.get(consumerIndex).getUserId());
            upload_BaProfilewithaudit(jsonFinalObject.toString(), loading, baProfile_ImageList.get(consumerIndex), consumerIndex);
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    public void upload_BaProfilewithaudit(String jsondata, final ProgressDialog loading, final MasterProfile object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    assert response.body() != null;
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateBaProfileStatus(object.getUserId(), object.getViisitDate(), CommonString.KEY_Y);
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != baProfile_ImageList.size()) {
                                        UploadBaProfile(loading, db, baProfile_ImageList, finalJsonIndex[0]);
                                    } else if (counterprofile_imgList.size() > 0) {
                                        UploadCounterProfile(loading, db, counterprofile_imgList, 0);
                                    } else if (meQuizList.size() > 0) {
                                        UploadMeQuiz(loading, db, meQuizList, 0);
                                    } else if (groomingList.size() > 0) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (counterList.size() > 0) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        ///finish activity
                                        loading.dismiss();
                                        calling_method();

                                    }
                                } else {
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Ba Profile). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            e.fillInStackTrace();
        }
    }

    private void UploadCounterProfile(ProgressDialog loading, Lorealba_Database db, ArrayList<JourneyPlan> counterimgList, int consumerIndex) {
        try {
            JSONArray storeDetail = new JSONArray();
            JSONObject jsonObject;
            if (counterimgList.size() > 0) {
                jsonObject = new JSONObject();
                db.open();
                jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_Id).getMID());
                jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId());
                jsonObject.put("ProfileImage1", counterimgList.get(consumerIndex).getProfileImage1());
                jsonObject.put("ProfileImage2", counterimgList.get(consumerIndex).getProfileImage2());
                jsonObject.put("Counterlength", counterimgList.get(consumerIndex).getCounterlength());
                jsonObject.put("Counterwidth", counterimgList.get(consumerIndex).getCounterwidth());
                jsonObject.put("SetupDate", counterimgList.get(consumerIndex).getSetupDate());
                jsonObject.put("Visit_Date", counterimgList.get(consumerIndex).getVisitDate());
                jsonObject.put("Counter_id", counter_Id);
                storeDetail.put(jsonObject);
            }

            jsonObject = new JSONObject();
            db.open();
            jsonObject.put("MID", db.getBIDfromJCP(counterimgList.get(consumerIndex).getUserId(), counter_Id).getMID());
            jsonObject.put("Keys", "ConterProfileData");
            jsonObject.put("JsonData", storeDetail.toString());
            jsonObject.put("UserId", counterimgList.get(consumerIndex).getUserId());
            upload_CounterProfile(jsonObject.toString(), loading, db, counterimgList.get(consumerIndex), consumerIndex);

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

    public void upload_CounterProfile(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String data = null;
                    if (response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.updateCounterProfileStatus(object.getUserId(), object.getVisitDate(), CommonString.KEY_Y);
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != counterprofile_imgList.size()) {
                                        UploadCounterProfile(loading, db, counterprofile_imgList, finalJsonIndex[0]);
                                    } else if (meQuizList.size() > 0) {
                                        UploadMeQuiz(loading, db, meQuizList, 0);
                                    } else if (groomingList.size() > 0) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (counterList.size() > 0) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        ///finish activity....
                                        loading.dismiss();
                                        calling_method();
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter Profile). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

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

    private void UploadMeQuiz(ProgressDialog loading, Lorealba_Database db, ArrayList<MEMEAuditQuestion> me_quizList, int consumerIndex) {
        try {
            if (me_quizList.size() > 0) {
                ArrayList<MEMEAuditQuestion> specific_meQuizList = db.getme_quiz_from_database(null, me_quizList.get(consumerIndex).getUser_Id(), visit_date, counter_Id, null);
                if (specific_meQuizList.size() > 0) {
                    db.open();
                    JourneyPlan jcp_Object = db.getBIDfromJCP(me_quizList.get(consumerIndex).getUser_Id(), counter_Id);
                    JSONArray consumerUserInfoArray = new JSONArray();
                    for (int k = 0; k < me_quizList.size(); k++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("BID", jcp_Object.getBID());
                        obj.put("VisiteDate", me_quizList.get(consumerIndex).getVisit_date());
                        obj.put("UserId", specific_meQuizList.get(k).getUser_Id());
                        obj.put("QuizId", specific_meQuizList.get(k).getQuizId());
                        obj.put("Question_Id", specific_meQuizList.get(k).getQuestionId());
                        obj.put("Question_Type", specific_meQuizList.get(k).getQuestionType());
                        JSONArray compArraymult = new JSONArray();
                        JSONObject objmultians = new JSONObject();
                        if (specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Single Choice")) {
                            objmultians.put("Answer", specific_meQuizList.get(k).getAnswer());
                            objmultians.put("Answer_Id", specific_meQuizList.get(k).getAnswerId());
                            objmultians.put("Answer_Image", specific_meQuizList.get(k).getStr_audit_img());
                            compArraymult.put(objmultians);
                        } else if (!specific_meQuizList.get(k).getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                            objmultians.put("Answer", specific_meQuizList.get(k).getAnswer());
                            objmultians.put("Answer_Id", 0);
                            objmultians.put("Answer_Image", "");
                            compArraymult.put(objmultians);
                        } else {
                            db.open();
                            ArrayList<MEMEAuditQuestion> multiansList = db.getquiz_answer(specific_meQuizList.get(k).getKeyId());
                            if (multiansList.size() > 0) {
                                for (int j2 = 0; j2 < multiansList.size(); j2++) {
                                    objmultians = new JSONObject();
                                    objmultians.put("Answer", multiansList.get(j2).getAnswer());
                                    objmultians.put("Answer_Id", multiansList.get(j2).getAnswerId());
                                    objmultians.put("Answer_Image", "");
                                    compArraymult.put(objmultians);
                                }
                            }
                        }
                        obj.put("AnsList", compArraymult);
                        consumerUserInfoArray.put(obj);
                    }

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("MID", jcp_Object.getMID());
                    jsonObject.put("Keys", "ME_Quiz_Data");
                    jsonObject.put("JsonData", consumerUserInfoArray.toString());
                    jsonObject.put("UserId", me_quizList.get(consumerIndex).getUser_Id().toLowerCase());
                    upload_me_Quiz(jsonObject.toString(), loading, db, me_quizList.get(consumerIndex), consumerIndex);
                }

            }

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

    private void UploadRetailExcellence(ProgressDialog loading, Lorealba_Database db, ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList, int consumerIndex) {
        try {
            if (masterRetailExcellenceArrayList.size() > 0) {
                ArrayList<MasterRetailExcellence> masterRetailExcellence = db.getRetailExcellencedata(null, masterRetailExcellenceArrayList.get(consumerIndex).getUser_Id(), visit_date, counter_Id);
                if (masterRetailExcellence.size() > 0) {
                    db.open();
                    JourneyPlan jcp_Object = db.getBIDfromJCP(masterRetailExcellence.get(consumerIndex).getUser_Id(), counter_Id);
                    JSONArray consumerUserInfoArray = new JSONArray();
                    for (int k = 0; k < masterRetailExcellence.size(); k++) {
                        JSONObject obj = new JSONObject();
                        obj.put("MID", jcp_Object.getMID());
                        obj.put("BID", jcp_Object.getBID());
                        obj.put("UserId", username.toLowerCase());
                        obj.put("VisiteDate", visit_date);
                        obj.put("ItemCategoryId", masterRetailExcellence.get(k).getItemCatId());
                        obj.put("ItemId", masterRetailExcellence.get(k).getItemId());
                        if (masterRetailExcellence.get(k).getAnswer().equalsIgnoreCase("Yes")) {
                            obj.put("Available", 1);
                        } else {
                            obj.put("Available", 0);
                        }
                        consumerUserInfoArray.put(obj);
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("MID", jcp_Object.getMID());
                    jsonObject.put("Keys", "Retail_Excellence_Data");
                    jsonObject.put("JsonData", consumerUserInfoArray.toString());
                    jsonObject.put("UserId", username.toLowerCase());
                    // upload_Retail_Excellence_Data(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex);
                    upload_retail_excellence(jsonObject.toString(), loading, db, masterRetailExcellence.get(consumerIndex), consumerIndex);
                }
            }
        } catch (JSONException e) {
            e.fillInStackTrace();
        }
    }

    private void UploadMeSaleData(ProgressDialog loading, Lorealba_Database db, ArrayList<ProductMaster> productMasterArrayListData, int consumerIndex) {
        try {
            if (productMasterArrayList.size() > 0) {
                ArrayList<ProductMaster> productMasterArrayList = db.getMeSaledata(null, productMasterArrayListData.get(consumerIndex).getUser_id(), visit_date, counter_Id);
                if (productMasterArrayList.size() > 0) {
                    db.open();
                    JourneyPlan jcp_Object = db.getBIDfromJCP(productMasterArrayList.get(consumerIndex).getUser_id(), counter_Id);
                    JSONArray consumerUserInfoArray = new JSONArray();
                    for (int k = 0; k < productMasterArrayList.size(); k++) {
                        if (productMasterArrayList.get(k).getStock() > 0) {
                            JSONObject obj = new JSONObject();
                            obj.put("MID", jcp_Object.getMID());
                            obj.put("BID", jcp_Object.getBID());
                            obj.put("UserId", username.toLowerCase());
                            obj.put("VisiteDate", visit_date);
                            obj.put("ProductId", productMasterArrayList.get(k).getProductId());
                            obj.put("Sale", productMasterArrayList.get(k).getStock());
                            consumerUserInfoArray.put(obj);
                        }
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("MID", jcp_Object.getMID());
                    jsonObject.put("Keys", "ME_Sale_Data");
                    jsonObject.put("JsonData", consumerUserInfoArray.toString());
                    jsonObject.put("UserId", username.toLowerCase());
                    upload_ME_Sale_Data(jsonObject.toString(), loading, db, productMasterArrayList.get(consumerIndex), consumerIndex);
                }

            }

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


    public void upload_me_Quiz(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MEMEAuditQuestion object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_Me_Quiz(counter_Id, object.getUser_Id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != meQuizList.size()) {
                                        UploadMeQuiz(loading, db, meQuizList, finalJsonIndex[0]);
                                    } else if (groomingList.size() > 0) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (counterList.size() > 0) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        ////finish activity...........
                                        loading.dismiss();
                                        calling_method();
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

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

    public void upload_retail_excellence(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final MasterRetailExcellence object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_retail_excellence(counter_Id, object.getUser_Id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != masterRetailExcellenceArrayList.size()) {
                                        UploadRetailExcellence(loading, db, masterRetailExcellenceArrayList, finalJsonIndex[0]);
                                    } else if (groomingList.size() > 0) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (counterList.size() > 0) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        ////finish activity...........
                                        loading.dismiss();
                                        calling_method();
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

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


    public void upload_ME_Sale_Data(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final ProductMaster object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_me_sale(counter_Id, object.getUser_id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != productMasterArrayList.size()) {
                                        UploadMeSaleData(loading, db, productMasterArrayList, finalJsonIndex[0]);
                                    } else if (groomingList.size() > 0) {
                                        UploadGrooming(loading, db, groomingList, 0);
                                    } else if (counterList.size() > 0) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        ////finish activity...........
                                        loading.dismiss();
                                        calling_method();
                                    }
                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Me Quiz). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

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

    private void UploadGrooming(ProgressDialog loading, Lorealba_Database db, ArrayList<GroomingGetterSetter> groomingList, int grooming_index) {
        try {
            if (groomingList.size() > 0) {
                db.open();
                JourneyPlan jcp_Object = db.getBIDfromJCP(groomingList.get(grooming_index).getUser_Id(), counter_Id);
                JSONArray consumerUserInfoArray = new JSONArray();
                JSONObject obj = new JSONObject();
                obj.put("MID", jcp_Object.getMID());
                obj.put("BID", jcp_Object.getBID());
                obj.put("VisiteDate", groomingList.get(grooming_index).getVisit_date());
                obj.put("UserId", groomingList.get(grooming_index).getUser_Id());
                obj.put("Groomed_Morng_Img", groomingList.get(grooming_index).getMorning_groom_img_str());
                obj.put("Groomed_Morng_Time_Str", groomingList.get(grooming_index).getMorning_groom_time_str());
                obj.put("Groomed_Noon_Img", groomingList.get(grooming_index).getNoon_groom_img_str());
                obj.put("Groomed_Noon_Time_Str", groomingList.get(grooming_index).getNoon_groom_time_str());
                obj.put("Groomed_Eveng_Img", groomingList.get(grooming_index).getEvenning_groom_img_str());
                obj.put("Groomed_Eveng_Time_Str", groomingList.get(grooming_index).getEvenning_groom_time_str());

                consumerUserInfoArray.put(obj);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", "Groomed_Data");
                jsonObject.put("JsonData", consumerUserInfoArray.toString());
                jsonObject.put("UserId", groomingList.get(grooming_index).getUser_Id());
                upload_grooming(jsonObject.toString(), loading, db, groomingList.get(grooming_index), grooming_index);
            }


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

    public void upload_grooming(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final GroomingGetterSetter object, final int index) {
        try {

            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter;
            adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_groomed_img(counter_Id, object.getVisit_date(), object.getUser_Id());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != groomingList.size()) {
                                        UploadGrooming(loading, db, groomingList, finalJsonIndex[0]);
                                    } else if (counterList.size() > 0) {
                                        UploadCounter(loading, db, counterList, 0);
                                    } else {
                                        ////finish
                                        loading.dismiss();
                                        calling_method();
                                    }

                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Grooming). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

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

    private void UploadCounter(ProgressDialog loading, Lorealba_Database db, ArrayList<JourneyPlan> counterList, int counter_index) {
        try {
            if (counterList.size() > 0) {
                db.open();
                JourneyPlan jcp_Object = db.getBIDfromJCP(null, counter_Id);
                JSONArray consumerUserInfoArray = new JSONArray();
                JSONObject obj = new JSONObject();
                String key = "";
                if (counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_BA) || counterList.get(counter_index).getUser_type().equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {
                    key = "Counter_Image_Data";
                    obj = new JSONObject();
                    consumerUserInfoArray = new JSONArray();
                    obj.put("MID", jcp_Object.getMID());
                    obj.put("VisitDate", counterList.get(counter_index).getVisitDate());
                    obj.put("UserId", counterList.get(counter_index).getUserId());
                    obj.put("Counter_Img_One", counterList.get(counter_index).getCounter_img_onefor_ba());
                    obj.put("Counter_Img_Two", counterList.get(counter_index).getCounter_img_two_for_ba());
                    consumerUserInfoArray.put(obj);
                } else {
                    key = "ME_Counter_Image_Data";
                    obj = new JSONObject();
                    consumerUserInfoArray = new JSONArray();

                    obj.put("MID", jcp_Object.getMID());
                    obj.put("VisitDate", counterList.get(counter_index).getVisitDate());
                    obj.put("UserId", counterList.get(counter_index).getUserId());
                    obj.put("PreSetUpImgOne", counterList.get(counter_index).getPresetup_img_one_str());
                    obj.put("PreSetUpImgTwo", counterList.get(counter_index).getPresetup_img_two_str());
                    obj.put("PostSetUpImgOne", counterList.get(counter_index).getPostsetup_img_one_str());
                    obj.put("PostSetUpImgTwo", counterList.get(counter_index).getPostsetup_img_two_str());
                    consumerUserInfoArray.put(obj);
                }


                JSONObject jsonObject = new JSONObject();
                jsonObject.put("MID", jcp_Object.getMID());
                jsonObject.put("Keys", key);
                jsonObject.put("JsonData", consumerUserInfoArray.toString());
                jsonObject.put("UserId", counterList.get(counter_index).getUserId());
                upload_counter(jsonObject.toString(), loading, db, counterList.get(counter_index), counter_index);
            }


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

    public void upload_counter(String jsondata, final ProgressDialog loading, final Lorealba_Database db, final JourneyPlan object, final int index) {
        try {
            final int[] finalJsonIndex = {index};
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    db.open();
                                    db.update_ba_counter_img(counter_Id, object.getVisitDate(), object.getUserId(), object.getTransId());
                                    finalJsonIndex[0]++;
                                    if (finalJsonIndex[0] != groomingList.size()) {
                                        UploadCounter(loading, db, counterList, finalJsonIndex[0]);
                                    } else {
                                        ///finish..
                                        loading.dismiss();
                                        calling_method();
                                    }

                                } else {
                                    loading.dismiss();
                                    AlertandMessages.showAlert((Activity) context, "Server Not Responding,(Counter). Please LogOut Again", false);
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " Please LogOut Again", false);
                    loading.dismiss();
                }
            });

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

    private void calling_method() {
        try {
            db.open();
            db.deleteSpecificStoreData();
            editor.putString("Previous_Login", "Previous_Login");
            editor.commit();
            startActivity(new Intent(getBaseContext(), UserLoginActivity.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            AlertandMessages.showToastMsg(context, "Data Upload Successfully");
            ManualUploadActivity.this.finish();
        } catch (Exception e) {
            e.fillInStackTrace();
            editor.putString("Previous_Login", "Previous_Login");
            editor.commit();
            startActivity(new Intent(getBaseContext(), UserLoginActivity.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            AlertandMessages.showToastMsg(context, "Data Upload Successfully");
            ManualUploadActivity.this.finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();

    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(CommonString.UPLOAD_PONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id) -> {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ManualUploadActivity.this.finish();
            }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());

            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ManualUploadActivity.this.finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_takebackup, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExportDialog();
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();


        if (id == R.id.nav_takebackup) {
            showExportDialog();
        } else if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(CommonString.UPLOAD_PONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id12) -> {
                    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    ManualUploadActivity.this.finish();
                }).setNegativeButton("Cancel", (dialog, id1) -> dialog.cancel());

                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ManualUploadActivity.this.finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

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


    public void showExportDialog() {
        android.app.AlertDialog.Builder builder1 = new android.app.AlertDialog.Builder(context).setTitle(R.string.dialog_title);
        builder1.setMessage(R.string.Areyou_sure_take_backup).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) -> {
            try {
                File sd = context.getExternalFilesDir("");
                File data = Environment.getDataDirectory();
                assert sd != null;
                if (sd.canWrite()) {
                    long date = System.currentTimeMillis();
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yy");
                    String dateString = sdf.format(date);
                    String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME;
                    String backupDBPath = username + CommonString.BACKUP_FOLDER_NAME + dateString.replace('/', '_') + CommonFunctions.getCurrentTime_only().replace(":", "") + ".db";
                    String path = CommonString.getBackupFolder(context);
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(path, backupDBPath);
                    if (currentDB.exists()) {
                        @SuppressWarnings("resource")
                        FileChannel src = new FileInputStream(currentDB).getChannel();
                        FileChannel dst = new FileOutputStream(backupDB).getChannel();
                        dst.transferFrom(src, 0, src.size());
                        src.close();
                        dst.close();
                    }
                    File dir = new File(CommonString.getBackupFolder(context));
                    ArrayList<String> list = new ArrayList<>();
                    list = getFileNames(dir.listFiles());
                    if (!list.isEmpty()) {
                        for (int i1 = 0; i1 < list.size(); i1++) {
                            if (list.get(i1).contains(CommonString.BACKUP_FOLDER_NAME)) {
                                File originalFile = new File(CommonString.getBackupFolder(context) + list.get(i1));
                                uploadBackup(context, originalFile.getName(), "DBBackup");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.fillInStackTrace();
                AlertandMessages.showAlert((Activity) context, context.getString(R.string.errordatabase_not_exporting), true);
            }
        }).setNegativeButton(android.R.string.cancel, (dialog, id) -> dialog.cancel());
        AlertDialog alert1 = builder1.create();
        alert1.show();
    }

}

