package com.cpm.lorealbaautomation.Database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter;
import com.cpm.lorealbaautomation.gettersetter.BaTenureDetail;
import com.cpm.lorealbaautomation.gettersetter.GeotaggingBeans;
import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter;
import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOffer;
import com.cpm.lorealbaautomation.gettersetter.MasterCompetitionOfferSaleRange;
import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVA;
import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVADrillDown;
import com.cpm.lorealbaautomation.gsonGetterSetter.BASurveyGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.DamagePreviousPending;
import com.cpm.lorealbaautomation.gsonGetterSetter.DamageReturnToDistributor;
import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.InwardSalesPO;
import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MEMEAuditQuestionUploadstatus;
import com.cpm.lorealbaautomation.gsonGetterSetter.MappingAppRestrictedKPI;
import com.cpm.lorealbaautomation.gsonGetterSetter.MappingCounterGroupBrand;
import com.cpm.lorealbaautomation.gsonGetterSetter.MappingVisibility;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterAgeLimit;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionOfferGet;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionOfferSet;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionProductType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitionPromoType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterCompetitonBrandWiseNuance;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterInvoiceTypeGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBreak;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterLeaveType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterLook;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReasonGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibility;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibilityGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetEntityItem;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetExclusionList;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetProductCatalog;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionGetProductGroup;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetEntityItem;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetExclusionList;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetProductCatalog;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromotionSetProductGroup;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterRetailExcellence;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterReturnReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSkinType;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestion;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSourcesOfSale;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurvey;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterSurveyUploadstatus;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterTermsCondition;
import com.cpm.lorealbaautomation.gsonGetterSetter.NotificationData;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportDamageStockHistory;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportMESale;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportMTDWorkingCounterME;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportProductGroupWiseSalesValue;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesDateWise;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesDetail;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesL3MValue;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTime;
import com.cpm.lorealbaautomation.gsonGetterSetter.ServerTimeGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.StockSummaryCheck;
import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoice;
import com.cpm.lorealbaautomation.gsonGetterSetter.TCounterInvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.TLeaveLedger;
import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummary;
import com.cpm.lorealbaautomation.gsonGetterSetter.TStockSummaryGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest;
import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.batbasale.BATBAPromoSale;
import com.cpm.lorealbaautomation.gsonGetterSetter.batbasale.BATBASale;
import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportConterValue;
import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportConterValueDetail;
import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolume;
import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolumeDetail;
import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStock;
import com.cpm.lorealbaautomation.gsonGetterSetter.inwordDetail.ReportCounterInwardStockDetail;
import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.MasterHoliday;
import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveLedgerSummary;
import com.cpm.lorealbaautomation.gsonGetterSetter.leaves.TLeaveRequestDetail;
import com.cpm.lorealbaautomation.gsonGetterSetter.stockledger.ReportCounterStockLedger;
import com.cpm.lorealbaautomation.gsonGetterSetter.stockledger.ReportCounterStockLedgerDetail;
import com.cpm.lorealbaautomation.gsonGetterSetter.testerreports.ReportTesterCounter;
import com.cpm.lorealbaautomation.gsonGetterSetter.testerreports.TesterCounter;
import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardIncentive;
import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardLeaderBoard;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceDetail;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportAttendanceSummary;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgBillValue;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgLinPerBill;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgTransactionPerDay;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportAvgUnitsPerBill;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportBAAvailability;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportInwardStockSummary;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportSalesValue;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportSellingPrice;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Value;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Volume;
import com.cpm.lorealbaautomation.reports.dailyTva.DailyTVA;
import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeCounter;
import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeNuance;
import com.cpm.lorealbaautomation.reports.offtakemodels.L3MOffTakeSubAxe;
import com.cpm.lorealbaautomation.reports.offtakemodels.OffTakeData;
import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthCounter;
import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthSubAxe;
import com.cpm.lorealbaautomation.reports.testerdetails.ReportTesterCounterDetail;
import com.prolificinteractive.materialcalendarview.CalendarDay;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * /**
 * Created by jeevanp on 15-12-2017.
 */

public class Lorealba_Database extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = CommonString.KEY_DB_NAME;
    public static final int DATABASE_VERSION = CommonString.KEY_DB_NAME_iD;
    private SQLiteDatabase db;
    Context context;

    public Lorealba_Database(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    public void open() {
        try {
            db = this.getWritableDatabase();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            //jeevan
            db.execSQL(CommonString.CREATE_TABLE_COMP_OFFERS);
            db.execSQL(CommonString.CREATE_TABLE_User_Login);
            db.execSQL(CommonString.CREATE_TABLE_COVERAGE_DATA);
            db.execSQL(CommonString.CREATE_TABLE_COUNTER_IMAGE_DATA);
            db.execSQL(CommonString.CREATE_TABLE_GROOMED_IMAGE_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FOCUS_PRODUCT_OPENINGHEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_STOCK_DATA);
            db.execSQL(CommonString.CREATE_TABLE_NOTIFICATION_DATA);
            db.execSQL(CommonString.Create_Table_Sale_Tracking_Header_Data);
            db.execSQL(CommonString.Create_Table_Sale_Tracking);
            db.execSQL(CommonString.Create_Table_Applyed_Promotion);
            db.execSQL(CommonString.Create_Table_PromoApplyeidOnProduct);
            db.execSQL(CommonString.Create_Table_Consumer_Return);
            db.execSQL(CommonString.Create_Table_Consumer_Return_Replace_Product);

            db.execSQL(CommonString.Create_Table_Leave_Management);
            db.execSQL(CommonString.Create_Table_Break_Management);
            db.execSQL(CommonString.Create_Table_Consumer_Return_Header_Data);
            db.execSQL(CommonString.Create_Table_Makeover_Capture);

            db.execSQL(CommonString.Create_Table_ME_QUIZ);
            db.execSQL(CommonString.Create_Table_ME_QUIZ_MULTI_ANSWER);
            db.execSQL(CommonString.Create_Table_Temp_Consumer_Sale);
            db.execSQL(CommonString.Create_Table_Temp_Temp_Promo_AplyDefinition);
            db.execSQL(CommonString.Create_Table_Temp_Temp_Promo_AplyDefinitionfor_and);
            db.execSQL(CommonString.CREATE_TABLE_RETURNTO_DISTRIBUTOR_DATA);
            db.execSQL(CommonString.Create_Table_Temp_Image);
            db.execSQL(CommonString.Create_Table_Temp_Sale);
            db.execSQL(CommonString.CREATE_TABLE_NOTIFICATION_USER);
            //----------------------
            db.execSQL(CommonString.CREATE_TABLE_TESTER_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_TESTER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_SAMPLE_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_SAMPLE_DATA);
            db.execSQL(CommonString.CREATE_TABLE_DAMAGED_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_DAMAGED_DATA);
            db.execSQL(CommonString.CREATE_TABLE_SUGGESTED_STOCK_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_SUGGESTED_STOCK_DATA);
            //usk
            db.execSQL(CommonString.CREATE_TABLE_VIISBILITY_DATA);
            db.execSQL(CommonString.CREATE_TABLE_AUDIT_DATA_SAVE);
            db.execSQL(CommonString.CREATE_TABLE_COUNTER_PROFILE_SAVE);
            db.execSQL(CommonString.CREATE_TABLE_BA_PROFILE_DATAE_SAVE);
            // neeraj
            db.execSQL(CommonString.CREATE_TABLE_INWARD_STOCK_CHILD_DATA);
            db.execSQL(CommonString.CREATE_TABLE_INWARD_STOCK_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_INWARD_STOCK_TRANSACTION);
            db.execSQL(CommonString.CREATE_TABLE_AUDIT_DATA_SAVE);
            db.execSQL(CommonString.CREATE_TABLE_MANUAL_INWARD_TRANSACTION);
            //YSY
            db.execSQL(CommonString.CREATE_TABLE_GWP_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_FIRST_TIME_GWP_DATA);
            db.execSQL(CommonString.CREATE_TABLE_TRANSACTION_DATA);
            db.execSQL(CommonString.CREATE_TABLE_BA_SURVEY_CHILD_DATA);
            db.execSQL(CommonString.CREATE_TABLE_BA_SURVEY_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_COUNTER_SURVEY_CHILD_DATA);
            db.execSQL(CommonString.CREATE_TABLE_COUNTER_SURVEY_HEADER_DATA);
            db.execSQL(CommonString.CREATE_TABLE_TRANSACTION_WISE_DATA);
            db.execSQL(CommonString.Create_Table_Skin_Genius_Table);
            db.execSQL(CommonString.Create_Table_Open_Skin_Genius_Table);
            db.execSQL(CommonString.Create_Table_Open_Mabelline_Table);
            db.execSQL(CommonString.Create_Table_Temp_Promotion_OffSameProduct);
            //
            db.execSQL(CommonString.CREATE_TABLE_STORE_STOCK_CHILD_ME_SALE_DATA);
            db.execSQL(CommonString.CREATE_TABLE_INSERT_HEADER_ME_SALE_DATA);
            db.execSQL(CommonString.Create_Table_Retail_Excellence_Header);
            db.execSQL(CommonString.Create_Table_Retail_Excellence_Child);
            db.execSQL(CommonString.CREATE_TABLE_STORE_GEOTAGGING);
        } catch (SQLException e) {
            e.fillInStackTrace();
        }
    }

    public void deleteSpecificStoreData() {
        try {
            if (!db.isOpen()) open();

            db.delete(CommonString.TABLE_BA_SURVEY_CHILD_DATA, null, null);
            db.delete(CommonString.TABLE_BA_SURVEY_HEADER_DATA, null, null);
            db.delete(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, null, null);
            db.delete(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, null, null);
            db.delete(CommonString.TABLE_INSERT_HEADER_STOCK_DATA, null, null);
            db.delete(CommonString.TABLE_STORE_STOCK_CHILD_DATA, null, null);
            db.delete(CommonString.TABLE_COUNTER_IMAGE_DATA, null, null);
            db.delete(CommonString.TABLE_GROOMED_IMAGE_DATA, null, null);
            db.delete(CommonString.TABLE_COVERAGE_DATA, null, null);
            db.delete(CommonString.TABLE_TRANSACTION_DATA, null, null);
            db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, null);
            db.delete(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, null, null);
            db.delete(CommonString.TABLE_INSERT_HEADER_TESTER_DATA, null, null);
            db.delete(CommonString.TABLE_TESTER_CHILD_DATA, null, null);
            db.delete(CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA, null, null);
            db.delete(CommonString.TABLE_SAMPLE_CHILD_DATA, null, null);
            db.delete(CommonString.TABLE_INSERT_HEADER_DAMAGED_DATA, null, null);
            db.delete(CommonString.TABLE_DAMAGED_CHILD_DATA, null, null);
            db.delete(CommonString.Table_visibilisty, null, null);
            db.delete(CommonString.TABLE_AUDIT_DATA_SAVE, null, null);
            db.delete(CommonString.Table_Consumer_Return, null, null);
            db.delete(CommonString.Table_Consumer_Return_Replace_Product, null, null);
            db.delete(CommonString.Table_Leave_Management, null, null);
            db.delete(CommonString.Table_Break_Management, null, null);
            db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, null, null);
            db.delete(CommonString.TABLE_COUNTER_PROFILE_DATA, null, null);
            db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, null, null);
            db.delete(CommonString.Table_Sale_Tracking_Header_Data, null, null);
            db.delete(CommonString.Table_Makeover_Capture, null, null);
            db.delete(CommonString.Table_Sale_Tracking, null, null);
            db.delete(CommonString.Table_Applyeid_Promotion, null, null);
            db.delete(CommonString.Table_PromoApplyeidOnProduct, null, null);
            db.delete(CommonString.Table_Consumer_Return_Header_Data, null, null);
            db.delete(CommonString.Table_ME_QUIZ, null, null);
            db.delete(CommonString.Table_ME_QUIZ_MULTI_ANSWER, null, null);
            db.delete(CommonString.Table_Skin_Genius_Table, null, null);
            db.delete(CommonString.Table_Open_Skin_Genius_Table, null, null);
            db.delete(CommonString.Table_Open_Maybelline_Table, null, null);
            db.delete(CommonString.TABLE_COMP_OFFERS, null, null);
            db.delete(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, null, null);
            db.delete(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, null, null);
            db.delete(CommonString.Table_Retail_Excellence_Header, null, null);
            db.delete(CommonString.Table_Retail_Excellence_Child, null, null);
            db.delete(CommonString.TABLE_STORE_GEOTAGGING, null, null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void deleteNotificationTableafterOneWeek() {
        try {
            if (!db.isOpen()) {
                open();
            }
            db.delete(CommonString.TABLE_NOTIFICATION_USER, null, null);
            db.delete(CommonString.TABLE_NOTIFICATION_DATA, null, null);

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public int createtable(String sqltext) {
        try {
            if (!db.isOpen()) {
                open();
            }
            db.execSQL(sqltext);
            return 1;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            return 0;
        }
    }


    public boolean insertJCPData(JCPGetterSetter data) {
        db.delete("Mapping_JourneyPlan", null, null);
        List<JourneyPlan> jcpList = data.getJourneyPlan();
        ContentValues values = new ContentValues();
        try {
            if (jcpList.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < jcpList.size(); i++) {
                values.put("StoreId", jcpList.get(i).getStoreId());
                values.put("CounterId", jcpList.get(i).getCounterId());
                values.put("EmpId", jcpList.get(i).getEmpId());
                values.put("ChainId", jcpList.get(i).getChainId());
                values.put("ChainName", jcpList.get(i).getChainName());
                values.put("StoreName", jcpList.get(i).getStoreName());
                values.put("Address", jcpList.get(i).getAddress());
                values.put("Location", jcpList.get(i).getLocation());
                values.put("Landmark", jcpList.get(i).getLandmark());
                values.put("CityId", jcpList.get(i).getCityId());
                values.put("CityName", jcpList.get(i).getCityName());
                values.put("CounterName", jcpList.get(i).getCounterName());
                values.put("IMEI", jcpList.get(i).getIMEI());
                values.put("ChannelId", jcpList.get(i).getChannelId());
                values.put("ChannelName", jcpList.get(i).getChannelName());
                values.put("StoreTypeId", jcpList.get(i).getStoreTypeId());
                values.put("StoreTypeName", jcpList.get(i).getStoreTypeName());
                values.put("ClassId", jcpList.get(i).getClassId());
                values.put("ClassName", jcpList.get(i).getClassName());
                values.put("CounterGroupId", jcpList.get(i).getCounterGroupId());
                values.put("CounterUploadStatus", jcpList.get(i).getCounterUploadStatus());
                values.put("BAUploadStatus", jcpList.get(i).getBAUploadStatus());
                values.put("MID", jcpList.get(i).getMID());
                values.put("BID", jcpList.get(i).getBID());
                values.put("RefImage", jcpList.get(i).getRefImage());
                values.put("ProfileImage1", jcpList.get(i).getProfileImage1());
                values.put("ProfileImage2", jcpList.get(i).getProfileImage2());
                values.put("CounterLength", jcpList.get(i).getCounterlength());
                values.put("CounterWidth", jcpList.get(i).getCounterwidth());
                values.put("SetUpDate", jcpList.get(i).getSetupDate());
                values.put("VisitDate", jcpList.get(i).getVisitDate());
                values.put("UserId", jcpList.get(i).getUserId().toLowerCase());

                values.put("Latitude", jcpList.get(i).getLatitude());
                values.put("Longitude", jcpList.get(i).getLongitude());
                values.put("GeoTag", jcpList.get(i).getGeoTag());
                values.put("GeoFencingRadius", jcpList.get(i).getGeoFencingRadius());
                values.put("GeoFencingAllow", jcpList.get(i).getGeoFencingAllow());

                if (!db.isOpen()) {
                    open();
                }
                long id = db.insert("Mapping_JourneyPlan", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Exception in Jcp", ex.toString());
            return false;
        }
    }


    public boolean insertBalistData(JCPGetterSetter data) {
        db.delete("BA_List", null, null);
        List<BaListGetterSetter> baList = data.getBAList();
        ContentValues values = new ContentValues();
        try {
            if (baList.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < baList.size(); i++) {
                values.put("EmpId", baList.get(i).getEmpId());
                values.put("UserName", baList.get(i).getUserName().toLowerCase());
                values.put("DesignationId", baList.get(i).getDesignationId());
                values.put("DesignationName", baList.get(i).getDesignationName());
                values.put("VisitDate", baList.get(i).getVisitDate());
                values.put("ProfilePath", baList.get(i).getProfilePath());
                values.put("Profile_Pic", baList.get(i).getProfilePic());
                values.put("CounterId", baList.get(i).getCounterId());

                long id = db.insert("BA_List", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            ex.fillInStackTrace();
            ////////test("Exception in Jcp", ex.toString());
            return false;
        }
    }


    public boolean insertmappingcountergroupBrand(JCPGetterSetter data) {
        db.delete("Mapping_CounterGroup_Brand", null, null);
        List<MappingCounterGroupBrand> baList = data.getMappingCounterGroupBrand();
        ContentValues values = new ContentValues();
        try {
            if (baList.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < baList.size(); i++) {
                values.put("CounterGroupId", baList.get(i).getCounterGroupId());
                values.put("BrandId", baList.get(i).getBrandId());

                long id = db.insert("Mapping_CounterGroup_Brand", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            ////////test("Exception in Jcp", ex.toString());
            return false;
        }
    }

    public long delete_table_data(String table_name) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            l = db.delete(table_name, null, null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }


    public boolean insertproductmasterdata(TableStructureGetterSetter data) {
        db.delete("Product_Master", null, null);
        List<ProductMaster> productList = data.getProductMaster();
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            if (productList.isEmpty()) {
                return false;
            }
            for (ProductMaster productMaster : productList) {
                values.put("ProductId", productMaster.getProductId());
                values.put("LorealCode", productMaster.getLorealCode().trim());
                values.put("ProductName", productMaster.getProductName().trim());

                values.put("NuanceId", productMaster.getNuanceId());
                values.put("NuanceName", productMaster.getNuanceName().trim());
                values.put("SubAxeId", productMaster.getSubAxeId());
                values.put("SubAxeName", productMaster.getSubAxeName().trim());
                values.put("AxeId", productMaster.getAxeId());
                values.put("AxeName", productMaster.getAxeName().trim());
                values.put("ReferenceId", productMaster.getReferenceId());
                values.put("ReferenceName", productMaster.getReferenceName().trim());
                values.put("SubBrandId", productMaster.getSubBrandId());
                values.put("SubBrandName", productMaster.getSubBrandName().trim());
                values.put("BrandId", productMaster.getBrandId());
                values.put("BrandName", productMaster.getBrandName().trim());
                values.put("SignatureId", productMaster.getSignatureId());
                values.put("SignatureName", productMaster.getSignatureName().trim());
                values.put("EanCode", productMaster.getEanCode().trim());
                values.put("Mrp", productMaster.getMrp());
                values.put("ProductType", productMaster.getProductType().trim());
                values.put("VisitDate", productMaster.getVisit_date());

                if (!db.isOpen()) {
                    open();
                }
                long id = db.insert("Product_Master", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }

            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            ////////test("Exception in Jcp", ex.toString());
            return false;
        }
    }


    public boolean insertmappingvisibility(TableStructureGetterSetter data) {
        db.delete("Mapping_Visibility", null, null);
        List<MappingVisibility> productList = data.getMappingVisibility();
        ContentValues values = new ContentValues();
        try {
            if (productList.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < productList.size(); i++) {
                values.put("CounterId", productList.get(i).getCounterId());
                values.put("PosmId", productList.get(i).getPosmId());

                if (!db.isOpen()) {
                    open();
                }
                long id = db.insert("Mapping_Visibility", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            ////////test("Exception in Jcp", ex.toString());
            return false;
        }
    }

    public boolean insertmappingposmdata(TableStructureGetterSetter data) {
        db.delete("Master_Posm", null, null);
        List<MasterPosm> productList = data.getMasterPosm();
        ContentValues values = new ContentValues();
        try {
            if (productList.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < productList.size(); i++) {
                values.put("Posm", productList.get(i).getPosm());
                values.put("PosmId", productList.get(i).getPosmId());
                values.put("PosmTypeId", productList.get(i).getPosmTypeId());
                values.put("RefImage", productList.get(i).getRefImage());

                long id = db.insert("Master_Posm", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            // do ALL your inserts here
            closeDb();
            return true;
        } catch (Exception ex) {
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            ex.fillInStackTrace();
            ////////test("Exception in Jcp", ex.toString());
            return false;
        }
    }


    public ArrayList<ProductMaster> getsku_fromproductusing_eancode(String ean_code, boolean for_sale_flag, String visit_date, String counterId, String userType) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = CommonString.T_StockSummary, additionalQueryMe = "", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID ";


                getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance";
                additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + "  AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" +

                        "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" +

                        ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId";
            }
            String query = "select distinct ProductName,ProductId,EanCode,Mrp,ProductType from Product_Master where EanCode='" + ean_code + "'";
            if (for_sale_flag) {
                query = "Select distinct  s.ProductId as ProductId," + getData + "," + "pm.ProductName as ProductName,pm.EanCode as EanCode,pm.Mrp as Mrp,pm.ProductType as ProductType" + " from Product_Master pm inner join  " + table + " s on pm.ProductId=s.ProductId Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from" + " (select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN" + " DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID" + " where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT  CounterId, ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + additionalQueryMe2 + ") as t" + " Group by CounterId, ProductId) as dm " + " on s.ProductId = dm.ProductId" + additionalQueryMe + " where pm.EanCode='" + ean_code + "' and SaleableBalance >0";
            }

            dbcursor = db.rawQuery(query, null);

            //test("query", query);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }

        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }


    public ArrayList<ProductMaster> getsku_fromproductusing_eancodefor_return(String ean_code) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode" + ",pm.Mrp as Mrp,pm.ProductType as ProductType from Product_Master pm " + "inner join T_StockSummary ts on ts.ProductId=pm.ProductId where pm.EanCode='" + ean_code + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }


    public ArrayList<JourneyPlan> getStoreData(String date, String user_Id, String counterId) {
        ArrayList<JourneyPlan> list = new ArrayList<JourneyPlan>();
        Cursor dbcursor = null;

        try {
            if (user_Id != null) {
                dbcursor = db.rawQuery("SELECT * FROM Mapping_JourneyPlan WHERE VisitDate ='" + date + "'and UserId='" + user_Id + "' and CounterId = " + counterId, null);
            } else {
                dbcursor = db.rawQuery("SELECT * FROM Mapping_JourneyPlan WHERE VisitDate ='" + date + "'", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    JourneyPlan sb = new JourneyPlan();
                    sb.setStoreId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StoreId"))));
                    sb.setCounterId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId"))));
                    sb.setEmpId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("EmpId"))));
                    sb.setChainId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ChainId"))));
                    sb.setChainName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ChainName")));
                    sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StoreName")));
                    sb.setAddress((dbcursor.getString(dbcursor.getColumnIndexOrThrow("Address"))));
                    sb.setLocation((dbcursor.getString(dbcursor.getColumnIndexOrThrow("Location"))));
                    sb.setLandmark(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Landmark")));
                    sb.setCityId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CityId")));
                    sb.setCityName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CityName")));
                    sb.setCounterName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName")));
                    sb.setIMEI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMEI")));
                    sb.setChannelId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ChannelId")));
                    sb.setChannelName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ChannelName")));
                    sb.setStoreTypeId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StoreTypeId"))));
                    sb.setStoreTypeName((dbcursor.getString(dbcursor.getColumnIndexOrThrow("StoreTypeName"))));
                    sb.setClassId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ClassId"))));
                    sb.setClassName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ClassName")));
                    sb.setCounterGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterGroupId")));
                    sb.setCounterUploadStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterUploadStatus")));
                    sb.setBAUploadStatus((dbcursor.getString(dbcursor.getColumnIndexOrThrow("BAUploadStatus"))));
                    sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID")));
                    sb.setBID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BID")));
                    sb.setRefImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RefImage")));
                    sb.setProfileImage1(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProfileImage1")));
                    sb.setProfileImage2(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProfileImage2")));
                    sb.setCounterlength(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("CounterLength")));
                    sb.setCounterwidth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("CounterWidth")));
                    sb.setSetupDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SetUpDate")));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));

                    sb.setLatitude(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Latitude")));
                    sb.setLongitude(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Longitude")));
                    sb.setGeoTag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GeoTag")));
                    sb.setGeoFencingRadius(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("GeoFencingRadius")));
                    sb.setGeoFencingAllow(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("GeoFencingAllow")));


                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return list;
        }


        return list;
    }

    //jeevan   nmjnmn,
    public ArrayList<InvoiceGetterSetter> getsalesTrackingByUserMobile(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select distinct SH.SOURCEOFSALES as SOURCEOFSALES,SH.SKIN_GENIUS as SKIN_GENIUS,SH.MAYBELLINE_VTO" + " as MAYBELLINE_VTO," + " SH.USER_ID as USER_ID, ST.PRODUCT_ID as PRODUCT_ID," + "ST.PRODUCT as PRODUCT,ST.QUANTITY as QUANTITY,ST.PRODUCT_RATE as PRODUCT_RATE," + "ST.TOTAL_AMOUNT as TOTAL_AMOUNT,ST.EAN_CODE as EAN_CODE,ST.DISCOUNT as DISCOUNT,ST.DISCOUNTED_VALUE as DISCOUNTED_VALUE" + ",ST.ACTUAL_PRICE as ACTUAL_PRICE,ST.SKU_TYPE as SKU_TYPE,ST.INVOICE_TYPE as INVOICE_TYPE," + "SH.POS_SALE_FLAG as POS_SALE_FLAG,SH.TERMCONDITION_FLAG as TERMCONDITION_FLAG,SH.CONSUMER_NOSALE_IMG as CONSUMER_NOSALE_IMG," + "SH.PER_TIMING as PER_TIMING,SH.RECCEPT_COUNT as RECCEPT_COUNT,SH.STORE_NAME as STORE_NAME,SH.STORE_ADDRESS as STORE_ADDRESS," + "SH.BUYER_NAME as BUYER_NAME,SH.CONTACT_NUMBER as CONTACT_NUMBER,SH.EMAIL_ID as EMAIL_ID," + "SH.AGE as AGE,SH.SKIN_TYPE as SKIN_TYPE,SH.DEMO_GIVEN as DEMO_GIVEN,SH.PRODUCT_SOLD as PRODUCT_SOLD,SH.UPLOAD_STATUS as UPLOAD_STATUS," + "SH.GENDER as GENDER,ST.PROMOTION as PROMOTION,ST.PROMOTION_ID as PROMOTION_ID,ST.PROMOTION_FLAG as PROMOTION_FLAG,ST.PROMO_TYPE as PROMO_TYPE" + " FROM SALE_TRACKING_TABLE ST INNER JOIN SALE_TRACKING_HEADER_TABLE SH ON SH.RECCEPT_COUNT=ST.RECCEPT_COUNT where SH.CONTACT_NUMBER='" + mobile_no + "'" + "and SH.Visit_Date ='" + visite_date + "' and SH.RECCEPT_COUNT=" + reciept_count + " and SH.COUNTER_ID =" + counterId + " and SH.USER_ID ='" + user_Id + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setPos_sale_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")).equals("1"));
                    sale.setPromo_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_FLAG")).equals("1"));
                    sale.setSourceofSales(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SOURCEOFSALES")));
                    sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG")));
                    sale.setConsumer_no_saleImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONSUMER_NOSALE_IMG")));
                    sale.setPercheasing_tym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PER_TIMING")));
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")));
                    sale.setStore_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_NAME")));
                    sale.setStore_address(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_ADDRESS")));
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID")));
                    sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE")));
                    sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE")));
                    sale.setDemo_given_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DEMO_GIVEN")));
                    sale.setProduct_sold_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_SOLD")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID")));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY")));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE")));
                    sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_AMOUNT")));
                    sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE")));
                    sale.setDiscount(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("DISCOUNT")));
                    sale.setDiscounted_value(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("DISCOUNTED_VALUE")));
                    sale.setActual_price_per_product(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("ACTUAL_PRICE")));
                    sale.setSkuType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKU_TYPE")));
                    sale.setStr_invoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INVOICE_TYPE")));
                    sale.setPromotion_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION")));
                    sale.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_ID")));
                    sale.setPromo_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_TYPE")));
                    sale.setSkin_genius_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS")));
                    sale.setMaybelline_vto_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MAYBELLINE_VTO")));
                    if (sale.isPromo_flag()) {
                        if (!db.isOpen()) open();
                        sale.setApplyiedproductList(getproductsapplyeidOnpromo(reciept_count, mobile_no, visite_date, counterId, user_Id, sale.getPromotion_Id()));
                    }
                    list.add(sale);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }

        return list;
    }


    public ArrayList<InvoiceGetterSetter> getproductsapplyeidOnpromo(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id, String promoId) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (promoId.isEmpty()) {
                dbcursor = db.rawQuery("SELECT Distinct t1.DISCOUNT as DISCOUNT ,t1.RECCEPT_COUNT as RECCEPT_COUNT,t1.PROMO_TYPE as" + " PROMO_TYPE,t1.PROMOTION_FLAG as PROMOTION_FLAG" + ",t1.PROMOTION as PROMOTION,t1.PROMOTION_ID as PROMOTION_ID," + "t1.PRODUCT_ID as PRODUCT_ID,t1.PRODUCT as PRODUCT,t1.EAN_CODE as EAN_CODE,t1.PRODUCT_QTY as PRODUCT_QTY," + "t1.MRP as MRP FROM DR_PROMOAPPLYED_PRODUCT t1 inner join SALE_TRACKING_HEADER_TABLE t2 on t2.RECCEPT_COUNT=t1.RECCEPT_COUNT" + " where t2.CONTACT_NUMBER='" + mobile_no + "' and t1.Visit_Date ='" + visite_date + "' and t1.RECCEPT_COUNT=" + reciept_count + " and t1.COUNTER_ID =" + counterId + " and t2.USER_ID ='" + user_Id + "' And t1.PROMOTION_FLAG = 1", null);

            } else {
                dbcursor = db.rawQuery("SELECT Distinct t1.DISCOUNT as DISCOUNT, t1.RECCEPT_COUNT as RECCEPT_COUNT,t1.PROMO_TYPE as" + " PROMO_TYPE,t1.PROMOTION_FLAG as PROMOTION_FLAG" + ",t1.PROMOTION as PROMOTION,t1.PROMOTION_ID as PROMOTION_ID," + "t1.PRODUCT_ID as PRODUCT_ID,t1.PRODUCT as PRODUCT,t1.EAN_CODE as EAN_CODE,t1.PRODUCT_QTY as PRODUCT_QTY," + "t1.MRP as MRP FROM DR_PROMOAPPLYED_PRODUCT t1 inner join SALE_TRACKING_HEADER_TABLE t2 on t2.RECCEPT_COUNT=t1.RECCEPT_COUNT" + " where t2.CONTACT_NUMBER='" + mobile_no + "' and t1.Visit_Date ='" + visite_date + "' and t1.RECCEPT_COUNT=" + reciept_count + " AND t1.PROMOTION_ID =" + promoId + " AND t1.COUNTER_ID =" + counterId + " and t2.USER_ID ='" + user_Id + "' And t1.PROMOTION_FLAG = 1", null);

            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setPromo_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_FLAG")).equals("1"));
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")));
                    sale.setPromo_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_TYPE")));
                    sale.setPromotion_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION")));
                    sale.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_ID")));
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID")));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT")));
                    sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_QTY")));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MRP")));
                    sale.setDiscounted_value_productwise(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DISCOUNT")));
                    list.add(sale);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }

        return list;
    }


    public ArrayList<InvoiceGetterSetter> getapplyeid_promotion(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("SELECT t1.RECCEPT_COUNT as RECCEPT_COUNT,t1.PROMO_TYPE as PROMO_TYPE,t1.PROMOTION_FLAG as PROMOTION_FLAG" + ",t1.PROMOTION as PROMOTION,t1.PROMOTION_ID as PROMOTION_ID," + "t1.PROMO_PRODUCT_ID as PROMO_PRODUCT_ID,t1.PROMO_PRODUCT as PROMO_PRODUCT,t1.EAN_CODE as EAN_CODE,t1.PROMO_PRODUCT_QTY as PROMO_PRODUCT_QTY," + "t1.PROMO_PRODUCT_MRP as PROMO_PRODUCT_MRP,t1.PROMO_DISCOUNT as PROMO_DISCOUNT" + " FROM APPLYED_PROMOTION_TABLE t1 inner join SALE_TRACKING_HEADER_TABLE t2 on t2.RECCEPT_COUNT=t1.RECCEPT_COUNT" + " where t2.CONTACT_NUMBER='" + mobile_no + "' and t1.Visit_Date ='" + visite_date + "' and t1.RECCEPT_COUNT=" + reciept_count + " and t1.COUNTER_ID =" + counterId + " and t2.USER_ID ='" + user_Id + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setPromo_flag(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_FLAG")).equals("1"));
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")));
                    sale.setPromo_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_TYPE")));
                    sale.setPromotion_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION")));
                    sale.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTION_ID")));
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT_ID")));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT")));
                    sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT_QTY")));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_PRODUCT_MRP")));
                    sale.setDiscounted_value(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("PROMO_DISCOUNT")));
                    if (sale.isPromo_flag()) {
                        sale.setApplyiedproductList(getproductsapplyeidOnpromo(reciept_count, mobile_no, visite_date, counterId, user_Id, sale.getPromotion_Id()));
                    }
                    list.add(sale);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }

        return list;
    }


    public ArrayList<InvoiceGetterSetter> getsalestrackingListusing_group(String CounterId, String visite_date, String user_Id, String userType) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (user_Id == null) {
                dbcursor = db.rawQuery("select T1.*, ifnull (T2.DISCOUNT,0) as DISCOUNT, ifnull (T3.DISCOUNT,0) as DISCOUNTOffProduct ," + "ifnull(T2.DISCOUNT,0) + ifnull(T3.DISCOUNT,0) as finalDiscount  FROM " + "(select m.USER_ID, m.DEMO_GIVEN,m.SKIN_GENIUS,m.MAYBELLINE_VTO,m.PRODUCT_SOLD, m.RECCEPT_COUNT, m.BUYER_NAME," + " m.CONTACT_NUMBER,m.SOURCEOFSALES,m.UPLOAD_STATUS," + "IFNULL(sum(t.QUANTITY),0) as QUANTITY, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) AS TOTAL_AMOUNT,m.POS_SALE_FLAG " + "from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "'and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T1 " + "LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "'and m.COUNTER_ID=" + CounterId + " And t." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " AND t.PRODUCT_ID = 0 AND (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='OffAdditionalProduct'OR t.PROMO_TYPE='ValueOffAdditionalProduct'" + " OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + "GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T2 ON T1.RECCEPT_COUNT = T2.RECCEPT_COUNT" + " LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from " + "SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t " + "on m.RECCEPT_COUNT = t.RECCEPT_COUNT WHERE M.Visit_Date ='" + visite_date + "'and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct'" + " OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " GROUP BY m.RECCEPT_COUNT,m.BUYER_NAME, m.CONTACT_NUMBER) AS T3 ON T1.RECCEPT_COUNT = T3.RECCEPT_COUNT", null);
            } else {
                dbcursor = db.rawQuery("SELECT T1.*, ifnull (T2.DISCOUNT,0) as DISCOUNT, ifnull (T3.DISCOUNT,0) as DISCOUNTOffProduct ," + "ifnull(T2.DISCOUNT,0) + ifnull(T3.DISCOUNT,0) as finalDiscount  FROM " + "(select m.USER_ID, m.DEMO_GIVEN,m.PRODUCT_SOLD,m.SKIN_GENIUS,m.MAYBELLINE_VTO, m.RECCEPT_COUNT, m.BUYER_NAME," + " m.CONTACT_NUMBER,m.SOURCEOFSALES,m.UPLOAD_STATUS," + "IFNULL(sum(t.QUANTITY),0) as QUANTITY, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) AS TOTAL_AMOUNT,m.POS_SALE_FLAG " + "from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "' and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T1 " + "LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join" + " SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visite_date + "' and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " AND t.PRODUCT_ID =0 AND (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='OffAdditionalProduct'OR" + " t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct') and m.USER_ID='" + user_Id + "'" + "GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER) AS T2 ON T1.RECCEPT_COUNT = T2.RECCEPT_COUNT" + " LEFT JOIN(select t.RECCEPT_COUNT, ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from " + "SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t " + "on m.RECCEPT_COUNT = t.RECCEPT_COUNT WHERE M.Visit_Date ='" + visite_date + "' and m.COUNTER_ID=" + CounterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " and m.USER_ID='" + user_Id + "'" + " GROUP BY m.RECCEPT_COUNT,m.BUYER_NAME, m.CONTACT_NUMBER) AS T3 ON T1.RECCEPT_COUNT = T3.RECCEPT_COUNT", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_AMOUNT")));
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY")));
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")));
                    sale.setDemo_given_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DEMO_GIVEN")));
                    sale.setProduct_sold_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_SOLD")));
                    sale.setSkin_genius_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS")));
                    sale.setMaybelline_vto_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MAYBELLINE_VTO")));
                    sale.setAplyieddiscountedprice(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("finalDiscount")));
                    sale.setSourceofSales(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SOURCEOFSALES")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setPos_sale_flag("1".equalsIgnoreCase(dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG"))));
                    list.add(sale);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }

    public ArrayList<ProductMaster> getstock_check_axeandsub_axe(String counterGroup_Id) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<ProductMaster> getsub_brand_name(String counterGroup_Id, String column_name, boolean GWPFlag) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (GWPFlag) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='GWP'", null);
            } else {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='Normal'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<ProductMaster> getbrand_wise_sku_fromStockData(String SubAxeName, String AxeName, String BrandName, String counterGroup_Id) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select * from Product_Master Where AxeName=\"" + AxeName + "\" and SubAxeName=\"" + SubAxeName + "\" and BrandName=\"" + BrandName + "\"", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setStock(0);

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public boolean insertInwordSalesPoData(TableStructureGetterSetter nonWorkingdata) {
        db.delete("InwardSales_PO", null, null);
        ContentValues values = new ContentValues();
        List<InwardSalesPO> data = nonWorkingdata.getInwardSalesPO();
        try {
            if (data.isEmpty()) {
                return false;
            }

            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("GrnDate", data.get(i).getGrnDate());
                values.put("GrnRefNo", data.get(i).getGrnRefNo());
                values.put("GrnType", data.get(i).getGrnType());
                values.put("MRP", data.get(i).getMRP());
                values.put("ProductCode", data.get(i).getProductCode());
                values.put("ProductId", data.get(i).getProductId());
                values.put("QTY", data.get(i).getQTY());
                values.put("StoreCode", data.get(i).getStoreCode());
                values.put("StoreId", data.get(i).getStoreId());
                values.put("UOM", data.get(i).getUOM());
                values.put("ProductName", data.get(i).getProductName());

                long id = db.insert("InwardSales_PO", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            // do ALL your inserts here
            closeDb();
            return true;
        } catch (Exception ex) {
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public long insertNotificationData(String title, String body, String path, String visited_date, String type, String counter_id) {
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put(CommonString.KEY_BODY, body);
            values.put(CommonString.KEY_TITLE, title);
            values.put(CommonString.KEY_COUNTER_ID, counter_id);
            values.put(CommonString.KEY_VISIT_DATE, visited_date);
            values.put(CommonString.KEY_PATH, path);
            values.put(CommonString.KEY_TYPE, type);
            values.put(CommonString.KEY_READ_STATUS, "0");
            id = db.insert(CommonString.TABLE_NOTIFICATION_DATA, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
        return id;
    }

    private void closeDb() {
        // do ALL your inserts here
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    public long insertnotification_users(String userId, String visit_date, String counter_id, String keyId) {
        db.delete(CommonString.TABLE_NOTIFICATION_USER, CommonString.KEY_ID + "='" + keyId + "'and " + CommonString.KEY_USER_ID + "='" + userId + "'", null);
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put(CommonString.KEY_COUNTER_ID, counter_id);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put(CommonString.KEY_USER_ID, userId);
            values.put(CommonString.KEY_ID, keyId);
            id = db.insert(CommonString.TABLE_NOTIFICATION_USER, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
        return id;
    }

    public ArrayList<NotificationData> getNotificationList() {
        ArrayList<NotificationData> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_NOTIFICATION_DATA + " order by " + CommonString.KEY_ID + " desc ", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    NotificationData notifyData = new NotificationData();
                    notifyData.setId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    notifyData.setBody(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_BODY)));
                    notifyData.setPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PATH)));
                    notifyData.setTitle(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TITLE)));
                    notifyData.setVisited_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    notifyData.setType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TYPE)));
                    notifyData.setRead_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_READ_STATUS)));
                    list.add(notifyData);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public InvoiceGetterSetter getcst_countandtotal_sale_value(String visit_date, String counterId, String userId, String userType) {
        InvoiceGetterSetter sb = new InvoiceGetterSetter();
        Cursor dbcursor = null;
        try {
            if (userId == null) {
                dbcursor = db.rawQuery("select count(RECCEPT_COUNT) as TotalCustomer, sum(TOTAL_AMOUNT) as TOTAL_AMOUNT from " + "(select m.RECCEPT_COUNT as RECCEPT_COUNT, m.BUYER_NAME as BUYER_NAME, m.CONTACT_NUMBER as CONTACT_NUMBER, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) " + "AS TOTAL_AMOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visit_date + "' and M.COUNTER_ID=" + counterId + " and m.POS_SALE_FLAG='1'" + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER, m.POS_SALE_FLAG) as t", null);

            } else {
                dbcursor = db.rawQuery("select count(RECCEPT_COUNT) as TotalCustomer, sum(TOTAL_AMOUNT) as TOTAL_AMOUNT from " + "(select  m.RECCEPT_COUNT as RECCEPT_COUNT, m.BUYER_NAME as BUYER_NAME, m.CONTACT_NUMBER as CONTACT_NUMBER, IFNULL(sum(t.QUANTITY*t.PRODUCT_RATE),0) " + "AS TOTAL_AMOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + "WHERE M.Visit_Date ='" + visit_date + "' and M.COUNTER_ID=" + counterId + " and M.USER_ID='" + userId + "' and m.POS_SALE_FLAG='1'" + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER, m.POS_SALE_FLAG) as t", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_AMOUNT")));
                    sb.setCst_count(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TotalCustomer")));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }

        return sb;
    }

    public ArrayList<InvoiceGetterSetter> getcst_totaldiscount(String visit_date, String counterId, String userId, String userType) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (userId == null) {
                dbcursor = db.rawQuery(" select sum (ifnull (DISCOUNT,0)) as DISCOUNT from (" + " select Ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t on" + " m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "'and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1'and t.PRODUCT_ID =0 AND" + " (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER " + "union all select  Ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "'and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1' AND" + " (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER)", null);

            } else {
                dbcursor = db.rawQuery(" select sum (ifnull (DISCOUNT,0)) as DISCOUNT from (" + " select  Ifnull (sum(t.PRODUCT),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "'and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1' and " + "t.PRODUCT_ID =0 AND (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct') and m.USER_ID='" + userId + "'GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER " + "union all select  Ifnull (sum(t.SKU_TYPE),0) AS DISCOUNT from SALE_TRACKING_HEADER_TABLE m LEFT join SALE_TRACKING_TABLE t" + " on m.RECCEPT_COUNT = t.RECCEPT_COUNT " + " WHERE m.Visit_Date ='" + visit_date + "' and m.COUNTER_ID=" + counterId + " And m." + CommonString.KEY_USER_TYPE + " ='" + userType + "'" + " and m.POS_SALE_FLAG='1' AND" + " (t.PROMO_TYPE='OffWorth' OR t.PROMO_TYPE='Worth' OR t.PROMO_TYPE='OffAdditionalProduct' OR t.PROMO_TYPE='ValueOffAdditionalProduct' OR t.PROMO_TYPE='OffSameProduct' OR t.PROMO_TYPE='WorthWithProduct')" + " and m.USER_ID='" + userId + "' GROUP BY m.RECCEPT_COUNT, m.BUYER_NAME, m.CONTACT_NUMBER)", null);

            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sb = new InvoiceGetterSetter();
                    sb.setAplyieddiscountedprice(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DISCOUNT")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }


    public long insertcounteruserdata(String counter_id, String user_id, String visit_date, JourneyPlan counterimg_object, String userType) {
        db.delete(CommonString.TABLE_COUNTER_IMAGE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put(CommonString.KEY_COUNTER_ID, counter_id);
            values.put(CommonString.KEY_USER_ID, user_id);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put(CommonString.KEY_USER_TYPE, userType);
            values.put("Pre_Setup_Img_One", counterimg_object.getPresetup_img_one_str());
            values.put("Pre_Setup_Img_Two", counterimg_object.getPresetup_img_two_str());
            values.put("Post_Setup_Img_One", counterimg_object.getPostsetup_img_one_str());
            values.put("Post_Setup_Img_Two", counterimg_object.getPostsetup_img_two_str());

            values.put("Counter_Img_One", counterimg_object.getCounter_img_onefor_ba());
            values.put("Counter_Img_Two", counterimg_object.getCounter_img_two_for_ba());
            values.put("UNIQUE_CODE", counterimg_object.getTransId());
            values.put("UPLOAD_STATUS", CommonString.KEY_N);

            id = db.insert(CommonString.TABLE_COUNTER_IMAGE_DATA, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
        return id;
    }

    public long inseetgroomingdata(String counter_id, String user_id, String visit_date, GroomingGetterSetter groomedObject) {
        db.delete(CommonString.TABLE_GROOMED_IMAGE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put(CommonString.KEY_COUNTER_ID, counter_id);
            values.put(CommonString.KEY_USER_ID, user_id);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("Mornning_groomed_img", groomedObject.getMorning_groom_img_str());
            values.put("Mornning_groomed_time", groomedObject.getMorning_groom_time_str());
            values.put("Noon_groomed_img", groomedObject.getNoon_groom_img_str());
            values.put("Noon_groomed_time", groomedObject.getNoon_groom_time_str());

            values.put("Evening_groomed_img", groomedObject.getEvenning_groom_img_str());
            values.put("Evening_groomed_time", groomedObject.getEvenning_groom_time_str());
            values.put("UPLOAD_STATUS", groomedObject.getUpload_status());
            values.put("UNIQUE_CODE", groomedObject.getTransId());

            id = db.insert(CommonString.TABLE_GROOMED_IMAGE_DATA, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }

        return id;
    }

    public GroomingGetterSetter getinserted_groomingdata(String counter_Id, String user_name, String visit_date) {
        GroomingGetterSetter sb = new GroomingGetterSetter();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where COUNTER_ID=" + counter_Id + " And " + CommonString.KEY_USER_ID + "='" + user_name + "'And Visit_Date='" + visit_date + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setMorning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img")));
                    sb.setMorning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_time")));
                    sb.setNoon_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img")));
                    sb.setNoon_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_time")));
                    sb.setEvenning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img")));
                    sb.setEvenning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_time")));
                    sb.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {

            return sb;
        }

        return sb;
    }


    public ArrayList<GroomingGetterSetter> getgroomingdata(String counter_Id, String visit_date, boolean previous_date) {
        ArrayList<GroomingGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (previous_date) {
                dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where COUNTER_ID=" + counter_Id + " And Visit_Date <>'" + visit_date + "' and UPLOAD_STATUS='N'", null);

            } else {
                dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where COUNTER_ID=" + counter_Id + " And Visit_Date='" + visit_date + "' and UPLOAD_STATUS='N'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    GroomingGetterSetter sb = new GroomingGetterSetter();
                    sb.setMorning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img")));
                    sb.setMorning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_time")));
                    sb.setNoon_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img")));
                    sb.setNoon_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_time")));
                    sb.setEvenning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img")));
                    sb.setEvenning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_time")));
                    sb.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sb.setUser_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    list.add(sb);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public ArrayList<BaListGetterSetter> getBa(String visitDate, String counterId) {

        ArrayList<BaListGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * FROM BA_List WHERE VisitDate ='" + visitDate + "' and CounterId <>" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    BaListGetterSetter ch = new BaListGetterSetter();
                    ch.setEmpId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpId"))));
                    ch.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserName")));
                    ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    ch.setDesignationId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DesignationId"))));
                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }


    public ArrayList<BaListGetterSetter> getBAListAllData(String visitDate, String counterId) {

        ArrayList<BaListGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * FROM BA_List WHERE VisitDate ='" + visitDate + "' and CounterId =" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    BaListGetterSetter ch = new BaListGetterSetter();
                    ch.setEmpId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpId"))));
                    ch.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserName")));
                    ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    ch.setDesignationId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DesignationId"))));
                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public ArrayList<BaListGetterSetter> getBAListData(String userType, String counterId) {

        ArrayList<BaListGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("SELECT * FROM BA_List WHERE DesignationName ='" + userType + "' and CounterId=" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    BaListGetterSetter ch = new BaListGetterSetter();
                    ch.setEmpId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpId"))));
                    ch.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserName")));
                    ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    ch.setDesignationId(Integer.valueOf(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DesignationId"))));
                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public long insertLoginData(LoginGetterSetter loginGetterSetter) {
        db.delete(CommonString.TABLE_User_Login, "USER_ID='" + loginGetterSetter.getUserId() + "'", null);
        ContentValues values = new ContentValues();
        long l = 0;
        try {
            db.beginTransaction();
            values.put("USER_ID", loginGetterSetter.getUserId().toLowerCase());
            values.put(CommonString.KEY_VISIT_DATE, loginGetterSetter.getVisitDate());
            values.put(CommonString.KEY_PASSWORD, loginGetterSetter.getPassword());
            values.put(CommonString.KEY_MPIN, loginGetterSetter.getMpin());
            ///jp_changes insert login tyme
            values.put(CommonString.KEY_USER_LOGINTIME, loginGetterSetter.getUserLoginTym());
            values.put(CommonString.KEY_USER_TYPE, loginGetterSetter.getUserType());
            values.put(CommonString.KEY_USER_Checkout, loginGetterSetter.getUser_checkout());
            values.put(CommonString.KEY_IMAGE, "");
            l = db.insert(CommonString.TABLE_User_Login, null, values);

            closeDb();
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
        }

        return l;
    }

    public long updateVisitDateLoginData(String userId, String visit_date) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put(CommonString.KEY_IMAGE, "");
            values.put(CommonString.KEY_USER_Checkout, "0");
            if (!db.isOpen()) {
                open();
            }
            l = db.update("User_login", values, "USER_ID='" + userId + "'", null);

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

        return l;
    }

    public long updateLoginTym(String userId, String visit_date, String loginTym) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put(CommonString.KEY_USER_LOGINTIME, loginTym);
            values.put(CommonString.KEY_USER_Checkout, "0");
            if (!db.isOpen()) {
                open();
            }
            l = db.update("User_login", values, "USER_ID='" + userId + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public ArrayList<ProductMaster> getAxeNSubAxe(String counterGroup_Id, String column_name, String brandName, String axeName) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (brandName == null) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master", null);
            } else if (column_name.equals("SubAxeName") && axeName != null) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where AxeName ='" + axeName + "'", null);
            } else {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where BrandName =\"" + brandName + "\"", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }

    //
    public long insertMESaleCapturedData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, String uploadstatus, String counterId, String unique_code, String username) {
        db.delete(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, null, null);
        db.delete(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, null, null);
        ContentValues values = new ContentValues();
        ContentValues values1 = new ContentValues();
        long lf = 0, l = 0;
        try {
            db.beginTransaction();
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                values.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                values.put("UploadStatus", uploadstatus);
                values.put("UNIQUE_CODE", unique_code);
                values.put("USER_ID", username);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                values.put("NuanceName", save_listDataHeader.get(i).getNuanceName());
                values.put("ImagePath", save_listDataHeader.get(i).getImagePath());
                lf = db.insert(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, null, values);
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                    values1.put(CommonString.KEY_COMMON_ID, l);
                    values1.put("USER_ID", username);
                    values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock());
                    values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock());
                    values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock());
                    values1.put("ImagePath", save_listDataHeader.get(i).getImagePath());
                    values1.put("UploadStatus", uploadstatus);
                    values1.put("UNIQUE_CODE", unique_code);
                    values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values1.put(CommonString.KEY_COUNTER_ID, counterId);
                    values1.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                    values1.put("NuanceName", save_listDataHeader.get(i).getNuanceName());
                    values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                    values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName());
                    values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    values1.put("EanCode", data.get(save_listDataHeader.get(i)).get(j).getEanCode());
                    values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp());
                    values1.put("SignatureName", data.get(save_listDataHeader.get(i)).get(j).getSignatureName());
                    values1.put("BrandName", data.get(save_listDataHeader.get(i)).get(j).getBrandName());
                    values1.put("SubBrandName", data.get(save_listDataHeader.get(i)).get(j).getSubBrandName());
                    values1.put("ReferenceName", data.get(save_listDataHeader.get(i)).get(j).getReferenceName());
                    l = db.insert(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, null, values1);
                }
            }
            closeDb();
        } catch (Exception ex) {
            ex.fillInStackTrace();
            closeDb();
        }
        return l;
    }


    //Insert Stock data
    public void insertStockCapturedData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, boolean completeFlag, String counterId) {
        db.delete(CommonString.TABLE_INSERT_HEADER_STOCK_DATA, null, null);
        db.delete(CommonString.TABLE_STORE_STOCK_CHILD_DATA, null, null);
        ContentValues values = new ContentValues();
        TStockSummary stockObj;
        try {
            db.beginTransaction();
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                values.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                values.put("NuanceName", save_listDataHeader.get(i).getNuanceName());
                values.put("ImagePath", save_listDataHeader.get(i).getImagePath());
                long l = db.insert(CommonString.TABLE_INSERT_HEADER_STOCK_DATA, null, values);
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                    int stock = data.get(save_listDataHeader.get(i)).get(j).getStock();
                    if (completeFlag && stock == -1) {
                        stock = 0;
                    }

                    if (!db.isOpen()) {
                        open();
                    }
                    // getting product details from TStockSummary Table
                    boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    if (stockFlag) {
                        // set stock to product
                        updateTStockData(stock, CommonString.SALEABLE, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date);
                    } else {
                        stockObj = getStockSummaryStatus(visit_date);
                        if (stockObj != null) {
                            insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.SALEABLE, stock, completeFlag, visit_date);
                        }
                    }
                }
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception ex) {
            ex.fillInStackTrace();
            closeDb();
        }
    }

    //get Stock header inserted data
    public ArrayList<LoginGetterSetter> getlistAllData(String visitDate, String user_name) {
        ArrayList<LoginGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("Select * from User_login where USER_ID='" + user_name + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    LoginGetterSetter ch = new LoginGetterSetter();
                    ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    ch.setImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_IMAGE)));
                    ch.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE)));
                    ch.setMpin(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_MPIN)));
                    ch.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    ch.setPassword(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PASSWORD)));
                    ch.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout)));
                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }


    //Insert Tester data
    public void insertTesterCapturedData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, boolean completeFlag, String counterId) {
        db.delete(CommonString.TABLE_INSERT_HEADER_TESTER_DATA, null, null);
        db.delete(CommonString.TABLE_TESTER_CHILD_DATA, null, null);
        ContentValues values = new ContentValues();

        try {
            db.beginTransaction();
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                values.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                values.put("ImagePath", save_listDataHeader.get(i).getImagePath());
                values.put("NuanceName", save_listDataHeader.get(i).getNuanceName());
                long l = db.insert(CommonString.TABLE_INSERT_HEADER_TESTER_DATA, null, values);
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                    if (db.isOpen()) {
                    } else {
                        open();
                    }
                    // getting product details from TStockSummary Table
                    boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    if (stockFlag) {
                        // set stock to product
                        updateTStockData(data.get(save_listDataHeader.get(i)).get(j).getStock(), CommonString.TESTER, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date);
                    } else {
                        if (db.isOpen()) {
                        } else {
                            open();
                        }
                        TStockSummary stockObj;
                        stockObj = getStockSummaryStatus(visit_date);
                        if (stockObj != null) {
                            insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.TESTER, data.get(save_listDataHeader.get(i)).get(j).getStock(), completeFlag, visit_date);
                        }
                    }
                }
            }

            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception ex) {
            ex.fillInStackTrace();
        }
    }

    //get Tester header inserted data
    public ArrayList<ProductMaster> getTesterHeaderInsertedData(String visitDate, boolean filledregularstock) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (filledregularstock) {
                dbcursor = db.rawQuery("select distinct t1.AxeName as AxeName,t1.SubAxeName as SubAxeName,t1.BrandName as BrandName," + "t1.SignatureName as SignatureName,t1.NuanceName as NuanceName,t1.ImagePath as ImagePath from DR_TESTER_HEADER_DATA t1 " + "inner join Product_Master t2 on  t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName " + "Inner Join  T_StockSummary TS ON  t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName  and  TS.ProductId = t2.ProductId  where TS.TesterBalance >'0' and t1.Visit_Date ='" + visitDate + "'", null);

            } else {
                dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_HEADER_TESTER_DATA + " where Visit_Date ='" + visitDate + "'", null);
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName")));
                    sb.setImagePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImagePath")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    //Insert Sample Data
    public void insertSampleCapturedData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, boolean completeFlag, String counterId) {
        db.delete(CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA, null, null);
        db.delete(CommonString.TABLE_SAMPLE_CHILD_DATA, null, null);
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            if (!db.isOpen()) {
                open();
            }
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                values.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                values.put("NuanceName", save_listDataHeader.get(i).getNuanceName());
                values.put("ImagePath", save_listDataHeader.get(i).getImagePath());
                long l = db.insert(CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA, null, values);
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                    if (!db.isOpen()) {
                        open();
                    }
                    // getting product details from TStockSummary Table
                    boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    if (stockFlag) {
                        // set stock to product
                        updateTStockData(data.get(save_listDataHeader.get(i)).get(j).getStock(), CommonString.SAMPLE, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date);
                    } else {
                        if (!db.isOpen()) {
                            open();
                        }
                        TStockSummary stockObj;
                        stockObj = getStockSummaryStatus(visit_date);
                        if (stockObj != null) {
                            insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.SAMPLE, data.get(save_listDataHeader.get(i)).get(j).getStock(), completeFlag, visit_date);
                        }
                    }
                }
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception ex) {
            ex.fillInStackTrace();

        }
    }

    //get Sample header inserted data
    public ArrayList<ProductMaster> getSampleHeaderInsertedData(String visitDate, String counterId, boolean regularstock) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (regularstock) {
                dbcursor = db.rawQuery("select distinct t1.AxeName as AxeName,t1.SubAxeName as SubAxeName,t1.BrandName as BrandName," + "t1.SignatureName as SignatureName,t1.NuanceName as NuanceName,t1.ImagePath as ImagePath from DR_SAMPLE_HEADER_DATA t1 " + "inner join Product_Master t2 on  t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName " + "Inner Join  T_StockSummary TS ON  t1.NuanceName= t2.NuanceName and t1.SubAxeName=t2.SubAxeName  and  TS.ProductId = t2.ProductId  where TS.SampleBalance >'0' and t1.Visit_Date ='" + visitDate + "'and t1.COUNTER_ID='" + counterId + "'", null);

            } else {
                dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_HEADER_SAMPLE_DATA + " where Visit_Date ='" + visitDate + "'and COUNTER_ID='" + counterId + "'", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName")));
                    sb.setImagePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImagePath")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    //Insert Damaged Data
    public long insertDamagedCapturedData(String visit_date, String counterId, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader) {
        db.delete(CommonString.TABLE_INSERT_HEADER_DAMAGED_DATA, null, null);
        db.delete(CommonString.TABLE_DAMAGED_CHILD_DATA, null, null);
        ContentValues values1 = new ContentValues();
        long l = 0;
        try {
            db.beginTransaction();
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {

                    values1.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                    values1.put("BrandName", save_listDataHeader.get(i).getBrandName());
                    values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values1.put(CommonString.KEY_COUNTER_ID, counterId);
                    values1.put("SubAxeName", save_listDataHeader.get(i).getReferenceName());
                    values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName());
                    values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock());
                    values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp());
                    values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock_receive());
                    values1.put("ImagePath", data.get(save_listDataHeader.get(i)).get(j).getImagePath());
                    l = db.insert(CommonString.TABLE_DAMAGED_CHILD_DATA, null, values1);
                }
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
        }

        return l;
    }


    //Insert Suggested Stock Data
    public void insertSuggestedStockCapturedData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader) {
        db.delete(CommonString.TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA, null, null);
        db.delete(CommonString.TABLE_SUGGESTED_STOCK_CHILD_DATA, null, null);

        ContentValues values = new ContentValues();
        ContentValues values1 = new ContentValues();

        try {
            db.beginTransaction();
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                values.put("AxeName", save_listDataHeader.get(i).getAxeName());
                values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                values.put("ImagePath", save_listDataHeader.get(i).getImagePath());
                long l = db.insert(CommonString.TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA, null, values);
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                    values1.put("Common_Id", (int) l);
                    values1.put("AxeName", save_listDataHeader.get(i).getAxeName());
                    values1.put("BrandName", save_listDataHeader.get(i).getBrandName());
                    values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                    values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName());
                    values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock());
                    values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp());
                    values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock_receive());

                    db.insert(CommonString.TABLE_SUGGESTED_STOCK_CHILD_DATA, null, values1);
                }
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
        }
    }

    //get Suggested Stock header inserted data
    public ArrayList<ProductMaster> getSuggestedStockHeaderInsertedData(String visitDate) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_HEADER_SUGGESTED_STOCK_DATA + " where Visit_Date ='" + visitDate + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setImagePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImagePath")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    //get Child Suggested data
    public ArrayList<ProductMaster> getSuggestedInsertedData(String axeName, String subAxeName, String brandName) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_SUGGESTED_STOCK_CHILD_DATA + " where SubAxeName =\"" + subAxeName + "\" AND AxeName=\"" + axeName + "\" AND BrandName=\"" + brandName + "\"", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("STOCK")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));


                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public boolean insertTCounterInvoiceData(TCounterInvoiceGetterSetter cst) {
        db.delete("T_CounterInvoice", null, null);
        ContentValues values = new ContentValues();
        List<TCounterInvoice> data = cst.getTCounterInvoice();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("InvId", data.get(i).getInvId());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("InvoiceNo", data.get(i).getInvoiceNo().trim());
                values.put("InvoiceDate", data.get(i).getInvoiceDate());
                values.put("ProductId", data.get(i).getProductId());
                values.put("Qty", data.get(i).getQty());
                values.put("Amount", data.get(i).getAmount());
                values.put("InvoiceType", data.get(i).getInvoiceType().trim());
                values.put("CounterConfirm", data.get(i).getCounterConfirm());
                values.put("InvoiceStatus", data.get(i).getInvoiceStatus());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("ActualQty", data.get(i).getActualQty());
                values.put("ReasonId", data.get(i).getReasonId());
                values.put("TranId", data.get(i).getTranId());

                if (!db.isOpen()) open();

                long id = db.insert("T_CounterInvoice", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertTStockSummaryData(TStockSummaryGetterSetter cst, String counterId, String date) {
        db.delete("T_StockSummary", null, null);
        ContentValues values = new ContentValues();
        List<TStockSummary> data = cst.gettStockSummary();
        try {

            if (data.isEmpty()) {
                return false;
            }

            ArrayList<StockSummaryCheck> sumcheck = getStockSummaryCheck(counterId, date);
            if (!sumcheck.isEmpty()) {
                int totallinecount = sumcheck.get(0).getTotalLine();
                int data_size = data.size();
                if (totallinecount != data_size) {
                    delete_table_data("T_StockSummary");
                    throw new Exception();
                }
            }
            db.beginTransaction();
            if (!data.isEmpty()) {
                for (TStockSummary tStockSummary : data) {
                    values = new ContentValues();
                    values.put("Id", tStockSummary.getId());
                    values.put("CounterId", tStockSummary.getCounterId());
                    values.put("ProductId", tStockSummary.getProductId());
                    values.put("SaleableIn", tStockSummary.getSaleableIn());
                    values.put("SaleableOut", tStockSummary.getSaleableOut());
                    values.put("SaleableDamage", tStockSummary.getSaleableDamage());
                    values.put("SaleableBalance", tStockSummary.getSaleableBalance());
                    values.put("TesterIn", tStockSummary.getTesterIn());
                    values.put("TesterOut", tStockSummary.getTesterOut());
                    values.put("TesterDamage", tStockSummary.getTesterDamage());
                    values.put("TesterBalance", tStockSummary.getTesterBalance());
                    values.put("SampleIn", tStockSummary.getSampleIn());
                    values.put("SampleOut", tStockSummary.getSampleOut());
                    values.put("SampleDamage", tStockSummary.getSampleDamage());
                    values.put("SampleBalance", tStockSummary.getSampleBalance());
                    values.put("GwpIn", tStockSummary.getGwpIn());
                    values.put("GwpOut", tStockSummary.getGwpOut());
                    values.put("GwpDamage", tStockSummary.getGwpDamage());
                    values.put("GwpBalance", tStockSummary.getGwpBalance());
                    values.put("SaleableStatus", tStockSummary.getSaleableStatus().trim());
                    values.put("TesterStatus", tStockSummary.getTesterStatus().trim());
                    values.put("SampleStatus", tStockSummary.getSampleStatus().trim());
                    values.put("GwpStatus", tStockSummary.getGwpStatus().trim());
                    values.put("VisitDate", tStockSummary.getVisitDate());
                    if (!db.isOpen()) {
                        open();
                    }
                    long l = db.insert("T_StockSummary", null, values);
                    if (l == -1) {
                        throw new Exception();
                    }

                }

                if (isTStockTotalLine(date, counterId, "T_StockSummary") != data.size()) {
                    delete_table_data("T_StockSummary");
                    throw new Exception();
                }
            }
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();

            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            db.setTransactionSuccessful();
            db.endTransaction();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public long updateLoginData(String userId, String new_password, boolean flag) {
        long l = 0;
        try {
            if (db.isOpen()) {
            } else {
                open();
            }
            ContentValues values = new ContentValues();
            if (flag) {
                values.put(CommonString.KEY_PASSWORD, new_password);
            } else {
                values.put(CommonString.KEY_USER_Checkout, "1");
            }

            l = db.update("User_login", values, "USER_ID='" + userId + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public ArrayList<MasterPosm> getVisibility_inserted_data(String counterId, String visit_date, String transId, boolean manual_upload) {
        ArrayList<MasterPosm> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (manual_upload) {
                dbcursor = db.rawQuery("Select distinct pt.UUID_ID as UUID_ID, Pt.Posm as Posm,Pt.PosmId as PosmId,Pt.PosmTypeId as PosmTypeId," + "Pt.RefImage as RefImage,Pt.Resion as Resion,Pt.Resion_id as Resion_id,pt.User_Id as User_Id," + "Pt.VISIBILITY_EXIST as VISIBILITY_EXIST,Pt.VISIBILITY_IMG as VISIBILITY_IMG from VISIBILITY_TABLE Pt Inner Join Master_Posm Pm " + "On Pt.PosmId=Pm.PosmId where Pt.COUNTER_ID='" + counterId + "' and " + CommonString.KEY_UUID + "='" + transId + "'and " + CommonString.KEY_STATUS + " ='N'", null);

            } else {

                dbcursor = db.rawQuery("Select distinct pt.UUID_ID as UUID_ID, Pt.Posm as Posm,Pt.PosmId as PosmId,Pt.PosmTypeId as PosmTypeId," + "Pt.RefImage as RefImage,Pt.Resion as Resion,Pt.Resion_id as Resion_id,pt.User_Id as User_Id," + "Pt.VISIBILITY_EXIST as VISIBILITY_EXIST,Pt.VISIBILITY_IMG as VISIBILITY_IMG from VISIBILITY_TABLE Pt Inner Join Master_Posm Pm " + "On Pt.PosmId=Pm.PosmId where Pt.COUNTER_ID='" + counterId + "' and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterPosm sale = new MasterPosm();

                    sale.setPosm(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Posm")));
                    sale.setPosmTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PosmId")));
                    sale.setPromotion_exists_state(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PosmTypeId")));
                    sale.setRefImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RefImage")));
                    sale.setPromotion_currect_ans(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Resion")));
                    sale.setPromotion_currect_ans_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Resion_id")));
                    sale.setPromotion_exists_state(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VISIBILITY_EXIST")));
                    sale.setPromotion_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VISIBILITY_IMG")));
                    sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UUID)));
                    sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));

                    list.add(sale);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {

            return list;
        }
        return list;
    }

    public ArrayList<MasterPosm> getVisibility_master_data(String counterId) {
        ArrayList<MasterPosm> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT MP.PosmId as PosmId,MP.Posm as Posm,MP.PosmTypeId as PosmTypeId,MP.RefImage as RefImage FROM Master_Posm MP inner join Mapping_Visibility MV ON MV.PosmId=MP.PosmId where MV.CounterId='" + counterId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    MasterPosm sale = new MasterPosm();
                    sale.setPosm(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Posm")));
                    sale.setPosmId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PosmId")));
                    sale.setPosmTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PosmTypeId")));
                    sale.setRefImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RefImage")));

                    sale.setPromotion_exists_state("");
                    sale.setPromotion_img("");
                    sale.setPromotion_currect_ans("");
                    sale.setPromotion_currect_ans_Id("0");

                    list.add(sale);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {

            return list;
        }
        return list;
    }

    public boolean insertMasterNonVisibilityData(MasterNonVisibilityGetterSetter cst) {
        db.delete("Master_NonVisibility", null, null);
        ContentValues values = new ContentValues();
        List<MasterNonVisibility> data = cst.getMasterNonVisibility();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Reason", data.get(i).getReason());
                values.put("ReasonId", data.get(i).getReasonId());
                long id = db.insert("Master_NonVisibility", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<MasterNonVisibility> getnon_promotion_reasonList() {
        ArrayList<MasterNonVisibility> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("Select * from Master_NonVisibility", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterNonVisibility sale = new MasterNonVisibility();
                    sale.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason")));
                    sale.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId")));
                    list.add(sale);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public long insertVisibility_data(String userId, String counterId, String visit_date, ArrayList<MasterPosm> visibilitylist, String uuid_ID) {
        db.delete(CommonString.Table_visibilisty, null, null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        ContentValues values = new ContentValues();
        ContentValues finalvalues = new ContentValues();
        long l = 0, masterreturn = 0;
        try {
            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, uuid_ID);
            finalvalues.put(CommonString.KEY_USER_ID, userId);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counterId);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.VISIBILITY);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);

            for (int k = 0; k < visibilitylist.size(); k++) {
                values.put(CommonString.KEY_UUID, uuid_ID);
                values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                values.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_USER_ID, userId);
                values.put("Posm", visibilitylist.get(k).getPosm());
                values.put("PosmId", visibilitylist.get(k).getPosmId());
                values.put("PosmTypeId", visibilitylist.get(k).getPosmTypeId());
                values.put("RefImage", visibilitylist.get(k).getRefImage());
                values.put("Resion", visibilitylist.get(k).getPromotion_currect_ans());
                values.put("Resion_id", visibilitylist.get(k).getPromotion_currect_ans_Id());
                values.put("VISIBILITY_EXIST", visibilitylist.get(k).getPromotion_exists_state());
                values.put("VISIBILITY_IMG", visibilitylist.get(k).getPromotion_img());

                l = db.insert(CommonString.Table_visibilisty, null, values);
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", ex.toString());
        }
        return l;
    }

    public long insertCompOffers(String userId, String counterId, String visit_date, ArrayList<MasterCompetitonBrandWiseNuance> compOffers, String uuid_ID) {
        long l = 0, masterreturn = 0;
        Gson gson = new Gson();
        try {
            db.delete(CommonString.TABLE_COMP_OFFERS, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
            db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
            ContentValues values = new ContentValues();
            ContentValues finalvalues = new ContentValues();

            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, uuid_ID);
            finalvalues.put(CommonString.KEY_USER_ID, userId);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counterId);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.COMP_OFFERS);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);

            for (int k = 0; k < compOffers.size(); k++) {
                values.put(CommonString.KEY_UUID, uuid_ID);
                values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                values.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_USER_ID, userId);
                values.put("PRESENT", compOffers.get(k).getPresent_str());
                values.put("DATA_FOR_MONTH", compOffers.get(k).getDateOfMonth());
                values.put("COMPANY", compOffers.get(k).getCompetitionBrand());
                values.put("COMPANY_ID", compOffers.get(k).getCompetitionBrandId());
                values.put("NUANCE", compOffers.get(k).getCompetitionNuance());
                values.put("NUANCE_ID", compOffers.get(k).getCompetitionNuanceId());
                values.put("PROMOTYPE", compOffers.get(k).getPromoType());
                values.put("PROMOTYPE_ID", compOffers.get(k).getPromoTypeId());
                values.put("NUM_COUNTER", compOffers.get(k).getCounter());
                values.put("NO_OF_BA", compOffers.get(k).getNoOfBa());
                values.put("SALE_RANGE", compOffers.get(k).getSaleRange());
                values.put("COMP_OFFER", compOffers.get(k).getPromoType());
                values.put("COMP_OFFER_ID", compOffers.get(k).getPromoTypeId());
                values.put("COMP_BUY_TYPE", compOffers.get(k).getBuyType());
                values.put("COMP_BUY_TYPE_ID", compOffers.get(k).getBuyTypeId());
                values.put("COMP_BUY_TYPE_INPUT_ID", compOffers.get(k).getBuyTypeInputId());
                values.put("COMP_BUY_TYPE_INPUT", compOffers.get(k).getBuyTypeInput());
                values.put("COMP_GET_TYPE_INPUT_ID", compOffers.get(k).getGetTypeInputId());
                values.put("COMP_GET_TYPE_INPUT", compOffers.get(k).getGetTypeInput());
                values.put("COMP_NEW_LAUNCH_MRP", compOffers.get(k).getNewLaunchMrp());
                values.put("COMPOFFERSET_QTY", compOffers.get(k).getBuyQuantity());
                values.put("COMPOFFERSET", compOffers.get(k).getCompOfferset());
                values.put("COMPOFFERSET_ID", compOffers.get(k).getCompOffersetId());
                values.put("COMPOFFERGET_QTY", compOffers.get(k).getGetQuantity());
                values.put("COMPOFFERGET", compOffers.get(k).getCompOfferGet());
                values.put("COMPOFFERGET_ID", compOffers.get(k).getCompOfferGetId());
                values.put("FROM_DATE", compOffers.get(k).getFromDate());
                values.put("TO_DATE", compOffers.get(k).getToDate());
                values.put("PRODUCTTYPE", compOffers.get(k).getProductType());
                values.put("PRODUCTTYPE_ID", compOffers.get(k).getProductTypeId());
                values.put("PROMO_DETAILS", compOffers.get(k).getCompPromDetail());
                values.put("PROMO_IMG", compOffers.get(k).getCompOfferImg());
                values.put("AVG_TARGET", compOffers.get(k).getAvgtarget());
                values.put("AVG_OFFTAKE", compOffers.get(k).getAvgOfftake());
                values.put("TVA_PER", compOffers.get(k).getTvapercent());
                values.put("GWP_AVAILABLE", compOffers.get(k).getGwpAvailable());
                values.put("GWP_IMAGE", compOffers.get(k).getGwpImage());
                String baInfoJson = gson.toJson(compOffers.get(k).getBaTenureDetailList());
                values.put("BA_INFO_LIST", baInfoJson);
                l = db.insert(CommonString.TABLE_COMP_OFFERS, null, values);
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", ex.toString());
        }

        return l;
    }

    public ArrayList<MasterCompetitonBrandWiseNuance> getInsertedCompOffers(String visit_date, String counterId, String transId, boolean upload) {
        ArrayList<MasterCompetitonBrandWiseNuance> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (upload) {
                dbcursor = db.rawQuery("SELECT * FROM " + CommonString.TABLE_COMP_OFFERS + " WHERE " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_UUID + "='" + transId + "'and " + CommonString.KEY_STATUS + " ='N'", null);
            } else {
                dbcursor = db.rawQuery("SELECT * FROM " + CommonString.TABLE_COMP_OFFERS + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "'", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitonBrandWiseNuance sb = new MasterCompetitonBrandWiseNuance();
                    sb.setKeyId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sb.setuUId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UUID)));
                    sb.setStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STATUS)));
                    sb.set_userId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    sb.setPresent_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRESENT")));
                    sb.setDateOfMonth(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DATA_FOR_MONTH")));
                    sb.setCompetitionBrand(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPANY")));
                    sb.setCompetitionBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMPANY_ID")));
                    sb.setCompetitionNuance(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NUANCE")));
                    sb.setCompetitionNuanceId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("NUANCE_ID")));
                    sb.setPromoType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMOTYPE")));
                    sb.setPromoTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PROMOTYPE_ID")));
                    sb.setCounter(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NUM_COUNTER")));
                    sb.setNoOfBa(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NO_OF_BA")));
                    sb.setSaleRange(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SALE_RANGE")));
                    sb.setBuyType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE")));
                    sb.setBuyTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE_ID")));
                    sb.setBuyTypeInput(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE_INPUT")));
                    sb.setBuyTypeInputId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMP_BUY_TYPE_INPUT_ID")));
                    sb.setGetTypeInput(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_GET_TYPE_INPUT")));
                    sb.setGetTypeInputId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMP_GET_TYPE_INPUT_ID")));
                    sb.setNewLaunchMrp(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMP_NEW_LAUNCH_MRP")));
                    sb.setCompOfferGet(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERGET")));
                    sb.setCompOfferGetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMPOFFERGET_ID")));
                    sb.setCompOfferset(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERSET")));
                    sb.setCompOffersetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("COMPOFFERSET_ID")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCTTYPE")));
                    sb.setProductTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PRODUCTTYPE_ID")));
                    sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FROM_DATE")));
                    sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TO_DATE")));
                    sb.setCompPromDetail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_DETAILS")));
                    sb.setCompOfferImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROMO_IMG")));
                    sb.setBuyQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERSET_QTY")));
                    sb.setGetQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COMPOFFERGET_QTY")));
                    sb.setAvgtarget(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AVG_TARGET")));
                    sb.setAvgOfftake(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AVG_OFFTAKE")));
                    sb.setTvapercent(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TVA_PER")));
                    sb.setGwpAvailable(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GWP_AVAILABLE")));
                    sb.setGwpImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GWP_IMAGE")));
                    String baInfoJson = dbcursor.getString(dbcursor.getColumnIndexOrThrow("BA_INFO_LIST"));
                    Type type = new TypeToken<List<BaTenureDetail>>() {
                    }.getType();
                    List<BaTenureDetail> baInfoList = new Gson().fromJson(baInfoJson, type);
                    sb.setBaTenureDetailList(baInfoList);
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " when fetching Primary Visibility !!!!!!!!!!! " + e.toString());
            return list;
        }
        ////////test("Fetching", " opening stock---------------------->Stop<-----------");
        return list;
    }

    // neeraj db changes added
    public ArrayList<TCounterInvoice> getInwardStockData(String counter_id, String visit_date) {
        ArrayList<TCounterInvoice> list = new ArrayList<>();
        Cursor dbcursor = null;
        String day = "", month = "", year = "", final_date = "";
        try {

            dbcursor = db.rawQuery(" select InvoiceNo, InvoiceDate,InvoiceStatus, InvoiceType, sum(CounterConfirm) as ApprovedLine," +
                    " count(ProductId) as NoofLine, sum(Amount) as FinalAmount from " +
                    "(select  InvoiceNo, Qty, Amount, InvoiceType, InvoiceDate,InvoiceStatus, ProductId, " +
                    "case when (CounterConfirm + localConfirm)>0 then 1 else 0 end as CounterConfirm from " +
                    "(select d.InvId, d.CounterId, d.InvoiceNo, d.InvoiceDate,d.InvoiceStatus, d.ProductId, d.Qty, d.Amount," +
                    " d.InvoiceType, d.CounterConfirm, t.InvId ," +
                    "  case when t.InvId is null then 0 else  1 end as  localConfirm from T_CounterInvoice d" +
                    " Left join DR_INWARD_STOCK_TRANSACTION t on d.InvId = t.InvId" +
                    "  Inner join Product_Master Pm on d.ProductId = Pm.ProductId where d.CounterId = '" + counter_id +
                    "' and d.VisitDate = '" + visit_date + "'" + "  )as t) as t  group by InvoiceNo, InvoiceDate, InvoiceType order by InvoiceDate desc ", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TCounterInvoice sb = new TCounterInvoice();
                    sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceNo")));
                    sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceType")));
                    String invoiceStatus = dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceStatus"));
                    String[] date_format = dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceDate")).split("-");
                    year = date_format[0];
                    month = date_format[1];
                    day = date_format[2];
                    final_date = month + "-" + day + "-" + year;
                    sb.setInvoiceDate(final_date);
                    sb.setApproved_line(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ApprovedLine")));
                    sb.setInvoiceStatus(invoiceStatus != null && invoiceStatus.equals("0") ? false : true);
                    sb.setNo_ofLine(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine")));
                    sb.setFinalAmount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FinalAmount")));
                    sb.setUpload_status("");
                    sb.setSource("");
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    // neeraj code commited
    public boolean insertServerTimeData(ServerTimeGetterSetter cst) {
        db.delete("ServerTime", null, null);
        ContentValues values = new ContentValues();
        List<ServerTime> data = cst.getServerTime();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("ServerDate", data.get(i).getServerDate());
                values.put("ServerTime", data.get(i).getServerTime());
                long id = db.insert("ServerTime", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertTStockSummaryCheck(ServerTimeGetterSetter cst) {
        db.delete("StockSummary_Check", null, null);
        ContentValues values = new ContentValues();
        List<StockSummaryCheck> data = cst.getStockSummaryCheck();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("TotalLine", data.get(i).getTotalLine());
                values.put("TotalStock", data.get(i).getTotalStock());
                values.put("VisitDate", data.get(i).getVisitDate());

                if (!db.isOpen()) {
                    open();
                }

                long id = db.insert("StockSummary_Check", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<StockSummaryCheck> getStockSummaryCheck(String counterId, String visit_date) {
        ArrayList<StockSummaryCheck> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select distinct TotalLine,TotalStock from StockSummary_Check where CounterId =" + counterId + " And VisitDate='" + visit_date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    StockSummaryCheck sb = new StockSummaryCheck();

                    sb.setTotalLine(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine")));
                    sb.setTotalStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalStock")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public long insert_makeover_capture(String user_Id, String visit_date, String store_Cd, InvoiceGetterSetter makeover_object) {
        db.delete(CommonString.Table_Makeover_Capture, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        ContentValues values = new ContentValues();
        long l = 0;
        try {
            db.beginTransaction();
            values.put("USER_ID", user_Id);
            values.put(CommonString.KEY_MASTER_TRANSACTION_ID, 0);
            values.put(CommonString.KEY_COUNTER_ID, store_Cd);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);

            values.put("UNIQUE_CODE", makeover_object.getUnique_code());
            values.put("BUYER_NAME", makeover_object.getCustomer_name());
            values.put("CONTACT_NUMBER", makeover_object.getMobile_no());
            values.put("EMAIL_ID", makeover_object.getConsumer_email_Id());
            values.put("AGE", makeover_object.getConsumer_age());
            values.put("SKIN_TYPE", makeover_object.getConsumer_skinType());
            values.put("LOOk", makeover_object.getLook_creater_str());
            values.put("GENDER", makeover_object.getCustomer_gender());
            values.put("BEFORE_MAKEOVER_IMG", makeover_object.getBefore_makeover_img());
            values.put("AFTER_MAKEOVER_IMG", makeover_object.getAfter_makeover_img());
            values.put("FEEDBACK", makeover_object.getCst_feed_back_value());
            values.put("UPLOAD_STATUS", makeover_object.getStr_upload_status());
            values.put("TERMCONDITION_FLAG", makeover_object.getStr_termcondition());
            values.put("POS_SALE_FLAG", makeover_object.isPos_sale_flag());

            l = db.insert(CommonString.Table_Makeover_Capture, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", ex.toString());
        }

        return l;
    }

    public long update_makeover_capture(String counterId, String visit_date, String user_Id, InvoiceGetterSetter makeover_object) {
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues values = new ContentValues();
        ContentValues valuesmasterT = new ContentValues();
        long l = 0, masterreturn = 0;
        try {
            db.beginTransaction();
            valuesmasterT.put(CommonString.KEY_UUID, makeover_object.getUnique_code());
            valuesmasterT.put(CommonString.KEY_USER_ID, user_Id);
            valuesmasterT.put(CommonString.KEY_COUNTER_ID, counterId);
            valuesmasterT.put(CommonString.KEY_VISIT_DATE, visit_date);
            valuesmasterT.put(CommonString.KEY_STOCK_TYPE, CommonString.MAKEOVER_CAPTURE);
            valuesmasterT.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            valuesmasterT.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, valuesmasterT);

            if (masterreturn > 0) {
                values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                values.put("UNIQUE_CODE", makeover_object.getUnique_code());
                values.put("BUYER_NAME", makeover_object.getCustomer_name());
                values.put("CONTACT_NUMBER", makeover_object.getMobile_no());
                values.put("EMAIL_ID", makeover_object.getConsumer_email_Id());
                values.put("AGE", makeover_object.getConsumer_age());
                values.put("SKIN_TYPE", makeover_object.getConsumer_skinType());
                values.put("LOOk", makeover_object.getLook_creater_str());
                values.put("GENDER", makeover_object.getCustomer_gender());
                values.put("BEFORE_MAKEOVER_IMG", makeover_object.getBefore_makeover_img());
                values.put("AFTER_MAKEOVER_IMG", makeover_object.getAfter_makeover_img());
                values.put("FEEDBACK", makeover_object.getCst_feed_back_value());
                values.put("UPLOAD_STATUS", makeover_object.getStr_upload_status());
                values.put("TERMCONDITION_FLAG", makeover_object.getStr_termcondition());

                if (makeover_object.isPos_sale_flag()) {
                    values.put("POS_SALE_FLAG", "1");
                } else {
                    values.put("POS_SALE_FLAG", "0");

                }

                if (!db.isOpen()) {
                    open();
                }
                l = db.update(CommonString.Table_Makeover_Capture, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and " + CommonString.KEY_ID + "='" + makeover_object.getReccept_count() + "'", null);

            }
            closeDb();
        } catch (Exception e) {
            closeDb();
            e.fillInStackTrace();
        }
        return l;
    }


    ///jeevanp
    public long deleteconsumersale(String visit_date, int reciept_count, String user_id) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }

            String whereClause = CommonString.KEY_RECCEPT_NUMBER + "='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and USER_ID='" + user_id + "'";
            l = db.delete(CommonString.Table_Sale_Tracking, whereClause, null);
            l = db.delete(CommonString.Table_Sale_Tracking_Header_Data, whereClause, null);
            l = db.delete(CommonString.Table_Applyeid_Promotion, whereClause, null);
            l = db.delete(CommonString.Table_PromoApplyeidOnProduct, whereClause, null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long delete_sale(String visit_date, int reciept_count, String user_id) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }

            l = db.delete(CommonString.Table_Sale_Tracking, CommonString.KEY_RECCEPT_NUMBER + "='" + String.valueOf(reciept_count) + "' and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and USER_ID='" + user_id + "'", null);

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

    public ArrayList<ProductMaster> get_inwrad_stock_header_data(String invoiceNo, String type, String counterId) {
        ArrayList<ProductMaster> list1 = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct Pm.SubAxeName as SubAxeName,Pm.SignatureName as SignatureName,Pm.BrandName as BrandName," + "Pm.SubBrandName as SubBrandName,Pm.ReferenceName as ReferenceName from T_CounterInvoice as ci " + "inner join Product_Master Pm on ci.ProductId = Pm.ProductId where ci.InvoiceNo ='" + invoiceNo + "' and ci.InvoiceType ='" + type + "' And ci.CounterId=" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));

                    list1.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list1;
            }
        } catch (Exception e) {

            return list1;
        }

        return list1;
    }


    public ArrayList<ProductMaster> get_inward_stock_child_product_data(String referenceName, String brandName, String subBrandName, String signatureName, String invoice_no, String type, String counterId) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            String qury = "Select Distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode,pm.Mrp as Mrp,tc.InvId as InvId," + "(ifnull(tc.Qty,0))as InvoiceQty," + "tc.CounterConfirm as CounterConfirm,tc.InvoiceStatus as InvoiceStatus,(ifnull(tc.ActualQty,0))as ActualQty," + "(ifnull(tc.ReasonId,0))as ReasonId,ifnull(tc.TranId,'')as" +
                    " TranId From Product_Master" + " pm inner join T_CounterInvoice tc on pm.ProductId=tc.ProductId" +
                    "  Where pm.SignatureName =trim(\"" + signatureName + "\") AND pm.BrandName=trim(\"" + brandName + "\") AND" +
                    " pm.SubBrandName =trim(\"" + subBrandName + "\") AND pm.ReferenceName =trim(\"" +
                    referenceName + "\") AND tc.InvoiceNo=trim('" + invoice_no + "') And " + "tc.CounterId=" + counterId +
                    " AND tc.InvoiceType='" + type + "' and tc. InvId not in(SELECT InvId From DR_INWARD_STOCK_CHILD_DATA Where" +
                    " SignatureName =trim(\"" + signatureName + "\") AND BrandName=trim(\"" + brandName + "\") And COUNTER_ID=" + counterId +
                    " AND SubBrandName =trim(\"" + subBrandName + "\") AND ReferenceName =trim(\"" + referenceName + "\") AND InvoiceNo=trim('"
                    + invoice_no + "')" + " AND InvoiceType=trim('" + type + "'))" + " UNION" +
                    " Select Distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode,pm.Mrp as Mrp,tc.InvId as InvId,"
                    + "(ifnull(tc.Invoice_Qty,0))as InvoiceQty," +
                    " tc.Sku_Confirmation_Check as CounterConfirm,tc.Invoice_Status as InvoiceStatus,(ifnull(tc.Actual_Qty,0))as ActualQty," +
                    "(ifnull(tc.REASON_ID,0))as ReasonId," + "ifnull((SELECT Transaction_Id FROM DR_INWARD_STOCK_TRANSACTION Where InvoiceNo='" +
                    invoice_no + "' and ProductId=tc.ProductId and InvId=tc.InvId),'')as TranId From Product_Master" +
                    " pm inner join DR_INWARD_STOCK_CHILD_DATA tc on pm.ProductId=tc.ProductId Where" +
                    " pm.SignatureName =trim(\"" + signatureName + "\")  AND pm.BrandName=trim(\"" + brandName + "\") AND" +
                    " pm.SubBrandName =trim(\"" + subBrandName + "\") AND pm.ReferenceName =trim(\"" + referenceName + "\") AND" +
                    " tc.InvoiceNo=trim('" + invoice_no + "') AND tc.InvoiceType=trim('" + type + "') And tc.COUNTER_ID=" + counterId + "";

            dbcursor = db.rawQuery(qury, null);

/*
            dbcursor = db.rawQuery("select  distinct Pm.ProductName,Pm.ProductId,Pm.EanCode,ci.Qty,Pm.Mrp," +
                    "ci.InvId,ci.CounterConfirm,ci.InvoiceStatus,ci.ActualQty,ci.ReasonId,ci.TranId  from T_CounterInvoice as ci" +
                    " inner join Product_Master Pm on ci.ProductId = Pm.ProductId " +
                    " where  Pm.SignatureName =\"" + signatureName + "\" AND Pm.BrandName=\"" + brandName +
                    "\" AND Pm.SubBrandName =\"" + subBrandName + "\" AND Pm.ReferenceName =\"" + referenceName + "\" " +
                    " AND ci.InvoiceNo='" + invoice_no + "' AND ci.InvoiceType='" + type + "'", null);
*/

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setInvId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvId")));
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setInvoice_Status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceStatus")));
                    String checkVal1 = dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterConfirm"));
                    sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceQty")));
                    int consumer = (dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ActualQty")));
                    if (consumer == 0 && checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) {
                        sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceQty")));
                    } else {
                        sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ActualQty")));
                    }

                    sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId")));
                    sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TranId")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    if (checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) {
                        sb.setConfirmChecked(false);
                    } else {
                        sb.setConfirmChecked(true);
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<MasterAgeLimit> getAgeLimitMasterData() {
        ArrayList<MasterAgeLimit> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct AgeLimit from Master_AgeLimit", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterAgeLimit sb = new MasterAgeLimit();
                    sb.setAgeLimit(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AgeLimit")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    public ArrayList<MasterSourcesOfSale> getsourceofsales() {
        ArrayList<MasterSourcesOfSale> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct SourcesOfSale from Master_SourcesOfSales", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterSourcesOfSale sb = new MasterSourcesOfSale();
                    sb.setSourcesOfSale(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SourcesOfSale")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    public ArrayList<MasterSkinType> getskinTypeMaster() {
        ArrayList<MasterSkinType> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct SkinType from Master_SkinType", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterSkinType sb = new MasterSkinType();
                    sb.setSkinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SkinType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }

    public boolean insertSkinTypeMaster(TableStructureGetterSetter cst) {
        db.delete("Master_SkinType", null, null);
        ContentValues values = new ContentValues();
        List<MasterSkinType> data = cst.getMasterSkinType();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("SkinType", data.get(i).getSkinType());
                long id = db.insert("Master_SkinType", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public String getStatus(String columnName, String counterId) {
        String status = null;
        Cursor dbcursor = null;
        try {
            if (columnName != null && columnName.equalsIgnoreCase(CommonString.KEY_GwpStatus)) {
                dbcursor = db.rawQuery("select distinct t1.GwpStatus as GwpStatus from T_StockSummary t1 INNER JOIN Product_Master t2 on t1.ProductId=t2.ProductId where t1.GwpStatus<>''and t1.CounterId=" + counterId + " and t2.ProductType='GWP'", null);

            } else {
                dbcursor = db.rawQuery("select distinct t1." + columnName + " from T_StockSummary t1 INNER JOIN Product_Master t2 on t1.ProductId=t2.ProductId where t1." + columnName + "<>''and t1.CounterId=" + counterId + " and t2.ProductType='Normal'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    status = dbcursor.getString(dbcursor.getColumnIndexOrThrow(columnName));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return status;
            }
        } catch (Exception e) {

            return status;
        }

        return status;
    }


    // neeraj database
    public boolean insertNonStockReasonData(MasterNonStockReasonGetterSetter nonWorkingdata) {
        db.delete("Master_NonStockReason", null, null);
        ContentValues values = new ContentValues();
        List<MasterNonStockReason> data = nonWorkingdata.getMasterNonStockReason();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {

                values.put("ReasonId", data.get(i).getReasonId());
                values.put("Reason", data.get(i).getReason());
                values.put("Applicable", data.get(i).getApplicable());

                long id = db.insert("Master_NonStockReason", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<MasterNonStockReason> getReasonData(boolean stockcheck_flag) {
        ArrayList<MasterNonStockReason> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (stockcheck_flag) {
                dbcursor = db.rawQuery("select * from Master_NonStockReason where Applicable=1", null);
            } else {
                dbcursor = db.rawQuery("select * from Master_NonStockReason", null);
            }

            MasterNonStockReason sb1 = new MasterNonStockReason();
            sb1.setReason("- Select Reason -");
            sb1.setReasonId(0);
            list.add(sb1);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterNonStockReason sb = new MasterNonStockReason();
                    sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason")));
                    sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public boolean insertMasterProfile(MasterProfileGetterSetter cst) {
        db.delete("Master_Profile", null, null);
        ContentValues values = new ContentValues();
        List<MasterProfile> data = cst.getMasterProfile();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Email", data.get(i).getEmail());
                values.put("FullName", data.get(i).getFullName());
                values.put("Supervisor", data.get(i).getSupervisor());
                values.put("Gender", data.get(i).getGender());
                values.put("dob", data.get(i).getDob());
                values.put("Current_BPgrade", data.get(i).getCurrentBPgrade());
                values.put("Mobile", data.get(i).getMobile());
                values.put("InstragramAddress", data.get(i).getInstragramAddress());
                values.put("Profile_Pic", data.get(i).getProfilePic());
                values.put("Address", data.get(i).getAddress());
                values.put("EmpCode", data.get(i).getEmpCode());
                values.put("UserId", data.get(i).getUserId().toLowerCase());
                values.put("VisitDate", data.get(i).getViisitDate());

                long id = db.insert("Master_Profile", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterProfileQuestion(MasterProfileQuestionGetterSetter cst) {
        db.delete("Master_ProfileQuestion", null, null);
        ContentValues values = new ContentValues();
        List<MasterProfileQuestion> data = cst.getMasterProfileQuestion();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Answer", data.get(i).getAnswer());
                values.put("AnswerId", data.get(i).getAnswerId());
                values.put("Category", data.get(i).getCategory());
                values.put("CategoryId", data.get(i).getCategoryId());
                values.put("Question", data.get(i).getQuestion());
                values.put("QuestionId", data.get(i).getQuestionId());
                values.put("QuestionType", data.get(i).getQuestionType());
                values.put("BA", data.get(i).getBA());
                values.put("TBA", data.get(i).getTBA());
                values.put("ME", data.get(i).getME());

                long id = db.insert("Master_ProfileQuestion", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<MasterProfile> getBAProfileListAllData(String userId, String visit_date) {

        ArrayList<MasterProfile> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * FROM Master_Profile WHERE UserId ='" + userId + "' AND VisitDate='" + visit_date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterProfile ch = new MasterProfile();

                    ch.setEmail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Email")));
                    ch.setFullName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FullName")));
                    ch.setSupervisor(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Supervisor")));
                    ch.setGender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Gender")));
                    ch.setDob(dbcursor.getString(dbcursor.getColumnIndexOrThrow("dob")));
                    ch.setCurrentBPgrade(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Current_BPgrade")));
                    ch.setMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mobile")));
                    ch.setInstragramAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InstragramAddress")));
                    ch.setProfilePic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Profile_Pic")));
                    ch.setAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Address")));
                    ch.setEmpCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpCode")));
                    ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserId")));
                    ch.setViisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));

                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }


    public long saveAuditQuestionAnswerData(HashMap<MasterProfileQuestion, ArrayList<AuditDataGetterSetter>> data, ArrayList<MasterProfileQuestion> save_listDataHeader, String userId, String visit_date) {
        db.delete(CommonString.TABLE_AUDIT_DATA_SAVE, CommonString.KEY_USER_ID + "='" + userId + "' AND Visit_Date='" + visit_date + "'", null);
        long id = 0;
        ContentValues values = new ContentValues();
        try {

            try {
                db.beginTransaction();
                for (int i = 0; i < save_listDataHeader.size(); i++) {

                    for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                        values.put("User_Id", userId);
                        values.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                        values.put("QUESTION_ID", data.get(save_listDataHeader.get(i)).get(j).getQUESTION_ID());
                        values.put("QUESTION", data.get(save_listDataHeader.get(i)).get(j).getQUESTION());
                        values.put("ANSWER_ID", data.get(save_listDataHeader.get(i)).get(j).getANSWER_ID());
                        values.put("ANSWER_TYPE", data.get(save_listDataHeader.get(i)).get(j).getANSWER_TYPE());
                        values.put("CATEGORY_ID", save_listDataHeader.get(i).getCategoryId());
                        values.put("VISIT_DATE", visit_date);

                        if (data.get(save_listDataHeader.get(i)).get(j).getANSWER_TYPE().equalsIgnoreCase("Multi selection")) {
                            for (int m = 0; m < data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().size(); m++) {
                                String txt = "";
                                int count = 0;
                                if (data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().size() > 0) {
                                    for (int k = 0; k < data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().size(); k++) {
                                        if (data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().get(k).isSelected()) {
                                            if (count == 0) {
                                                txt = data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().get(k).getName();
                                            } else {
                                                txt = txt + " , " + data.get(save_listDataHeader.get(i)).get(j).getSelectedSamplingData().get(k).getName();
                                            }

                                            count++;
                                        }
                                    }
                                    values.put("ANSWER", txt);
                                }
                            }

                        } else {

                            values.put("ANSWER", data.get(save_listDataHeader.get(i)).get(j).getANSWER());
                        }

                        values.put("OTHERS_TVALUE", data.get(save_listDataHeader.get(i)).get(j).getSpin_others_for_edt());

                        id = db.insert(CommonString.TABLE_AUDIT_DATA_SAVE, null, values);

                    }
                }

                closeDb();
            } catch (Exception ex) {
                closeDb();
                ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString());
            }

            return id;
        } catch (Exception ex) {
            return 0;
        }
    }


    public ArrayList<MasterProfileQuestion> getAuditQuestionCategoryData(String userType) {
        Cursor cursordata = null;
        ArrayList<MasterProfileQuestion> auditData = new ArrayList<>();
        try {
            if (userType.trim().equalsIgnoreCase("BA")) {
                cursordata = db.rawQuery("select distinct CategoryId,Category from Master_ProfileQuestion where BA='1'", null);
            } else if (userType.trim().equalsIgnoreCase("TBA")) {
                cursordata = db.rawQuery("select distinct CategoryId,Category from Master_ProfileQuestion where TBA='1'", null);
            } else if (userType.trim().equalsIgnoreCase("ME")) {
                cursordata = db.rawQuery("select distinct CategoryId,Category from Master_ProfileQuestion where ME='1'", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterProfileQuestion sb = new MasterProfileQuestion();
                    sb.setCategoryId(cursordata.getInt(cursordata.getColumnIndexOrThrow("CategoryId")));
                    sb.setCategory(cursordata.getString(cursordata.getColumnIndexOrThrow("Category")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

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

        return auditData;

    }


    public ArrayList<AuditDataGetterSetter> getAfterSaveAuditQuestionAnswerData(String userId, String categodyId) {
        ArrayList<AuditDataGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {
            if (categodyId == null) {
                dbcursor = db.rawQuery("Select * " + "From " + CommonString.TABLE_AUDIT_DATA_SAVE + " where User_Id='" + userId + "'", null);

            } else {
                dbcursor = db.rawQuery("Select * " + "From " + CommonString.TABLE_AUDIT_DATA_SAVE + " where User_Id='" + userId + "' AND CATEGORY_ID ='" + categodyId + "'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    AuditDataGetterSetter sb = new AuditDataGetterSetter();
                    sb.setQUESTION_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUESTION_ID")));
                    sb.setQUESTION(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUESTION")));
                    sb.setANSWER_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER_ID")));
                    sb.setANSWER(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER")));
                    sb.setMENU_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CATEGORY_ID")));
                    sb.setANSWER_TYPE(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER_TYPE")));
                    sb.setSpin_others_for_edt(dbcursor.getString(dbcursor.getColumnIndexOrThrow("OTHERS_TVALUE")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }

    public ArrayList<AuditDataGetterSetter> getAuditCategoryWise(int categoryId) {
        Cursor cursordata = null;

        ArrayList<AuditDataGetterSetter> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select distinct QuestionId,Question, QuestionType FROM Master_ProfileQuestion " + "where CategoryId ='" + categoryId + "'", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    AuditDataGetterSetter sb = new AuditDataGetterSetter();
                    sb.setQUESTION(cursordata.getString(cursordata.getColumnIndexOrThrow("Question")));
                    sb.setQUESTION_ID(cursordata.getString(cursordata.getColumnIndexOrThrow("QuestionId")));
                    sb.setANSWER_TYPE(cursordata.getString(cursordata.getColumnIndexOrThrow("QuestionType")));
                    sb.setKEYACCOUNT_ID("0");

                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }

    public ArrayList<AuditDataGetterSetter> getAuditAnswerData(AuditDataGetterSetter auditGetSet, String select) {

        ArrayList<AuditDataGetterSetter> list = new ArrayList<>();
        if (auditGetSet.getANSWER_TYPE().equalsIgnoreCase("Single selection")) {
            AuditDataGetterSetter sb1 = new AuditDataGetterSetter();
            sb1.setANSWER_ID("0");
            sb1.setANSWER(select);
            list.add(0, sb1);
        } else if (auditGetSet.getANSWER_TYPE().equalsIgnoreCase("Text")) {
            AuditDataGetterSetter sb1 = new AuditDataGetterSetter();
            sb1.setANSWER_ID("0");
            sb1.setANSWER("");
            list.add(0, sb1);
        }

        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("select distinct QuestionType,AnswerId,Answer FROM Master_ProfileQuestion where QuestionId =" + auditGetSet.getQUESTION_ID() + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    AuditDataGetterSetter sb = new AuditDataGetterSetter();

                    sb.setANSWER_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AnswerId")));
                    sb.setANSWER(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }
        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    ///jp work
    public ArrayList<ProductMaster> getproduct_masterlist(String invoice_type, String visit_date, String counterId, String userType) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = CommonString.T_StockSummary, additionalQueryMe2 = "", additionalQueryMe = " Where SaleableBalance >0", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID ";

                getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance";
                additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + "  AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId";
            }
            if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("Sample")) {
                dbcursor = db.rawQuery("select distinct ProductName,pm.ProductId as ProductId,ReferenceId,ReferenceName," + "SubBrandId,SubBrandName," + "BrandId,BrandName,Mrp,EanCode,ProductType from Product_Master pm inner join " + table + " ts" + " on ts.ProductId=pm.ProductId where SampleBalance>0", null);
            } else if (invoice_type != null && invoice_type.equalsIgnoreCase("GWP")) {
                dbcursor = db.rawQuery("select distinct ProductName,pm.ProductId as ProductId,ReferenceId,ReferenceName," + "SubBrandId,SubBrandName,BrandId," + "BrandName,Mrp,EanCode,ProductType from Product_Master pm inner join " + table + " ts" + " on ts.ProductId=pm.ProductId where GwpBalance>0", null);
            } else if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("T_StockSummary")) {
                dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.ReferenceId as ReferenceId," + "pm.ReferenceName as ReferenceName,pm.SubBrandId as SubBrandId,pm.SubBrandName as SubBrandName,pm.BrandId as BrandId," + "pm.BrandName as BrandName,pm.Mrp as Mrp,pm.EanCode as EanCode,pm.ProductType as ProductType from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID  where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from" + " (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select  ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR" + " WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "' " + additionalQueryMe + ") as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null);

            } else {
                dbcursor = db.rawQuery("select distinct ProductName,ProductId,ReferenceId," + "ReferenceName,SubBrandId,SubBrandName," + "BrandId,BrandName" + ",Mrp,EanCode,ProductType from Product_Master", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setReferenceId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReferenceId")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setSubBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SubBrandId")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BrandId")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public ArrayList<ProductMaster> getproductdata_dialog(String column_name, String column_name_Id, boolean flag_for_filtr_stocksm, String stock_summary_balance, String visit_date, String counterId, String userType) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = CommonString.T_StockSummary, additionalQueryMe = " Where SaleableBalance >0", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID ";

                getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance";
                additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + "  AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId";
            }

            if (flag_for_filtr_stocksm) {
                dbcursor = db.rawQuery("Select distinct " + column_name + "," + column_name_Id + " from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + stock_summary_balance + ">0", null);
            } else {
                dbcursor = db.rawQuery("select distinct pm." + column_name + ",pm." + column_name_Id + "  from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID  where  T.STOCK_TYPE=trim('DAMAGE') AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select  ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "'" + additionalQueryMe + ") as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null);
            }

            //test("Query2---", dbcursor.toString());

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_name_Id)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getproductdata_formanual_inwarddialog(String column_name, String column_name_Id) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct " + column_name + "," + column_name_Id + " from Product_Master", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_name_Id)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<ProductMaster> getproductdata_dialogfor_return(String column_name, String column_name_Id, boolean flag_for_filtr_stocksm, String stock_summary_balance) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct " + column_name + "," + column_name_Id + " from Product_Master pm inner join T_StockSummary ts on ts.ProductId=pm.ProductId", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_name_Id)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getsub_brand_using_brand_Id(String dialog_brand_Id, String column_name, String column_Id, String value_get_column_name, String invoice_type, String visit_date, String counterId, boolean consumersale_flag, String userType) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = CommonString.T_StockSummary, additionalQueryMe = " Where SaleableBalance >0", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID ";


                getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance";
                additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + "  AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId";
            }
            if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("Sample")) {
                dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + value_get_column_name + "=\"" + dialog_brand_Id + "\"" + " and SampleBalance>0", null);
            } else if (invoice_type != null && invoice_type.trim().equalsIgnoreCase("GWP")) {
                dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + value_get_column_name + "=\"" + dialog_brand_Id + "\"" + " and GwpBalance>0", null);
            } else if (value_get_column_name == null && dialog_brand_Id.isEmpty()) {
                if (consumersale_flag) {
                    dbcursor = db.rawQuery("select distinct pm." + column_name + ",pm." + column_Id + "  from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID  where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select  ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "' " + additionalQueryMe + " ) as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null);

                } else {
                    dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master", null);
                }

            } else {
                if (consumersale_flag) {
                    dbcursor = db.rawQuery("select distinct pm." + column_name + ",pm." + column_Id + "  from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID  where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select  ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "'" + additionalQueryMe + " ) as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 and pm." + value_get_column_name + " =\"" + dialog_brand_Id + "\"", null);

                } else {
                    dbcursor = db.rawQuery("select distinct " + column_name + "," + column_Id + " from Product_Master where " + value_get_column_name + " =\"" + dialog_brand_Id + "\"", null);

                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    sb.setBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(column_Id)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }


    public ArrayList<ProductMaster> getSubBrandOrReference(String counterGroup_Id, String column_name, String signatureName, String brandName, String subBrand, boolean GWPFlag) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String productType = "Normal";
            if (GWPFlag) {
                productType = "GWP";
            }

            if (signatureName == null) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='" + productType + "'", null);
            } else if (column_name != null && column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SubBrandName =trim(\"" + subBrand + "\") and ProductType =trim('" + productType + "')", null);
            } else if (brandName != null) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " BrandName =trim(\"" + brandName + "\") and ProductType =trim('" + productType + "')", null);
            } else {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master " + "where SignatureName =trim(\"" + signatureName + "\") and ProductType =trim('" + productType + "')", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    //get Signature Brand Sub Brand and Reference
    public ArrayList<ProductMaster> getbrand_wise_sku_fromproduct(String brand_Id, String stock_summary_balance, String visit_date, String counterId, String userType) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = CommonString.T_StockSummary, additionalQueryMe = " Where SaleableBalance >0", additionalQueryMe2 = "", getData = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                additionalQueryMe2 = "UNION ALL Select T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME='ME' GROUP BY T1.PRODUCT_ID UNION ALL select S.PROMO_PRODUCT_ID AS ProductId ," + " SUM(S.PROMO_PRODUCT_QTY) AS DamageQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product'" + " AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S.RIGHTNAME='ME' GROUP BY S.PROMO_PRODUCT_ID ";


                getData = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance";
                additionalQueryMe = " left join (select ProductId, case when (Select count(*) from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId)" + " c where c.ProductId = t.Productid)>0 then (Select TempQty from (Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + "  AND T1.RIGHTNAME !='ME' AND T2.POS_SALE_FLAG='1' GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG ='1' GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId";
            }
            if (stock_summary_balance != null && brand_Id == null) {
                dbcursor = db.rawQuery(" select distinct ProductName,pm.ProductId as ProductId,EanCode,Mrp,LorealCode,ProductType from Product_Master pm inner join " + table + " ts on ts.ProductId=pm.ProductId where " + stock_summary_balance + ">0", null);
            } else if (stock_summary_balance == null && brand_Id == null) {
                dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.LorealCode as" + " LorealCode,pm.Mrp as Mrp," + "pm.EanCode as EanCode,pm.ProductType as ProductType from Product_Master pm" + " left join (Select s.ProductId," + getData + " from " + table + " s Left join (Select ProductId, sum(DamageQty) as DamageQty" + " from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T " + "INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID  where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID ='" + counterId + "'" + " Union All SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending'" + additionalQueryMe2 + ") as t Group by ProductId) as dm" + " on s.ProductId = dm.ProductId Left Join (Select ProductId, sum(ReturnQty) as ReturnQty " + "from (select ProductId, ReturnQty from Damage_ReturnToDistributor" + " WHERE CounterId='" + counterId + "'and VERIFY ='Pending' Union All select  ProductId, " + "STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID='" + counterId + "') as" + " t Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) and s.CounterId ='" + counterId + "'" + additionalQueryMe + ") as TS ON TS.ProductId = pm.ProductId where TS.SaleableBalance >0 ", null);

            } else {
                dbcursor = db.rawQuery("select distinct ProductName,ProductId,EanCode,Mrp,LorealCode,ProductType " + "from Product_Master where BrandId='" + brand_Id + "'", null);
            }
            //test("query3--", dbcursor.toString());
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setLorealCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LorealCode")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public ArrayList<ProductMaster> getbrand_wise_sku_fromproductformanual() {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct ProductName,ProductId,EanCode,Mrp,LorealCode,ProductType from Product_Master", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setLorealCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LorealCode")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }


    public ArrayList<ProductMaster> getbrand_wise_sku_fromproductfor_return() {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct pm.ProductName as ProductName,pm.ProductId as ProductId,pm.EanCode as EanCode,pm.Mrp as Mrp," + "pm.LorealCode as LorealCode,pm.ProductType as ProductType from Product_Master pm inner join T_StockSummary ts on ts.ProductId=pm.ProductId", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setLorealCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LorealCode")));
                    sb.setProductType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }


    public boolean insert_return_reason(MasterProfileQuestionGetterSetter cst) {
        db.delete("Master_ReturnReason", null, null);
        ContentValues values = new ContentValues();
        List<MasterReturnReason> data = cst.getMasterReturnReason();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("ReasonId", data.get(i).getReasonId());
                values.put("Reason", data.get(i).getReason());

                long id = db.insert("Master_ReturnReason", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<MasterReturnReason> getreturn_reasonList() {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<MasterReturnReason> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct ReasonId,Reason from Master_ReturnReason", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterReturnReason sb = new MasterReturnReason();

                    sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReasonId")));
                    sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public boolean inserterm_condition(MasterProfileQuestionGetterSetter cst) {
        db.delete("Master_TermsCondition", null, null);
        ContentValues values = new ContentValues();
        List<MasterTermsCondition> data = cst.getMasterTermsCondition();
        try {
            if (data.isEmpty()) {
                return false;
            }

            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {

                values.put("TermsCondition", data.get(i).getTermsCondition());

                long id = db.insert("Master_TermsCondition", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception ", ex.toString());
            return false;
        }
    }

    public MasterTermsCondition getterm_and_condition() {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        MasterTermsCondition list = new MasterTermsCondition();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct TermsCondition from Master_TermsCondition", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    list.setTermsCondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TermsCondition")));

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public ArrayList<InvoiceGetterSetter> getconsumerReturndataformDb(String storeid, String visite_date, String user_Id) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Consumer_Return + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' and USER_ID='" + user_Id + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setConsumer_return_bill_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BILL_NO")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID")));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY")));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE")));
                    sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_PRICE")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE")));
                    sale.setCon_return_reason_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON_ID")));
                    sale.setCon_return_reason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStore_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STORE_NAME)));
                    sale.setStore_address(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_ADDRESS")));
                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }

    public boolean insertInvoiceTypeMasterData(MasterInvoiceTypeGetterSetter cst) {
        db.delete("Master_InvoiceType", null, null);
        ContentValues values = new ContentValues();
        List<MasterInvoiceType> data = cst.getMasterInvoiceType();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("InvoiceType", data.get(i).getInvoiceType().trim());

                long id = db.insert("Master_InvoiceType", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    private long updateInvoiceStatus(String invoiceNo, boolean newproductInward) {
        long l = 0;
        try {
            if (!db.isOpen()) open();
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_INVOICE_STATUS, "1");
            l = db.update(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, values, CommonString.KEY_INVOICE_NUMBER + " ='" + invoiceNo + "' AND " + CommonString.KEY_NEW_PRODUCT + "= " + (newproductInward ? 1 : 0), null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }

    public ProductMaster getInwardStockCheckTransactionData(Integer productId, String invId, String invoiceNo) {
        Cursor dbcursor = null;
        ProductMaster sb = null;
        try {

            dbcursor = db.rawQuery("SELECT * FROM " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " WHERE " + CommonString.KEY_INVOICE_ID + " ='" + invId + "'AND " + CommonString.KEY_INVOICE_NUMBER + " ='" + invoiceNo + "' AND " + CommonString.KEY_ProductId + " =" + productId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new ProductMaster();
                    sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID)));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {

            return sb;
        }

        return sb;
    }


    public ArrayList<ProductMaster> get_inward_sub_brand_name(String column_name, String invoiceNo, String type) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct Pm." + column_name + " from T_CounterInvoice as ci inner join Product_Master Pm on ci.ProductId = Pm.ProductId " + "where ci.InvoiceNo ='" + invoiceNo + "' and ci.InvoiceType ='" + type + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<ProductMaster> getInwardSubBrandOrReference(String column_name, String signatureName, String brandName, String subBrand, String invoiceNo, String type) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (signatureName == null) {
                dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId WHERE  t.InvoiceNo = '" + invoiceNo + "' and t.InvoiceType = '" + type + "'", null);
            } else if (column_name != null && column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) {
                dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId  WHERE p.SubBrandName =trim(\"" + subBrand + "\") and t.InvoiceNo = '" + invoiceNo + "' and t.InvoiceType =trim('" + type + "')", null);
            } else if (brandName != null) {
                dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId  WHERE p.BrandName =trim(\"" + brandName + "\") and  t.InvoiceNo =trim('" + invoiceNo + "')" + " and t.InvoiceType =trim('" + type + "')", null);
            } else {
                dbcursor = db.rawQuery("select distinct p." + column_name + " from Product_Master p inner join " + "T_CounterInvoice t on p.ProductId = t.ProductId  WHERE p.SignatureName =trim(\"" + signatureName + "\") and " + " t.InvoiceNo =trim('" + invoiceNo + "') and t.InvoiceType =trim('" + type + "')", null);
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }

    public boolean insertLeaveRequest(MasterProfileQuestionGetterSetter cst) {
        db.delete("T_LeaveRequest", null, null);
        ContentValues values = new ContentValues();
        List<T_LeaveRequest> data = cst.gettLeaveRequestList();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {

                values.put("Id", data.get(i).getId());
                values.put("RequestDate", data.get(i).getRequestDate());
                values.put("UserId", data.get(i).getUserId().toLowerCase());
                values.put("FromDate", data.get(i).getFromDate());
                values.put("ToDate", data.get(i).getToDate());
                values.put("LeaveStatus", data.get(i).getLeaveStatus());
                values.put("LeaveType", data.get(i).getLeaveType());
                values.put("LeaveTypeDesc", data.get(i).getLeaveTypeDesc());

                long id = db.insert("T_LeaveRequest", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public long insertNewInwardProductStockData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, String invoiceNo, String type, String invDate, String counter_id, String username, String source, String transactionId, boolean checked_checkbox_flag) {
        long id = 0, id2 = 0, masterreturn = 0;
        db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " ='" + type + "'", null);
        db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " = '" + type + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues values;
        ContentValues values1;
        ContentValues valuesmasterT;
        ContentValues values2;
        ProductMaster transactionList;
        TStockSummary stockObj;
        try {
            db.beginTransaction();
            if (save_listDataHeader.size() > 0) {
                if (checked_checkbox_flag) {
                    valuesmasterT = new ContentValues();
                    valuesmasterT.put(CommonString.KEY_UUID, transactionId);
                    valuesmasterT.put(CommonString.KEY_USER_ID, username);
                    valuesmasterT.put(CommonString.KEY_COUNTER_ID, counter_id);
                    valuesmasterT.put(CommonString.KEY_VISIT_DATE, visit_date);
                    valuesmasterT.put(CommonString.KEY_STOCK_TYPE, CommonString.INWARD_DMS_NEW_SKU);
                    valuesmasterT.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
                    valuesmasterT.put(CommonString.KEY_STATUS, CommonString.KEY_N);

                    if (!db.isOpen()) open();

                    masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, valuesmasterT);
                }
                for (int i = 0; i < save_listDataHeader.size(); i++) {
                    values = new ContentValues();
                    values.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName());
                    values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                    values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                    values.put("ReferenceName", save_listDataHeader.get(i).getReferenceName());
                    values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                    values.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values.put(CommonString.KEY_COUNTER_ID, counter_id);
                    values.put(CommonString.KEY_USER_ID, username);
                    values.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                    values.put(CommonString.KEY_INVOICE_DATE, invDate);
                    values.put(CommonString.KEY_INVOICE_TYPE, type);

                    if (!db.isOpen()) open();

                    long l = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, null, values);

                    for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                        values1 = new ContentValues();
                        values1.put(CommonString.KEY_COMMON_ID, (int) l);
                        values1.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName());
                        values1.put("BrandName", save_listDataHeader.get(i).getBrandName());
                        values1.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                        values1.put("ReferenceName", save_listDataHeader.get(i).getReferenceName());
                        values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                        values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                        values1.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked());
                        values1.put(CommonString.KEY_COUNTER_ID, counter_id);
                        values1.put(CommonString.KEY_USER_ID, username);
                        values1.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                        values1.put(CommonString.KEY_INVOICE_TYPE, type);
                        values1.put(CommonString.KEY_INVOICE_ID, Objects.requireNonNull(data.get(save_listDataHeader.get(i))).get(j).getInvId());
                        values1.put(CommonString.KEY_Product, data.get(save_listDataHeader.get(i)).get(j).getProductName());
                        values1.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId());
                        values1.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty());
                        values1.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp());
                        values1.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                        values1.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId());
                        values1.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status());

                        transactionList = getInwardStockCheckTransactionData(data.get(save_listDataHeader.get(i)).get(j).getProductId(), data.get(save_listDataHeader.get(i)).get(j).getInvId(), invoiceNo);
                        stockObj = getTStockSummaryProductDetails(data.get(save_listDataHeader.get(i)).get(j).getProductId());

                        if (transactionList == null && data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked() && masterreturn > 0 && stockObj == null) {
                            values2 = new ContentValues();
                            values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                            values2.put(CommonString.KEY_VISIT_DATE, visit_date);
                            values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked());
                            values2.put(CommonString.KEY_COUNTER_ID, counter_id);
                            values2.put(CommonString.KEY_USER_ID, username);
                            values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                            values2.put(CommonString.KEY_INVOICE_DATE, invDate);
                            values2.put(CommonString.KEY_INVOICE_TYPE, type);
                            values2.put(CommonString.KEY_SOURCE, source);
                            values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N);
                            values2.put(CommonString.KEY_INVOICE_ID, data.get(save_listDataHeader.get(i)).get(j).getInvId());
                            values2.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId());
                            values2.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty());
                            values2.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp());
                            values2.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                            values2.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId());

                            if (save_listDataHeader.get(i).getInvoice_Status().equals("1")) {
                                values2.put(CommonString.KEY_INVOICE_STATUS, "1");
                                ///For Update Invoice Status if Confirmed invoice
                                if (!db.isOpen()) open();
                                updateInvoiceStatus(invoiceNo, true);
                            } else {
                                values2.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status());
                            }
                            values2.put(CommonString.KEY_TRANSACTION_ID, transactionId);
                            values2.put(CommonString.KEY_NEW_PRODUCT, 1);
                            if (!db.isOpen()) open();
                            stockObj = getStockSummaryStatus(visit_date);
                            if (stockObj != null) {
                                //Insert New Data comming
                                insertTStockSummaryManualData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counter_id, type, data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                            }

                            // only for damaged stock
                            int ReasonId = data.get(save_listDataHeader.get(i)).get(j).getReasonId();
                            if (ReasonId == 2 && type.trim().equalsIgnoreCase("Sellable")) {
                                ///change by jp Updated Damage Stock QTY from T_StockSummery
                                int damageStockQty = Integer.parseInt(data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                                updateStockSummaryDamageValue(data.get(save_listDataHeader.get(i)).get(j).getProductId(), damageStockQty, counter_id);
                            }
                            if (!db.isOpen()) open();
                            id2 = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, null, values2);
                            if (id2 > 0) {
                                //updated counter invoice Confirm status using Invoice Id
                                updateT_CounterInvoiceConfirmCounter(data.get(save_listDataHeader.get(i)).get(j).getInvId(), data.get(save_listDataHeader.get(i)).get(j).getProductId());
                            }
                        }
                        if (!db.isOpen()) open();
                        id = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, null, values1);
                    }
                }
            }
            closeDb();
            if (id > 0) {
                return id;
            } else {
                return 0;
            }

        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
    }


    public long insertInwardStockData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, String invoiceNo, String type, String invDate, String counter_id, String username, String source, String transactionId, boolean checked_checkbox_flag) {
        long id = 0, id2 = 0, masterreturn = 0;
        db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " ='" + type + "'", null);
        db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counter_id + "' AND " + CommonString.KEY_INVOICE_TYPE + " = '" + type + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues values;
        ContentValues values1;
        ContentValues valuesmasterT;
        ContentValues values2;
        ProductMaster transactionList;
        TStockSummary stockObj;

        try {
            db.beginTransaction();
            if (save_listDataHeader.size() > 0) {
                if (checked_checkbox_flag) {
                    valuesmasterT = new ContentValues();
                    valuesmasterT.put(CommonString.KEY_UUID, transactionId);
                    valuesmasterT.put(CommonString.KEY_USER_ID, username);
                    valuesmasterT.put(CommonString.KEY_COUNTER_ID, counter_id);
                    valuesmasterT.put(CommonString.KEY_VISIT_DATE, visit_date);
                    valuesmasterT.put(CommonString.KEY_STOCK_TYPE, CommonString.INWARD_DMS);
                    valuesmasterT.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
                    valuesmasterT.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                    if (!db.isOpen()) open();
                    masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, valuesmasterT);
                }
                for (int i = 0; i < save_listDataHeader.size(); i++) {
                    values = new ContentValues();
                    values.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName());
                    values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                    values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                    values.put("ReferenceName", save_listDataHeader.get(i).getReferenceName());
                    values.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                    values.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values.put(CommonString.KEY_COUNTER_ID, counter_id);
                    values.put(CommonString.KEY_USER_ID, username);
                    values.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                    values.put(CommonString.KEY_INVOICE_DATE, invDate);
                    values.put(CommonString.KEY_INVOICE_TYPE, type);

                    if (!db.isOpen()) open();
                    long l = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_HEADER_DATA, null, values);

                    if (data.get(save_listDataHeader.get(i)).size() > 0) {
                        for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                            values1 = new ContentValues();
                            values1.put(CommonString.KEY_COMMON_ID, (int) l);
                            values1.put("SubBrandName", save_listDataHeader.get(i).getSubBrandName());
                            values1.put("BrandName", save_listDataHeader.get(i).getBrandName());
                            values1.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                            values1.put("ReferenceName", save_listDataHeader.get(i).getReferenceName());
                            values1.put("SubAxeName", save_listDataHeader.get(i).getSubAxeName());
                            values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                            values1.put(CommonString.KEY_COUNTER_ID, counter_id);
                            values1.put(CommonString.KEY_USER_ID, username);
                            values1.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                            values1.put(CommonString.KEY_INVOICE_TYPE, type);
                            values1.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked());
                            values1.put(CommonString.KEY_INVOICE_ID, data.get(save_listDataHeader.get(i)).get(j).getInvId());
                            values1.put(CommonString.KEY_Product, data.get(save_listDataHeader.get(i)).get(j).getProductName());
                            values1.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId());
                            values1.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty());
                            values1.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp());
                            values1.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                            values1.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId());
                            values1.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status());

                            if (!db.isOpen()) open();
                            transactionList = getInwardStockCheckTransactionData(data.get(save_listDataHeader.get(i)).get(j).getProductId(), data.get(save_listDataHeader.get(i)).get(j).getInvId(), invoiceNo);
                            stockObj = getTStockSummaryProductDetails(data.get(save_listDataHeader.get(i)).get(j).getProductId());
                            if (transactionList == null && data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked() && masterreturn > 0 && stockObj != null && stockObj.getProductId() != null) {
                                values2 = new ContentValues();
                                values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                                values2.put(CommonString.KEY_VISIT_DATE, visit_date);
                                values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, data.get(save_listDataHeader.get(i)).get(j).isConfirmChecked());
                                values2.put(CommonString.KEY_COUNTER_ID, counter_id);
                                values2.put(CommonString.KEY_USER_ID, username);
                                values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                                values2.put(CommonString.KEY_INVOICE_DATE, invDate);
                                values2.put(CommonString.KEY_INVOICE_TYPE, type);
                                values2.put(CommonString.KEY_SOURCE, source);
                                values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N);

                                values2.put(CommonString.KEY_INVOICE_ID, data.get(save_listDataHeader.get(i)).get(j).getInvId());
                                values2.put(CommonString.KEY_ProductId, data.get(save_listDataHeader.get(i)).get(j).getProductId());
                                values2.put(CommonString.KEY_INVOICE_QTY, data.get(save_listDataHeader.get(i)).get(j).getConsumer_qty());
                                values2.put(CommonString.KEY_MRP, data.get(save_listDataHeader.get(i)).get(j).getMrp());
                                values2.put(CommonString.KEY_ACTUAL_QTY, data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                                values2.put(CommonString.KEY_REASON_ID, data.get(save_listDataHeader.get(i)).get(j).getReasonId());
                                // only for damaged stock
                                if (data.get(save_listDataHeader.get(i)).get(j).getReasonId() == 2 && type != null && type.trim().equalsIgnoreCase("Sellable")) {
                                    ///change by jp Updated Damage Stock QTY from T_StockSummery
                                    int damageStockQty = Integer.parseInt(data.get(save_listDataHeader.get(i)).get(j).getActualQty());
                                    if (!db.isOpen()) open();
                                    updateStockSummaryDamageValue(data.get(save_listDataHeader.get(i)).get(j).getProductId(), damageStockQty, counter_id);
                                }
                                if (save_listDataHeader.get(i).getInvoice_Status().equals("1")) {
                                    values2.put(CommonString.KEY_INVOICE_STATUS, "1");
                                    ///For Update Invoice Status if Confirmed invoice
                                    updateInvoiceStatus(invoiceNo, false);
                                } else {
                                    values2.put(CommonString.KEY_INVOICE_STATUS, save_listDataHeader.get(i).getInvoice_Status());
                                }
                                values2.put(CommonString.KEY_TRANSACTION_ID, transactionId);
                                values2.put(CommonString.KEY_NEW_PRODUCT, 0);
                                // if stockObj is not null means product exist in stock summary table data then update value in TStockSummary
                                updateStockSummaryData(stockObj, type, data.get(save_listDataHeader.get(i)).get(j).getActualQty(), visit_date);
                                if (!db.isOpen()) open();
                                id2 = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, null, values2);
                                if (id2 > 0) {
                                    updateT_CounterInvoiceConfirmCounter(data.get(save_listDataHeader.get(i)).get(j).getInvId(), data.get(save_listDataHeader.get(i)).get(j).getProductId());
                                }
                            }
                            if (!db.isOpen()) open();
                            id = db.insert(CommonString.TABLE_INSERT_INWARD_STOCK_CHILD_DATA, null, values1);
                        }
                    }
                }
            }
            closeDb();
            if (id > 0) {
                return id;
            } else {
                return 0;
            }

        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
    }


    public boolean insert_leave_status(MasterProfileQuestionGetterSetter cst) {
        db.delete("T_LeaveLedger", null, null);
        ContentValues values = new ContentValues();
        List<TLeaveLedger> data = cst.getTLeaveLedger();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("UserId", data.get(i).getUserId().toLowerCase());
                values.put("TotalLeave", data.get(i).getTotalLeave());
                values.put("LeaveTaken", data.get(i).getLeaveTaken());
                values.put("BalanceLeave", data.get(i).getBalanceLeave());

                long id = db.insert("T_LeaveLedger", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<TLeaveLedger> getleave_balance_status(String user_Id) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<TLeaveLedger> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct TotalLeave,LeaveTaken,BalanceLeave from T_LeaveLedger where UserId='" + user_Id + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TLeaveLedger sb = new TLeaveLedger();
                    sb.setTotalLeave(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalLeave")));
                    sb.setLeaveTaken(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("LeaveTaken")));
                    sb.setBalanceLeave(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("BalanceLeave")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public long insert_leave_management_data(String user_Id, String visit_date, String store_Cd, T_LeaveRequest invoiceList) {
        db.delete(CommonString.Table_Leave_Management, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        ContentValues values = new ContentValues();
        ContentValues finalvalues = new ContentValues();
        long l = 0, masterreturn = 0;
        try {
            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, invoiceList.getTransId());
            finalvalues.put(CommonString.KEY_USER_ID, user_Id);
            finalvalues.put(CommonString.KEY_COUNTER_ID, store_Cd);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.LEAVE_MANAGEMENT);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);

            values.put("USER_ID", user_Id);
            values.put("UNIQUE_CODE", invoiceList.getTransId());
            values.put(CommonString.KEY_COUNTER_ID, store_Cd);
            values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("Request_Date", invoiceList.getRequestDate());
            values.put("From_Date", invoiceList.getFromDate());
            values.put("Upload_From_Date", invoiceList.getUpload_start_date_str());
            values.put("To_Date", invoiceList.getToDate());
            values.put("Upload_To_Date", invoiceList.getUpload_end_date_str());
            values.put("LeaveReason", invoiceList.getLeave_reason());
            values.put("Leave_Status", invoiceList.getLeaveStatus());
            values.put("One_Day_Leave", invoiceList.getOne_day_leave_str());
            values.put("UPLOAD_STATUS", CommonString.KEY_N);
            values.put("LeaveType", invoiceList.getStr_leaveType());
            values.put("LeaveTypeId", invoiceList.getStr_leaveTypeId());

            l = db.insert(CommonString.Table_Leave_Management, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", ex.toString());
        }

        return l;
    }

    public boolean insert_master_break(MasterProfileQuestionGetterSetter cst) {
        db.delete("Master_Break", null, null);
        ContentValues values = new ContentValues();
        List<MasterBreak> data = cst.getMasterBreak();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("BreakId", data.get(i).getBreakId());
                values.put("BreakType", data.get(i).getBreakType());

                long id = db.insert("Master_Break", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<MasterBreak> getmasterBreak() {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<MasterBreak> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct BreakId,BreakType from Master_Break", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    MasterBreak sb = new MasterBreak();
                    sb.setBreakId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BreakId")));
                    sb.setBreakType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BreakType")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }

        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public long insertBreakManagement(String user_Id, String visit_date, String counterId, MasterBreak breakObject) {
        db.delete(CommonString.Table_Break_Management, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        ContentValues values = new ContentValues();

        long l = 0;

        try {
            db.beginTransaction();
            values.put("USER_ID", user_Id);
            values.put(CommonString.KEY_COUNTER_ID, counterId);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("LoginTym", breakObject.getLoginTym());
            values.put("BreakType", breakObject.getBreakType());
            values.put("BreakId", breakObject.getBreakId());
            values.put("StartTym", breakObject.getStartTym());
            values.put("EndTym", breakObject.getEndTym());
            values.put("TotalDuration", breakObject.getTotalDuration());
            values.put("UPLOAD_STATUS", breakObject.getUpload_status());
            values.put("UNIQUE_CODE", breakObject.getTransId());
            values.put(CommonString.KEY_MASTER_TRANSACTION_ID, 0);

            l = db.insert(CommonString.Table_Break_Management, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", ex.toString());
        }

        return l;
    }


    public long update_break_management(String counterId, String visit_date, String user_Id, MasterBreak breakObject) {
        ContentValues values = new ContentValues();
        ContentValues finalvalues = new ContentValues();
        long l = 0, masterreturn = 0;
        try {

            if (!db.isOpen()) open();
            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, breakObject.getTransId());
            finalvalues.put(CommonString.KEY_USER_ID, user_Id);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counterId);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.BREAK_MANAGEMENT);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);
            if (masterreturn > 0) {
                values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                values.put("EndTym", breakObject.getEndTym());
                values.put("TotalDuration", breakObject.getTotalDuration());
                values.put("UNIQUE_CODE", breakObject.getTransId());
                values.put("UPLOAD_STATUS", CommonString.KEY_N);

                l = db.update(CommonString.Table_Break_Management, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and " + CommonString.KEY_ID + "='" + breakObject.getKeyId() + "'", null);
            }
            closeDb();
        } catch (Exception e) {
            e.fillInStackTrace();
            closeDb();
        }
        return l;
    }

    public ArrayList<MasterBreak> getBreakManagementList(String storeid, String visite_date, String user_Id, String upload_status) {
        ArrayList<MasterBreak> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (upload_status != null && user_Id == null) {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "'and UPLOAD_STATUS='N'", null);

            } else if (upload_status != null) {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' and USER_ID='" + user_Id + "'and UPLOAD_STATUS='N'", null);

            } else {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' and USER_ID='" + user_Id + "'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterBreak sale = new MasterBreak();

                    sale.setLoginTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LoginTym")));
                    sale.setBreakType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BreakType")));
                    sale.setBreakId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BreakId")));
                    sale.setStartTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTym")));
                    sale.setEndTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTym")));
                    sale.setTotalDuration(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TotalDuration")));
                    sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setKeyId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }

    //get Signature Brand Sub Brand and Reference
    public ArrayList<ProductMaster> getStockSignatureBrandSubBrandReference(String counterGroup_Id, boolean gwp_flag, boolean regularstock, String columnName) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (regularstock) {
                if (gwp_flag) {
                    dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join  T_StockSummary TS ON TS.ProductId = p.ProductId  where TS." + columnName + " >0 and p.ProductType='GWP'", null);

                } else {
                    dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join  T_StockSummary TS ON TS.ProductId = p.ProductId  where TS." + columnName + " > 0 and p.ProductType='Normal'", null);
                }
            } else {
                if (gwp_flag) {
                    dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master where ProductType='GWP'", null);

                } else {
                    dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master where ProductType='Normal'", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    //sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getMESaleSignatureBrandSubBrandReference(String counterGroup_Id, boolean gwp_flag, boolean regularstock, String columnName) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (regularstock) {
                dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join  T_StockSummary TS ON TS.ProductId = p.ProductId  where p.ProductType='Normal'", null);
            } else {
                dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master where ProductType='Normal'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    //sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getStockSignatureBrandSubBrandReferenceforfilled(String counterGroup_Id, String activity_name) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) {
                dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join  T_StockSummary TS" + " ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.ProductType='Normal'", null);

            } else {

                dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p inner join  T_StockSummary TS" + " ON TS.ProductId = p.ProductId where TS.TesterBalance >0 and p.ProductType='Normal'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    //sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    //get Signature Brand Sub Brand and Reference
    public ArrayList<ProductMaster> getGWPSignatureBrandSubBrandReference(boolean regular_flag, String counterId, String visit_date) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (regular_flag) {
                dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName,AxeName,SubAxeName from Product_Master p inner join" + " (Select  s.ProductId, (s.GwpBalance - ifnull(dm.DamageQty,0))  as GwpBalance" + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT " + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='GWP' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID,S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId)" + " as TS ON TS.ProductId = p.ProductId where TS.GwpBalance >0 and p.ProductType='GWP'", null);

            } else {
                dbcursor = db.rawQuery("select distinct SignatureName,BrandName,SubBrandName,ReferenceName, AxeName,SubAxeName from Product_Master where ProductType = 'GWP'", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    //get stock child default data
    public ArrayList<ProductMaster> getDefaultGWPOnSignatureData(String SubBrandName, String ReferenceName, String BrandName, String columnBalance, boolean regularstock, String visit_date, String counterId) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (regularstock) {
                dbcursor = db.rawQuery("select distinct p.ProductId as ProductId,p.ProductName as ProductName,p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from" + " Product_Master p left JOIN(Select s.ProductId,(s." + columnBalance + " - ifnull(dm.DamageQty,0)) as " + columnBalance + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0'" + " AND T1.INVOICE_TYPE='GWP' GROUP BY T1.PRODUCT_ID UNION ALL" + " select  S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID ,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0' GROUP BY S.PROMO_PRODUCT_ID) as t Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId) as" + " TS ON TS.ProductId = p.ProductId" + " Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND p.ReferenceName=trim(\"" + ReferenceName + "\")" + " AND BrandName=trim(\"" + BrandName + "\") AND p.ProductType =trim('GWP')and TS." + columnBalance + " >0", null);
            } else {
                dbcursor = db.rawQuery("select  p.ProductId, as ProductId p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + "LEFT JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + "Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND p.ReferenceName=trim(\"" + ReferenceName + "\")" + " AND BrandName=trim(\"" + BrandName + "\") AND p.ProductType ='GWP'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));
                    sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public boolean insertAgeLimitMaster(TableStructureGetterSetter cst) {
        db.delete("Master_AgeLimit", null, null);
        ContentValues values = new ContentValues();
        List<MasterAgeLimit> data = cst.getMasterAgeLimit();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("AgeLimit", data.get(i).getAgeLimit());
                long id = db.insert("Master_AgeLimit", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    //usk
    public long insertCounterProfiledata(String counter_id, String user_id, String user_type, String visit_date, JourneyPlan counterimg_object, String status, String uuid_ID) {
        db.delete(CommonString.TABLE_COUNTER_PROFILE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_COUNTER_PROFILE_DATA, "COUNTER_ID" + "='" + counter_id + "' And Visit_Date='" + visit_date + "'", null);
        long id = 0;
        ContentValues values = new ContentValues();

        try {
            db.beginTransaction();
            values.put(CommonString.KEY_UUID, uuid_ID);
            values.put("COUNTER_ID", counter_id);
            values.put(CommonString.KEY_STATUS, status);
            values.put(CommonString.KEY_USER_ID, user_id);
            values.put(CommonString.KEY_USER_TYPE, user_type);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("IMAGE1", counterimg_object.getProfileImage1());
            values.put("IMAGE2", counterimg_object.getProfileImage2());
            values.put("HIGHT", counterimg_object.getCounterlength());
            values.put("WIDTH", counterimg_object.getCounterwidth());
            values.put("SETUP_DATE", counterimg_object.getSetupDate());
            values.put("COUNTER_AGEING", counterimg_object.getStoreName());
            if (!db.isOpen()) {
                open();
            }
            id = db.insert(CommonString.TABLE_COUNTER_PROFILE_DATA, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }

        return id;
    }

    public long insertBaProfiledata(String counter_id, String user_id, String user_type, String visit_date, MasterProfile ba_object) {
        db.delete(CommonString.TABLE_BA_PROFILE_DATA, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_BA_PROFILE_DATA, "COUNTER_ID" + "='" + counter_id + "' And User_Id='" + user_id + "' And Visit_Date='" + visit_date + "'", null);
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put(CommonString.KEY_STATUS, CommonString.KEY_N);
            values.put("COUNTER_ID", counter_id);
            values.put(CommonString.KEY_USER_ID, user_id);
            values.put(CommonString.KEY_USER_TYPE, user_type);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("ADDRESS", ba_object.getAddress());
            values.put("DOB", ba_object.getDob());
            values.put("MOBILE_NO", ba_object.getMobile());
            values.put("EMAIL_ADDRESS", ba_object.getEmail());
            values.put("INSTAGRAM_ADDRESS", ba_object.getInstragramAddress());
            values.put("PROFILE_IMAGE", ba_object.getProfilePic());
            values.put("LANDMARK", ba_object.getLandmark());
            values.put("LOCATION", ba_object.getLocation());

            id = db.insert(CommonString.TABLE_BA_PROFILE_DATA, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }

        return id;
    }


    public MasterProfile getBaProfileData(String userId, String visit_date, boolean flag) {
        MasterProfile sb = new MasterProfile();
        Cursor dbcursor = null;
        try {
            if (flag) {
                dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE Visit_Date='" + visit_date + "'and STATUS='N'", null);
            } else {
                dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE User_Id ='" + userId + "' AND Visit_Date='" + visit_date + "'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))));
                    sb.setViisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sb.setAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ADDRESS")));
                    sb.setDob(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DOB")));
                    sb.setMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MOBILE_NO")));
                    sb.setEmail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ADDRESS")));
                    sb.setInstragramAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INSTAGRAM_ADDRESS")));
                    sb.setProfilePic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROFILE_IMAGE")));
                    sb.setLandmark(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LANDMARK")));
                    sb.setLocation(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOCATION")));
                    sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STATUS)));

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return sb;
        }

        return sb;
    }


    public ArrayList<MasterProfile> getBaProfileListData(String visit_date, String counterId, boolean previous_date) {
        ArrayList<MasterProfile> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (previous_date) {
                dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE Visit_Date <>'" + visit_date + "'and " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and STATUS='N'", null);

            } else {
                dbcursor = db.rawQuery("SELECT * FROM BA_PROFILE_DATA WHERE Visit_Date='" + visit_date + "'and " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and STATUS='N'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterProfile sb = new MasterProfile();
                    sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))));
                    sb.setViisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sb.setAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ADDRESS")));
                    sb.setDob(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DOB")));
                    sb.setMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MOBILE_NO")));
                    sb.setEmail(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ADDRESS")));
                    sb.setInstragramAddress(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INSTAGRAM_ADDRESS")));
                    sb.setProfilePic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PROFILE_IMAGE")));
                    sb.setLandmark(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LANDMARK")));
                    sb.setLocation(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOCATION")));
                    sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_STATUS)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return list;
        }
        return list;
    }

    public JourneyPlan getCounterProfileData(String userId, String visit_date, String counterId, boolean flag) {
        JourneyPlan sb = new JourneyPlan();
        Cursor dbcursor = null;
        try {
            if (userId == null && flag) {
                dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE COUNTER_ID ='" + counterId + "' AND Visit_Date='" + visit_date + "'", null);
            } else {
                dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE User_Id ='" + userId + "' AND Visit_Date='" + visit_date + "'AND COUNTER_ID='" + counterId + "'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sb.setProfileImage1(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE1")));
                    sb.setProfileImage2(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE2")));
                    sb.setCounterlength(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("HIGHT")));
                    sb.setCounterwidth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("WIDTH")));
                    sb.setSetupDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SETUP_DATE")));
                    sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COUNTER_AGEING")));
                    sb.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UUID)));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return sb;
        }

        return sb;
    }


    public ArrayList<JourneyPlan> getCounterProfileListData(String visit_date, String counterId, boolean previous_date) {
        ArrayList<JourneyPlan> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (previous_date) {
                dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE COUNTER_ID ='" + counterId + "' AND Visit_Date <>'" + visit_date + "' and STATUS='N'", null);
            } else {
                dbcursor = db.rawQuery("SELECT * FROM COUNTER_PROFILE_DATA WHERE COUNTER_ID ='" + counterId + "' AND Visit_Date='" + visit_date + "' and STATUS='N'", null);
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    JourneyPlan sb = new JourneyPlan();
                    sb.setUserId((dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID))));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sb.setProfileImage1(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE1")));
                    sb.setProfileImage2(dbcursor.getString(dbcursor.getColumnIndexOrThrow("IMAGE2")));
                    sb.setCounterlength(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("HIGHT")));
                    sb.setCounterwidth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("WIDTH")));
                    sb.setSetupDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SETUP_DATE")));
                    sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("COUNTER_AGEING")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return list;
        }

        return list;
    }

    public long insertmanualinwardinDraft(ArrayList<InvoiceGetterSetter> selected_list, String invoice_status, String invoice_id, String counter_confirm, String draft_status, String counter_id, String username, String invoiceNo, String invoiceType, String invDate, String source, String visit_date, String invoice_img) {
        db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "=" + counter_id + " AND " + CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_INVOICE_ID + "='" + invoice_id + "'", null);

        ContentValues values2 = new ContentValues();
        long id = 0;
        try {

            db.beginTransaction();
            for (int j = 0; j < selected_list.size(); j++) {
                values2 = new ContentValues();
                values2.put(CommonString.KEY_VISIT_DATE, visit_date);
                values2.put(CommonString.KEY_COUNTER_ID, counter_id);
                values2.put(CommonString.KEY_USER_ID, username);
                values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                values2.put(CommonString.KEY_INVOICE_DATE, invDate);
                values2.put(CommonString.KEY_INVOICE_TYPE, invoiceType);
                values2.put(CommonString.KEY_INVOICE_ID, invoice_id);
                values2.put(CommonString.KEY_INVOICE_IMG, invoice_img);
                values2.put(CommonString.KEY_Product, selected_list.get(j).getProduct());
                values2.put(CommonString.KEY_ProductId, selected_list.get(j).getProduct_Id());
                values2.put(CommonString.KEY_INVOICE_QTY, selected_list.get(j).getQuantity());
                values2.put(CommonString.KEY_MRP, selected_list.get(j).getProduct_rate());
                values2.put(CommonString.KEY_ACTUAL_QTY, selected_list.get(j).getActualQty());
                //Total amount
                int totalAmount = Integer.parseInt(selected_list.get(j).getActualQty()) * Integer.parseInt(selected_list.get(j).getProduct_rate());
                values2.put(CommonString.KEY_TOTAL_AMOUNT, totalAmount);
                values2.put(CommonString.KEY_REASON_ID, selected_list.get(j).getReasonId());
                values2.put(CommonString.KEY_COUNTER_CONFIRM, counter_confirm);
                values2.put(CommonString.KEY_DRAFT_STATUS, draft_status);
                values2.put(CommonString.KEY_VIEW_MODE, "-1");
                values2.put(CommonString.KEY_SOURCE, source);
                values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, selected_list.get(j).isConfirmChecked());
                values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N);
                values2.put(CommonString.KEY_TRANSACTION_ID, "");
                values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, 0);
                values2.put(CommonString.KEY_INVOICE_STATUS, invoice_status);
                values2.put(CommonString.KEY_NEW_PRODUCT, 0);
                id = db.insert(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, null, values2);
            }

            closeDb();

            if (id > 0) {
                return id;
            } else {
                return 0;
            }
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
    }


    public long deletemanualinwardbyInvoiceid(String counter_id, String visit_date, String invoiceNo, String invoiceType) {
        long l = 0;

        try {
            l = db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "=" + counter_id + " AND " + CommonString.KEY_INVOICE_NUMBER + "='" + invoiceNo + "' AND " + CommonString.KEY_INVOICE_TYPE + "='" + invoiceType + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;

    }


    public long insertManualInwardStockData(ArrayList<InvoiceGetterSetter> selected_list, String counter_id, String username, String invoiceNo, String invoiceType, String invDate, String visit_date, String invoice_img, String transactionId, boolean newinwardproduct) {
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        long id = 0, masterreturn = 0;
        ContentValues values2;
        ContentValues values1;
        String invoice_status = "1", invoiceId = "0", counter_confirm = "1", draft_status = "1", source = "Manual";
        int totalAmount = 0;
        try {

            db.beginTransaction();
            values1 = new ContentValues();
            values1.put(CommonString.KEY_UUID, transactionId);
            values1.put(CommonString.KEY_USER_ID, username);
            values1.put(CommonString.KEY_COUNTER_ID, counter_id);
            values1.put(CommonString.KEY_VISIT_DATE, visit_date);
            if (newinwardproduct) {
                values1.put(CommonString.KEY_STOCK_TYPE, CommonString.MANUALINWARD_DMS_NEWPRODUCT);
            } else {
                values1.put(CommonString.KEY_STOCK_TYPE, CommonString.MANUALINWARD_DMS);
            }
            values1.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            values1.put(CommonString.KEY_STATUS, CommonString.KEY_N);
            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, values1);
            if (masterreturn > 0) {
                for (int j = 0; j < selected_list.size(); j++) {
                    values2 = new ContentValues();
                    values2.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_N);
                    values2.put(CommonString.KEY_TRANSACTION_ID, transactionId);
                    values2.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                    values2.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values2.put(CommonString.KEY_COUNTER_ID, counter_id);
                    values2.put(CommonString.KEY_USER_ID, username);
                    values2.put(CommonString.KEY_INVOICE_NUMBER, invoiceNo);
                    values2.put(CommonString.KEY_INVOICE_DATE, invDate);
                    values2.put(CommonString.KEY_INVOICE_TYPE, invoiceType);
                    values2.put(CommonString.KEY_INVOICE_ID, invoiceId);
                    values2.put(CommonString.KEY_INVOICE_IMG, invoice_img);
                    values2.put(CommonString.KEY_COUNTER_CONFIRM, counter_confirm);
                    values2.put(CommonString.KEY_DRAFT_STATUS, draft_status);
                    values2.put(CommonString.KEY_VIEW_MODE, "-1");
                    values2.put(CommonString.KEY_SOURCE, source);
                    values2.put(CommonString.KEY_INVOICE_STATUS, invoice_status);

                    values2.put(CommonString.KEY_Product, selected_list.get(j).getProduct());
                    values2.put(CommonString.KEY_ProductId, selected_list.get(j).getProduct_Id());
                    values2.put(CommonString.KEY_INVOICE_QTY, selected_list.get(j).getQuantity());
                    values2.put(CommonString.KEY_MRP, selected_list.get(j).getProduct_rate());
                    values2.put(CommonString.KEY_ACTUAL_QTY, selected_list.get(j).getActualQty());
                    totalAmount = Integer.parseInt(selected_list.get(j).getActualQty()) * Integer.parseInt(selected_list.get(j).getProduct_rate());
                    values2.put(CommonString.KEY_TOTAL_AMOUNT, totalAmount);
                    values2.put(CommonString.KEY_REASON_ID, selected_list.get(j).getReasonId());
                    values2.put(CommonString.KEY_SKU_CONFIRMATION_CHECK, selected_list.get(j).isConfirmChecked());
                    if (newinwardproduct) {
                        values2.put(CommonString.KEY_NEW_PRODUCT, 1);
                    } else {
                        values2.put(CommonString.KEY_NEW_PRODUCT, 0);
                    }
                    if (!db.isOpen()) open();

                    id = db.insert(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, null, values2);
                    if (id > 0) {
                        if (!db.isOpen()) open();
                        TStockSummary stockObj = getTStockSummaryProductDetails(Integer.parseInt(selected_list.get(j).getProduct_Id()));
                        if (stockObj != null) {
                            // if stockObj is not null means product exist in stock summary table data then update value in TStockSummary
                            updateStockSummaryData(stockObj, invoiceType, selected_list.get(j).getActualQty(), visit_date);
                        } else {
                            if (!db.isOpen()) open();
                            stockObj = getStockSummaryStatus(visit_date);
                            if (stockObj.getId() != null) {
                                if (!db.isOpen()) open();
                                insertTStockSummaryManualData(stockObj, Integer.parseInt(selected_list.get(j).getProduct_Id()), counter_id, invoiceType, selected_list.get(j).getActualQty());
                            }
                        }
                        if (selected_list.get(j).getReasonId() == 2 && invoiceType.equalsIgnoreCase("Sellable")) {
                            int damageStockQty = Integer.parseInt(selected_list.get(j).getActualQty());
                            updateStockSummaryDamageValue(Integer.parseInt(selected_list.get(j).getProduct_Id()), damageStockQty, counter_id);
                        }
                    }
                }
            }

            db.setTransactionSuccessful();
            db.endTransaction();
            if (id > 0) {
                return id;
            } else {
                return 0;
            }
        } catch (Exception ex) {
            ////////test("Database Exception ", ex.toString());
            return 0;
        }
    }


    public ArrayList<TCounterInvoice> getManualInwardStockData(String counter_id, String visit_date) {
        ArrayList<TCounterInvoice> list = new ArrayList<>();

        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select distinct " + CommonString.KEY_INVOICE_NUMBER + "," + CommonString.KEY_TRANSACTION_ID + "," + CommonString.KEY_UPLOAD_STATUS + "," + CommonString.KEY_INVOICE_TYPE + "," + CommonString.KEY_INVOICE_DATE + "," + CommonString.KEY_INVOICE_STATUS + "," + CommonString.KEY_SOURCE + "," + CommonString.KEY_COUNTER_CONFIRM + ",count(" + CommonString.KEY_ProductId + ") as NoofLine,sum(" + CommonString.KEY_TOTAL_AMOUNT + ") as FinalAmount , " + CommonString.KEY_INVOICE_IMG + " from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_COUNTER_ID + " = '" + counter_id + "' and " + CommonString.KEY_VISIT_DATE + " = '" + visit_date + "' group by InvoiceNo order by InvoiceDate desc ", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TCounterInvoice sb = new TCounterInvoice();
                    sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER)));
                    sb.setInvoiceDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE)));
                    sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE)));
                    sb.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG)));
                    String counterconfirm = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_CONFIRM));
                    String invoiceStatus = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS));
                    sb.setCounterConfirm(counterconfirm == null || counterconfirm.equals("0") ? false : true);
                    sb.setApproved_line(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine")));
                    sb.setInvoiceStatus(invoiceStatus == null || invoiceStatus.equals("0") ? false : true);
                    sb.setNo_ofLine(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine")));
                    sb.setFinalAmount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FinalAmount")));
                    sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE)));
                    sb.setTransactionId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID)));
                    sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS)));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }

    private String getinwardStockTransactionId(String invoiceNo, int product_id) {
        Cursor dbcursor = null;
        String transId = "";
        try {
            dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " where " + CommonString.KEY_INVOICE_NUMBER + " = '" + invoiceNo + "' " + "and " + CommonString.KEY_ProductId + " =" + product_id + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    transId = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return transId;
            }
        } catch (Exception e) {

            return transId;
        }

        return transId;
    }

    ///jp_update_getSaleable Stock
    public ProductMaster getActualSaleableStock(String productId, String coulmn_name, String visit_date, String counterId, String userType) {
        ProductMaster list = new ProductMaster();
        Cursor dbcursor = null;
        String q1 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND T1." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND T1." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND T2.POS_SALE_FLAG='0'";
        String q2 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND S." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND S." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND S1.POS_SALE_FLAG ='0'";
        String additionQueryMe = "", getDataMe = "(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance";
        try {
            if (!db.isOpen()) {
                open();
            }
            String table = "T_StockSummary", query = "";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                getDataMe = "((s.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(dm.DamageQty,0)) as SaleableBalance";
                additionQueryMe = " left join (select ProductId, case when (Select count(*) from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " and T1.PRODUCT_ID=" + productId + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + "and S.PROMO_PRODUCT_ID=" + productId + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + ")" + " c where c.ProductId = t.Productid)>0 then" + " (Select TempQty from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " and T1.PRODUCT_ID=" + productId + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + "and S.PROMO_PRODUCT_ID=" + productId + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on s.ProductId=tempsale.ProductId";
            }

            if (coulmn_name != null && coulmn_name.equalsIgnoreCase("GwpBalance")) {
                query = "select distinct (ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance from Product_Master PM" + " inner join " + table + " ts on ts.ProductId= PM.ProductID Left join (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + "  AND T2.Visit_Date='" + visit_date + "'" + q1 + " AND T1.INVOICE_TYPE='GWP' and T1.PRODUCT_ID=" + productId + " GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "' and S.PROMO_PRODUCT_ID=" + productId + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' and Product_Type='GWP' and ProductId=" + productId + " GROUP By ProductId) as t Group by CounterId, ProductId" + " ) as t on PM.ProductId = t.ProductId" +

                        " where ts.GwpBalance >0";
            } else if (coulmn_name != null && coulmn_name.equalsIgnoreCase("SampleBalance")) {
                query = "select distinct " + coulmn_name + " from " + table + " where ProductId='" + productId + "'";
            } else {
                query = " Select " + getDataMe + " from " + table + " s" + " Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from" + " TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE'" + " AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " and T.ProductId = " + productId + " Union All SELECT  CounterId, ProductId, DamageQty from Damage_PreviousPending Where" + " CounterId =" + counterId + " and Verify ='Pending' and ProductId=" + productId + " UNION ALL" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty" + " FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " and T1.PRODUCT_ID=" + productId + q1 + " GROUP BY T1.PRODUCT_ID UNION ALL" + " select  S.COUNTER_ID as CounterId, S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS DamageQty" + " from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' and S.PROMO_PRODUCT_ID=" + productId + q2 + " GROUP BY S.PROMO_PRODUCT_ID) as" + " t Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId" + additionQueryMe + " where s.ProductId=" + productId;
            }

            dbcursor = db.rawQuery(query, null);

            //test("Query--", query);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    if (coulmn_name != null && coulmn_name.equalsIgnoreCase("SampleBalance") || coulmn_name != null && coulmn_name.equalsIgnoreCase("GwpBalance")) {
                        list.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(coulmn_name)));
                    } else {
                        list.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SaleableBalance")));
                    }

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public boolean insertReportSaleValue(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_SalesValue", null, null);
        ContentValues values = new ContentValues();
        List<ReportSalesValue> data = cst.getReportSalesValue();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("KPI", data.get(i).getKPI());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("AchPer", data.get(i).getAchPer());
                values.put("Pending", data.get(i).getPending());
                values.put("RunRate", data.get(i).getRunRate());

                long id = db.insert("Report_SalesValue", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertReportSaleDetails(MasterProfileQuestionGetterSetter cst, boolean me) {
        String table = "Report_Sales_Detail";
        List<ReportSalesDetail> data = cst.getReportSalesDetail();
        if (me) {
            table = "Report_Sales_DetailME";
            data = cst.getReportSalesDetailMe();
        }
        db.delete(table, null, null);
        ContentValues values = new ContentValues();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("ProductId", data.get(i).getProductId());
                values.put("Qty", data.get(i).getQty());
                values.put("SalesValue", data.get(i).getSalesValue());

                long id = db.insert(table, null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertReportAvgTransationperDay(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_AvgTransactionPerDay", null, null);
        ContentValues values = new ContentValues();
        List<ReportAvgTransactionPerDay> data = cst.getReportAvgTransactionPerDay();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("KPI", data.get(i).getKPI());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("AchPer", data.get(i).getAchPer());
                values.put("Pending", data.get(i).getPending());
                long id = db.insert("Report_AvgTransactionPerDay", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertReportAvgBillUnit(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_AvgBillValue", null, null);
        ContentValues values = new ContentValues();
        List<ReportAvgBillValue> data = cst.getReportAvgBillValue();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("KPI", data.get(i).getKPI());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("AchPer", data.get(i).getAchPer());
                values.put("Pending", data.get(i).getPending());
                long id = db.insert("Report_AvgBillValue", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertReportAvgPerBillDay(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_AvgUnitsPerBill", null, null);
        ContentValues values = new ContentValues();
        List<ReportAvgUnitsPerBill> data = cst.getReportAvgUnitsPerBill();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("KPI", data.get(i).getKPI());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("AchPer", data.get(i).getAchPer());
                values.put("Pending", data.get(i).getPending());
                long id = db.insert("Report_AvgUnitsPerBill", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<MasterInvoiceType> getInvoiceTypeList() {
        ArrayList<MasterInvoiceType> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select * from Master_InvoiceType", null);

            MasterInvoiceType sb1 = new MasterInvoiceType();
            sb1.setInvoiceType("- Select Invoice Type -");
            list.add(sb1);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterInvoiceType sb = new MasterInvoiceType();
                    sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("InvoiceType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public long deleteTableWithLogin(String userName) {
        long l = 0;
        try {
            l = db.delete("User_login", "USER_ID='" + userName + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }


    public ArrayList<InvoiceGetterSetter> getInsertedManualStockData(String invNumber, String invType, String date) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " WHERE " + CommonString.KEY_INVOICE_NUMBER + "='" + invNumber + "' " + " AND " + CommonString.KEY_INVOICE_TYPE + "='" + invType + "' and " + CommonString.KEY_VISIT_DATE + "='" + date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setKeyId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId)));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_Product)));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY)));
                    sale.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY)));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_MRP)));
                    sale.setViewMode(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VIEW_MODE)));
                    sale.setInvoice_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS)));
                    sale.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_REASON_ID)));
                    sale.setDraft_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_DRAFT_STATUS)));
                    sale.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG)));
                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public boolean insertReportAvgLinPerBill(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_AvgLinPerBill", null, null);
        ContentValues values = new ContentValues();
        List<ReportAvgLinPerBill> data = cst.getReportAvgLinPerBill();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("KPI", data.get(i).getKPI());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("AchPer", data.get(i).getAchPer());
                values.put("Pending", data.get(i).getPending());
                long id = db.insert("Report_AvgLinPerBill", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertReportSelingPrice(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_SellingPrice", null, null);
        ContentValues values = new ContentValues();
        List<ReportSellingPrice> data = cst.getReportSellingPrice();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("KPI", data.get(i).getKPI());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("Pending", data.get(i).getPending());
                values.put("AchPer", data.get(i).getAchPer());
                long id = db.insert("Report_SellingPrice", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertReportTop10Volume(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_Top10Volume", null, null);
        ContentValues values = new ContentValues();
        List<ReportTop10Volume> data = cst.getReportTop10Volume();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("BrandName", data.get(i).getBrandName());
                values.put("SubBrandName", data.get(i).getSubBrandName());
                values.put("ReferenceName", data.get(i).getReferenceName());
                values.put("EanCode", data.get(i).getEanCode());
                values.put("ProductName", data.get(i).getProductName());
                values.put("MTDVolume", data.get(i).getMTDVolume());
                values.put("AvgPerDayVolume", data.get(i).getAvgPerDayVolume());
                long id = db.insert("Report_Top10Volume", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertReportTop10Value(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_Top10Value", null, null);
        ContentValues values = new ContentValues();
        List<ReportTop10Value> data = cst.getReportTop10Value();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("BrandName", data.get(i).getBrandName());
                values.put("SubBrandName", data.get(i).getSubBrandName());
                values.put("ReferenceName", data.get(i).getReferenceName());
                values.put("EanCode", data.get(i).getEanCode());
                values.put("ProductName", data.get(i).getProductName());
                values.put("MTDValue", data.get(i).getMTDValue());
                values.put("AvgPerDayValue", data.get(i).getAvgPerDayValue());
                long id = db.insert("Report_Top10Value", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMeSaleReport(MasterProfileQuestionGetterSetter cst) {
        db.delete("Report_ME_Sale", null, null);
        ContentValues values = new ContentValues();
        List<ReportMESale> data = cst.getReportMeSaleList();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("TotalUnitSale", data.get(i).getTotalunitsale());
                values.put("TotalSale", data.get(i).getTotalsale());
                long id = db.insert("Report_ME_Sale", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportAvgUnitsPerBill> getDashboardReport(String CounterId) {
        ArrayList<ReportAvgUnitsPerBill> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (CounterId == null) {
                dbcursor = db.rawQuery("Select *,0 as RunRate from Report_AvgBillValue " + " Union " + "Select *,0 as RunRate from Report_AvgLinPerBill " + " Union " + "Select *,0 as RunRate from Report_AvgTransactionPerDay " + " Union " + "Select *,0 as RunRate from Report_AvgUnitsPerBill " + " Union " + "Select *,0 as RunRate from Report_SellingPrice " + " Union " + "Select * from Report_SalesValue order by RunRate desc", null);
            } else {
                dbcursor = db.rawQuery("Select *,0 as RunRate from Report_AvgBillValue where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_AvgLinPerBill where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_AvgTransactionPerDay where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_AvgUnitsPerBill where CounterId='" + CounterId + "'" + " Union " + "Select *,0 as RunRate from Report_SellingPrice where CounterId='" + CounterId + "'" + " Union " + "Select * from Report_SalesValue where CounterId='" + CounterId + "'order by RunRate desc", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ReportAvgUnitsPerBill sb = new ReportAvgUnitsPerBill();
                    sb.setKPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setMTDTg(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDTg")));
                    sb.setMTDAch(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDAch")));
                    sb.setAchPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("AchPer")));
                    sb.setPending(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Pending")));
                    sb.setRunRate(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RunRate")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    //Insert GWP data
    public void insertGWPCapturedData(String visit_date, HashMap<ProductMaster, List<ProductMaster>> data, List<ProductMaster> save_listDataHeader, boolean completeFlag, String counterId) {
        db.delete(CommonString.TABLE_INSERT_HEADER_GWP_DATA, null, null);
        db.delete(CommonString.TABLE_GWP_CHILD_DATA, null, null);
        ContentValues values = new ContentValues();
        ContentValues values1 = new ContentValues();
        try {
            db.beginTransaction();
            for (int i = 0; i < save_listDataHeader.size(); i++) {
                values.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                values.put("BrandName", save_listDataHeader.get(i).getBrandName());
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_COUNTER_ID, counterId);
                values.put("SubAxeName", save_listDataHeader.get(i).getReferenceName());
                values.put("SignatureName", save_listDataHeader.get(i).getSignatureName());
                long l = db.insert(CommonString.TABLE_INSERT_HEADER_GWP_DATA, null, values);
                for (int j = 0; j < data.get(save_listDataHeader.get(i)).size(); j++) {
                    values1.put("Common_Id", (int) l);
                    values1.put(CommonString.KEY_COUNTER_ID, counterId);
                    values1.put("AxeName", save_listDataHeader.get(i).getSubBrandName());
                    values1.put("BrandName", save_listDataHeader.get(i).getBrandName());
                    values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values1.put("SubAxeName", save_listDataHeader.get(i).getReferenceName());
                    values1.put("ProductName", data.get(save_listDataHeader.get(i)).get(j).getProductName());
                    values1.put("ProductId", data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    values1.put("STOCK", data.get(save_listDataHeader.get(i)).get(j).getStock());
                    values1.put("Mrp", data.get(save_listDataHeader.get(i)).get(j).getMrp());
                    values1.put("STOCK_RECEIVED", data.get(save_listDataHeader.get(i)).get(j).getStock_receive());
                    values1.put("ImagePath", data.get(save_listDataHeader.get(i)).get(j).getImagePath());
                    values1.put("REASON", data.get(save_listDataHeader.get(i)).get(j).getResion());
                    if (!db.isOpen()) open();

                    boolean stockFlag = isTStockSummaryProductFilled(data.get(save_listDataHeader.get(i)).get(j).getProductId());
                    if (stockFlag) {
                        // set stock to product
                        updateTStockData(data.get(save_listDataHeader.get(i)).get(j).getStock(), CommonString.GWP, data.get(save_listDataHeader.get(i)).get(j).getProductId(), completeFlag, visit_date);
                    } else {
                        if (!db.isOpen()) open();

                        TStockSummary stockObj;
                        stockObj = getStockSummaryStatus(visit_date);
                        if (stockObj != null) {
                            insertTStockSummaryData(stockObj, data.get(save_listDataHeader.get(i)).get(j).getProductId(), counterId, CommonString.GWP, data.get(save_listDataHeader.get(i)).get(j).getStock(), completeFlag, visit_date);
                        }
                    }

                    db.insert(CommonString.TABLE_GWP_CHILD_DATA, null, values1);
                }
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
        }
    }

    ///jp changes
    public JourneyPlan getBIDfromJCP(String UserId, String CounterId) {
        JourneyPlan sb = new JourneyPlan();
        Cursor dbcursor = null;
        try {
            if (UserId == null) {
                dbcursor = db.rawQuery("SELECT distinct MID,BID,VisitDate from Mapping_JourneyPlan where CounterId=" + CounterId, null);
            } else {
                dbcursor = db.rawQuery("SELECT distinct MID,BID,VisitDate from Mapping_JourneyPlan where UserId='" + UserId + "' and CounterId=" + CounterId, null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    if (UserId == null) {
                        sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                        sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID")));
                        sb.setBID(0);
                    } else {
                        sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID")));
                        sb.setBID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BID")));
                        sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    }

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return sb;
        }

        return sb;
    }

    //jeevan   nmjnmn,
    public long update_SaleTRacking(String counterId, String user_Id, String reciept_count) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            l = db.update(CommonString.Table_Sale_Tracking_Header_Data, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND USER_ID='" + user_Id + "' AND RECCEPT_COUNT='" + reciept_count + "'", null);
            l = db.update(CommonString.Table_Sale_Tracking, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND USER_ID='" + user_Id + "' AND RECCEPT_COUNT='" + reciept_count + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long insert_consumer_sales_data(String user_Id, String visit_date, String counter_Id, String total_value, boolean pos_sale_flag, String UID_code, String termcondition_str, HashMap<InvoiceGetterSetter, List<InvoiceGetterSetter>> data, List<InvoiceGetterSetter> invoiceHeaderList, String demo_image, String userType) {
        db.delete(CommonString.Table_Sale_Tracking, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.Table_Applyeid_Promotion, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.Table_Sale_Tracking_Header_Data, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        db.delete(CommonString.Table_PromoApplyeidOnProduct, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);

        ContentValues finalvalues = new ContentValues();
        ContentValues promovalues = new ContentValues();
        ContentValues values4 = new ContentValues();
        ContentValues values = new ContentValues();
        ContentValues values1 = new ContentValues();
        long finalreturen = 0, masterreturn = 0, l3 = 0, header_return = 0;
        try {
            db.beginTransaction();
            if (pos_sale_flag && !invoiceHeaderList.isEmpty()) {
                finalvalues.put(CommonString.KEY_UUID, UID_code);
                finalvalues.put(CommonString.KEY_USER_ID, user_Id);
                finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id);
                finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
                finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.CONSUMERSALE);
                finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
                finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                if (!db.isOpen()) open();

                masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);

            }

            for (int i = 0; i < invoiceHeaderList.size(); i++) {
                values.put("USER_ID", user_Id);
                values.put("UNIQUE_CODE", UID_code);
                values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                values.put(CommonString.KEY_COUNTER_ID, counter_Id);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put("BUYER_NAME", invoiceHeaderList.get(i).getCustomer_name());
                values.put("CONTACT_NUMBER", invoiceHeaderList.get(i).getMobile_no());
                values.put("EMAIL_ID", invoiceHeaderList.get(i).getConsumer_email_Id());
                values.put("AGE", invoiceHeaderList.get(i).getConsumer_age());
                values.put("SKIN_TYPE", invoiceHeaderList.get(i).getConsumer_skinType());
                values.put("GENDER", invoiceHeaderList.get(i).getCustomer_gender());
                values.put("DEMO_GIVEN", invoiceHeaderList.get(i).getDemo_given_str());
                values.put("PRODUCT_SOLD", invoiceHeaderList.get(i).getProduct_sold_str());
                values.put("SKIN_GENIUS", invoiceHeaderList.get(i).getSkin_genius_str());
                values.put("MAYBELLINE_VTO", invoiceHeaderList.get(i).getMaybelline_vto_str());
                values.put("PER_TIMING", invoiceHeaderList.get(i).getPercheasing_tym());
                values.put(CommonString.KEY_STORE_NAME, invoiceHeaderList.get(i).getStore_name());
                values.put("STORE_ADDRESS", invoiceHeaderList.get(i).getStore_address());
                values.put("UPLOAD_STATUS", invoiceHeaderList.get(i).getStr_upload_status());
                values.put("CONSUMER_NOSALE_IMG", demo_image);
                values.put("SOURCEOFSALES", invoiceHeaderList.get(i).getSourceofSales());
                if (pos_sale_flag) {
                    values.put("POS_SALE_FLAG", "1");
                } else {
                    values.put("POS_SALE_FLAG", "0");
                }
                values.put("TERMCONDITION_FLAG", termcondition_str);
                values.put(CommonString.KEY_USER_TYPE, userType);
                if (!db.isOpen()) {
                    open();
                }

                header_return = db.insert(CommonString.Table_Sale_Tracking_Header_Data, null, values);

                if (invoiceHeaderList.get(i).getProduct_sold_str().trim().equalsIgnoreCase("Yes")) {
                    for (int j = 0; j < Objects.requireNonNull(data.get(invoiceHeaderList.get(i))).size(); j++) {
                        values1.put(CommonString.KEY_RECCEPT_NUMBER, (int) header_return);
                        values1.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                        values1.put("USER_ID", user_Id);
                        if (pos_sale_flag) {
                            values1.put("POS_SALE_FLAG", "1");
                        } else {
                            values1.put("POS_SALE_FLAG", "0");
                        }

                        values1.put("TOTAL_AMOUNT", total_value);
                        values1.put(CommonString.KEY_COUNTER_ID, counter_Id);
                        values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                        values1.put("UNIQUE_CODE", UID_code);
                        values.put("CONSUMER_NOSALE_IMG", demo_image);
                        values.put("TERMCONDITION_FLAG", termcondition_str);
                        values1.put(CommonString.KEY_STORE_NAME, data.get(invoiceHeaderList.get(i)).get(j).getStore_name());
                        values1.put("STORE_ADDRESS", data.get(invoiceHeaderList.get(i)).get(j).getStore_address());
                        values1.put("EMAIL_ID", data.get(invoiceHeaderList.get(i)).get(j).getConsumer_email_Id());
                        values1.put("AGE", data.get(invoiceHeaderList.get(i)).get(j).getConsumer_age());
                        values1.put("SKIN_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getConsumer_skinType());
                        values1.put("DEMO_GIVEN", data.get(invoiceHeaderList.get(i)).get(j).getDemo_given_str());
                        values1.put("PRODUCT_SOLD", data.get(invoiceHeaderList.get(i)).get(j).getProduct_sold_str());
                        values1.put("SKIN_GENIUS", data.get(invoiceHeaderList.get(i)).get(j).getSkin_genius_str());
                        values1.put("MAYBELLINE_VTO", data.get(invoiceHeaderList.get(i)).get(j).getMaybelline_vto_str());
                        values1.put("SOURCEOFSALES", data.get(invoiceHeaderList.get(i)).get(j).getSourceofSales());

                        values1.put("BUYER_NAME", data.get(invoiceHeaderList.get(i)).get(j).getCustomer_name());
                        values1.put("CONTACT_NUMBER", data.get(invoiceHeaderList.get(i)).get(j).getMobile_no());
                        values1.put("PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id());
                        values1.put("PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                        values1.put("SKU_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getSkuType());
                        values1.put("QUANTITY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity());
                        values1.put("PRODUCT_RATE", data.get(invoiceHeaderList.get(i)).get(j).getProduct_rate());
                        values1.put("GENDER", data.get(invoiceHeaderList.get(i)).get(j).getCustomer_gender());
                        values1.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code());
                        values1.put("PER_TIMING", data.get(invoiceHeaderList.get(i)).get(j).getPercheasing_tym());
                        values1.put("ACTUAL_PRICE", data.get(invoiceHeaderList.get(i)).get(j).getActual_price_per_product());
                        values1.put("DISCOUNTED_VALUE", data.get(invoiceHeaderList.get(i)).get(j).getDiscounted_value());
                        values1.put("UPLOAD_STATUS", data.get(invoiceHeaderList.get(i)).get(j).getStr_upload_status());
                        values1.put("INVOICE_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getStr_invoiceType());
                        //////addd discount items
                        values1.put("PROMOTION", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_name());
                        values1.put("PROMOTION_ID", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_Id());
                        if (data.get(invoiceHeaderList.get(i)).get(j).isPromo_flag()) {
                            values1.put("PROMOTION_FLAG", 1);
                        } else {
                            values1.put("PROMOTION_FLAG", 0);
                        }

                        values1.put("PROMO_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getPromo_type().trim());
                        ///update Sample,GWP, Saleable product--Not Promo------------
                        if (pos_sale_flag && userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                            InvoiceGetterSetter obj = data.get(invoiceHeaderList.get(i)).get(j);
                            if (!obj.isPromo_flag()) {
                                if (!db.isOpen()) {
                                    open();
                                }
                                update_tstock_summery_using_consumer_sales(counter_Id, obj.getProduct_Id(), obj.getQuantity(), obj.getStr_invoiceType());
                            }
                        }
                        if (!db.isOpen()) {
                            open();
                        }
                        values1.put(CommonString.KEY_USER_TYPE, userType);
                        finalreturen = db.insert(CommonString.Table_Sale_Tracking, null, values1);
                        //////for applyied promotion insert
                        if (Objects.requireNonNull(data.get(invoiceHeaderList.get(i))).get(j).isPromo_flag()) {
                            String promoType = data.get(invoiceHeaderList.get(i)).get(j).getPromo_type().trim();
                            promovalues.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                            promovalues.put(CommonString.KEY_RECCEPT_NUMBER, (int) header_return);
                            promovalues.put(CommonString.KEY_COUNTER_ID, counter_Id);
                            promovalues.put(CommonString.KEY_VISIT_DATE, visit_date);
                            promovalues.put("UNIQUE_CODE", UID_code);
                            promovalues.put("USER_ID", user_Id);
                            promovalues.put("PROMOTION_FLAG", 1);
                            promovalues.put("PROMO_TYPE", promoType);
                            promovalues.put("INVOICE_TYPE", data.get(invoiceHeaderList.get(i)).get(j).getStr_invoiceType());
                            promovalues.put("PROMOTION", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_name());
                            promovalues.put("PROMOTION_ID", data.get(invoiceHeaderList.get(i)).get(j).getPromotion_Id());

                            if (promoType.equalsIgnoreCase("OffSameProduct")) {
                                promovalues.put("PROMO_PRODUCT_ID", 0);
                                promovalues.put("PROMO_PRODUCT", "");
                                promovalues.put("EAN_CODE", "");
                                promovalues.put("PROMO_PRODUCT_QTY", 0);
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                            } else if (promoType.equalsIgnoreCase("OffAdditionalProduct")) {
                                promovalues.put("PROMO_PRODUCT_ID", 0);
                                promovalues.put("PROMO_PRODUCT", "");
                                promovalues.put("EAN_CODE", "");
                                promovalues.put("PROMO_PRODUCT_QTY", 0);
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                            } else if (promoType.equalsIgnoreCase("ValueOffAdditionalProduct")) {
                                promovalues.put("PROMO_PRODUCT_ID", 0);
                                promovalues.put("PROMO_PRODUCT", "");
                                promovalues.put("EAN_CODE", "");
                                promovalues.put("PROMO_PRODUCT_QTY", 0);
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                            } else if (promoType.equalsIgnoreCase("OffWorth") || promoType.equalsIgnoreCase("WorthWithProduct")) {
                                promovalues.put("PROMO_PRODUCT_ID", 0);
                                promovalues.put("PROMO_PRODUCT", "");
                                promovalues.put("EAN_CODE", "");
                                promovalues.put("PROMO_PRODUCT_QTY", 0);
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());

                            } else if (promoType.equalsIgnoreCase("OffProduct")) {
                                promovalues.put("PROMO_PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id());
                                promovalues.put("PROMO_PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                                promovalues.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code());
                                promovalues.put("PROMO_PRODUCT_QTY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity());
                                promovalues.put("PROMO_PRODUCT_MRP", data.get(invoiceHeaderList.get(i)).get(j).getProduct_rate());
                                promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getSkuType());

                            } else if (promoType.equalsIgnoreCase("Product")) {
                                promovalues.put("PROMO_PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id());
                                promovalues.put("PROMO_PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                                promovalues.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code());
                                promovalues.put("PROMO_PRODUCT_QTY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity());
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", 0);

                            } else if (promoType.equalsIgnoreCase("Worth")) {
                                promovalues.put("PROMO_PRODUCT_ID", 0);
                                promovalues.put("PROMO_PRODUCT", "");
                                promovalues.put("EAN_CODE", "");
                                promovalues.put("PROMO_PRODUCT_QTY", 0);
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());

                            } else if (promoType.equalsIgnoreCase("Gift")) {
                                promovalues.put("PROMO_PRODUCT_ID", data.get(invoiceHeaderList.get(i)).get(j).getProduct_Id());
                                promovalues.put("PROMO_PRODUCT", data.get(invoiceHeaderList.get(i)).get(j).getProduct());
                                promovalues.put("EAN_CODE", data.get(invoiceHeaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code());
                                promovalues.put("PROMO_PRODUCT_QTY", data.get(invoiceHeaderList.get(i)).get(j).getQuantity());
                                promovalues.put("PROMO_PRODUCT_MRP", 0);
                                promovalues.put("PROMO_DISCOUNT", 0);
                            }

                            if (pos_sale_flag && userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                                //------------------update product qty in T_Stock summery..---------//
                                InvoiceGetterSetter obj = data.get(invoiceHeaderList.get(i)).get(j);
                                if (obj.getPromo_type().equalsIgnoreCase("Product")) {
                                    update_tstock_summery_using_promotion(counter_Id, obj.getProduct_Id(), obj.getQuantity(), true);
                                } else if (obj.getPromo_type().equalsIgnoreCase("Gift")) {
                                    update_tstock_summery_using_promotion(counter_Id, obj.getProduct_Id(), obj.getQuantity(), false);
                                } else if (obj.getPromo_type().equalsIgnoreCase("OffProduct")) {
                                    update_tstock_summery_using_promotion(counter_Id, obj.getProduct_Id(), obj.getQuantity(), true);
                                }
                            }
                            if (!db.isOpen()) {
                                open();
                            }
                            promovalues.put(CommonString.KEY_USER_TYPE, userType);
                            l3 = db.insert(CommonString.Table_Applyeid_Promotion, null, promovalues);
                            ////insert promo applyed on Products
                            InvoiceGetterSetter obj = data.get(invoiceHeaderList.get(i)).get(j);
                            if (l3 > 0 && !obj.getApplyiedproductList().isEmpty()) {
                                values4 = new ContentValues();
                                for (int d = 0; d < obj.getApplyiedproductList().size(); d++) {
                                    values4.put(CommonString.KEY_COMMON_ID, l3);
                                    values4.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                                    values4.put(CommonString.KEY_RECCEPT_NUMBER, (int) header_return);
                                    values4.put(CommonString.KEY_COUNTER_ID, counter_Id);
                                    values4.put(CommonString.KEY_VISIT_DATE, visit_date);
                                    values4.put("UNIQUE_CODE", UID_code);
                                    values4.put("USER_ID", user_Id);
                                    values4.put("PROMOTION_FLAG", 1);
                                    values4.put("PROMO_TYPE", promoType);
                                    values4.put("INVOICE_TYPE", obj.getStr_invoiceType());
                                    values4.put("PROMOTION", obj.getPromotion_name());
                                    values4.put("PROMOTION_ID", obj.getPromotion_Id());
                                    values4.put("PRODUCT_ID", obj.getApplyiedproductList().get(d).getProduct_Id());
                                    values4.put("PRODUCT", obj.getApplyiedproductList().get(d).getProduct());
                                    values4.put("EAN_CODE", obj.getApplyiedproductList().get(d).getScan_ean_code_or_enterd_ean_code());
                                    values4.put("PRODUCT_QTY", obj.getApplyiedproductList().get(d).getQuantity());
                                    values4.put("MRP", obj.getApplyiedproductList().get(d).getProduct_rate());
                                    values4.put("DISCOUNT", obj.getApplyiedproductList().get(d).getDiscounted_value_productwise());
                                    if (!db.isOpen()) {
                                        open();
                                    }
                                    values4.put(CommonString.KEY_USER_TYPE, userType);
                                    long l7 = db.insert(CommonString.Table_PromoApplyeidOnProduct, null, values4);
                                }
                            }
                        }
                    }
                }
            }

            if (finalreturen == 0 && header_return > 0) {
                finalreturen = header_return;
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Posm Master Data " + ex);
        }

        return finalreturen;
    }


    public long insert_temp_sales_data(String visit_date, String counter_Id, ArrayList<InvoiceGetterSetter> saleList) {
        db.delete(CommonString.Table_Temp_Sale, null, null);
        ContentValues values = new ContentValues();
        long l2 = 0;
        try {
            db.beginTransaction();
            for (int k = 0; k < saleList.size(); k++) {
                values.put(CommonString.KEY_COUNTER_ID, counter_Id);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put("ProductId", saleList.get(k).getProduct_Id());
                values.put("Quantity", saleList.get(k).getQuantity());
                values.put("Product_Type", saleList.get(k).getStr_invoiceType());
                if (!db.isOpen()) open();
                l2 = db.insert(CommonString.Table_Temp_Sale, null, values);
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString());
        }

        return l2;
    }

    public ArrayList<InvoiceGetterSetter> getsaleTrackingHeaderData(String visite_date, String counterId, String user_Id, boolean flagfor_sale, boolean flagforuuid, String uuid_Id) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (flagforuuid) {
                dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where UNIQUE_CODE ='" + uuid_Id + "'", null);
            } else {
                if (flagfor_sale) {
                    dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "' and UPLOAD_STATUS='N'", null);
                } else if (user_Id == null) {
                    dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' and POS_SALE_FLAG='1' and UPLOAD_STATUS='N'", null);
                } else {
                    dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Sale_Tracking_Header_Data + " Where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "' and POS_SALE_FLAG='1' and UPLOAD_STATUS='N'", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID")));
                    sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE")));
                    sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setDemo_given_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("DEMO_GIVEN")));
                    sale.setProduct_sold_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_SOLD")));
                    sale.setSkin_genius_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS")));
                    sale.setMaybelline_vto_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MAYBELLINE_VTO")));
                    sale.setPercheasing_tym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PER_TIMING")));
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setConsumer_no_saleImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONSUMER_NOSALE_IMG")));
                    sale.setSourceofSales(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SOURCEOFSALES")));
                    sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sale.setPos_sale_flag("1".equalsIgnoreCase(dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG"))));
                    sale.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE)));
                    list.add(sale);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }

    public long updateCounterProfileStatus(String userId, String visit_date, String status) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_STATUS, status);
            l = db.update(CommonString.TABLE_COUNTER_PROFILE_DATA, values, CommonString.KEY_USER_ID + " ='" + userId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }


    public long updateBaProfileStatus(String userId, String visit_date, String status) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_STATUS, status);
            if (!db.isOpen()) {
                open();
            }
            l = db.update("BA_PROFILE_DATA", values, CommonString.KEY_USER_ID + " ='" + userId + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }


    public JourneyPlan getinserted_counter_images(String counterId, String visit_date) {
        JourneyPlan list = new JourneyPlan();
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_COUNTER_IMAGE_DATA + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    list.setPresetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One")));
                    list.setPresetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_Two")));
                    list.setPostsetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_One")));
                    list.setPostsetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_Two")));
                    list.setCounter_img_onefor_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One")));
                    list.setCounter_img_two_for_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_Two")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }

    //jeevan   nmjnmn,
    public long update_CounterImage(String counterId, String user_Id, String visit_date, JourneyPlan counterimageObject) {
        long l = 0;
        try {
            if (db.isOpen()) {
            } else {
                open();
            }
            ContentValues values = new ContentValues();
            values.put("Pre_Setup_Img_One", counterimageObject.getPresetup_img_one_str());
            values.put("Pre_Setup_Img_Two", counterimageObject.getPresetup_img_two_str());
            values.put("Post_Setup_Img_One", counterimageObject.getPostsetup_img_one_str());
            values.put("Post_Setup_Img_Two", counterimageObject.getPostsetup_img_two_str());
            values.put("UNIQUE_CODE", counterimageObject.getTransId());
            l = db.update(CommonString.TABLE_COUNTER_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND USER_ID='" + user_Id + "' AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long update_Groomed_images(String counterId, String user_Id, String visit_date, GroomingGetterSetter groomedObject, String transId) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put("Mornning_groomed_img", groomedObject.getMorning_groom_img_str());
            values.put("Mornning_groomed_time", groomedObject.getMorning_groom_time_str());
            values.put("Noon_groomed_img", groomedObject.getNoon_groom_img_str());
            values.put("Noon_groomed_time", groomedObject.getNoon_groom_time_str());
            values.put("Evening_groomed_img", groomedObject.getEvenning_groom_img_str());
            values.put("Evening_groomed_time", groomedObject.getEvenning_groom_time_str());
            values.put("UNIQUE_CODE", transId);

            l = db.update(CommonString.TABLE_GROOMED_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_USER_ID + "='" + user_Id + "' AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);

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

        return l;
    }


    ////jp get ba login tyme
    public LoginGetterSetter get_baLoginTym(String visit_date, String userId) {
        LoginGetterSetter sb = new LoginGetterSetter();
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select * FROM User_login where " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and USER_ID ='" + userId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setUserLoginTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_LOGINTIME)));
                    sb.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE)));
                    sb.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout)));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {

            return sb;
        }
        return sb;
    }

    public TStockSummary getTStockSummaryProductDetails(int productId) {
        Cursor dbcursor = null;
        TStockSummary sb = null;
        try {

            dbcursor = db.rawQuery("SELECT * FROM T_StockSummary WHERE " + CommonString.KEY_ProductId + " =" + productId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new TStockSummary();
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId)));
                    sb.setSaleableIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SALEABLE_IN)));
                    sb.setSaleableBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SaleableBalance)));
                    sb.setTesterIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TESTER_IN)));
                    sb.setTesterBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TesterBalance)));
                    sb.setSampleIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SAMPLE_IN)));
                    sb.setSampleBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SampleBalance)));
                    sb.setGwpIn(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_GWP_IN)));
                    sb.setGwpBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_GWP_BALANCE)));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public long updateStockSummaryData(TStockSummary stockObj, String type, String actualQty, String visit_date) {
        long id = 0;
        int saleableIn = 0, saleableBalance = 0, gwpIn = 0, gwpBalance = 0, sampleIn = 0, sampleBalance = 0, testerIn = 0, testerBalance = 0;
        ContentValues values = new ContentValues();
        try {
            values.put("VisitDate", visit_date);
            if (type.equalsIgnoreCase("Sellable")) {
                saleableIn = stockObj.getSaleableIn();
                saleableIn = saleableIn + Integer.parseInt(actualQty);

                saleableBalance = stockObj.getSaleableBalance();
                saleableBalance = saleableBalance + Integer.parseInt(actualQty);

                values.put(CommonString.KEY_SALEABLE_IN, saleableIn);
                values.put(CommonString.KEY_SaleableBalance, saleableBalance);
            } else if (type.equalsIgnoreCase("Sample")) {
                sampleIn = stockObj.getSampleIn();
                sampleIn = sampleIn + Integer.parseInt(actualQty);

                sampleBalance = stockObj.getSampleBalance();
                sampleBalance = sampleBalance + Integer.parseInt(actualQty);

                values.put(CommonString.KEY_SAMPLE_IN, sampleIn);
                values.put(CommonString.KEY_SampleBalance, sampleBalance);
            } else if (type.equalsIgnoreCase("Tester")) {
                testerIn = stockObj.getTesterIn();
                testerIn = testerIn + Integer.parseInt(actualQty);

                testerBalance = stockObj.getTesterBalance();
                testerBalance = testerBalance + Integer.parseInt(actualQty);

                values.put(CommonString.KEY_TESTER_IN, testerIn);
                values.put(CommonString.KEY_TesterBalance, testerBalance);
            } else {
                gwpIn = stockObj.getGwpIn();
                gwpIn = gwpIn + Integer.parseInt(actualQty);

                gwpBalance = stockObj.getGwpBalance();
                gwpBalance = gwpBalance + Integer.parseInt(actualQty);

                values.put(CommonString.KEY_GWP_IN, gwpIn);
                values.put(CommonString.KEY_GWP_BALANCE, gwpBalance);
            }
            if (!db.isOpen()) open();
            id = db.update(CommonString.T_StockSummary, values, CommonString.KEY_ProductId + "=" + stockObj.getProductId(), null);
        } catch (Exception ex) {
            return 0;
        }
        return id;
    }


    public TStockSummary getStockSummaryStatus(String visit_date) {
        Cursor dbcursor = null;
        TStockSummary tStockSummaryObj = null;
        int id = 0;
        try {
            dbcursor = db.rawQuery("select distinct MAX(Id) as Id,SaleableStatus,TesterStatus,SampleStatus,GwpStatus,VisitDate from T_StockSummary", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    tStockSummaryObj = new TStockSummary();
                    if (dbcursor.getString(dbcursor.getColumnIndexOrThrow("Id")) == null) {
                        id = 1;
                        tStockSummaryObj.setId(id);
                        tStockSummaryObj.setSaleableStatus("Draft");
                        tStockSummaryObj.setTesterStatus("Draft");
                        tStockSummaryObj.setGwpStatus("Draft");
                        tStockSummaryObj.setSampleStatus("Draft");
                        tStockSummaryObj.setVisitDate(visit_date);
                    } else {
                        id = Integer.parseInt(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Id")));
                        id = id + 1;
                        tStockSummaryObj.setId(id);
                        tStockSummaryObj.setSaleableStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SaleableStatus)));
                        tStockSummaryObj.setTesterStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TesterStatus)));
                        tStockSummaryObj.setGwpStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_GwpStatus)));
                        tStockSummaryObj.setSampleStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SampleStatus)));
                        tStockSummaryObj.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    }

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return tStockSummaryObj;
            }
        } catch (Exception e) {

            return tStockSummaryObj;
        }

        return tStockSummaryObj;
    }


    public boolean insertTStockSummaryManualData(TStockSummary stockObj, Integer productId, String counter_id, String type, String actualQty) {
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put("Id", stockObj.getId());
            values.put("CounterId", counter_id);
            values.put("ProductId", productId);

            if (type.equalsIgnoreCase("Sellable")) {
                values.put("SaleableIn", actualQty);
                values.put("SaleableBalance", actualQty);
            } else {
                values.put("SaleableIn", 0);
                values.put("SaleableBalance", 0);
            }

            if (type.equalsIgnoreCase("Sample")) {
                values.put("SampleIn", actualQty);
                values.put("SampleBalance", actualQty);
            } else {
                values.put("SampleIn", 0);
                values.put("SampleBalance", 0);
            }

            if (type.equalsIgnoreCase("Tester")) {
                values.put("TesterIn", actualQty);
                values.put("TesterBalance", actualQty);
            } else {
                values.put("TesterIn", 0);
                values.put("TesterBalance", 0);
            }

            if (type.equalsIgnoreCase("Consumer Offer (PWP)")) {
                values.put("GwpIn", actualQty);
                values.put("GwpBalance", actualQty);
            } else {
                values.put("GwpIn", 0);
                values.put("GwpBalance", 0);
            }

            values.put("SaleableOut", 0);
            values.put("SaleableDamage", 0);
            values.put("TesterOut", 0);
            values.put("TesterDamage", 0);
            values.put("SampleOut", 0);
            values.put("SampleDamage", 0);
            values.put("GwpOut", 0);
            values.put("GwpDamage", 0);

            values.put("SaleableStatus", stockObj.getSaleableStatus());
            values.put("TesterStatus", stockObj.getTesterStatus());
            values.put("SampleStatus", stockObj.getSampleStatus());
            values.put("GwpStatus", stockObj.getGwpStatus());
            values.put("VisitDate", stockObj.getVisitDate());

            if (!db.isOpen()) open();

            long id = db.insert("T_StockSummary", null, values);
            if (id == -1) {
                throw new Exception();
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    //get JCP is filled
    public boolean isProductMasterFilled(String visit_date) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("SELECT * FROM Product_Master where VisitDate ='" + visit_date + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                int icount = dbcursor.getCount();
                dbcursor.close();
                if (icount > 0) {
                    filled = true;
                } else {
                    filled = false;
                }

            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }

        return filled;
    }

    public boolean isCheck_Old_Product(String visit_date) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("SELECT * FROM Product_Master where VisitDate <>'" + visit_date + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                int icount = dbcursor.getCount();
                dbcursor.close();
                if (icount > 0) {
                    filled = true;
                } else {
                    filled = false;
                }
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    public boolean isTStockSummaryFilled(String visit_date) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select * from T_StockSummary where VisitDate ='" + visit_date + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                int icount = dbcursor.getCount();
                dbcursor.close();
                if (icount > 0) {
                    filled = true;
                } else {
                    filled = false;
                }
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }

        return filled;
    }

    public boolean isTStockCorrectedinsert(String visit_date, String counterId) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("SELECT  (ifnull(T4.TotLine,0) + ifnull(T4.TotalStock,0)) as StockStatus From" + " (select case when c.TotalLine = t.TotLine then 1 else 0 end as TotLine," + " case when c.TotalStock = t.TotValue then 1 else 0 end as TotalStock from" + " (SELECT * FROM StockSummary_Check Where VisitDate='" + visit_date + "' and CounterId=" + counterId + ") as c" + " INNER JOIN" + " (select counterId, count(*) as TotLIne, sum(SaleableBalance)as TotValue from T_StockSummary Where VisitDate='" + visit_date + "' and CounterId=" + counterId + " group by CounterId) AS t" + " ON c.CounterId = t.CounterId) as T4", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockStatus"));
                    if (icount == 2) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }

                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());

            return filled;
        }

        return filled;
    }


    public boolean isTStockt(String visit_date, String counterId) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FRom T_StockSummary Where VisitDate='" + visit_date + "' And CounterId=" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine"));
                    if (icount > 0) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }

                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());

            return filled;
        }

        return filled;
    }

    public int isTStockTotalLine(String visit_date, String counterId, String table_name) {
        int filled = 0;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FRom " + table_name + " Where VisitDate='" + visit_date + "' And CounterId=" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine"));
                    if (icount > 0) {
                        filled = icount;
                        break;
                    } else {
                        filled = 0;
                    }

                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());

            return filled;
        }

        return filled;
    }

    public boolean isTStockSummeryCheckNoData(String visit_date, String counterId) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FRom StockSummary_Check Where VisitDate='" + visit_date + "' And CounterId=" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine"));
                    if (icount > 0) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }

                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());

            return filled;
        }

        return filled;
    }


    public boolean isCompOffersFilled(String visit_date, String counterId) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT Count(*) As TotalLine FROM " + CommonString.TABLE_COMP_OFFERS + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "' AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_STATUS + "<>'N'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    int icount = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalLine"));
                    if (icount > 0) {
                        filled = true;
                        break;
                    }

                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());

            return filled;
        }

        return filled;
    }

    public ArrayList<TCounterInvoice> getInsertedManualInwardStockData(String counter_id, String invoiceNo) {
        ArrayList<TCounterInvoice> list = new ArrayList<>();

        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_COUNTER_ID + " = '" + counter_id + "' " + "and " + CommonString.KEY_INVOICE_NUMBER + " = '" + invoiceNo + "' ", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TCounterInvoice sb = new TCounterInvoice();
                    sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    public void update_tstock_summery_using_consumer_sales(String counterId, String product_Id, String productQty, String invoiceType) {
        try {
            if (!db.isOpen()) {
                open();
            }
            String table = CommonString.T_StockSummary;

            if (!invoiceType.isEmpty() && invoiceType.trim().equalsIgnoreCase("Sample")) {
                db.execSQL("update " + table + " set SampleOut =SampleOut  +" + productQty + ",SampleBalance= SampleBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id);
            } else if (!invoiceType.isEmpty() && invoiceType.trim().equalsIgnoreCase("GWP")) {
                db.execSQL("update " + table + " set GwpOut =GwpOut  +" + productQty + ",GwpBalance= GwpBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id);
            } else {
                db.execSQL("update " + table + " set SaleableOut =SaleableOut  +" + productQty + ",SaleableBalance= SaleableBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }

    }


    public void update_tstock_summery_using_promotion(String counterId, String product_Id, String productQty, boolean salaebleflag) {
        try {
            if (!db.isOpen()) {
                open();
            }
            String table = CommonString.T_StockSummary;

            if (!salaebleflag) {
                db.execSQL("update " + table + " set GwpOut =GwpOut  +" + productQty + ",GwpBalance= GwpBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id);
            } else {
                db.execSQL("update " + table + " set SaleableOut =SaleableOut  +" + productQty + ",SaleableBalance= SaleableBalance - " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id);
            }

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

    }


    public T_LeaveRequest getinserted_leave_request_data(String storeid, String user_id, String visit_date, String TransId, boolean manualupload) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        T_LeaveRequest sb = new T_LeaveRequest();
        Cursor dbcursor = null;
        try {
            if (manualupload) {
                dbcursor = db.rawQuery("select * From " + CommonString.Table_Leave_Management + " where " + CommonString.KEY_COUNTER_ID + "='" + storeid + "'AND UNIQUE_CODE='" + TransId + "'and UPLOAD_STATUS='N'", null);
            } else {
                if (TransId != null) {
                    dbcursor = db.rawQuery("select * From " + CommonString.Table_Leave_Management + " where " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'and UNIQUE_CODE='" + TransId + "'", null);
                } else {
                    dbcursor = db.rawQuery("select * From " + CommonString.Table_Leave_Management + " where " + CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'and UPLOAD_STATUS='N'", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sb.setRequestDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Request_Date")));
                    sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("From_Date")));
                    sb.setUpload_start_date_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Upload_From_Date")));
                    sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("To_Date")));
                    sb.setUpload_end_date_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Upload_To_Date")));
                    sb.setLeave_reason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveReason")));
                    sb.setLeaveStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Leave_Status")));
                    sb.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sb.setOne_day_leave_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("One_Day_Leave")));

                    sb.setStr_leaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")));
                    sb.setStr_leaveTypeId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveTypeId")));
                    sb.setUpload_request_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    dbcursor.moveToNext();

                }

                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return sb;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return sb;
    }

    public MasterBreak getBreakManagementforuploadList(String counterId, String visite_date, String user_Id, String TRansId, boolean manual_upload) {
        MasterBreak sale = new MasterBreak();
        Cursor dbcursor = null;
        try {

            if (manual_upload) {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' and UNIQUE_CODE='" + TRansId + "'and UPLOAD_STATUS='N'", null);
            } else {
                if (TRansId != null) {
                    dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' and USER_ID='" + user_Id + "' and UNIQUE_CODE='" + TRansId + "'", null);
                } else {
                    dbcursor = db.rawQuery("SELECT * from " + CommonString.Table_Break_Management + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "' and USER_ID='" + user_Id + "' and UPLOAD_STATUS='N'", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setLoginTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LoginTym")));
                    sale.setBreakType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BreakType")));
                    sale.setBreakId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BreakId")));
                    sale.setStartTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTym")));
                    sale.setEndTym(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTym")));
                    sale.setTotalDuration(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TotalDuration")));
                    sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sale;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return sale;
        }
        return sale;
    }

    public long insert_consumer_return_headerchild_data(String user_Id, String visit_date, String counter_Id, String UID_code, HashMap<InvoiceGetterSetter, List<InvoiceGetterSetter>> data, List<InvoiceGetterSetter> returnheaderList, String bill_img, ArrayList<InvoiceGetterSetter> replaceproductList) {
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.Table_Consumer_Return, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.Table_Consumer_Return_Header_Data, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.Table_Consumer_Return_Replace_Product, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        ContentValues finalvalues = new ContentValues();
        ContentValues values = new ContentValues();
        ContentValues values1 = new ContentValues();
        ContentValues values2 = new ContentValues();
        long l2 = 0, masterreturn = 0;

        try {
            db.beginTransaction();

            finalvalues.put(CommonString.KEY_UUID, UID_code);
            finalvalues.put(CommonString.KEY_USER_ID, user_Id);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.CONSUMERRETURN);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);
            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);

            for (int i = 0; i < returnheaderList.size(); i++) {
                values.put("USER_ID", user_Id);
                values.put("UNIQUE_CODE", UID_code);
                values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                values.put(CommonString.KEY_COUNTER_ID, counter_Id);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_STORE_NAME, returnheaderList.get(i).getStore_name());
                values.put("STORE_ADDRESS", returnheaderList.get(i).getStore_address());
                values.put("BUYER_NAME", returnheaderList.get(i).getCustomer_name());
                values.put("BILL_NO", returnheaderList.get(i).getConsumer_return_bill_no());
                values.put("CONTACT_NUMBER", returnheaderList.get(i).getMobile_no());
                values.put("EMAIL", returnheaderList.get(i).getConsumer_email_Id());
                values.put("INVOICE_IMG", bill_img);
                values.put("GENDER", returnheaderList.get(i).getCustomer_gender());
                values.put("UPLOAD_STATUS", returnheaderList.get(i).getStr_upload_status());

                long l = db.insert(CommonString.Table_Consumer_Return_Header_Data, null, values);

                for (int j = 0; j < data.get(returnheaderList.get(i)).size(); j++) {
                    values1.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                    values1.put(CommonString.KEY_RECCEPT_NUMBER, (int) l);
                    values1.put("USER_ID", user_Id);
                    values1.put(CommonString.KEY_COUNTER_ID, counter_Id);
                    values1.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values1.put("UNIQUE_CODE", UID_code);
                    values1.put("UPLOAD_STATUS", returnheaderList.get(i).getStr_upload_status());
                    values1.put("PRODUCT_ID", data.get(returnheaderList.get(i)).get(j).getProduct_Id());
                    values1.put("PRODUCT", data.get(returnheaderList.get(i)).get(j).getProduct());
                    values1.put("QUANTITY", data.get(returnheaderList.get(i)).get(j).getQuantity());
                    values1.put("ACTUAL_QTY", data.get(returnheaderList.get(i)).get(j).getActualQty());
                    values1.put("PRODUCT_RATE", data.get(returnheaderList.get(i)).get(j).getProduct_rate());
                    values1.put("TOTAL_PRICE", data.get(returnheaderList.get(i)).get(j).getTotal_amount());
                    values1.put("EAN_CODE", data.get(returnheaderList.get(i)).get(j).getScan_ean_code_or_enterd_ean_code());
                    values1.put("REASON_ID", data.get(returnheaderList.get(i)).get(j).getCon_return_reason_Id());
                    values1.put("REASON", data.get(returnheaderList.get(i)).get(j).getCon_return_reason());

                    if (db.isOpen()) {
                    } else {
                        open();
                    }

                    update_tstock_summery_using_consumer_return(counter_Id, data.get(returnheaderList.get(i)).get(j).getProduct_Id(), data.get(returnheaderList.get(i)).get(j).getQuantity(), data.get(returnheaderList.get(i)).get(j).getCon_return_reason());

                    l2 = db.insert(CommonString.Table_Consumer_Return, null, values1);
                }


                for (int j = 0; j < replaceproductList.size(); j++) {
                    values2.put(CommonString.KEY_RECCEPT_NUMBER, (int) l);
                    values2.put("USER_ID", user_Id);
                    values2.put(CommonString.KEY_COUNTER_ID, counter_Id);
                    values2.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values2.put("UNIQUE_CODE", UID_code);
                    values2.put("UPLOAD_STATUS", returnheaderList.get(i).getStr_upload_status());

                    values2.put("PRODUCT_ID", replaceproductList.get(j).getProduct_Id());
                    values2.put("PRODUCT", replaceproductList.get(j).getProduct());
                    values2.put("QUANTITY", replaceproductList.get(j).getQuantity());
                    values2.put("PRODUCT_RATE", replaceproductList.get(j).getProduct_rate());
                    values2.put("EAN_CODE", replaceproductList.get(j).getScan_ean_code_or_enterd_ean_code());
                    if (db.isOpen()) {
                    } else {
                        open();
                    }
                    db.execSQL("update T_StockSummary set SaleableOut =SaleableOut  +" + replaceproductList.get(j).getQuantity() + ",SaleableBalance= SaleableBalance - " + replaceproductList.get(j).getQuantity() + " where CounterId=" + counter_Id + " and ProductId=" + replaceproductList.get(j).getProduct_Id() + "");
                    l2 = db.insert(CommonString.Table_Consumer_Return_Replace_Product, null, values2);
                }
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString());
        }

        return l2;
    }

    public ArrayList<InvoiceGetterSetter> getsaleReturnHeaderData(String visite_date, String counterId, String user_Id, boolean flag, boolean flagforsequence, String uuid_Id) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (flagforsequence) {
                dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where UNIQUE_CODE='" + uuid_Id + "'", null);

            } else {
                if (flag && user_Id == null) {
                    dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' and UPLOAD_STATUS='N'", null);

                } else if (flag) {
                    dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "' and UPLOAD_STATUS='N'", null);
                } else {
                    dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Header_Data + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null);

                }
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setConsumer_return_bill_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BILL_NO")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setReturn_bill_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("INVOICE_IMG")));
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public long update_leave_management_status(String storeid, String visit_date, String user_Id, String TransId, boolean manual_upload) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();

            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            if (manual_upload) {
                l = db.update(CommonString.Table_Leave_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'and UNIQUE_CODE='" + TransId + "'", null);

            } else {
                l = db.update(CommonString.Table_Leave_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and UNIQUE_CODE='" + TransId + "'", null);

            }


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

    public long update_break_management_status(String storeid, String visit_date, String user_Id, String TransId, boolean manual_upload) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            if (manual_upload) {
                l = db.update(CommonString.Table_Break_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'and UNIQUE_CODE='" + TransId + "'", null);
            } else {
                l = db.update(CommonString.Table_Break_Management, values, CommonString.KEY_COUNTER_ID + "='" + storeid + "' AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and UNIQUE_CODE='" + TransId + "'", null);

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


    public ArrayList<InvoiceGetterSetter> getsalesReturnChildData(int reciept_count, String visite_date, String counterId, String user_Id, boolean flag) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (flag) {
                dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "'", null);

            } else {
                dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null);

            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID")));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY")));
                    sale.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ACTUAL_QTY")));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE")));
                    sale.setTotal_amount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TOTAL_PRICE")));
                    sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE")));
                    sale.setCon_return_reason_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON_ID")));
                    sale.setCon_return_reason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("REASON")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getsalesReturnReplaceProduct(int reciept_count, String visite_date, String counterId, String user_Id, boolean flag) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (flag) {
                dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Replace_Product + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'and USER_ID ='" + user_Id + "'", null);
            } else {
                dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Consumer_Return_Replace_Product + "" + " where RECCEPT_COUNT='" + reciept_count + "' and " + CommonString.KEY_VISIT_DATE + " ='" + visite_date + "' and " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "'", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_ID")));
                    sale.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT")));
                    sale.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QUANTITY")));
                    sale.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PRODUCT_RATE")));
                    sale.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EAN_CODE")));
                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    //check if data exists for product in T_StockSummary
    public boolean isTStockSummaryProductFilled(int productId) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select * from " + CommonString.T_StockSummary + " where " + CommonString.KEY_ProductId + "=" + productId + "", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                int icount = dbcursor.getCount();
                dbcursor.close();
                if (icount > 0) {
                    filled = true;
                } else {
                    filled = false;
                }
            }

        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }

        return filled;
    }

    private long updateTStockData(int stock, String type, int productId, boolean completeFlag, String visit_date) {
        long id = 0;

        ContentValues values = new ContentValues();
        try {

            values.put("VisitDate", visit_date);
            if (type.equalsIgnoreCase(CommonString.SALEABLE)) {
                values.put(CommonString.KEY_SALEABLE_IN, stock);
                values.put(CommonString.KEY_SaleableBalance, stock);
                if (completeFlag) {
                    values.put("SaleableStatus", "Complete");
                }
            } else if (type.equalsIgnoreCase(CommonString.SAMPLE)) {
                values.put(CommonString.KEY_SAMPLE_IN, stock);
                values.put(CommonString.KEY_SampleBalance, stock);
                if (completeFlag) {
                    values.put("SampleStatus", "Complete");
                }

            } else if (type.equalsIgnoreCase(CommonString.TESTER)) {
                values.put(CommonString.KEY_TESTER_IN, stock);
                values.put(CommonString.KEY_TesterBalance, stock);
                if (completeFlag) {
                    values.put("TesterStatus", "Complete");
                }
            } else {
                values.put(CommonString.KEY_GWP_IN, stock);
                values.put(CommonString.KEY_GWP_BALANCE, stock);
                if (completeFlag) {
                    values.put("GwpStatus", "Complete");
                }
            }

            if (!db.isOpen()) {
                open();
            }

            id = db.update(CommonString.T_StockSummary, values, CommonString.KEY_ProductId + "=" + productId + "", null);

        } catch (Exception ex) {
            return 0;
        }

        return id;
    }

    //insert T_Stock_summary row if size zero
    private boolean insertTStockSummaryData(TStockSummary stockObj, Integer productId, String counter_id, String type, int stock, boolean completeFlag, String visitDate) {
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            values.put("Id", stockObj.getId());
            values.put("CounterId", counter_id);
            values.put("ProductId", productId);
            values.put("VisitDate", visitDate);

            values.put("SaleableStatus", stockObj.getSaleableStatus());
            values.put("TesterStatus", stockObj.getTesterStatus());
            values.put("SampleStatus", stockObj.getSampleStatus());
            values.put("GwpStatus", stockObj.getGwpStatus());

            if (type.equalsIgnoreCase(CommonString.SALEABLE)) {
                values.put("SaleableIn", stock);
                values.put("SaleableBalance", stock);
                if (completeFlag) {
                    values.put("SaleableStatus", "Complete");
                }
            } else {
                values.put("SaleableIn", 0);
                values.put("SaleableBalance", 0);
            }

            if (type.equalsIgnoreCase(CommonString.SAMPLE)) {
                values.put("SampleIn", stock);
                values.put("SampleBalance", stock);
                if (completeFlag) {
                    values.put("SampleStatus", "Complete");
                }
            } else {
                values.put("SampleIn", 0);
                values.put("SampleBalance", 0);
            }

            if (type.equalsIgnoreCase(CommonString.TESTER)) {
                values.put("TesterIn", stock);
                values.put("TesterBalance", stock);
                if (completeFlag) {
                    values.put("TesterStatus", "Complete");
                }
            } else {
                values.put("TesterIn", 0);
                values.put("TesterBalance", 0);
            }

            if (type.equalsIgnoreCase(CommonString.GWP)) {
                values.put("GwpIn", stock);
                values.put("GwpBalance", stock);
                if (completeFlag) {
                    values.put("GwpStatus", "Complete");
                }
            } else {
                values.put("GwpIn", 0);
                values.put("GwpBalance", 0);
            }

            values.put("SaleableOut", 0);
            values.put("SaleableDamage", 0);
            values.put("TesterOut", 0);
            values.put("TesterDamage", 0);
            values.put("SampleOut", 0);
            values.put("SampleDamage", 0);
            values.put("GwpOut", 0);
            values.put("GwpDamage", 0);

            if (!db.isOpen()) {
                open();
            }

            long id = db.insert("T_StockSummary", null, values);
            if (id == -1) {
                throw new Exception();
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<LoginGetterSetter> getlistAllUserIdData(String visitDate, String user_id, boolean flag_forspin) {

        ArrayList<LoginGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (flag_forspin) {
                if (visitDate != null) {
                    dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_VISIT_DATE + "<>'" + visitDate + "'and " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null);
                } else {
                    dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null);
                }
            } else {
                if (visitDate != null) {
                    dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_VISIT_DATE + "='" + visitDate + "'and " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null);
                } else {
                    dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_USER_NAME + "='" + user_id + "'", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    LoginGetterSetter ch = new LoginGetterSetter();
                    ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    ch.setImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_IMAGE)));
                    ch.setPassword(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PASSWORD)));
                    ch.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout)));
                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }


    public boolean insertBaProfileValue(MasterBAProfileGetterSetter cst) {
        db.delete("Master_BAProfile", null, null);
        ContentValues values = new ContentValues();
        List<MasterBAProfile> data = cst.getMasterBAProfile();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Answer", data.get(i).getAnswer());
                values.put("AnswerId", data.get(i).getAnswerId());
                values.put("EmpId", data.get(i).getEmpId());
                values.put("QuestionId", data.get(i).getQuestionId());
                values.put("OthersValue", data.get(i).getOthersValue());
                long id = db.insert("Master_BAProfile", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<AuditDataGetterSetter> getSaveServerData(String categoryId, String userId) {
        ArrayList<AuditDataGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {
            dbcursor = db.rawQuery("select distinct mp.QuestionId as QuestionId,mp.Question as Question,mb.AnswerId as AnswerId,mb.Answer as Answer," + "mp.QuestionType as QuestionType" + ",mp.CategoryId as CategoryId,mb.OthersValue as OthersValue from (select distinct QuestionId, Question, QuestionType, CategoryId from Master_ProfileQuestion) as mp " + "inner join Master_BAProfile mb on mp.QuestionId=mb.QuestionId inner join BA_List bl on bl.EmpId=mb.EmpId " + "where mp.CategoryId='" + categoryId + "' and bl.UserName='" + userId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    AuditDataGetterSetter sb = new AuditDataGetterSetter();

                    sb.setQUESTION_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QuestionId")));
                    sb.setQUESTION(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Question")));
                    sb.setANSWER_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AnswerId")));
                    sb.setANSWER(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer")));
                    sb.setMENU_ID(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CategoryId")));
                    sb.setANSWER_TYPE(dbcursor.getString(dbcursor.getColumnIndexOrThrow("QuestionType")));
                    sb.setSpin_others_for_edt(dbcursor.getString(dbcursor.getColumnIndexOrThrow("OthersValue")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    public long update_ba_counter_img(String storeid, String visit_date, String user_Id, String TransId) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);

            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_COUNTER_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + storeid + " AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_Id + "'and UNIQUE_CODE='" + TransId + "'", null);

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

    public JourneyPlan getba_counter_img(String counterId, String visite_date, String user_Id, String TRansId) {
        JourneyPlan sale = new JourneyPlan();
        Cursor dbcursor = null;
        try {

            if (TRansId != null) {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UNIQUE_CODE='" + TRansId + "'", null);

            } else {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UPLOAD_STATUS='N'", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sale.setCounter_img_onefor_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One")));
                    sale.setCounter_img_two_for_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_Two")));
                    sale.setUpload_status_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));

                    sale.setPresetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One")));
                    sale.setPresetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_Two")));
                    sale.setPostsetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_One")));
                    sale.setPostsetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_Two")));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sale;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return sale;
        }
        return sale;
    }


    public ArrayList<JourneyPlan> getba_counterimgList(String counterId, String visite_date, boolean previous_date) {
        ArrayList<JourneyPlan> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (previous_date) {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "<>'" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UPLOAD_STATUS='N'", null);
            } else {
                dbcursor = db.rawQuery("SELECT * from " + CommonString.TABLE_COUNTER_IMAGE_DATA + " WHERE " + CommonString.KEY_VISIT_DATE + "='" + visite_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and UPLOAD_STATUS='N'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    JourneyPlan sale = new JourneyPlan();
                    sale.setCounter_img_onefor_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One")));
                    sale.setCounter_img_two_for_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_Two")));
                    sale.setUpload_status_ba(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setTransId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));

                    sale.setPresetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One")));
                    sale.setPresetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_Two")));
                    sale.setPostsetup_img_one_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_One")));
                    sale.setPostsetup_img_two_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Post_Setup_Img_Two")));
                    sale.setUser_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE)));
                    sale.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    sale.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }

        return list;
    }


    public ArrayList<LoginGetterSetter> getlistLoginData(String visitDate, String user_Id, String counterId) {

        ArrayList<LoginGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (user_Id != null) {
                dbcursor = db.rawQuery("select distinct u.ID as ID,u.PASSWORD as PASSWORD,u.USER_ID as USER_ID,u.Visit_Date as Visit_Date," + "u.STORE_IMAGE as STORE_IMAGE,u.LoginTime as LoginTime,u.RIGHTNAME as RIGHTNAME,u.UserCheckout as UserCheckout," + "u.MPIN as MPIN,b.ProfilePath as ProfilePath,b.Profile_Pic as Profile_Pic from " + "User_login u inner join BA_List b on b.UserName=u.USER_ID where Visit_Date='" + visitDate + "' and u.USER_ID='" + user_Id + "' and b.CounterId=" + counterId + "", null);

            } else {
                dbcursor = db.rawQuery("select distinct u.ID as ID,u.PASSWORD as PASSWORD,u.USER_ID as USER_ID,u.Visit_Date as Visit_Date," + "u.STORE_IMAGE as STORE_IMAGE,u.LoginTime as LoginTime,u.RIGHTNAME as RIGHTNAME,u.UserCheckout as UserCheckout," + "u.MPIN as MPIN,b.ProfilePath as ProfilePath,b.Profile_Pic as Profile_Pic from " + "User_login u inner join BA_List b on b.UserName=u.USER_ID where Visit_Date='" + visitDate + "' and b.CounterId=" + counterId + "", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    LoginGetterSetter ch = new LoginGetterSetter();
                    ch.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    ch.setImg(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_IMAGE)));
                    ch.setUserType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_TYPE)));
                    ch.setMpin(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_MPIN)));
                    ch.setUser_checkout(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_Checkout)));
                    ch.setProfilePath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProfilePath")));
                    ch.setProfile_Pic(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Profile_Pic")));
                    list.add(ch);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public JourneyPlan getspecific_storenamewith_counter_name(String date, String counter_id, String userId) {
        JourneyPlan sb = new JourneyPlan();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * from Mapping_JourneyPlan where VisitDate='" + date + "' and CounterId=" + counter_id + " and UserId='" + userId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    sb.setCounterId((dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId"))));
                    sb.setStoreName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StoreName")));
                    sb.setCounterName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName")));
                    sb.setAddress((dbcursor.getString(dbcursor.getColumnIndexOrThrow("Address"))));
                    sb.setCityName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CityName")));

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return sb;
        }

        return sb;
    }

    public long updateImageLoginData(String userId, String strImg) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put("STORE_IMAGE", strImg);
            if (!db.isOpen()) {
                open();
            }
            l = db.update("User_login", values, "USER_ID='" + userId + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }

    public long updateLoginMpnData(String userId, String mpin) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put("MPIN", mpin);
            values.put("UserCheckout", "0");
            if (!db.isOpen()) {
                open();
            }
            l = db.update("User_login", values, "USER_ID='" + userId + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public ArrayList<ReportTop10Value> gettop10Value(String counterId) {
        Cursor cursordata = null;
        ArrayList<ReportTop10Value> auditData = new ArrayList<>();
        try {
            if (counterId == null) {
                cursordata = db.rawQuery("select * FROM Report_Top10Value", null);
            } else {
                cursordata = db.rawQuery("select * FROM Report_Top10Value where CounterId=" + counterId + "", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportTop10Value sb = new ReportTop10Value();
                    sb.setBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("BrandName")));
                    sb.setSubBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(cursordata.getString(cursordata.getColumnIndexOrThrow("ReferenceName")));
                    sb.setEanCode(cursordata.getString(cursordata.getColumnIndexOrThrow("EanCode")));
                    sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow("ProductName")));
                    sb.setMTDValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("MTDValue"))));
                    sb.setAvgPerDayValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("AvgPerDayValue"))));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }


    public ArrayList<ReportTop10Value> gettop10Valume(String counterId) {
        Cursor cursordata = null;
        ArrayList<ReportTop10Value> auditData = new ArrayList<>();
        try {
            if (counterId == null) {
                cursordata = db.rawQuery("select * FROM Report_Top10Volume", null);
            } else {
                cursordata = db.rawQuery("select * FROM Report_Top10Volume where CounterId=" + counterId + "", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportTop10Value sb = new ReportTop10Value();
                    sb.setBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("BrandName")));
                    sb.setSubBrandName(cursordata.getString(cursordata.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(cursordata.getString(cursordata.getColumnIndexOrThrow("ReferenceName")));
                    sb.setEanCode(cursordata.getString(cursordata.getColumnIndexOrThrow("EanCode")));
                    sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow("ProductName")));
                    sb.setMTDValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("MTDVolume"))));
                    sb.setAvgPerDayValue((cursordata.getDouble(cursordata.getColumnIndexOrThrow("AvgPerDayVolume"))));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }

    public boolean isBreakManagmentEndTymChecked(String visit_date, String user_id, String counter_Id) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery(" SELECT * from BREAK_MANAGEMENT_TABLE WHERE USER_ID='" + user_id + "'and " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String StartTym = dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTym"));
                    String EndTym = dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTym"));
                    if (!StartTym.equals("") && EndTym.equals("")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }
                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    // NEERAJ CODE ADDED
    public ArrayList<ProductMaster> getinwardStockTransactionList(String counter_id, String date) {
        Cursor dbcursor = null;
        ArrayList<ProductMaster> list = new ArrayList<>();
        long id = 0;
        try {
            dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " where " + CommonString.KEY_VISIT_DATE + " <> '" + date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY)));
                    sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY)));
                    sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID)));
                    sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<TCounterInvoice> getManualInwardStockList(String counter_id, String visit_date) {
        ArrayList<TCounterInvoice> list = new ArrayList<>();

        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct " + CommonString.KEY_INVOICE_NUMBER + "," + CommonString.KEY_UPLOAD_STATUS + "," + CommonString.KEY_INVOICE_TYPE + "," + CommonString.KEY_INVOICE_DATE + "," + CommonString.KEY_INVOICE_STATUS + "," + CommonString.KEY_SOURCE + "," + CommonString.KEY_COUNTER_CONFIRM + ",count(" + CommonString.KEY_ProductId + ") as NoofLine,sum(" + CommonString.KEY_TOTAL_AMOUNT + ") as FinalAmount" + " from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "' group by InvoiceNo", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TCounterInvoice sb = new TCounterInvoice();
                    sb.setInvoiceNo(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER)));
                    sb.setInvoiceDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE)));
                    sb.setInvoiceType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE)));
                    sb.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG)));
                    String val = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_CONFIRM));
                    String value = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS));

                    if (val == null || val.equalsIgnoreCase("0")) {
                        sb.setCounterConfirm(false);
                    } else {
                        sb.setCounterConfirm(true);
                    }

                    sb.setApproved_line(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine")));

                    if (value == null || value.equalsIgnoreCase("0")) {
                        sb.setInvoiceStatus(false);
                    } else {
                        sb.setInvoiceStatus(true);
                    }

                    sb.setNo_ofLine(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NoofLine")));
                    sb.setFinalAmount(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FinalAmount")));
                    sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE)));
                    sb.setUpload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS)));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    public void deleteInwardStockData(String counter_id, String visit_date) {
        try {
            if (!db.isOpen()) {
                open();
            }
            db.delete(CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void deleteManualStockData(String counter_id, String visit_date) {
        try {
            if (!db.isOpen()) {
                open();
            }
            db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public GroomingGetterSetter getGroomedList(String counter_Id, String user_Id, String visit_date) {
        GroomingGetterSetter sb = new GroomingGetterSetter();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and " + CommonString.KEY_USER_ID + "='" + user_Id + "'And " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setUser_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    sb.setMorning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img")));
                    sb.setMorning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_time")));
                    sb.setNoon_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img")));
                    sb.setNoon_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_time")));
                    sb.setEvenning_groom_img_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img")));
                    sb.setEvenning_groom_time_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_time")));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }

        return sb;
    }

    public long update_groomed_img(String storeid, String visit_date, String user_Id) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_GROOMED_IMAGE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + storeid + " AND " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND " + CommonString.KEY_USER_ID + "='" + user_Id + "'", null);

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

        return l;
    }

    public boolean isCounterChecked(String visit_date, String counter_Id) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_COUNTER_IMAGE_DATA + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String counterimg_one = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Counter_Img_One"));
                    if (!counterimg_one.equals("")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }
                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }

    public boolean isCounterCheckedforme(String visit_date, String counter_Id) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_COUNTER_IMAGE_DATA + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String counterimg_one = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Pre_Setup_Img_One"));
                    if (!counterimg_one.equals("")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }
                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }

    public String isGroomedChecked(String counter_Id, String user_name, String visit_date) {
        String filled = "";
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_GROOMED_IMAGE_DATA + " where " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and " + CommonString.KEY_USER_ID + "='" + user_name + "'And " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String morng_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mornning_groomed_img"));
                    String noon_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Noon_groomed_img"));
                    String evening_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Evening_groomed_img"));
                    if (!morng_img.equals("") && !noon_img.equals("") && !evening_img.equals("")) {
                        filled = "Green";
                        break;
                    } else if (!morng_img.equals("") && !noon_img.equals("")) {
                        filled = "Amber";
                        break;
                    } else if (!noon_img.equals("") && !evening_img.equals("")) {
                        filled = "Amber";
                        break;
                    } else {
                        filled = "";
                    }

                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    public long updateNotificationDetails(String readStatus, String keyId) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_READ_STATUS, readStatus);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_NOTIFICATION_DATA, values, CommonString.KEY_ID + " ='" + keyId + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }


    public ArrayList<NotificationData> getNotificationList(String userId) {
        ArrayList<NotificationData> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = getReadableDatabase().rawQuery("select * from Notification_Data WHERE ID NOT IN ( SELECT ID FROM Notification_User_Table WHERE  User_Id='" + userId + "')", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    NotificationData notifyData = new NotificationData();
                    notifyData.setId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    notifyData.setBody(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_BODY)));
                    notifyData.setPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_PATH)));
                    notifyData.setTitle(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TITLE)));
                    notifyData.setVisited_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    notifyData.setType(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TYPE)));
                    notifyData.setRead_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_READ_STATUS)));
                    list.add(notifyData);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }

    public boolean insertPromoOffers(MasterBAProfileGetterSetter cst) {
        db.delete("Master_PromoOffers", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromoOffer> data = cst.getMasterPromoOffers();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("PromoId", data.get(i).getPromoId());
                values.put("PromoPath", data.get(i).getPromoPath());
                values.put("PromoOfferTab", data.get(i).getPromoOfferTab());
                values.put("PromoOfferMobile", data.get(i).getPromoOfferMobile());
                values.put("Description", data.get(i).getDescription());
                values.put("StartDate", data.get(i).getStartDate());
                values.put("EndDate", data.get(i).getEndDate());
                if (!db.isOpen()) {
                    open();
                }
                long id = db.insert("Master_PromoOffers", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<MasterPromoOffer> getmaterPromoOffers() {
        ArrayList<MasterPromoOffer> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("Select * from Master_PromoOffers", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterPromoOffer sb = new MasterPromoOffer();
                    sb.setPromoId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId")));
                    sb.setPromoPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoPath")));
                    sb.setPromoOfferTab(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferTab")));
                    sb.setPromoOfferMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferMobile")));

                    sb.setDescription(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Description")));
                    sb.setStartDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartDate")));
                    sb.setEndDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndDate")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public MasterPromoOffer getmaterPromoOffersbypromoId(String promoId) {
        MasterPromoOffer sb = new MasterPromoOffer();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("Select * from Master_PromoOffers where PromoId='" + promoId + "'", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setPromoId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId")));
                    sb.setPromoPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoPath")));
                    sb.setPromoOfferTab(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferTab")));
                    sb.setPromoOfferMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferMobile")));
                    sb.setDescription(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Description")));
                    sb.setStartDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartDate")));
                    sb.setEndDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndDate")));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }

        return sb;
    }

    public int receipt_count_userwise(String visit_date, String counter_Id, String user_name) {
        int filled = 0;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select count(RECCEPT_COUNT) as RECCEPT_COUNT from SALE_TRACKING_HEADER_TABLE " + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + " and USER_ID='" + user_name + "' group by USER_ID", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    filled = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("RECCEPT_COUNT"));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    public boolean isGroomedCheckedfornotification(String visit_date, String counter_Id, String user_Id, String coulmn_name) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * FROM " + CommonString.TABLE_GROOMED_IMAGE_DATA + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + " and " + CommonString.KEY_USER_ID + "='" + user_Id + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String groomed_img = dbcursor.getString(dbcursor.getColumnIndexOrThrow(coulmn_name));
                    if (groomed_img != null && !groomed_img.equals("")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                        break;
                    }
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }

    public boolean isRetailExcellenceFilled(String visit_date, String counter_Id, String user_Id) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * FROM " + CommonString.Table_Retail_Excellence_Child + "" + " where " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' and " + CommonString.KEY_COUNTER_ID + " =" + counter_Id + " and " + "USER_ID" + "='" + user_Id + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String answer = dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer"));
                    if (answer != null && !answer.equals("")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                        break;
                    }
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    public long insertStockTransactionMasterData(String counterId, String visit_date, String userId, String stockType, SaleableGetterSetter stock, String regular_stock) {
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_DATA, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);

        ContentValues values = new ContentValues();
        ContentValues returntoDbvalues = new ContentValues();
        ContentValues values1 = new ContentValues();
        List<ProductMaster> productList = stock.getProductList();
        long masterreturn = 0, l1 = 0, l2 = 0;
        try {
            db.beginTransaction();
            values1.put(CommonString.KEY_UUID, stock.getTransactionId());
            values1.put(CommonString.KEY_USER_ID, userId);
            values1.put(CommonString.KEY_COUNTER_ID, counterId);
            values1.put(CommonString.KEY_VISIT_DATE, visit_date);
            values1.put(CommonString.KEY_STOCK_TYPE, stockType);
            values1.put(CommonString.KEY_ENTRY_TYPE, regular_stock);
            values1.put(CommonString.KEY_STATUS, CommonString.KEY_N);
            if (!db.isOpen()) {
                open();
            }
            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, values1);
            if (stockType != null && stockType.equalsIgnoreCase(CommonString.RETURNTO_DB)) {
                for (int i = 0; i < productList.size(); i++) {
                    returntoDbvalues.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                    returntoDbvalues.put(CommonString.KEY_UUID, stock.getTransactionId());
                    returntoDbvalues.put(CommonString.KEY_USER_ID, userId);
                    returntoDbvalues.put(CommonString.KEY_STOCK_TYPE, stockType);
                    returntoDbvalues.put(CommonString.KEY_COUNTER_ID, counterId);
                    returntoDbvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
                    returntoDbvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                    returntoDbvalues.put(CommonString.KEY_ProductId, productList.get(i).getProductId());
                    returntoDbvalues.put(CommonString.KEY_STOCK, productList.get(i).getStock());
                    if (!db.isOpen()) {
                        open();
                    }
                    l1 = db.insert(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, null, returntoDbvalues);
                }
            } else {
                for (int i = 0; i < productList.size(); i++) {
                    values.put(CommonString.KEY_UUID, stock.getTransactionId());
                    values.put(CommonString.KEY_USER_ID, userId);
                    values.put(CommonString.KEY_COUNTER_ID, counterId);
                    values.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values.put(CommonString.KEY_STOCK_TYPE, stockType);
                    values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
                    values.put(CommonString.KEY_ProductId, productList.get(i).getProductId());
                    values.put(CommonString.KEY_STATUS, CommonString.KEY_N);
                    values.put(CommonString.KEY_REASON_ID, productList.get(i).getReasonId());
                    values.put(CommonString.KEY_IMAGE, productList.get(i).getImagePath());
                    values.put(CommonString.KEY_ENTRY_TYPE, regular_stock);

                    if (stockType.trim().equalsIgnoreCase(CommonString.DAMAGE) && regular_stock.trim().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        if (stock.getProductList().get(i).getStock() == -1) {
                            values.put(CommonString.KEY_STOCK, 0);
                        } else {
                            values.put(CommonString.KEY_STOCK, stock.getProductList().get(i).getStock());
                        }
                    } else if (regular_stock != null && regular_stock.trim().equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        values.put(CommonString.KEY_STOCK, stock.getProductList().get(i).getStock_receive() - stock.getProductList().get(i).getStock());
                    } else {
                        if (stock.getProductList().get(i).getStock() == -1) {
                            values.put(CommonString.KEY_STOCK, 0);
                        } else {
                            values.put(CommonString.KEY_STOCK, stock.getProductList().get(i).getStock());
                        }
                    }
                    if (!db.isOpen()) {
                        open();
                    }
                    l2 = db.insert(CommonString.TABLE_TRANSACTION_DATA, null, values);
                }
            }

            closeDb();
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
        }

        return l2;
    }

    public long updateStockTransactionDataStatus(String transactionId) {
        long l = 0;
        ContentValues values = new ContentValues();
        try {
            values.put(CommonString.KEY_STATUS, CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_TRANSACTION_DATA, values, CommonString.KEY_UUID + "='" + transactionId + "'", null);

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

        }

        return l;

    }

    public long updateVisibilityStatus(String transactionId) {
        long l = 0;
        ContentValues values = new ContentValues();
        try {
            values.put(CommonString.KEY_STATUS, CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.Table_visibilisty, values, CommonString.KEY_UUID + "='" + transactionId + "'", null);

        } catch (Exception ex) {
            ex.fillInStackTrace();
        }
        return l;
    }

    public long updateMasterTransactionDataStatus(String transactionId) {
        long l = 0;
        ContentValues values = new ContentValues();
        try {
            values.put(CommonString.KEY_STATUS, CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, values, CommonString.KEY_UUID + "='" + transactionId + "'", null);

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

        }
        return l;

    }

    public ServerTime getserverTym(String date) {
        ServerTime sb = new ServerTime();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * from ServerTime where ServerDate='" + date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb.setServerDate((dbcursor.getString(dbcursor.getColumnIndexOrThrow("ServerDate"))));
                    sb.setServerTime(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ServerTime")));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return sb;
        }

        return sb;
    }

    //ysy
    public JourneyPlan getJCP() {
        JourneyPlan sb = new JourneyPlan();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * from Mapping_JourneyPlan ", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    sb.setMID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("MID")));
                    sb.setBID(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("BID")));
                    sb.setCounterGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterGroupId")));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }

        } catch (Exception e) {
            ////////test("Exception get JCP!", e.toString());
            return sb;
        }

        return sb;
    }

    public boolean CheckPreviousProduct(String visit_date) {
        Cursor dbcursor = null;
        boolean status = false;
        try {

            dbcursor = db.rawQuery("select * from Product_Master where VisitDate<>'" + visit_date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                int icount = dbcursor.getCount();
                dbcursor.close();

                if (icount > 0) {
                    status = true;
                } else {
                    status = false;
                }
                dbcursor.close();
            }

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

        return status;
    }


    //get Signature Brand Sub Brand and Reference
    public ArrayList<ProductMaster> getDamageBrandSubBrandReference(String counterGroup_Id, String counterId, String visit_date, String damagaged_stock) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (damagaged_stock != null && damagaged_stock.equals("1")) {
                dbcursor = db.rawQuery(" select distinct SubAxeName,SignatureName,BrandName,SubBrandName,ReferenceName from Product_Master p left join " + "(Select  s.CounterId, s.ProductId, (s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance," + " (s.SaleableDamage + ifnull(dm.DamageQty,0)) - ifnull(rd.ReturnQty,0) as SaleableDamage , ifnull(dm.DamageQty,0) as DamageQty," + " ifnull(rd.ReturnQty,0) as ReturnQty  from T_StockSummary s Left join " + "(Select ProductId, sum(DamageQty) as DamageQty from (select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID " + " where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All " + "SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending') as t " + "Group by ProductId) as dm on s.ProductId = dm.ProductId Left Join " + "(Select ProductId, sum(ReturnQty) as ReturnQty from " + "(select ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId=" + counterId + " and VERIFY ='Pending' Union All " + "select  ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID=" + counterId + ") as t " + "Group by ProductId ) as rd on trim(s.ProductId) = trim(rd.ProductId) " + "and s.CounterId ='" + counterId + "') as TS ON TS.ProductId = p.ProductId where (TS.SaleableBalance<>0 OR SaleableDamage<>0)", null);


            } else if (damagaged_stock != null && damagaged_stock.equals("0")) {
                ////for damaged return to distributor Query......
                dbcursor = db.rawQuery("select distinct SubAxeName,SignatureName,BrandName,SubBrandName,ReferenceName from " + "(select SubAxeName,SignatureName,BrandName,SubBrandName,ReferenceName, TS.SaleableDamage, ifnull(RN.ReturnQty,0) as ReturnQty,  TS.SaleableDamage - ifnull(RN.ReturnQty,0) as DamageQty from Product_Master p" + " INNER JOIN T_StockSummary TS ON TS.ProductId = p.ProductId AND TS.SaleableDamage<>0 LEFT JOIN (SELECT ProductId, sum(ReturnQty) as ReturnQty FROM " + "(select  trim(ProductId) as ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId =" + counterId + " and VERIFY ='Pending' Union " + "select  trim(ProductId) as ProductId, Stock as ReturnQty  from TABLE_RETURNTO_DISTRIBUTOR where COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "') AS T " + "GROUP BY ProductId) AS RN ON P.ProductId = RN.ProductId) as t " + "Where DamageQty >0 ", null);


            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    //get damage default data
    //get damage default data
    public ArrayList<ProductMaster> getDefaultDamageChildData(String counterId, String visit_date, String SubBrandName, String ReferenceName, String BrandName, String columnBalance, String damagaged_stock, String counterGroupId) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (damagaged_stock != null && damagaged_stock.equals("1")) {
                dbcursor = db.rawQuery("select p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp,(TS.SaleableDamage +" + " ifnull(dm.DamageQty,0)) - ifnull(rd.ReturnQty,0) as SaleableDamage," + "TS.SaleableBalance - ifnull(dm.DamageQty,0) as SaleableBalance from Product_Master p  INNER JOIN T_StockSummary TS " + "ON trim(TS.ProductId) = trim(p.ProductId) LEFT JOIN (Select ProductId, sum(DamageQty) as DamageQty from " + "(select T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON" + " T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID " + "where  T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All " + " SELECT ProductId, DamageQty from Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending') as t " + "Group by ProductId) as dm on trim(p.ProductId) = trim(dm.ProductId) Left Join (Select ProductId, sum(ReturnQty) as ReturnQty from " + "(select ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId=" + counterId + " and VERIFY ='Pending' Union All " + "select  ProductId, STOCK as ReturnQty from TABLE_RETURNTO_DISTRIBUTOR WHERE  Visit_Date='" + visit_date + "' AND COUNTER_ID=" + counterId + ") as t Group by ProductId) as rd " + "on trim(p.ProductId) = trim(rd.ProductId) " + "Where  p.SubBrandName=trim(\"" + SubBrandName + "\") AND " + "p.ReferenceName=trim(\"" + ReferenceName + "\") AND p.BrandName=trim(\"" + BrandName + "\") AND (TS.SaleableBalance<>0 OR SaleableDamage<>0)", null);


            } else if (damagaged_stock != null && damagaged_stock.equals("0")) {
                ////Qury return to db Child ............................
                dbcursor = db.rawQuery(" select p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode,  p.Mrp as Mrp , TS.SaleableDamage as SaleableDamage," + "ifnull(RN.ReturnQty,0) as ReturnQty,(TS.SaleableDamage - ifnull(RN.ReturnQty,0)) as DamageQty from Product_Master p" + " INNER JOIN T_StockSummary TS ON TS.ProductId = p.ProductId AND TS.SaleableDamage<>0 LEFT JOIN " + "(SELECT ProductId, sum(ReturnQty) as ReturnQty FROM (select  trim(ProductId) as ProductId, ReturnQty from Damage_ReturnToDistributor WHERE CounterId =" + counterId + " and VERIFY ='Pending'" + "Union All select  trim(ProductId) as ProductId, Stock as ReturnQty  from TABLE_RETURNTO_DISTRIBUTOR where COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "') AS T " + "GROUP BY ProductId) AS RN ON P.ProductId = RN.ProductId " + "Where p.SubBrandName=trim(\"" + SubBrandName + "\") AND p.ReferenceName=trim(\"" + ReferenceName + "\") AND" + " p.BrandName=trim(\"" + BrandName + "\") and DamageQty >0", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setImagePath("");
                    if (damagaged_stock != null && damagaged_stock.equals("0")) {
                        ///availeble Damage Stock
                        sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DamageQty")));
                        sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DamageQty")));
                        ///total damage
                        sb.setSaleable_stock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SaleableDamage")));
                        sb.setBlockproductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReturnQty")));

                    } else if (damagaged_stock != null && damagaged_stock.equals("1")) {
                        ////Query for damaged stock
                        sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));
                        sb.setSaleable_stock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("SaleableBalance")));
                        sb.setBlockproductId(0);
                        sb.setStock(0);

                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    //get Signature Brand Sub Brand and Reference
    public ArrayList<ProductMaster> getSubAxe(String counterGroup_Id, boolean normalproducttype) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (normalproducttype) {
                dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master where ProductType='Normal'", null);

            } else {
                dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master where ProductType='GWP'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getSubAxeforinward(String counterGroup_Id) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct SubAxeName from Product_Master", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    //get Function Name - NuanceName
    public ArrayList<ProductMaster> getFunctionName(String counterGroup_Id, String subAxeName, boolean regularstock, String columnName, String counterId, String visit_date) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (regularstock) {
                if (subAxeName.equals("")) {
                    if (columnName.equalsIgnoreCase(CommonString.KEY_SaleableBalance)) {
                        dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join" + " (Select  s.ProductId, (s.SaleableBalance - ifnull(dm.DamageQty,0))  as SaleableBalance" + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId,ProductId,DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT " + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='Saleable' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID,S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId)" + " as TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.ProductType='Normal'", null);

                    } else {
                        dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join T_StockSummary TS" + " ON TS.ProductId = p.ProductId  where TS." + columnName + " >0 and TS.CounterId=" + counterId + " and p.ProductType='Normal'", null);
                    }
                } else {
                    if (columnName.equalsIgnoreCase(CommonString.KEY_SaleableBalance)) {
                        dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join" + " (Select  s.ProductId as ProductId, (s.SaleableBalance - ifnull(dm.DamageQty,0))  as SaleableBalance" + " from T_StockSummary s Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId,ProductId,DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT " + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='Saleable' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID,S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId)" + " as TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.SubAxeName = '" + subAxeName + "'and p.ProductType='Normal'", null);
                    } else {
                        dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS." + columnName + " >0 and p.SubAxeName ='" + subAxeName + "'and TS.CounterId=" + counterId + " and p.ProductType='Normal'", null);
                    }
                }
            } else {
                if (subAxeName.equals("")) {
                    dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master where ProductType='Normal'", null);

                } else {
                    dbcursor = db.rawQuery("select distinct NuanceName from Product_Master where SubAxeName = '" + subAxeName + "' and ProductType='Normal'", null);
                }
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getFunctionMEHeader(String counterGroup_Id, String subAxeName, boolean regularstock, String columnName, String counterId, String visit_date) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (regularstock) {
                if (subAxeName.equals("")) {
                    dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join T_StockSummary TS" + " ON TS.ProductId = p.ProductId  where TS.CounterId=" + counterId + " and p.ProductType='Normal'", null);
                } else {
                    dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where p.SubAxeName ='" + subAxeName + "'and TS.CounterId=" + counterId + " and p.ProductType='Normal'", null);
                }
            } else {
                if (subAxeName.equals("")) {
                    dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master where ProductType='Normal'", null);

                } else {
                    dbcursor = db.rawQuery("select distinct NuanceName from Product_Master where SubAxeName = '" + subAxeName + "' and ProductType='Normal'", null);
                }
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<ProductMaster> getFunctionforFilledName(String counterGroup_Id, String subAxeName, String activity_name) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) {
                if (subAxeName.equals("")) {
                    dbcursor = db.rawQuery("select distinct SubAxeName,NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 ", null);
                } else {
                    dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.SaleableBalance >0 and p.SubAxeName ='" + subAxeName + "'", null);
                }
            } else {
                if (subAxeName.equals("")) {
                    dbcursor = db.rawQuery("select distinct SubAxeName, NuanceName from Product_Master p inner join T_StockSummary TS ON TS.ProductId = p.ProductId where TS.TesterBalance >0 ", null);
                } else {
                    dbcursor = db.rawQuery("select distinct NuanceName from Product_Master p inner join  T_StockSummary TS ON TS.ProductId = p.ProductId where TS.TesterBalance >0 and p.SubAxeName = '" + subAxeName + "'", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    //sb.setAxeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("AxeId")));
                    //sb.setAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AxeName")));
                    sb.setSubAxeName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubAxeName")));
                    sb.setNuanceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("NuanceName")));
                    //sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    //get child on Nuance - Function
    //get stock child default data
    public ArrayList<ProductMaster> getDefaultStockOnFunctionData(String functionName, String columnBalance, String counterId, boolean filledregularstock, String visit_date) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (filledregularstock) {
                if (columnBalance.equalsIgnoreCase(CommonString.KEY_SaleableBalance)) {
                    dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId,p.ProductName as ProductName,p.EanCode as EanCode,p.Mrp as Mrp," + "TS.SaleableBalance as SaleableBalance from" + " Product_Master p left JOIN(Select s.ProductId,(s.SaleableBalance - ifnull(dm.DamageQty,0)) as SaleableBalance from T_StockSummary s" + " Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN  DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId ='" + counterId + "' and Verify ='Pending' Union All" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T2.POS_SALE_FLAG='0' AND T1.INVOICE_TYPE='Saleable' GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select  S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID ,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "' AND S1.POS_SALE_FLAG ='0'" + " GROUP BY S.PROMO_PRODUCT_ID) as t Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId) as" + " TS ON TS.ProductId = p.ProductId Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS.SaleableBalance > 0 order by p.ProductName", null);

                } else {
                    dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId," + " p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p Inner JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + " Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null);
                }
            } else {
                dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN (select * from T_StockSummary where CounterId = " + counterId + ") as  TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') order by p.ProductName", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    if (dbcursor.getString(dbcursor.getColumnIndexOrThrow(columnBalance)) == null) {
                        sb.setStock(-1);
                        sb.setStock_receive(-1);
                    } else {
                        sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));
                        sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));
                    }
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public ArrayList<ProductMaster> getInsertedMEChildData(String functionName, String columnBalance, String visit_date, String counterId) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("SELECT distinct ProductId,UploadStatus,ProductName,SubAxeName,AxeName,STOCK,STOCK_RECEIVED,COUNTER_ID,EanCode,Mrp,SignatureName,BrandName,SubBrandName,ReferenceName FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "='" + counterId + "'AND " + "NuanceName" + "='" + functionName + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setUploadStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UploadStatus")));
                    sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("STOCK")));
                    sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("STOCK")));
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }


    public ArrayList<ProductMaster> getDefaultMESaleFunctionData(String functionName, String columnBalance, String counterId, boolean filledregularstock, String visit_date) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (filledregularstock) {
                dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId," + " p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p Inner JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + " Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null);
            } else {
                dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN (select * from T_StockSummary where CounterId = " + counterId + ") as  TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') order by p.ProductName", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setStock(0);
                    sb.setStock_receive(0);
                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public ArrayList<ProductMaster> getDefaultStockOnFunctionDataforFilled(String functionName, String counterId, String activity_name) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String columnBalance = "";
            if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) {
                columnBalance = CommonString.KEY_SaleableBalance;
                dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId, p.ProductName as ProductName, p.EanCode as EanCode," + " p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType = 'Normal' and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null);

            } else {
                columnBalance = CommonString.KEY_TesterBalance;
                dbcursor = db.rawQuery("select distinct p.SignatureName as SignatureName,p.BrandName as BrandName,p.SubBrandName as SubBrandName," + "p.ReferenceName as ReferenceName,p.ProductId as ProductId," + " p.ProductName as ProductName, p.EanCode as EanCode, p.Mrp as Mrp, TS." + columnBalance + " from Product_Master p " + " LEFT JOIN T_StockSummary TS ON TS.ProductId = p.ProductId " + "Where p.NuanceName=trim(\"" + functionName + "\") AND p.ProductType =trim('Normal') and TS." + columnBalance + " > 0 and TS.CounterId=" + counterId + " order by p.ProductName", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Mrp")));
                    if (dbcursor.getString(dbcursor.getColumnIndexOrThrow(columnBalance)) == null) {
                        sb.setStock(-1);
                        sb.setStock_receive(-1);
                    } else {
                        sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));
                        sb.setStock_receive(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(columnBalance)));
                    }

                    sb.setSignatureName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SignatureName")));
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BrandName")));
                    sb.setSubBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SubBrandName")));
                    sb.setReferenceName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ReferenceName")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<TStockSummary> getStockCheckReport(String visit_date, String counterId, boolean me, String column_name) {
        ArrayList<TStockSummary> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String query = "Select " + column_name + ", sum(SaleableBalance) as StockQty, sum(StockValue) as StockValue from (" + " Select s.ProductId as ProductId,  pm." + column_name + " as " + column_name + ", pm.Mrp as Mrp, " + "(ifnull(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) as SaleableBalance," + " IFNULL(pm.Mrp,0)*(IFNULL(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) As StockValue from" + " T_StockSummary s inner join Product_Master pm on s.ProductId = pm.ProductId left join (Select CounterId, ProductId," + " sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty  from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT CounterId, ProductId, DamageQty from Damage_PreviousPending  Where CounterId =" + counterId + " and Verify ='Pending') as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId Where s.SaleableBalance>0 and s.CounterId = " + counterId + ") as t group by " + column_name;
            if (me) {
                query = "Select distinct VisitDate as " + column_name + ",CounterName,CounterCode from Report_MTD_WorkingCounterME";
            }

            dbcursor = db.rawQuery(query, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TStockSummary sb = new TStockSummary();
                    sb.setBrand_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    if (me) {
                        sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName")));
                        sb.setGwpStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterCode")));
                    } else {
                        sb.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockQty")));
                        sb.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockValue")));
                    }
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public TStockSummary getStockCheckTotalStockWithQty(String visit_date, String counterId) {
        TStockSummary list = new TStockSummary();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT sum(ifnull(T3.StockQty,0)) as StockQty, sum(ifnull(StockValue,0)) as StockValue FROM" + " (Select NuanceName, sum(SaleableBalance) as StockQty, sum(StockValue) as StockValue from (" + " Select s.ProductId,  pm.NuanceName, pm.Mrp, (ifnull(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) as SaleableBalance," + " IFNULL(pm.Mrp,0)*(IFNULL(s.SaleableBalance,0) - ifnull(dm.DamageQty,0)) As StockValue from" + " T_StockSummary s inner join Product_Master pm on s.ProductId = pm.ProductId left join (Select CounterId, ProductId," + " sum(DamageQty) as DamageQty from (select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty  from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M" + " ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT  CounterId, ProductId, DamageQty from Damage_PreviousPending  Where CounterId =" + counterId + " and Verify ='Pending') as t" + " Group by CounterId, ProductId) as dm on s.ProductId = dm.ProductId Where s.SaleableBalance>0 and s.CounterId =" + counterId + " ) as t group by NuanceName) AS T3", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    list.setStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockQty")));
                    list.setMrp(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("StockValue")));

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }


    public TStockSummary gettesterstock(String counterId) {
        TStockSummary list = new TStockSummary();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select sum(ifnull(TS.TesterBalance,0)) as TesterBalance from Product_Master PM" + " Inner Join T_StockSummary TS on TS.ProductId=PM.ProductId where TS.TesterBalance >0 And TS.CounterId=" + counterId, null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    list.setTesterBalance(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TesterBalance")));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    //get filter list according to SubAxe
    public ArrayList<ProductMaster> getsub_brand_name(String counterGroup_Id, String column_name, boolean GWPFlag, String subAxe) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        if (!db.isOpen()) open();
        try {
            if (GWPFlag) {
                dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='GWP'", null);
            } else {
                if (subAxe.equals("")) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='Normal' ", null);
                } else {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType =trim('Normal')" + " AND SubAxeName=trim(\"" + subAxe + "\")", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getSubBrandOrReference(String counterGroup_Id, String column_name, String signatureName, String brandName, String subBrand, boolean GWPFlag, String subAxe) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String productType = "Normal";
            if (GWPFlag) {
                productType = "Gwp";
            }

            if (subAxe.equals("")) {
                if (signatureName == null) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType ='" + productType + "'", null);

                } else if (column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SubBrandName =trim(\"" + subBrand + "\") and ProductType =trim('" + productType + "')", null);
                } else if (brandName != null) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " BrandName =trim(\"" + brandName + "\") and ProductType =trim('" + productType + "')", null);
                } else {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SignatureName =trim(\"" + signatureName + "\") and ProductType =trim('" + productType + "')", null);
                }

            } else {
                if (signatureName == null) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where ProductType =trim('" + productType + "')" + " and SubAxeName=trim(\"" + subAxe + "\")", null);
                } else if (column_name.trim().equalsIgnoreCase("ReferenceName") && subBrand != null) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where SubBrandName =trim(\"" + subBrand + "\") and" + " ProductType =trim('" + productType + "') and SubAxeName=trim(\"" + subAxe + "\")", null);
                } else if (brandName != null) {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " BrandName =trim(\"" + brandName + "\") and ProductType =trim('" + productType + "') and SubAxeName=trim(\"" + subAxe + "\")", null);
                } else {
                    dbcursor = db.rawQuery("select distinct " + column_name + " from Product_Master where" + " SignatureName =trim(\"" + signatureName + "\") and ProductType =trim('" + productType + "') and SubAxeName=trim(\"" + subAxe + "\")", null);
                }
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setBrandName(dbcursor.getString(dbcursor.getColumnIndexOrThrow(column_name)));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }
        return list;
    }


    public boolean insertreport_attendence_details(MasterBAProfileGetterSetter cst) {
        db.delete("Report_AttendanceDetail", null, null);
        ContentValues values = new ContentValues();
        List<ReportAttendanceDetail> data = cst.getReportAttendanceDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("BAName", data.get(i).getBAName());
                values.put("BAUserId", data.get(i).getBAUserId());
                values.put("AttDate", data.get(i).getAttDate());
                values.put("Attendance", data.get(i).getAttendance());
                long id = db.insert("Report_AttendanceDetail", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportAttendanceDetail> getAttendanceDetails() {
        Cursor cursordata = null;
        ArrayList<ReportAttendanceDetail> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select * FROM Report_AttendanceDetail order by AttDate desc", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportAttendanceDetail sb = new ReportAttendanceDetail();
                    sb.setBAName(cursordata.getString(cursordata.getColumnIndexOrThrow("BAName")));
                    sb.setBAUserId(cursordata.getString(cursordata.getColumnIndexOrThrow("BAUserId")));
                    sb.setAttDate(cursordata.getString(cursordata.getColumnIndexOrThrow("AttDate")));
                    sb.setAttendance(cursordata.getString(cursordata.getColumnIndexOrThrow("Attendance")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }


    public boolean insertreport_attendence_summery(MasterBAProfileGetterSetter cst) {
        db.delete("Report_AttendanceSummary", null, null);
        ContentValues values = new ContentValues();
        List<ReportAttendanceSummary> data = cst.getReportAttendanceSummary();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("AttendanceStatus", data.get(i).getAttendanceStatus());
                values.put("LastMonth", data.get(i).getLastMonth());
                values.put("MTD", data.get(i).getMTD());
                long id = db.insert("Report_AttendanceSummary", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportAttendanceSummary> getAttendanceSummary() {
        Cursor cursordata = null;
        ArrayList<ReportAttendanceSummary> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select * FROM Report_AttendanceSummary order by AttendanceStatus", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportAttendanceSummary sb = new ReportAttendanceSummary();
                    sb.setAttendanceStatus(cursordata.getString(cursordata.getColumnIndexOrThrow("AttendanceStatus")));
                    sb.setLastMonth(cursordata.getInt(cursordata.getColumnIndexOrThrow("LastMonth")));
                    sb.setMTD(cursordata.getInt(cursordata.getColumnIndexOrThrow("MTD")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }

    public ArrayList<MasterLook> getlook_creation() {
        Cursor cursordata = null;
        ArrayList<MasterLook> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select * FROM Master_Looks", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterLook sb = new MasterLook();
                    sb.setLooks(cursordata.getString(cursordata.getColumnIndexOrThrow("Looks")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }


    public boolean insertreport_inword_stock_summery(MasterBAProfileGetterSetter cst) {
        db.delete("Report_InwardStockSummary", null, null);
        ContentValues values = new ContentValues();
        List<ReportInwardStockSummary> data = cst.getReportInwardStockSummary();
        try {
            if (data.isEmpty()) {
                return false;
            }

            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("InvoiceNo", data.get(i).getInvoiceNo());
                values.put("InvoiceDate", data.get(i).getInvoiceDate());
                values.put("InvoiceType", data.get(i).getInvoiceType());
                values.put("Source", data.get(i).getSource());
                values.put("InvoiceValue", data.get(i).getInvoiceValue());
                values.put("TotalLine", data.get(i).getTotalLine());
                values.put("ConfirmLine", data.get(i).getConfirmLine());
                values.put("PendingLine", data.get(i).getPendingLine());
                long id = db.insert("Report_InwardStockSummary", null, values);

                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportInwardStockSummary> getinwordStockSummary(String counterId) {
        Cursor cursordata = null;
        ArrayList<ReportInwardStockSummary> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select * FROM Report_InwardStockSummary", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportInwardStockSummary sb = new ReportInwardStockSummary();
                    sb.setInvoiceNo(cursordata.getString(cursordata.getColumnIndexOrThrow("InvoiceNo")));
                    sb.setInvoiceDate(cursordata.getString(cursordata.getColumnIndexOrThrow("InvoiceDate")));
                    sb.setInvoiceType(cursordata.getString(cursordata.getColumnIndexOrThrow("InvoiceType")));
                    sb.setSource(cursordata.getString(cursordata.getColumnIndexOrThrow("Source")));
                    sb.setInvoiceValue(cursordata.getDouble(cursordata.getColumnIndexOrThrow("InvoiceValue")));
                    sb.setTotalLine((cursordata.getInt(cursordata.getColumnIndexOrThrow("TotalLine"))));
                    sb.setConfirmLine((cursordata.getInt(cursordata.getColumnIndexOrThrow("ConfirmLine"))));
                    sb.setPendingLine((cursordata.getInt(cursordata.getColumnIndexOrThrow("PendingLine"))));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {

        }
        return auditData;
    }


    public ArrayList<TStockSummary> getreport_tester_stock(String counterId, String column) {
        Cursor cursordata = null;
        ArrayList<TStockSummary> auditData = new ArrayList<>();
        try {

            if (counterId == null) {
                cursordata = db.rawQuery("select distinct sum(ifnull(TesterBalance,0)) as TesterBalance," + column + " from Product_Master" + " PM Inner Join T_StockSummary TS on TS.ProductId=PM.ProductId where TesterBalance>0 GROUP by " + column, null);
            } else {
                cursordata = db.rawQuery("select distinct sum(ifnull(TesterBalance,0)) as TesterBalance," + column + " from Product_Master" + " PM Inner Join T_StockSummary TS on TS.ProductId=PM.ProductId where TesterBalance>0 and TS.CounterId=" + counterId + " GROUP by " + column, null);
            }


            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    TStockSummary sb = new TStockSummary();
                    sb.setTesterBalance(cursordata.getInt(cursordata.getColumnIndexOrThrow("TesterBalance")));
                    sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow(column)));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

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

        return auditData;
    }

    public boolean insert_ba_availability(MasterBAProfileGetterSetter cst) {
        db.delete("Report_BA_Availability", null, null);
        ContentValues values = new ContentValues();
        List<ReportBAAvailability> data = cst.getReportBAAvailability();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Date", data.get(i).getDate());
                values.put("BudgetedMandays", data.get(i).getBudgetedMandays());
                values.put("AchievedMandays", data.get(i).getAchievedMandays());
                values.put("TotalTime", data.get(i).getTotalTime());
                long id = db.insert("Report_BA_Availability", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insert_master_look(MasterBAProfileGetterSetter cst) {
        db.delete("Master_Looks", null, null);
        ContentValues values = new ContentValues();
        List<MasterLook> data = cst.getMasterLooks();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Looks", data.get(i).getLooks());
                long id = db.insert("Master_Looks", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insert_me_audit_question(MasterBAProfileGetterSetter cst) {
        db.delete("ME_MEAuditQuestion", null, null);
        ContentValues values = new ContentValues();
        List<MEMEAuditQuestion> data = cst.getMEMEAuditQuestion();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CategoryId", data.get(i).getCategoryId());
                values.put("Category", data.get(i).getCategory());
                values.put("AuditType", data.get(i).getAuditType());
                values.put("QuestionId", data.get(i).getQuestionId());
                values.put("Question", data.get(i).getQuestion());
                values.put("QuestionType", data.get(i).getQuestionType());
                values.put("AnswerId", data.get(i).getAnswerId());
                values.put("Answer", data.get(i).getAnswer());
                values.put("QuizId", data.get(i).getQuizId());
                values.put("QuizName", data.get(i).getQuizName());
                values.put("ImageAllow", data.get(i).getImageAllow());
                long id = db.insert("ME_MEAuditQuestion", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insert_me_quizuploadstatus(MasterBAProfileGetterSetter cst) {
        db.delete("ME_MEAuditQuestion_UploadStatus", null, null);
        ContentValues values = new ContentValues();
        List<MEMEAuditQuestionUploadstatus> data = cst.getMEMEAuditQuestionUploadStatus();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("QuizId", data.get(i).getQuizId());
                values.put("EmpId", data.get(i).getEmpId());
                values.put("UploadStatus", data.get(i).getUploadStatus());
                long id = db.insert("ME_MEAuditQuestion_UploadStatus", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<ReportBAAvailability> getreport_ba_availability() {
        Cursor cursordata = null;
        ArrayList<ReportBAAvailability> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select * from Report_BA_Availability order by Date desc", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportBAAvailability sb = new ReportBAAvailability();
                    sb.setDate(cursordata.getString(cursordata.getColumnIndexOrThrow("Date")));
                    sb.setBudgetedMandays(cursordata.getInt(cursordata.getColumnIndexOrThrow("BudgetedMandays")));
                    sb.setAchievedMandays(cursordata.getInt(cursordata.getColumnIndexOrThrow("AchievedMandays")));
                    sb.setTotalTime(cursordata.getInt(cursordata.getColumnIndexOrThrow("TotalTime")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

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

        return auditData;
    }

    public ArrayList<ReportMESale> getreportMeSale() {
        Cursor cursordata = null;
        ArrayList<ReportMESale> auditData = new ArrayList<>();
        try {
            cursordata = db.rawQuery("select * from Report_ME_Sale order by VisitDate DESC", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ReportMESale sb = new ReportMESale();
                    sb.setVisitDate(cursordata.getString(cursordata.getColumnIndexOrThrow("VisitDate")));
                    sb.setCounterCode(cursordata.getString(cursordata.getColumnIndexOrThrow("CounterCode")));
                    sb.setCounterName(cursordata.getString(cursordata.getColumnIndexOrThrow("CounterName")));
                    sb.setTotalsale(cursordata.getDouble(cursordata.getColumnIndexOrThrow("TotalSale")));
                    sb.setTotalunitsale(cursordata.getInt(cursordata.getColumnIndexOrThrow("TotalUnitSale")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }
        } catch (Exception ex) {
            ex.fillInStackTrace();
        }
        return auditData;
    }

    public void update_tstock_summery_using_consumer_return(String counterId, String product_Id, String productQty, String invoiceType) {
        try {
            if (!db.isOpen()) {
                open();
            }

            if (!invoiceType.equals("") && invoiceType.trim().equalsIgnoreCase("Damaged")) {
                db.execSQL("update T_StockSummary set SaleableDamage = SaleableDamage + " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id + "");
            } else {
                db.execSQL("update T_StockSummary set SaleableBalance = SaleableBalance + " + productQty + " where CounterId=" + counterId + " and ProductId=" + product_Id + "");
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public boolean ischeck_login_data(String user_id) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select * from User_login where " + CommonString.KEY_USER_NAME + " ='" + user_id + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_NAME));
                    if (user_idget != null && !user_idget.equals("")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }
                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    public ArrayList<T_LeaveRequest> get_leave_List(String user_id, String visit_date, boolean flag) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<T_LeaveRequest> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (flag) {
                dbcursor = db.rawQuery("select RequestDate, UserId, FromDate, ToDate, LeaveStatus,LeaveType,LeaveTypeDesc from T_LeaveRequest where UserId ='" + user_id +
                        "' order by RequestDate asc, FromDate desc", null);
            } else {
                dbcursor = db.rawQuery("select d.Visit_Date as RequestDate,  d.USER_ID as UserId, d.From_Date as FromDate, d.To_Date as ToDate," +
                        " ifnull(t.LeaveStatus, 'Pending') as LeaveStatus, d.One_Day_Leave as LeaveType, d.LeaveType as LeaveTypeDesc " +
                        "  from (select * from LEAVE_MANAGEMENT_TABLE  where  USER_ID='" + user_id + "' and Visit_Date='" + visit_date +
                        "' ) as d left join " + "(select * from T_LeaveRequest where UserId ='" + user_id + "' and  RequestDate ='" + visit_date + "') as t " +
                        "on d.USER_ID = t.UserId and d.Visit_Date = t.RequestDate and d.From_Date = t.FromDate " + "and d.To_Date = t.ToDate Union " +
                        "select RequestDate, UserId, FromDate, ToDate, LeaveStatus,LeaveType,LeaveTypeDesc from T_LeaveRequest where UserId ='" + user_id + "' and  RequestDate<>'"
                        + visit_date + "' order by RequestDate asc, From_Date desc", null);
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    T_LeaveRequest sb = new T_LeaveRequest();
                    sb.setRequestDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("RequestDate")));
                    sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FromDate")));
                    sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ToDate")));
                    sb.setLeaveStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveStatus")));
                    sb.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UserId")));

                    String onedayleaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"));
                    if (!onedayleaveType.equals("")) {
                        String leaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveTypeDesc"));
                        sb.setStr_leaveType(leaveType + " - " + onedayleaveType);
                    } else {
                        sb.setStr_leaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveTypeDesc")));
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }

        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }

    public ArrayList<T_LeaveRequest> getinserted_leave_requestList(String storeid, String user_id, String visit_date, String upload_status) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<T_LeaveRequest> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (upload_status != null) {
                dbcursor = db.rawQuery("select * From LEAVE_MANAGEMENT_TABLE where " + CommonString.KEY_COUNTER_ID + "=" + storeid + " and " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'and UPLOAD_STATUS='N'", null);

            } else {
                dbcursor = db.rawQuery("select * From LEAVE_MANAGEMENT_TABLE where " + CommonString.KEY_COUNTER_ID + "=" + storeid + " and " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "'AND USER_ID='" + user_id + "'", null);

            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    T_LeaveRequest sb = new T_LeaveRequest();
                    sb.setRequestDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Request_Date")));
                    sb.setFromDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("From_Date")));
                    sb.setToDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("To_Date")));
                    sb.setUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sb.setUpload_request_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));

                    String onedayleaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("One_Day_Leave"));
                    if (!onedayleaveType.equals("")) {
                        String leaveType = dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType"));
                        sb.setStr_leaveType(leaveType + " - " + onedayleaveType);
                    } else {
                        sb.setStr_leaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")));
                    }

                    list.add(sb);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception ", "when fetching opening stock!!!!!!!!!!!" + e.toString());
            return list;
        }
        ////////test("Fetching ", "opening stock---------------------->Stop<-----------");
        return list;
    }


    public long deleteManualStockWithKeyIdData(String counter_id, String visit_date, String keyId) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            l = db.delete(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'and " + CommonString.KEY_ID + "='" + keyId + "'", null);

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


    public long updateTStockSaleableDamageReturnData() {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            l = db.delete(CommonString.TABLE_DAMAGED_CHILD_DATA, null, null);

        } catch (Exception ex) {
            //return 0;
        }
        return l;
    }


    public long updateStockSummaryDamageValue(int product_id, int damagedQty, String counterId) {
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            if (!db.isOpen()) open();
            values.put(CommonString.KEY_SaleableDamage, damagedQty);
            id = db.update(CommonString.T_StockSummary, values, CommonString.KEY_ProductId + "=" + product_id + " and CounterId=" + counterId + "", null);
        } catch (Exception ex) {
            return 0;
        }
        return id;
    }


    public long updateT_CounterInvoiceConfirmCounter(String invId, int ProductId) {
        long id = 0;
        ContentValues values = new ContentValues();
        try {
            values.put(CommonString.KEY_COUNTER_CONFIRM, "1");
            if (!db.isOpen()) open();
            id = db.update(CommonString.KEY_TABLE_T_CounterInvoice, values, CommonString.KEY_INVOICE_ID + "='" + invId + "' And ProductId=" + ProductId + "", null);
        } catch (Exception ex) {
            return 0;
        }
        return id;
    }


    public ArrayList<InvoiceGetterSetter> getMakeoverCaptureByUserMobile(int reciept_count, String mobile_no, String visite_date, String counterId, String user_Id) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (mobile_no == null) {
                dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null);

            } else {
                dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE CONTACT_NUMBER='" + mobile_no + "'" + "and Visit_Date ='" + visite_date + "' and " + CommonString.KEY_ID + "=" + reciept_count + " and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    if (dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")).equals("1")) {
                        sale.setPos_sale_flag(true);
                    } else {
                        sale.setPos_sale_flag(false);
                    }

                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG")));
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID")));
                    sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE")));
                    sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE")));
                    sale.setLook_creater_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOOk")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setBefore_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BEFORE_MAKEOVER_IMG")));
                    sale.setAfter_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AFTER_MAKEOVER_IMG")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setCst_feed_back_value(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FEEDBACK")));
                    sale.setUserName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getMakeover(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (manual_upload) {
                dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE COUNTER_ID =" + counterId + " and POS_SALE_FLAG ='1' " + "and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null);

            } else {
                if (user_Id == null) {
                    dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and POS_SALE_FLAG='1'", null);

                } else {
                    dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null);
                }
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    if (dbcursor.getString(dbcursor.getColumnIndexOrThrow("POS_SALE_FLAG")).equals("1")) {
                        sale.setPos_sale_flag(true);
                    } else {
                        sale.setPos_sale_flag(false);
                    }

                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG")));
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID")));
                    sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE")));
                    sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE")));
                    sale.setLook_creater_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOOk")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setBefore_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BEFORE_MAKEOVER_IMG")));
                    sale.setAfter_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AFTER_MAKEOVER_IMG")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setCst_feed_back_value(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FEEDBACK")));
                    sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getskinGeniusData(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (manual_upload) {
                dbcursor = db.rawQuery("SELECT * FROM SKIN_GENIUS_TABLE WHERE COUNTER_ID =" + counterId + " and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null);

            } else {
                if (user_Id == null) {
                    dbcursor = db.rawQuery("SELECT * FROM SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + "", null);

                } else {
                    dbcursor = db.rawQuery("SELECT * FROM SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null);
                }
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_RECCEPT_NUMBER)));
                    sale.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_GENIUS_IMG")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CAPTURED_TIME")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getOpenskinGeniusData(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (manual_upload) {
                dbcursor = db.rawQuery("SELECT * FROM OPEN_SKIN_GENIUS_TABLE WHERE COUNTER_ID =" + counterId + " and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null);

            } else {
                if (user_Id == null) {
                    dbcursor = db.rawQuery("SELECT * FROM OPEN_SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + "", null);

                } else {
                    dbcursor = db.rawQuery("SELECT * FROM OPEN_SKIN_GENIUS_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null);
                }
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_RECCEPT_NUMBER)));
                    sale.setMaybellineorskingenius_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("OPENSKIN_GENIUS_COUNT")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getOpenMaybellineData(String visite_date, String counterId, String user_Id, String transId, boolean manual_upload) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (manual_upload) {
                dbcursor = db.rawQuery("SELECT * FROM OPEN_MAYBELLINE_TABLE WHERE COUNTER_ID =" + counterId + " and UPLOAD_STATUS='N' and UNIQUE_CODE='" + transId + "'", null);

            } else {
                if (user_Id == null) {
                    dbcursor = db.rawQuery("SELECT * FROM OPEN_MAYBELLINE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + "", null);

                } else {
                    dbcursor = db.rawQuery("SELECT * FROM OPEN_MAYBELLINE_TABLE WHERE Visit_Date='" + visite_date + "' and COUNTER_ID =" + counterId + " and USER_ID ='" + user_Id + "'", null);
                }
            }


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_RECCEPT_NUMBER)));
                    sale.setMaybellineorskingenius_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("OPEN_MAYBELLINE_COUNT")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getMakeoverCapture(String visite_date, String counterId) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT * FROM MAKEOVER_CAPTURE_TABLE WHERE COUNTER_ID=" + counterId + " and Visit_Date ='" + visite_date + "'and POS_SALE_FLAG='1' and UPLOAD_STATUS='N'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sale = new InvoiceGetterSetter();
                    sale.setReccept_count(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sale.setStr_termcondition(dbcursor.getString(dbcursor.getColumnIndexOrThrow("TERMCONDITION_FLAG")));
                    sale.setCustomer_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BUYER_NAME")));
                    sale.setMobile_no(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CONTACT_NUMBER")));
                    sale.setConsumer_email_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EMAIL_ID")));
                    sale.setConsumer_age(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AGE")));
                    sale.setConsumer_skinType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SKIN_TYPE")));
                    sale.setLook_creater_str(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LOOk")));
                    sale.setStr_upload_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UPLOAD_STATUS")));
                    sale.setCustomer_gender(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GENDER")));
                    sale.setBefore_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BEFORE_MAKEOVER_IMG")));
                    sale.setAfter_makeover_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow("AFTER_MAKEOVER_IMG")));
                    sale.setUnique_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("UNIQUE_CODE")));
                    sale.setStrUserId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("USER_ID")));
                    sale.setCst_feed_back_value(dbcursor.getString(dbcursor.getColumnIndexOrThrow("FEEDBACK")));

                    list.add(sale);

                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            ////////test("Exception Brands", e.toString());
            return list;
        }

        return list;
    }


    public ArrayList<MEMEAuditQuestion> getAuditQuestionCategoryDataNew(String quizId) {
        Cursor cursordata = null;
        ArrayList<MEMEAuditQuestion> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("Select Distinct CategoryId,Category from ME_MEAuditQuestion where QuizId=" + quizId + "", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();

                    sb.setCategoryId(cursordata.getInt(cursordata.getColumnIndexOrThrow("CategoryId")));
                    sb.setCategory(cursordata.getString(cursordata.getColumnIndexOrThrow("Category")).trim());

                    auditData.add(sb);

                    cursordata.moveToNext();
                }

                cursordata.close();
            }

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

        return auditData;

    }

    public ArrayList<MasterRetailExcellence> getRetailExcellenceData() {
        Cursor cursordata = null;
        ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList = new ArrayList<>();
        try {
            cursordata = db.rawQuery("Select Distinct ItemCategoryId,ItemCategoryName from Master_RetailExcellence_Item", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterRetailExcellence sb = new MasterRetailExcellence();

                    sb.setItemCatId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemCategoryId")));
                    sb.setItemCatName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemCategoryName")).trim());

                    masterRetailExcellenceArrayList.add(sb);

                    cursordata.moveToNext();
                }

                cursordata.close();
            }

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

        return masterRetailExcellenceArrayList;

    }


    public ArrayList<MEMEAuditQuestion> getMeQuiz() {
        Cursor cursordata = null;
        ArrayList<MEMEAuditQuestion> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("Select Distinct QuizId,QuizName from ME_MEAuditQuestion", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setQuizId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuizId")));
                    sb.setQuizName(cursordata.getString(cursordata.getColumnIndexOrThrow("QuizName")));

                    auditData.add(sb);

                    cursordata.moveToNext();
                }

                cursordata.close();
            }

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

        return auditData;

    }


    public ArrayList<MEMEAuditQuestion> getAuditCategoryWiseDataNew(int categoryID, String quizId) {
        Cursor cursordata = null;

        ArrayList<MEMEAuditQuestion> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("Select distinct Question,QuestionId,QuestionType from ME_MEAuditQuestion where CategoryId =" + categoryID + " and QuizId=" + quizId + "", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setQuestion(cursordata.getString(cursordata.getColumnIndexOrThrow("Question")).trim());
                    sb.setQuestionId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuestionId")));
                    sb.setQuestionType(cursordata.getString(cursordata.getColumnIndexOrThrow("QuestionType")));
                    sb.setAnswer("");
                    sb.setAnswerId(0);
                    sb.setStr_audit_img("");
                    sb.setImageAllow(false);
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in  " + ex);
        }
        return auditData;
    }

    public ArrayList<MasterRetailExcellence> getRetailCategoryWiseDataNew(int ItemCategoryId) {
        Cursor cursordata = null;

        ArrayList<MasterRetailExcellence> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("Select distinct ItemId,ItemName from Master_RetailExcellence_Item where ItemCategoryId =" + ItemCategoryId + "", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterRetailExcellence sb = new MasterRetailExcellence();
                    sb.setItemName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemName")).trim());
                    sb.setItemId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemId")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in  " + ex.toString());
        }
        return auditData;
    }

    public ArrayList<MEMEAuditQuestion> getAuditAnswerDataNew(MEMEAuditQuestion auditGetSet, String select) {
        ArrayList<MEMEAuditQuestion> list = new ArrayList<>();
        if (auditGetSet.getQuestionType().equalsIgnoreCase("List Single Choice")) {
            MEMEAuditQuestion sb1 = new MEMEAuditQuestion();
            sb1.setAnswerId(0);
            sb1.setAnswer(select);
            list.add(0, sb1);
        } else if (auditGetSet.getQuestionType().equalsIgnoreCase("Text")) {
            MEMEAuditQuestion sb1 = new MEMEAuditQuestion();
            sb1.setAnswerId(0);
            sb1.setAnswer("");
            list.add(0, sb1);
        }
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select * from ME_MEAuditQuestion where QuestionId =" + auditGetSet.getQuestionId() + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setAnswerId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("AnswerId")));
                    sb.setAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Answer")));
                    String img_allow = dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImageAllow"));
                    sb.setImageAllow(img_allow.equals("1"));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    public long insertRetailExcellence_data(String counter_Id, String visit_Date, String userId, ArrayList<MasterRetailExcellence> savelistheader, HashMap<MasterRetailExcellence, ArrayList<MasterRetailExcellence>> data, MasterRetailExcellence obj, String unique_code) {
        long l = 0, lf = 0;
        try {
            db.delete(CommonString.Table_Retail_Excellence_Header, CommonString.KEY_VISIT_DATE + " ='" + visit_Date + "'", null);
            db.delete(CommonString.Table_Retail_Excellence_Child, CommonString.KEY_VISIT_DATE + " ='" + visit_Date + "'", null);
            ContentValues values = new ContentValues();
            ContentValues valuesproduct = new ContentValues();
            db.beginTransaction();
            for (int i = 0; i < savelistheader.size(); i++) {
                values.put("USER_ID", userId);
                values.put("UNIQUE_CODE", unique_code);
                values.put(CommonString.KEY_COUNTER_ID, counter_Id);
                values.put(CommonString.KEY_VISIT_DATE, visit_Date);
                values.put("UPLOAD_STATUS", CommonString.KEY_N);
                values.put("ItemCategoryId", savelistheader.get(i).getItemCatId());
                values.put("ItemCategoryName", savelistheader.get(i).getItemCatName());
                if (!db.isOpen()) {
                    open();
                }
                lf = db.insert(CommonString.Table_Retail_Excellence_Header, null, values);
                for (int j = 0; j < data.get(savelistheader.get(i)).size(); j++) {
                    valuesproduct.put(CommonString.KEY_COMMON_ID, lf);
                    valuesproduct.put("UPLOAD_STATUS", CommonString.KEY_N);
                    valuesproduct.put("USER_ID", userId);
                    valuesproduct.put("UNIQUE_CODE", unique_code);
                    valuesproduct.put(CommonString.KEY_COUNTER_ID, counter_Id);
                    valuesproduct.put(CommonString.KEY_VISIT_DATE, visit_Date);
                    valuesproduct.put("ItemCategoryId", savelistheader.get(i).getItemCatId());
                    valuesproduct.put("ItemCategoryName", savelistheader.get(i).getItemCatName());
                    valuesproduct.put("ItemId", data.get(savelistheader.get(i)).get(j).getItemId());
                    valuesproduct.put("ItemName", data.get(savelistheader.get(i)).get(j).getItemName());
                    valuesproduct.put("Answer", data.get(savelistheader.get(i)).get(j).getAnswer());
                    if (!db.isOpen()) {
                        open();
                    }
                    l = db.insert(CommonString.Table_Retail_Excellence_Child, null, valuesproduct);

                }
            }
            closeDb();
        } catch (Exception ex) {
            ex.fillInStackTrace();
            closeDb();
        }

        return l;
    }

    public long insert_me_quiz_data(String counter_Id, String visit_Date, String userId, ArrayList<MEMEAuditQuestion> listDataHeader, HashMap<MEMEAuditQuestion, ArrayList<MEMEAuditQuestion>> listDataChild, MEMEAuditQuestion obj, String unique_code) {
        db.delete(CommonString.Table_ME_QUIZ, CommonString.KEY_VISIT_DATE + " <>'" + visit_Date + "'", null);
        db.delete(CommonString.Table_ME_QUIZ_MULTI_ANSWER, CommonString.KEY_VISIT_DATE + " <>'" + visit_Date + "'", null);

        db.delete(CommonString.Table_ME_QUIZ, CommonString.KEY_VISIT_DATE + "='" + visit_Date + "' and " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and USER_ID='" + userId + "'", null);
        db.delete(CommonString.Table_ME_QUIZ_MULTI_ANSWER, CommonString.KEY_VISIT_DATE + "='" + visit_Date + "' and " + CommonString.KEY_COUNTER_ID + "=" + counter_Id + " and USER_ID='" + userId + "'", null);
        ContentValues values = new ContentValues();
        ContentValues valuesproduct = new ContentValues();
        long l = 0, l2 = 0, l3 = 0;
        try {
            db.beginTransaction();
            for (int k = 0; k < listDataHeader.size(); k++) {
                for (int j = 0; j < listDataChild.get(listDataHeader.get(k)).size(); j++) {
                    values.put("USER_ID", userId);
                    values.put("UNIQUE_CODE", unique_code);
                    values.put("QuizName", obj.getQuizName());
                    values.put("UPLOAD_STATUS", CommonString.KEY_N);
                    values.put("QuizId", obj.getQuizId().toString());
                    values.put(CommonString.KEY_COUNTER_ID, counter_Id);
                    values.put(CommonString.KEY_VISIT_DATE, visit_Date);

                    values.put("CATEGORY", listDataHeader.get(k).getCategory());
                    values.put("CATEGORY_Id", listDataHeader.get(k).getCategoryId());
                    values.put("QUESTION", listDataChild.get(listDataHeader.get(k)).get(j).getQuestion());
                    values.put("QUESTION_Id", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionId());
                    values.put("QUESTION_TYPE", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType());
                    values.put("IMAGE_STR", listDataChild.get(listDataHeader.get(k)).get(j).getStr_audit_img());
                    if (listDataChild.get(listDataHeader.get(k)).get(j).getImageAllow()) {
                        values.put("IMAGE_ALLOW", 1);
                    } else {
                        values.put("IMAGE_ALLOW", 0);

                    }

                    if (listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType().equalsIgnoreCase("List Single Choice")) {
                        values.put("ANSWER", listDataChild.get(listDataHeader.get(k)).get(j).getAnswer());
                        values.put("ANSWER_Id", listDataChild.get(listDataHeader.get(k)).get(j).getAnswerId());
                    } else if (!listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                        values.put("ANSWER", listDataChild.get(listDataHeader.get(k)).get(j).getAnswer());
                        values.put("ANSWER_Id", 0);
                    }
                    if (!db.isOpen()) {
                        open();
                    }

                    l = db.insert(CommonString.Table_ME_QUIZ, null, values);

                    if (listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                        for (int k2 = 0; k2 < listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().size(); k2++) {
                            valuesproduct.put("USER_ID", userId);
                            valuesproduct.put(CommonString.KEY_COMMON_ID, l);
                            valuesproduct.put("QuizName", obj.getQuizName());
                            valuesproduct.put("QuizId", obj.getQuizId().toString());
                            valuesproduct.put(CommonString.KEY_COUNTER_ID, counter_Id);
                            valuesproduct.put(CommonString.KEY_VISIT_DATE, visit_Date);
                            valuesproduct.put("CATEGORY_Id", listDataHeader.get(k).getCategoryId().toString());
                            valuesproduct.put("QUESTION_Id", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionId());
                            valuesproduct.put("QUESTION_TYPE", listDataChild.get(listDataHeader.get(k)).get(j).getQuestionType());
                            valuesproduct.put("ANSWER", listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().get(k2).getAnswer());
                            valuesproduct.put("ANSWER_Id", listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().get(k2).getAnswerId());
                            if (listDataChild.get(listDataHeader.get(k)).get(j).getAnswerList().get(k2).isSelected()) {
                                valuesproduct.put("IS_SELECTED", "1");
                            } else {
                                valuesproduct.put("IS_SELECTED", "0");
                            }
                            if (!db.isOpen()) {
                                open();
                            }
                            l2 = db.insert(CommonString.Table_ME_QUIZ_MULTI_ANSWER, null, valuesproduct);
                        }

                    }

                }
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
        }

        return l3;
    }

    public ArrayList<MasterRetailExcellence> getRetailExcellencedata(String categoryID, String userId, String visit_date, String counterId) {
        Cursor cursordata = null;
        ArrayList<MasterRetailExcellence> auditData = new ArrayList<>();
        try {
            if (categoryID == null && userId == null) {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_Retail_Excellence_Child + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            } else if (categoryID == null) {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_Retail_Excellence_Child + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            } else {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_Retail_Excellence_Child + " where ItemCategoryId =" + categoryID + " AND USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterRetailExcellence sb = new MasterRetailExcellence();
                    sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID")));
                    sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID)));
                    sb.setItemId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemId")));
                    sb.setItemName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemName")));
                    sb.setAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow("Answer")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }
        return auditData;
    }

    public ArrayList<ProductMaster> getMeSaledata(String categoryID, String userId, String visit_date, String counterId) {
        Cursor cursordata = null;
        ArrayList<ProductMaster> productMasterArrayList = new ArrayList<>();
        try {
            if (categoryID == null && userId == null) {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null);
            } else if (categoryID == null) {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null);
            } else {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where ItemCategoryId =" + categoryID + " AND USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ProductId")));
                    sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID)));
                    sb.setImagePath(cursordata.getString(cursordata.getColumnIndexOrThrow("ImagePath")));
                    sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID)));
                    sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK)));
                    productMasterArrayList.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }

        return productMasterArrayList;
    }

    public ArrayList<MEMEAuditQuestion> getme_quiz_from_database(String categoryID, String userId, String visit_date, String counterId, String quizId) {
        Cursor cursordata = null;
        ArrayList<MEMEAuditQuestion> auditData = new ArrayList<>();

        try {
            if (categoryID == null && userId == null && quizId == null) {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            } else if (categoryID == null && quizId == null) {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            } else {
                cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where CATEGORY_Id =" + categoryID + " AND USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and QuizId=" + quizId + "", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setQuizId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuizId")));
                    sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID")));
                    sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_ID)));
                    sb.setQuestion(cursordata.getString(cursordata.getColumnIndexOrThrow("QUESTION")));
                    sb.setQuestionId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QUESTION_Id")));
                    sb.setQuestionType(cursordata.getString(cursordata.getColumnIndexOrThrow("QUESTION_TYPE")));
                    sb.setAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow("ANSWER")));
                    sb.setAnswerId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ANSWER_Id")));
                    sb.setStr_audit_img(cursordata.getString(cursordata.getColumnIndexOrThrow("IMAGE_STR")));
                    if (cursordata.getString(cursordata.getColumnIndexOrThrow("IMAGE_ALLOW")).equals("1")) {
                        sb.setImageAllow(true);
                    } else {
                        sb.setImageAllow(false);
                    }

                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }

        return auditData;
    }


    public ArrayList<MEMEAuditQuestion> getme_quiz_from(String visit_date, String counterId, boolean previous_date) {
        Cursor cursordata = null;
        ArrayList<MEMEAuditQuestion> auditData = new ArrayList<>();
        try {

            if (previous_date) {
                cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_ME_QUIZ + " where Visit_Date <>'" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            } else {
                cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_ME_QUIZ + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            }
            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID")));
                    sb.setVisit_date(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }

        return auditData;
    }


    public ArrayList<MasterRetailExcellence> getRetailExcellence_from(String visit_date, String counterId, boolean previous_date) {
        Cursor cursordata = null;
        ArrayList<MasterRetailExcellence> auditData = new ArrayList<>();
        try {

            if (previous_date) {
                cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_Retail_Excellence_Child + " where Visit_Date <>'" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            } else {
                cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.Table_Retail_Excellence_Child + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UPLOAD_STATUS='N'", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterRetailExcellence sb = new MasterRetailExcellence();
                    sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID")));
                    sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID)));
                    sb.setItemId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ItemId")));
                    sb.setItemName(cursordata.getString(cursordata.getColumnIndexOrThrow("ItemName")));
                    sb.setAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow("Answer")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }

        return auditData;
    }

    public ArrayList<ProductMaster> getProductMasterMeSale_from(String visit_date, String counterId, boolean previous_date) {
        Cursor cursordata = null;
        ArrayList<ProductMaster> productMasterArrayList = new ArrayList<>();
        try {

            if (previous_date) {
                cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date <>'" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null);
            } else {
                cursordata = db.rawQuery("SELECT distinct USER_ID FROM " + CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA + " where Visit_Date='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UploadStatus='N'", null);
            }
            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ProductId")));
                    sb.setKeyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COMMON_ID)));
                    sb.setImagePath(cursordata.getString(cursordata.getColumnIndexOrThrow("ImagePath")));
                    sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID)));
                    sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK)));
                    productMasterArrayList.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }

        return productMasterArrayList;
    }


    public ArrayList<MEMEAuditQuestion> getme_quiz(String userId, String visit_date, String counterId, String quizId) {
        Cursor cursordata = null;
        ArrayList<MEMEAuditQuestion> auditData = new ArrayList<>();

        try {

            cursordata = db.rawQuery("SELECT * FROM " + CommonString.Table_ME_QUIZ + " where USER_ID='" + userId + "'AND " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + " and QuizId=" + quizId + "", null);


            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setQuizId(cursordata.getInt(cursordata.getColumnIndexOrThrow("QuizId")));
                    sb.setUser_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("USER_ID")));

                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }

        return auditData;
    }

    public ArrayList<MEMEAuditQuestion> getquiz_answer(String keyId) {
        ArrayList<MEMEAuditQuestion> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * from ME_QUIZ_MULTI_ANS_TABLE where Common_Id ='" + keyId + "' AND IS_SELECTED='1'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MEMEAuditQuestion sb = new MEMEAuditQuestion();
                    sb.setAnswerId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ANSWER_Id")));
                    sb.setAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ANSWER")));
                    String img_allow = dbcursor.getString(dbcursor.getColumnIndexOrThrow("IS_SELECTED"));
                    if (img_allow.equals("1")) {
                        sb.setSelected(true);
                    } else {
                        sb.setSelected(false);
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    public boolean ischeckedgetquiz_answer(String keyId, String userId, String ansId) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * from ME_QUIZ_MULTI_ANS_TABLE where Common_Id ='" + keyId + "'and USER_ID='" + userId + "'and ANSWER_Id='" + ansId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("IS_SELECTED"));
                    if (user_idget != null && user_idget.equals("1")) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }

                    dbcursor.moveToNext();
                }
                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }

        return filled;
    }

    //jeevan   nmjnmn,
    public long update_Me_Quiz(String counterId, String user_Id) {
        long l = 0;
        ContentValues values = new ContentValues();
        try {
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.Table_ME_QUIZ, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null);

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

    public long update_retail_excellence(String counterId, String user_Id) {
        long l = 0;
        ContentValues values = new ContentValues();
        try {
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.Table_Retail_Excellence_Header, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null);
            l = db.update(CommonString.Table_Retail_Excellence_Child, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }

    public long update_me_sale(String counterId, String user_Id) {
        long l = 0;
        ContentValues values = new ContentValues();
        try {
            values.put("UploadStatus", CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_INSERT_HEADER_ME_SALE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null);
            l = db.update(CommonString.TABLE_STORE_STOCK_CHILD_ME_SALE_DATA, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }

    public long update_makeover(String counterId, String user_Id, String keyId, boolean manual_upload) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            if (manual_upload) {
                if (!db.isOpen()) {
                    open();
                }
                l = db.update(CommonString.Table_Makeover_Capture, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + keyId + "'", null);

            } else {
                if (!db.isOpen()) {
                    open();
                }
                l = db.update(CommonString.Table_Makeover_Capture, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND USER_ID='" + user_Id + "' AND " + CommonString.KEY_ID + "='" + keyId + "'", null);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return l;
    }

    public boolean insertPromotionMaster(ResponseResult cst) {
        db.delete("Master_Promotion", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotion> data = cst.getMasterPromotion();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("PromoId", data.get(i).getPromoId());
                values.put("PromotionSetEntityType", data.get(i).getPromotionSetEntityType().trim());
                values.put("PromotionGetEntityType", data.get(i).getPromotionGetEntityType().trim());
                values.put("PromotionSetEntityValue", data.get(i).getPromotionSetEntityValue());
                values.put("PromotionGetEntityValue", data.get(i).getPromotionGetEntityValue());
                values.put("PromotionCode", data.get(i).getPromotionCode().trim());
                values.put("PromotionName", data.get(i).getPromotionName().trim());
                values.put("StartTime", data.get(i).getStartTime());
                values.put("EndTime", data.get(i).getEndTime());

                values.put("StartDate", data.get(i).getStartDate());
                values.put("EndDate", data.get(i).getEndDate());
                values.put("PromoPath", data.get(i).getPromoPath());
                values.put("PromoOfferTab", data.get(i).getPromoOfferTab());
                values.put("PromoOfferMobile", data.get(i).getPromoOfferMobile());
                values.put("MaxValue", data.get(i).getMaxValue());
                values.put("PromoType", data.get(i).getPromoType().trim());

                if (!db.isOpen()) {
                    open();
                }
                long id = db.insert("Master_Promotion", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertPromotionSetEntityItemMaster(ResponseResult cst) {
        db.delete("Master_PromotionSetEntityItem", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionSetEntityItem> data = cst.getMasterPromotionSetEntityItem();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("PromoId", data.get(i).getPromoId());
                values.put("SetEntityListType", data.get(i).getSetEntityListType());
                values.put("SetEntityListItem", data.get(i).getSetEntityListItem());
                values.put("ItemCount", data.get(i).getItemCount());
                values.put("Id", data.get(i).getId());

                long id = db.insert("Master_PromotionSetEntityItem", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertPromotionGetEntityItemMaster(ResponseResult cst) {
        db.delete("Master_PromotionGetEntityItem", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionGetEntityItem> data = cst.getMasterPromotionGetEntityItem();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("PromoId", data.get(i).getPromoId());
                values.put("GetEntityListType", data.get(i).getGetEntityListType());
                values.put("GetEntityListItem", data.get(i).getGetEntityListItem());

                long id = db.insert("Master_PromotionGetEntityItem", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertPromotionGetProductGroupMaster(ResponseResult cst) {
        db.delete("Master_PromotionGetProductGroup", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionGetProductGroup> data = cst.getMasterPromotionGetProductGroup();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("ProductGroupId", data.get(i).getProductGroupId());
                values.put("ProductId", data.get(i).getProductId());

                long id = db.insert("Master_PromotionGetProductGroup", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterPromotionSetProductCatalog(ResponseResult cst) {
        db.delete("Master_PromotionSetProductCatalog", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionSetProductCatalog> data = cst.getMasterPromotionSetProductCatalog();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CatalogId", data.get(i).getCatalogId());
                values.put("ProductId", data.get(i).getProductId());

                long id = db.insert("Master_PromotionSetProductCatalog", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterPromotionGetProductCatalog(ResponseResult cst) {
        db.delete("Master_PromotionGetProductCatalog", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionGetProductCatalog> data = cst.getMasterPromotionGetProductCatalog();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CatalogId", data.get(i).getCatalogId());
                values.put("ProductId", data.get(i).getProductId());

                long id = db.insert("Master_PromotionGetProductCatalog", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertPromotionSetProductGroupMaster(ResponseResult cst) {
        db.delete("Master_PromotionSetProductGroup", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionSetProductGroup> data = cst.getMasterPromotionSetProductGroup();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("ProductGroupId", data.get(i).getProductGroupId());
                values.put("ProductId", data.get(i).getProductId());

                long id = db.insert("Master_PromotionSetProductGroup", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    //get Promotion master data
    public ArrayList<MasterPromotion> getPromotionMaster(boolean flag) {
        ArrayList<MasterPromotion> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (flag) {
                dbcursor = db.rawQuery("Select * from Master_Promotion where PromotionSetEntityType='Product' and" + " PromotionGetEntityType in " + "('Product' ,'Worth','Gift','OffWorth','OffProduct','OffSameProduct','WorthWithProduct')", null);
            } else {
                dbcursor = db.rawQuery("Select * from Master_Promotion where PromotionSetEntityType='Worth'" + " and PromotionGetEntityType in " + "('Product' ,'Worth' ,'Gift','OffWorth','OffProduct','OffAdditionalProduct','ValueOffAdditionalProduct')", null);
            }
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterPromotion sb = new MasterPromotion();
                    sb.setPromoId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PromoId")));
                    sb.setPromotionSetEntityType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionSetEntityType")));
                    sb.setPromotionGetEntityType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionGetEntityType")));
                    sb.setPromotionSetEntityValue(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionSetEntityValue")));
                    sb.setPromotionGetEntityValue(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionGetEntityValue")));
                    sb.setPromotionCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionCode")));
                    sb.setPromotionName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromotionName")));
                    sb.setStartTime(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartTime")));
                    sb.setEndTime(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndTime")));
                    sb.setStartDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("StartDate")));
                    sb.setEndDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EndDate")));
                    sb.setPromoPath(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoPath")));
                    sb.setPromoOfferTab(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferTab")));
                    sb.setPromoOfferMobile(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoOfferMobile")));
                    sb.setMaxValue(dbcursor.getString(dbcursor.getColumnIndexOrThrow("MaxValue")));
                    sb.setPromoType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoType")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    public ArrayList<InvoiceGetterSetter> getqualified_Product_List(String counterId, String userId, String visit_date, int promoId) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select distinct PM.EanCode as EanCode, PM.ProductName as ProductName,TA.Quantity as Quantity,TA.Rate as Rate," + "TA.ProductId as ProductId,TA.PromoId as PromoId" + " from Temp_Promo_AplyDefinition TA inner join" + " Product_Master PM on PM.ProductId=TA.ProductId where COUNTER_ID =" + counterId + " and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + promoId + " Order By Rate Desc", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sb = new InvoiceGetterSetter();
                    sb.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Quantity")));
                    sb.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Rate")));
                    sb.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId")));
                    sb.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e);
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    public ArrayList<InvoiceGetterSetter> getqualifiedOffSameProduct(String counterId, String userId, String visit_date, int promoId) {
        ArrayList<InvoiceGetterSetter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select distinct PM.EanCode as EanCode, PM.ProductName as ProductName,TA.Quantity as Quantity,TA.Rate as Rate," + "TA.ProductId as ProductId,TA.PromoId as PromoId from Temp_Promotion_OffSameProduct TA inner join" + " Product_Master PM on PM.ProductId=TA.ProductId where COUNTER_ID =" + counterId + " and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + promoId + " Order By Rate Desc", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    InvoiceGetterSetter sb = new InvoiceGetterSetter();
                    sb.setProduct(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setQuantity(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Quantity")));
                    sb.setProduct_rate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Rate")));
                    sb.setProduct_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductId")));
                    sb.setPromotion_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("PromoId")));
                    sb.setScan_ean_code_or_enterd_ean_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    //get Promotion Set Entity Item
    //get Promotion Set Product Group

    @SuppressLint("Recycle")
    public ArrayList<MasterPromotionSetProductGroup> getPromotiongetProduct(int promoId, String getentityType, String visit_date, String counterId, String userType) {
        ArrayList<MasterPromotionSetProductGroup> list = new ArrayList<>();
        Cursor dbcursor = null;
        Cursor dbcursor1 = null;
        String balancekey = "";
        String q1 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND T1." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND T1." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND T2.POS_SALE_FLAG='0'";
        String q2 = userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? " AND S." + CommonString.KEY_USER_TYPE + "='" + CommonString.TAG_FROM_ME + "'" : " AND S." + CommonString.KEY_USER_TYPE + "!='" + CommonString.TAG_FROM_ME + "' AND S1.POS_SALE_FLAG ='0'";

        String additionQueryMe = "", getDataMe = "(ts.SaleableBalance - ifnull(t.DamageQty,0)) as SaleableBalance";
        String table = "T_StockSummary", query = "", ts_banace_me = " and ts.SaleableBalance >0";
        if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
            ts_banace_me = "";
            getDataMe = "((ts.SaleableBalance + ifnull(tempsale.TempSale,0) ) - ifnull(t.DamageQty,0)) as SaleableBalance";

            additionQueryMe = " left join (select ProductId, case when (Select count(*) from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + ")" + " c where c.ProductId = t.Productid)>0 then" + " (Select TempQty from (" + " Select CounterId, ProductId," + "sum(TempQty) as TempQty from ( Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS TempQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + " AND T1.RIGHTNAME !='ME' AND T1.POS_SALE_FLAG !=0 GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID as CounterId," + " S.PROMO_PRODUCT_ID AS ProductId , SUM(S.PROMO_PRODUCT_QTY) AS TempQty from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + " AND S.RIGHTNAME !='ME' AND S1.POS_SALE_FLAG !=0 GROUP BY S.PROMO_PRODUCT_ID)as t Group by CounterId, ProductId" + " ) c where c.productId = t.Productid) else (" + "Select sum(QtySold)as QtySold from (select SaleQty as QtySold from Report_BA_TBASale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "'" + "UNION all select SaleQty as QtySold from Report_BA_TBAPromoSale s where s.ProductId = t.ProductId and s.CounterId=" + counterId + " and VisitDate='" + visit_date + "')" + ") end as TempSale" + " from T_StockSummary t) as tempsale on ts.ProductId=tempsale.ProductId";
        }

        try {

            dbcursor1 = db.rawQuery("Select * from Master_PromotionGetEntityItem where PromoId=" + promoId, null);

            if (dbcursor1 != null) {
                dbcursor1.moveToFirst();
                while (!dbcursor1.isAfterLast()) {
                    String setentitiy_listType = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("GetEntityListType"));
                    ////changes for all Products 03-16-2020.................
                    String get_entity_list_itemfor_product = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("GetEntityListItem"));
                    if (getentityType.equalsIgnoreCase("Gift")) {
                        balancekey = "GwpBalance";
                    } else {
                        balancekey = "SaleableBalance";
                    }
                    if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("ProductGroup")) {
                        if (getentityType.equalsIgnoreCase("Gift")) {
                            dbcursor = db.rawQuery("WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM" + " Master_PromotionGetEntityItem WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + "(ts.GwpBalance - ifnull(t.DamageQty,0)) as" + " GwpBalance from Master_PromotionGetProductGroup MP" + " inner join Product_Master PM on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from" + " APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "' and Product_Type='GWP' GROUP By ProductId) as t" + " Group by CounterId, ProductId)  as t on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + " where ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) and ts.GwpBalance >0" +

                                    " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);
                        } else {
                            dbcursor = db.rawQuery("WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM" + " Master_PromotionGetEntityItem" + " WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + getDataMe + " from Master_PromotionGetProductGroup MP inner join Product_Master PM" + " on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT  CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + "  AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from" + " APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale where" + " COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' GROUP By ProductId) as t Group by CounterId, ProductId) as t" + " on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + additionQueryMe + " where ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC)" +

                                    ts_banace_me +

                                    " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);

                        }

                    } else if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("Catalog")) {
                        if (!getentityType.equals("") && getentityType.equalsIgnoreCase("Gift")) {
                            dbcursor = db.rawQuery("WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ','" + " from Master_PromotionGetEntityItem WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " from neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + "(ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance from Master_PromotionGetProductCatalog MP" + " inner join Product_Master PM on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + " left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale where" + " COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' and Product_Type='GWP' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + " where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) and ts.GwpBalance >0" +

                                    " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);

                        } else {
                            dbcursor = db.rawQuery(" WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , GetEntityListItem || ','" + " from Master_PromotionGetEntityItem WHERE PromoId=" + promoId + " UNION ALL SELECT id, SUBSTR(etc, 0, INSTR(etc, ',')) ," + " SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select distinct MP.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + getDataMe + " from" + " Master_PromotionGetProductCatalog MP" + " inner join Product_Master PM on PM.ProductID=MP.ProductID inner join " + table + " ts on ts.ProductId= PM.ProductID" + "  left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " select T.COUNTER_ID as CounterId, T.ProductId as ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE' AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All" + " SELECT  CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending' Union All" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND" + " T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID UNION ALL" + " select  S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from" + " APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale where" + " COUNTER_ID =" + counterId + " and Visit_Date ='" + visit_date + "' and Product_Type='Saleable' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId and t.ProductId=MP.ProductId" + additionQueryMe + " where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC)" + ts_banace_me + " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);
                        }

                    } else {
                        ////changes for all Products 03-16-2020.................
                        if (get_entity_list_itemfor_product != null && get_entity_list_itemfor_product.equalsIgnoreCase("All")) {
                            if (getentityType.equalsIgnoreCase("Gift")) {
                                //-----------Get Gift product All form T_Stock
                                dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName," + "PM.Mrp as Mrp,PM.EanCode as EanCode,(ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance from Product_Master PM" + " inner join " + table + " ts on ts.ProductId= PM.ProductID Left join (Select CounterId, ProductId, sum(DamageQty) as DamageQty from (" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId,SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1 INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON" + " T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + "  AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "' and Product_Type='GWP' GROUP By ProductId) as t Group by CounterId, ProductId" + " ) as t on PM.ProductId = t.ProductId where ts.GwpBalance >0" +

                                        " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);
                            } else {
                                ////Get product Saleable all from T_Stock Summery------------
                                dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + "TS.SaleableBalance as SaleableBalance from" + " Product_Master PM left join (" + " Select  ts.ProductId as ProductId," + getDataMe + " from " + table + " ts Left join(Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'" + " Union All" + " Select T2.COUNTER_ID AS CounterId,  T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL" + " select S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID,SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1" + " ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID = " + counterId + " AND S1.VISIT_DATE = '" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL" + " SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "'and Product_Type='Saleable' GROUP By ProductId" + " ) as t" + " Group by CounterId, ProductId) as t on ts.ProductId = t.ProductId" + additionQueryMe + ")  as" + " TS ON TS.ProductId = PM.ProductId " + " where TS.SaleableBalance > 0 order by PM.ProductName and PM.ProductType = 'Normal'" +

                                        " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);
                            }

                        } else {
                            ////for some product Query with Master_PromotionGetEntityItem
                            if (getentityType.equalsIgnoreCase("Gift")) {
                                ///for get Gift product using mapping-------
                                dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + " (ts.GwpBalance - ifnull(t.DamageQty,0)) as GwpBalance" + " from Product_Master PM inner join " + table + " ts on ts.ProductId= PM.ProductID Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='GWP'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Gift' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "'and Product_Type='GWP' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId where PM.ProductId " + " in(WITH RECURSIVE neat( id,ProductId, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM Master_PromotionGetEntityItem" + " WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)FROM neat WHERE etc <> '')" + " SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) and ts.GwpBalance >0" +

                                        " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);
                            } else {
                                //-------For get Saleable product using mapping-------------
                                dbcursor = db.rawQuery("select distinct PM.ProductId as ProductId,PM.ProductName as ProductName,PM.Mrp as Mrp,PM.EanCode as EanCode," + getDataMe + " from Product_Master PM inner join " + table + " ts on ts.ProductId= PM.ProductID Left join" + " (Select CounterId, ProductId, sum(DamageQty) as DamageQty from(" + " select T.COUNTER_ID as CounterId, T.ProductId, T.Stock as DamageQty from TABLE_TRANSACTION_DATA T" + " INNER JOIN DR_TABLE_TRANSACTION_WISE_MASTER M ON T.MASTER_TRANSACTION_ID = M.MASTER_TRANSACTION_ID where" + " T.STOCK_TYPE='DAMAGE'  AND T.Visit_Date ='" + visit_date + "' and T.COUNTER_ID =" + counterId + " Union All SELECT CounterId, ProductId, DamageQty from" + " Damage_PreviousPending Where CounterId =" + counterId + " and Verify ='Pending'Union All" + " Select T2.COUNTER_ID AS CounterId,T1.PRODUCT_ID AS ProductId , SUM(T1.QUANTITY) AS DamageQty FROM SALE_TRACKING_TABLE T1" + " INNER JOIN SALE_TRACKING_HEADER_TABLE T2 ON T2.RECCEPT_COUNT=T1.RECCEPT_COUNT" + " WHERE T2.COUNTER_ID =" + counterId + " AND T2.Visit_Date='" + visit_date + "' AND T1.INVOICE_TYPE='Saleable'" + q1 + " GROUP BY T1.PRODUCT_ID" + " UNION ALL select  S.COUNTER_ID, S.PROMO_PRODUCT_ID AS PRODUCT_ID , SUM(S.PROMO_PRODUCT_QTY) AS QUANTITY from APPLYED_PROMOTION_TABLE S" + " INNER JOIN SALE_TRACKING_HEADER_TABLE S1 ON S.RECCEPT_COUNT=S1.RECCEPT_COUNT" + " Where S.PROMO_TYPE ='Product' AND S.COUNTER_ID =" + counterId + " AND S1.VISIT_DATE ='" + visit_date + "'" + q2 + " GROUP BY S.PROMO_PRODUCT_ID UNION ALL SELECT COUNTER_ID as CounterId,ProductId,Quantity as DamageQty from Temp_Sale" + " where COUNTER_ID =" + counterId + " and Visit_Date = '" + visit_date + "'and Product_Type='Saleable' GROUP By ProductId) as t" + " Group by CounterId, ProductId) as t on PM.ProductId = t.ProductId " + additionQueryMe + " where PM.ProductId " + " in(WITH RECURSIVE neat( id,ProductId, etc) AS(SELECT PromoId, '' , GetEntityListItem || ',' FROM Master_PromotionGetEntityItem" + " WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)FROM neat WHERE etc <> '')" + " SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) and ts.SaleableBalance >0" +

                                        " and PM.ProductId not in( WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , GetExclusionList || ','" + " FROM Master_PromotionGetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1)" + " FROM neat WHERE etc <> '') SELECT ProductId FROM neat WHERE ProductId <> '')", null);
                            }
                        }
                    }

                    if (dbcursor != null) {
                        dbcursor.moveToFirst();
                        while (!dbcursor.isAfterLast()) {
                            MasterPromotionSetProductGroup sb = new MasterPromotionSetProductGroup();
                            sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductId")));
                            sb.setProductname(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                            sb.setMrp_product(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Mrp")));
                            sb.setEan_code(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                            sb.setSallable_stock_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(balancekey)));
                            list.add(sb);
                            dbcursor.moveToNext();
                        }
                        dbcursor.close();
                        return list;
                    }
                }
            }

        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    public boolean insertMasterSurvey(ResponseResult cst) {
        db.delete("Master_Survey", null, null);
        ContentValues values = new ContentValues();
        List<MasterSurvey> data = cst.getMasterSurvey();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("SurveyId", data.get(i).getSurveyId());
                values.put("SurveyName", data.get(i).getSurveyName());
                values.put("SurveyType", data.get(i).getSurveyType());
                values.put("SurveyQuestionId", data.get(i).getSurveyQuestionId());
                values.put("SurveyQuestion", data.get(i).getSurveyQuestion());
                values.put("SurveyQuestionType", data.get(i).getSurveyQuestionType());
                values.put("SurveyAnswerId", data.get(i).getSurveyAnswerId());
                values.put("SurveyAnswer", data.get(i).getSurveyAnswer());
                values.put("ImageAllow", data.get(i).getImageAllow());
                values.put("UploadStatus", data.get(i).getUploadStatus());

                long id = db.insert("Master_Survey", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertMasterLeaveType(ResponseResult cst) {
        db.delete("Master_LeaveType", null, null);
        ContentValues values = new ContentValues();
        List<MasterLeaveType> data = cst.getMasterLeaveType();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("LeaveTypeId", data.get(i).getLeaveTypeId());
                values.put("LeaveType", data.get(i).getLeaveType());
                values.put("Show", data.get(i).getShow());
                long id = db.insert("Master_LeaveType", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertdamagedReturnToDistributor(ResponseResult cst) {
        db.delete("Damage_ReturnToDistributor", null, null);
        ContentValues values = new ContentValues();
        List<DamageReturnToDistributor> data = cst.getDamageReturnToDistributor();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("ProductId", data.get(i).getProductId());
                values.put("ReturnQty", data.get(i).getReturnQty());
                values.put("Verify", data.get(i).getVerify());
                long id = db.insert("Damage_ReturnToDistributor", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertbaservaystusupload(ResponseResult cst) {
        db.delete("Master_Survey_UploadStatus", null, null);
        ContentValues values = new ContentValues();
        List<MasterSurveyUploadstatus> data = cst.getMasterSurveyUploadStatus();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("EmpId", data.get(i).getEmpId());
                values.put("SurveyId", data.get(i).getSurveyId());
                values.put("SurveyType", data.get(i).getSurveyType());
                values.put("CounterSurveyUpload", data.get(i).getCounterSurveyUpload());
                values.put("BASurveyUpload", data.get(i).getBASurveyUpload());
                long id = db.insert("Master_Survey_UploadStatus", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertGroupWiseSale(ResponseResult cst) {
        db.delete("Report_ProductGroupWiseSalesValue", null, null);
        ContentValues values = new ContentValues();
        List<ReportProductGroupWiseSalesValue> data = cst.getReportProductGroupWiseSalesValue();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("ProductGroupId", data.get(i).getProductGroupId());
                values.put("ProductGroupName", data.get(i).getProductGroupName().trim());
                values.put("MTDTg", data.get(i).getMTDTg());
                values.put("MTDAch", data.get(i).getMTDAch());
                values.put("AchPer", data.get(i).getAchPer());
                values.put("Pending", data.get(i).getPending());
                long id = db.insert("Report_ProductGroupWiseSalesValue", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertReportDaywiseSale(ResponseResult cst, boolean me) {
        try {
            String table = "Report_SalesDateWise";
            List<ReportSalesDateWise> data = cst.getReportSalesDateWise();
            if (me) {
                table = "Report_SalesDateWiseME";
                data = cst.getReportSalesDateWiseMe();
            }
            db.delete(table, null, null);
            ContentValues values = new ContentValues();

            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("WeekDays", data.get(i).getWeekDays().trim());
                values.put("Qty", data.get(i).getQty());
                values.put("SalesValue", data.get(i).getSalesValue());
                long id = db.insert(table, null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertDamagedPending(ResponseResult cst) {
        db.delete("Damage_PreviousPending", null, null);
        ContentValues values = new ContentValues();
        List<DamagePreviousPending> data = cst.getDamagePreviousPending();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("ProductId", data.get(i).getProductId());
                values.put("DamageQty", data.get(i).getDamageQty());
                values.put("Verify", data.get(i).getVerify());
                long id = db.insert("Damage_PreviousPending", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMeWorkingcounterDetails(ResponseResult cst) {
        try {
            List<ReportMTDWorkingCounterME> data = cst.getReportMTDWorkingCounterME();
            db.delete("Report_MTD_WorkingCounterME", null, null);
            ContentValues values = new ContentValues();

            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                long id = db.insert("Report_MTD_WorkingCounterME", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertreportsalemonth(ResponseResult cst, boolean me) {
        try {
            String table = "Report_SalesL3MValue";
            List<ReportSalesL3MValue> data = cst.getReportSalesL3MValue();
            if (me) {
                table = "Report_SalesL3MValueME";
                data = cst.getReportSalesL3MValueMe();
            }
            db.delete(table, null, null);
            ContentValues values = new ContentValues();

            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Month", data.get(i).getMonth());
                values.put("Qty", data.get(i).getQty());
                values.put("SalesValue", data.get(i).getSalesValue());
                long id = db.insert(table, null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertpromogetexclusion(ResponseResult cst) {
        db.delete("Master_PromotionGetExclusionList", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionGetExclusionList> data = cst.getMasterPromotionGetExclusionList();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Id", data.get(i).getId());
                values.put("PromoId", data.get(i).getPromoId());
                values.put("GetExclusionList", data.get(i).getGetExclusionList());

                long id = db.insert("Master_PromotionGetExclusionList", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertpromosetExclusion(ResponseResult cst) {
        db.delete("Master_PromotionSetExclusionList", null, null);
        ContentValues values = new ContentValues();
        List<MasterPromotionSetExclusionList> data = cst.getMasterPromotionSetExclusionList();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Id", data.get(i).getId());
                values.put("PromoId", data.get(i).getPromoId());
                values.put("SetExclusionList", data.get(i).getSetExclusionList());

                long id = db.insert("Master_PromotionSetExclusionList", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertdamagestockhistory(ResponseResult cst) {
        db.delete("Report_DamageStockHistory", null, null);
        ContentValues values = new ContentValues();
        List<ReportDamageStockHistory> data = cst.getReportDamageStockHistory();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("ProductCode", data.get(i).getProductCode());
                values.put("ProductName", data.get(i).getProductName());
                values.put("EanCode", data.get(i).getEanCode());
                values.put("Mrp", data.get(i).getMrp());
                values.put("DamageQty", data.get(i).getDamageQty());
                values.put("Verify", data.get(i).getVerify());
                values.put("VerifyDate", data.get(i).getVerifyDate());

                long id = db.insert("Report_DamageStockHistory", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertsourceofsales(ResponseResult cst) {
        db.delete("Master_SourcesOfSales", null, null);
        ContentValues values = new ContentValues();
        List<MasterSourcesOfSale> data = cst.getMasterSourcesOfSales();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("SourcesOfSale", data.get(i).getSourcesOfSale());
                long id = db.insert("Master_SourcesOfSales", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<MasterCompetitonBrandWiseNuance> getcompanies(boolean flag_nuance, int companyId) {
        ArrayList<MasterCompetitonBrandWiseNuance> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            String query = "Select Distinct CompetitionBrandId,CompetitionBrand From Master_CompetitonBrandWiseNuance";
            if (flag_nuance) {
                query = "Select Distinct CompetitionNuanceId,CompetitionNuance From Master_CompetitonBrandWiseNuance Where CompetitionBrandId =" + companyId + "";
            }
            dbcursor = db.rawQuery(query, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitonBrandWiseNuance sb = new MasterCompetitonBrandWiseNuance();
                    if (flag_nuance) {
                        sb.setCompetitionNuanceId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionNuanceId")));
                        sb.setCompetitionNuance(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionNuance")));
                        sb.setCompetitionBrandId(companyId);
                    } else {
                        sb.setCompetitionBrandId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionBrandId")));
                        sb.setCompetitionBrand(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionBrand")));
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }


    public ArrayList<MasterCompetitionPromoType> getCompPromotionType() {
        ArrayList<MasterCompetitionPromoType> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select Distinct CompetitionPromoTypeId,CompetitionPromoType From Master_CompetitionPromoType", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitionPromoType sb = new MasterCompetitionPromoType();
                    sb.setCompetitionPromoTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionPromoTypeId")));
                    sb.setCompetitionPromoType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionPromoType")));


                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public ArrayList<MasterCompetitionOfferSaleRange> getCompOfferSaleRange() {
        ArrayList<MasterCompetitionOfferSaleRange> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select  SaleRange From Master_CompetitionOfferSaleRange", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitionOfferSaleRange sb = new MasterCompetitionOfferSaleRange();
                    sb.setSaleRange(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SaleRange")));


                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public ArrayList<MasterCompetitionOfferSet> getComOfferSet() {
        ArrayList<MasterCompetitionOfferSet> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select Distinct CompetitionOfferSetId,CompetitionOfferSet From Master_CompetitionOfferSet", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitionOfferSet sb = new MasterCompetitionOfferSet();
                    sb.setCompetitionOfferSetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionOfferSetId")));
                    sb.setCompetitionOfferSet(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionOfferSet")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }


    public ArrayList<MasterCompetitionOfferGet> getComOfferGet(int competitionOfferSetId) {
        ArrayList<MasterCompetitionOfferGet> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select Distinct CompetitionOfferGet,CompetitionOfferGetId,ShowProductTypeDropdown From Master_CompetitionOfferGet " + "Where CompetitionOfferSetId = " + competitionOfferSetId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitionOfferGet sb = new MasterCompetitionOfferGet();
                    sb.setCometitionOfferGetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompetitionOfferGetId")));
                    sb.setCompetitionOfferGet(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompetitionOfferGet")));
                    sb.setShowProductTypeDropdown("1".equals(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ShowProductTypeDropdown"))));


                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public boolean insertMasterCompetitonBrandWiseNuance(ResponseResult cst) {
        db.delete("Master_CompetitonBrandWiseNuance", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitonBrandWiseNuance> data = cst.getMasterCompetitonBrandWiseNuance();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CompetitionBrandId", data.get(i).getCompetitionBrandId());
                values.put("CompetitionNuanceId", data.get(i).getCompetitionNuanceId());
                values.put("CompetitionBrand", data.get(i).getCompetitionBrand());
                values.put("CompetitionNuance", data.get(i).getCompetitionNuance());
                long id = db.insert("Master_CompetitonBrandWiseNuance", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterCompetitionOfferSet(ResponseResult cst) {
        db.delete("Master_CompetitionOfferSet", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitionOfferSet> data = cst.getMasterCompetitionOfferSet();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CompetitionOfferSetId", data.get(i).getCompetitionOfferSetId());
                values.put("CompetitionOfferSet", data.get(i).getCompetitionOfferSet());

                long id = db.insert("Master_CompetitionOfferSet", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertMasterCompetitionOfferGet(ResponseResult cst) {
        db.delete("Master_CompetitionOfferGet", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitionOfferGet> data = cst.getMasterCompetitionOfferGet();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CompetitionOfferSetId", data.get(i).getCompetitionOfferSetId());
                values.put("CompetitionOfferGetId", data.get(i).getCometitionOfferGetId());
                values.put("CompetitionOfferGet", data.get(i).getCompetitionOfferGet());
                values.put("ShowProductTypeDropdown", data.get(i).getShowProductTypeDropdown());

                long id = db.insert("Master_CompetitionOfferGet", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertMasterCompetitionPromoType(ResponseResult cst) {
        db.delete("Master_CompetitionPromoType", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitionPromoType> data = cst.getMasterCompetitionPromoType();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CompetitionPromoTypeId", data.get(i).getCompetitionPromoTypeId());
                values.put("CompetitionPromoType", data.get(i).getCompetitionPromoType());

                long id = db.insert("Master_CompetitionPromoType", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterCompProductType(ResponseResult cst) {
        db.delete("Master_CompetitionProductType", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitionProductType> data = cst.getMasterCompetitionProductType();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CompetitionProductType", data.get(i).getCompetitionProductType());
                values.put("CompetitionProductTypeId", data.get(i).getCompetitionProductTypeId());

                long id = db.insert("Master_CompetitionProductType", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportSalesL3MValue> getreportthreemonthsalevalue(String userType) {
        ArrayList<ReportSalesL3MValue> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {
            String table = "Report_SalesL3MValue";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                table = "Report_SalesL3MValueME";
            }
            dbcursor = db.rawQuery("Select * from " + table + " ORDER BY Month DESC", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ReportSalesL3MValue sb = new ReportSalesL3MValue();
                    sb.setMonth(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Month")));
                    sb.setQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Qty")));
                    sb.setSalesValue(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("SalesValue")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    public ArrayList<MasterCompetitionOffer> getCompOfferType(boolean compoffer, boolean buyType, boolean buyTypeInput, boolean getTypeInput, int compOfferId, int compBuyTypeId, int compSetTypeId) {
        ArrayList<MasterCompetitionOffer> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String query = "";
            if (compoffer) {
                query = "Select Distinct CompOfferId,CompOffer From Master_CompetitionOffer";
            } else if (buyType) {
                query = "Select Distinct CompBuyType,CompBuyTypeId From Master_CompetitionOffer Where CompOfferId =" + compOfferId;
            } else if (buyTypeInput) {
                query = "Select Distinct CompSetName,CompSetId From Master_CompetitionOffer Where CompBuyTypeId =" + compBuyTypeId;
            } else {
                query = "Select Distinct CompGetName,CompGetId From Master_CompetitionOffer Where CompSetId =" + compSetTypeId;
            }

            dbcursor = db.rawQuery(query, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterCompetitionOffer sb = new MasterCompetitionOffer();
                    if (compoffer) {
                        sb.setCompOffer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompOffer")));
                        sb.setCompOfferId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompOfferId")));
                    } else if (buyType) {
                        sb.setCompBuyType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompBuyType")));
                        sb.setCompBuyTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompBuyTypeId")));
                    } else if (buyTypeInput) {
                        sb.setCompSetName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompSetName")));
                        sb.setCompSetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompSetId")));
                    } else {
                        sb.setCompGetName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CompGetName")));
                        sb.setCompGetId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CompGetId")));
                    }
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    public ArrayList<ReportDamageStockHistory> getdamagestockhistory(String counterId) {
        ArrayList<ReportDamageStockHistory> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select * from Report_DamageStockHistory Where CounterId=" + counterId + " ORDER BY VisitDate DESC", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();

                while (!dbcursor.isAfterLast()) {
                    ReportDamageStockHistory sb = new ReportDamageStockHistory();
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    sb.setProductCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductCode")));
                    sb.setProductName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductName")));
                    sb.setEanCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EanCode")));
                    sb.setMrp(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Mrp")));
                    sb.setDamageQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("DamageQty")));
                    sb.setVerify(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Verify")));
                    sb.setVerifyDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VerifyDate")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    public ArrayList<ReportSalesDateWise> getreportdaywisesale(String counterId, String userType) {
        ArrayList<ReportSalesDateWise> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {
            String table = "Report_SalesDateWise";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                table = "Report_SalesDateWiseME";
            }
            dbcursor = db.rawQuery("Select * from " + table + " where CounterId=" + counterId + " order by VisitDate desc", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();

                while (!dbcursor.isAfterLast()) {
                    ReportSalesDateWise sb = new ReportSalesDateWise();
                    sb.setCounterId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId")));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    sb.setWeekDays(dbcursor.getString(dbcursor.getColumnIndexOrThrow("WeekDays")));
                    sb.setQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Qty")));
                    sb.setSalesValue(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("SalesValue")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    public ArrayList<ReportProductGroupWiseSalesValue> getmasterLeaveType(String counterId) {
        ArrayList<ReportProductGroupWiseSalesValue> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select * from Report_ProductGroupWiseSalesValue where CounterId=" + counterId + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ReportProductGroupWiseSalesValue sb = new ReportProductGroupWiseSalesValue();
                    sb.setProductGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductGroupId")));
                    sb.setProductGroupName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductGroupName")));
                    sb.setMTDTg(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDTg")));
                    sb.setMTDAch(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MTDAch")));
                    sb.setAchPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("AchPer")));
                    sb.setPending(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Pending")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }

    public ArrayList<MasterLeaveType> getmasterLeaveType(boolean emargancy) {
        ArrayList<MasterLeaveType> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            if (emargancy) {
                dbcursor = db.rawQuery("Select * from Master_LeaveType where Show ='1'", null);
            } else {
                dbcursor = db.rawQuery("Select * from Master_LeaveType", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterLeaveType sb = new MasterLeaveType();

                    sb.setLeaveTypeId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("LeaveTypeId")));
                    sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    public long saveBASurveyAnswerData(ArrayList<MasterSurvey> listDataHeader, HashMap<MasterSurvey, ArrayList<BASurveyGetterSetter>> data, String counter_id, String visit_date, JourneyPlan jcp_Object, String surveyType) {
        long l = 0, l2 = 0;
        if (surveyType.trim().equalsIgnoreCase("BA")) {
            db.delete(CommonString.TABLE_BA_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null);
            db.delete(CommonString.TABLE_BA_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " = " + counter_id + "", null);
        } else {
            db.delete(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null);
            db.delete(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + "", null);
        }

        ContentValues values = new ContentValues();
        ContentValues values1 = new ContentValues();

        try {
            db.beginTransaction();
            for (int i = 0; i < listDataHeader.size(); i++) {
                if (surveyType.equalsIgnoreCase("BA")) {
                    values.put(CommonString.KEY_BID, jcp_Object.getBID());
                } else {
                    values.put(CommonString.KEY_MID, jcp_Object.getMID());
                }
                values.put(CommonString.KEY_COUNTER_ID, counter_id);
                values.put(CommonString.KEY_VISIT_DATE, visit_date);
                values.put(CommonString.KEY_Survey_Id, listDataHeader.get(i).getSurveyId());
                values.put(CommonString.KEY_Survey_Name, listDataHeader.get(i).getSurveyName());
                values.put(CommonString.KEY_Survey_Type, listDataHeader.get(i).getSurveyType());
                values.put(CommonString.KEY_UPLOAD_STATUS, "0");
                if (surveyType.trim().equalsIgnoreCase("BA")) {
                    if (!db.isOpen()) {
                        open();
                    }
                    l = db.insert(CommonString.TABLE_BA_SURVEY_HEADER_DATA, null, values);
                } else {
                    if (!db.isOpen()) {
                        open();
                    }
                    l = db.insert(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, null, values);
                }
                for (int j = 0; j < data.get(listDataHeader.get(i)).size(); j++) {
                    values1.put(CommonString.KEY_COMMON_ID, (int) l);
                    if (surveyType.equalsIgnoreCase("BA")) {
                        values1.put(CommonString.KEY_BID, jcp_Object.getBID());
                    } else {
                        values1.put(CommonString.KEY_MID, jcp_Object.getMID());
                    }
                    values1.put(CommonString.KEY_COUNTER_ID, counter_id);
                    values1.put(CommonString.KEY_Survey_Id, listDataHeader.get(i).getSurveyId());
                    values1.put(CommonString.KEY_Survey_Question, data.get(listDataHeader.get(i)).get(j).getSurveyQuestion());
                    values1.put(CommonString.KEY_Survey_Question_Id, data.get(listDataHeader.get(i)).get(j).getSurveyQuestionId());
                    values1.put(CommonString.KEY_Correct_Answer_Id, data.get(listDataHeader.get(i)).get(j).getCorrect_answer_id());
                    values1.put(CommonString.KEY_Image_Allow, data.get(listDataHeader.get(i)).get(j).getImageAllow());
                    values1.put(CommonString.KEY_Question_Type, data.get(listDataHeader.get(i)).get(j).getSurveyQuestionType());
                    values1.put(CommonString.KEY_Survey_Question_Image, data.get(listDataHeader.get(i)).get(j).getCam_image());
                    values1.put(CommonString.KEY_UPLOAD_STATUS, "0");
                    values1.put(CommonString.KEY_Correct_Answer, data.get(listDataHeader.get(i)).get(j).getSurveyAnswer());
                    if (surveyType.trim().equalsIgnoreCase("BA")) {
                        if (!db.isOpen()) {
                            open();
                        }
                        l2 = db.insert(CommonString.TABLE_BA_SURVEY_CHILD_DATA, null, values1);
                    } else {
                        if (!db.isOpen()) {
                            open();
                        }
                        l2 = db.insert(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, null, values1);
                    }
                }
            }
            closeDb();
        } catch (Exception ex) {
            closeDb();
        }

        return l2;
    }


    public ArrayList<MasterSurvey> getSurveyData(String surveyType) {
        Cursor cursordata = null;
        ArrayList<MasterSurvey> auditData = new ArrayList<>();
        try {
            cursordata = db.rawQuery("Select distinct SurveyId,SurveyName,UploadStatus from Master_Survey where SurveyType = '" + surveyType + "'", null);
            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterSurvey sb = new MasterSurvey();
                    sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow("SurveyId")));
                    sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyName")));
                    sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow("UploadStatus")));
                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in  Master_Survey" + ex.toString());
        }
        return auditData;

    }


    public boolean getSurveyUploadStatus(String surveyType, String surveyId, String userId, String counterId) {
        Cursor dbcursor = null;
        boolean uploadstatus = false;
        try {
            if (surveyType != null && surveyType.equalsIgnoreCase(CommonString.TAG_FROM_BA)) {
                dbcursor = db.rawQuery("select distinct BASurveyUpload as surveyupload from Master_Survey_UploadStatus T1 Inner Join BA_List T2 on T1.EmpId=T2.EmpId " + "where T2.UserName='" + userId + "' and T1.SurveyType='" + surveyType + "' and T1.SurveyId=" + surveyId + " and T2.CounterId=" + counterId + "", null);

            } else {
                dbcursor = db.rawQuery("select distinct CounterSurveyUpload as surveyupload from Master_Survey_UploadStatus T1 " + "where T1.SurveyType='" + surveyType + "' and T1.SurveyId=" + surveyId + " and T1.CounterId=" + counterId + "", null);

            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("surveyupload"));
                    if (user_idget != null && !user_idget.equals("") && !user_idget.equalsIgnoreCase(CommonString.KEY_N)) {
                        uploadstatus = true;
                        break;

                    } else {
                        uploadstatus = false;
                    }

                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }

        } catch (Exception ex) {
            return uploadstatus;

        }

        return uploadstatus;

    }


    public boolean getMeQuizUploadStatus(String QuizId, String userId, String counterId) {
        Cursor dbcursor = null;
        boolean uploadstatus = false;
        try {

            dbcursor = db.rawQuery("select distinct UploadStatus from ME_MEAuditQuestion_UploadStatus T1 Inner Join BA_List T2 on T1.EmpId=T2.EmpId " + "where T2.UserName='" + userId + "' and T2.DesignationName='ME' and T1.QuizId=" + QuizId + " and T2.CounterId=" + counterId + "", null);


            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {

                    String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("UploadStatus"));
                    if (user_idget != null && !user_idget.equals("") && !user_idget.equalsIgnoreCase(CommonString.KEY_N)) {
                        uploadstatus = true;
                        break;

                    } else {
                        uploadstatus = false;
                    }

                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }

        } catch (Exception ex) {
            return uploadstatus;

        }

        return uploadstatus;

    }


    public ArrayList<MasterSurvey> getSurveyData(String surveyType, String surveyId) {
        Cursor cursordata = null;
        ArrayList<MasterSurvey> auditData = new ArrayList<>();
        try {
            cursordata = db.rawQuery("Select distinct SurveyId,SurveyName,SurveyType,UploadStatus from Master_Survey where SurveyType = '" + surveyType + "' and SurveyId =" + surveyId + "", null);
            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterSurvey sb = new MasterSurvey();

                    sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow("SurveyId")));
                    sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyName")));
                    sb.setSurveyType(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyType")));
                    sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow("UploadStatus")));

                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in  Master_Survey" + ex.toString());
        }
        return auditData;

    }


    //Category wise Audit
    public ArrayList<BASurveyGetterSetter> getSurveyWiseData(int surveyId) {
        Cursor cursordata = null;

        ArrayList<BASurveyGetterSetter> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("Select  distinct SurveyQuestionId,SurveyQuestion,ImageAllow,SurveyQuestionType from " + "Master_Survey where SurveyId =" + surveyId + "", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    BASurveyGetterSetter sb = new BASurveyGetterSetter();

                    sb.setSurveyQuestion(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyQuestion")));
                    sb.setSurveyQuestionId(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyQuestionId")));
                    sb.setSurveyQuestionType(cursordata.getString(cursordata.getColumnIndexOrThrow("SurveyQuestionType")));
                    sb.setImageAllow(cursordata.getString(cursordata.getColumnIndexOrThrow("ImageAllow")));

                    auditData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }
        return auditData;
    }

    public ArrayList<BASurveyGetterSetter> getSurveyAnswerData(BASurveyGetterSetter auditGetSet, String select) {
        ////////test("Fetching", "Storedata--------------->Start<------------");
        ArrayList<BASurveyGetterSetter> list = new ArrayList<>();
        if (auditGetSet.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") || auditGetSet.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice")) {
            BASurveyGetterSetter sb1 = new BASurveyGetterSetter();
            sb1.setSurveyAnswerId("0");
            sb1.setSurveyAnswer(select);
            list.add(0, sb1);
        } else if (auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Text")) {
            BASurveyGetterSetter sb1 = new BASurveyGetterSetter();
            sb1.setSurveyAnswerId("0");
            sb1.setSurveyAnswer("");
            list.add(0, sb1);
        }


        Cursor dbcursor = null;

        try {

            if (auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Text") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Number") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Decimal")) {
                dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_CHILD_DATA + " where Survey_Question_Id =" + auditGetSet.getSurveyQuestionId() + "", null);
            } else {
                dbcursor = db.rawQuery("Select * from Master_Survey where SurveyQuestionId = " + auditGetSet.getSurveyQuestionId() + "", null);
            }

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    BASurveyGetterSetter sb = new BASurveyGetterSetter();
                    if (auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Text") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Number") || auditGetSet.getSurveyQuestionType().trim().equalsIgnoreCase("Decimal")) {
                        //sb.setCorrect_answer_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Correct_Answer_Id")));
                        sb.setSurveyAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Question_Correct_Answer")));
                        sb.setCam_image(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Survey_Question_Image")));
                    } else {
                        sb.setSurveyAnswerId(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SurveyAnswerId")));
                        sb.setSurveyAnswer(dbcursor.getString(dbcursor.getColumnIndexOrThrow("SurveyAnswer")));
                    }
                    BASurveyGetterSetter obj = getInsertedChildData(auditGetSet.getSurveyQuestionId());
                    if (obj != null) {
                        sb.setCorrect_answer_id(obj.getCorrect_answer_id());
                        sb.setCam_image(obj.getCam_image());
                    } else {
                        sb.setCorrect_answer_id("");
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return list;
        }
        ////////test("Fetching", " audit answer-->Stop<-");
        return list;
    }


    private BASurveyGetterSetter getInsertedChildData(String question_id) {
        Cursor dbcursor = null;
        BASurveyGetterSetter sb = null;
        try {
            dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_CHILD_DATA + " where Survey_Question_Id =" + question_id + "", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new BASurveyGetterSetter();

                    sb.setCorrect_answer_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Correct_Answer_Id")));
                    sb.setCam_image(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Survey_Question_Image")));

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return sb;
        }
        ////////test("Fetching", " audit answer-->Stop<-");
        return sb;
    }

    public ArrayList<MasterSurvey> getBASurveySavedData(String surveyType, JourneyPlan jcp_object, String date) {
        Cursor cursordata = null;

        ArrayList<MasterSurvey> surveyData = new ArrayList<>();
        try {

            if (surveyType.trim().equalsIgnoreCase("BA")) {
                cursordata = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_BID + " = '" + jcp_object.getBID() + "' and " + CommonString.KEY_VISIT_DATE + " = '" + date + "'", null);
            } else {
                cursordata = db.rawQuery("Select * from " + CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_MID + " = '" + jcp_object.getMID() + "' and " + CommonString.KEY_VISIT_DATE + " = '" + date + "'", null);
            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterSurvey sb = new MasterSurvey();
                    sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Name)));
                    sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Id)));
                    sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS)));
                    sb.setSurveyType(cursordata.getString(cursordata.getColumnIndexOrThrow("Survey_Type")));
                    sb.setCommon_id(cursordata.getString(cursordata.getColumnIndexOrThrow("KEY_ID")));
                    surveyData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in  " + ex.toString());
        }
        return surveyData;
    }

    public ArrayList<BASurveyGetterSetter> getChildData(String surveyType, JourneyPlan jcp_object, String visit_date, String common_id) {
        Cursor cursordata = null;

        ArrayList<BASurveyGetterSetter> surveyData = new ArrayList<>();
        try {

            if (surveyType.trim().equalsIgnoreCase("BA")) {
                cursordata = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_CHILD_DATA + " where " + CommonString.KEY_BID + " = '" + jcp_object.getBID() + "' and " + CommonString.KEY_COMMON_ID + " = '" + common_id + "'", null);
            } else {
                cursordata = db.rawQuery("Select * from " + CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA + " where " + CommonString.KEY_MID + " = '" + jcp_object.getMID() + "' and " + CommonString.KEY_COMMON_ID + " = '" + common_id + "'", null);
            }
            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    BASurveyGetterSetter sb = new BASurveyGetterSetter();

                    sb.setSurveyId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Id)));

                    sb.setSurveyQuestionId(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Question_Id)));

                    sb.setCam_image(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Question_Image)));

                    sb.setSurveyAnswer(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Correct_Answer)));

                    sb.setCorrect_answer_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Correct_Answer_Id)));

                    surveyData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }
        return surveyData;
    }

    public void updateBASurveyData(String surveyType, String status) {
        ContentValues values = new ContentValues();
        try {
            values.put(CommonString.KEY_UPLOAD_STATUS, status);
            if (!db.isOpen()) {
                open();
            }
            if (surveyType.trim().equalsIgnoreCase("BA")) {
                db.update(CommonString.TABLE_BA_SURVEY_HEADER_DATA, values, null, null);
                db.update(CommonString.TABLE_BA_SURVEY_CHILD_DATA, values, null, null);
            } else {
                db.update(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, values, null, null);
                db.update(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, values, null, null);
            }
        } catch (Exception ex) {
            ex.fillInStackTrace();
        }
    }


    public void deleteBASurveyData(String counter_id, String visit_date) {
        try {
            if (!db.isOpen()) {
                open();
            }
            db.delete(CommonString.TABLE_BA_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null);
            db.delete(CommonString.TABLE_BA_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void deleteCompOffers(String counter_id, String visit_date, String keyId) {
        try {

            db.delete(CommonString.TABLE_COMP_OFFERS, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " ='" + visit_date + "' AND " + CommonString.KEY_ID + "=" + keyId + "", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }


    public void deleteCounterSurveyData(String counter_id, String visit_date) {
        try {
            if (!db.isOpen()) {
                open();
            }
            db.delete(CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null);
            db.delete(CommonString.TABLE_COUNTER_SURVEY_CHILD_DATA, CommonString.KEY_COUNTER_ID + " =" + counter_id + " and " + CommonString.KEY_VISIT_DATE + " <> '" + visit_date + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }


    public ArrayList<MasterSurvey> getBASurveySavedData1(String surveyType, JourneyPlan jcp_object, String date) {
        Cursor cursordata = null;

        ArrayList<MasterSurvey> surveyData = new ArrayList<>();
        try {

            if (surveyType.trim().equalsIgnoreCase("BA")) {
                cursordata = db.rawQuery("Select * from " + CommonString.TABLE_BA_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_BID + " = '" + jcp_object.getBID() + "' and " + CommonString.KEY_VISIT_DATE + " <> '" + date + "'", null);
            } else {
                cursordata = db.rawQuery("Select * from " + CommonString.TABLE_COUNTER_SURVEY_HEADER_DATA + " where Survey_Type = '" + surveyType + "' and " + CommonString.KEY_MID + " = '" + jcp_object.getMID() + "' and " + CommonString.KEY_VISIT_DATE + " <> '" + date + "'", null);
            }
            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    MasterSurvey sb = new MasterSurvey();

                    sb.setSurveyName(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Name)));

                    sb.setSurveyId(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_Survey_Id)));

                    sb.setUploadStatus(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_UPLOAD_STATUS)));

                    sb.setSurveyType(cursordata.getString(cursordata.getColumnIndexOrThrow("Survey_Type")));
                    sb.setCommon_id(cursordata.getString(cursordata.getColumnIndexOrThrow("KEY_ID")));

                    surveyData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }
        return surveyData;
    }


    public long insert_consumer_tempsales_data(String user_Id, String visit_date, String counter_Id, ArrayList<InvoiceGetterSetter> invoiceHeaderList) {
        db.delete(CommonString.Table_Temp_Consumer_Sale, null, null);
        ContentValues values = new ContentValues();
        long l2 = 0;

        try {

            db.beginTransaction();
            for (int i = 0; i < invoiceHeaderList.size(); i++) {
                if (!invoiceHeaderList.get(i).getStr_invoiceType().isEmpty() && invoiceHeaderList.get(i).getStr_invoiceType().equalsIgnoreCase("Saleable")) {
                    values.put("USER_ID", user_Id);
                    values.put(CommonString.KEY_COUNTER_ID, counter_Id);
                    values.put(CommonString.KEY_VISIT_DATE, visit_date);
                    values.put("ProductId", invoiceHeaderList.get(i).getProduct_Id());
                    values.put("Quantity", invoiceHeaderList.get(i).getQuantity());
                    values.put("Amount", invoiceHeaderList.get(i).getProduct_rate());
                    if (!db.isOpen()) {
                        open();
                    }
                    l2 = db.insert(CommonString.Table_Temp_Consumer_Sale, null, values);
                }
            }

            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Table_Temp_Consumer_Sale Data " + ex.toString());
        }

        return l2;
    }


    public long updatereturntodistributor(String counterId, String uuid) {
        long l = 0;
        try {
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_STATUS, CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.TABLE_RETURNTO_DISTRIBUTOR_DATA, values, CommonString.KEY_UUID + " ='" + uuid + "' and " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long updateinwarddms(String counterId, String uuid) {
        long l = 0;
        try {

            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update("DR_INWARD_STOCK_TRANSACTION", values, CommonString.KEY_TRANSACTION_ID + " ='" + uuid + "' AND " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long updatemanualinward(String counterId, String uuid) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_UPLOAD_STATUS, CommonString.KEY_Y);
            l = db.update(CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION, values, CommonString.KEY_TRANSACTION_ID + " ='" + uuid + "' and " + CommonString.KEY_COUNTER_ID + "=" + counterId + "", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long update_SalesTRacking(String counterId, String uuid_Id) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            l = db.update(CommonString.Table_Sale_Tracking_Header_Data, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null);
            l = db.update(CommonString.Table_Sale_Tracking, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long update_ConsumersReturn(String counterId, String uuid_Id) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);
            l = db.update(CommonString.Table_Consumer_Return_Header_Data, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null);
            l = db.update(CommonString.Table_Consumer_Return, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + uuid_Id + "'", null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }


    public ArrayList<ProductMaster> getreturntodistributor_byUUID(String uuid) {
        Cursor cursordata = null;
        ArrayList<ProductMaster> auditData = new ArrayList<>();
        try {

            cursordata = db.rawQuery("select * from TABLE_RETURNTO_DISTRIBUTOR where UUID_ID ='" + uuid + "'and STATUS='N'", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();

                    sb.setStock_type(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK_TYPE)));
                    sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID)));
                    sb.setTransaction_Id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_UUID)));
                    sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_ProductId)));
                    sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow(CommonString.KEY_STOCK)));
                    sb.setUser_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));

                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }
        } catch (Exception ex) {
            ////////test("Exception ", " in  Master_Survey" + ex.toString());
        }

        return auditData;

    }


    public long insert_temp_image(String file_name, String visit_date) {
        db.delete(CommonString.Table_Temp_Image, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues values = new ContentValues();
        long l2 = 0;

        try {
            db.beginTransaction();
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("ImageName", file_name);
            long l = db.insert(CommonString.Table_Temp_Image, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Posm Master Data " + ex.toString());
        }


        return l2;
    }


    public boolean ischeck_uploaded_image(String visit_date, String imagepath) {
        boolean filled = false;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * from " + CommonString.Table_Temp_Image + " where " + CommonString.KEY_VISIT_DATE + "='" + visit_date + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    String user_idget = dbcursor.getString(dbcursor.getColumnIndexOrThrow("ImageName"));
                    if (user_idget != null && !user_idget.equals("") && user_idget.equalsIgnoreCase(imagepath)) {
                        filled = true;
                        break;
                    } else {
                        filled = false;
                    }
                    dbcursor.moveToNext();
                }

                dbcursor.close();
            }
        } catch (Exception e) {
            ////////test("Exception--", e.toString());
            return filled;
        }
        return filled;
    }


    public ArrayList<ProductMaster> getsalesReports(String type, String userType) {
        Cursor cursordata = null;
        ArrayList<ProductMaster> surveyData = new ArrayList<>();
        try {
            String query = "", table = "Report_Sales_Detail";
            if (userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                table = "Report_Sales_DetailME";
            }
            if (type.equalsIgnoreCase("Product")) {
                query = "select P.ProductId, p.ProductName, s.Qty, ifnull(s.SalesValue,0) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId";
            } else if (type.equalsIgnoreCase("Axe")) {
                query = "select  p.AxeName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.AxeName";
            } else if (type.equalsIgnoreCase("Sub Axe")) {
                query = "select  p.SubAxeName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.SubAxeName";
            } else if (type.equalsIgnoreCase("Signature")) {
                query = "select  p.SignatureName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.SignatureName";
            } else if (type.equalsIgnoreCase("Sub Brand")) {
                query = "select  p.SubBrandName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.SubBrandName";
            } else if (type.equalsIgnoreCase("Brand")) {
                query = "select  p.BrandName as ProductName, sum(ifnull(s.Qty,0)) as Qty, sum(ifnull(s.SalesValue,0)) as Value from " + table + " s " + "inner join Product_Master p on s.ProductId = p.ProductId group by p.BrandName";
            }

            cursordata = db.rawQuery(query, null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setProductName(cursordata.getString(cursordata.getColumnIndexOrThrow("ProductName")));
                    sb.setActualQty(cursordata.getString(cursordata.getColumnIndexOrThrow("Qty")));
                    sb.setSaleValue(cursordata.getDouble(cursordata.getColumnIndexOrThrow("Value")));
                    surveyData.add(sb);
                    cursordata.moveToNext();
                }
                cursordata.close();
            }

        } catch (Exception ex) {
            ////////test("Exception ", " in ADDITIONAL_QUESTION " + ex.toString());
        }
        return surveyData;
    }


    public long update_temp_promo_apply_definition(String counterId, String userId, String promoId, String visit_date) {
        ContentValues values1 = new ContentValues();
        long l = 0;
        try {
            values1.put("Qualified_Status", "Ok");
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.Table_Temp_Temp_Promo_AplyDefinition, values1, "COUNTER_ID=" + counterId + " and Visit_Date ='" + visit_date + "' and USER_ID ='" + userId + "' and PromoId ='" + promoId + "'", null);
        } catch (Exception ex) {
            ex.fillInStackTrace();
        }

        return l;
    }

    public long update_temp_promo_apply_definitionfor_andpromo(int masterId, String counterId, String userId, int promoId, String visit_date) {
        ContentValues values1 = new ContentValues();
        long l = 0;
        try {
            values1.put("Qualified_Status", "Ok");
            if (!db.isOpen()) {
                open();
            }
            l = db.update(CommonString.Table_Temp_Temp_Promo_AplyDefinitionfor_and, values1, "COUNTER_ID=" + counterId + " and Visit_Date ='" + visit_date + "' and USER_ID ='" + userId + "' and PromoId =" + promoId + " and MasterId=" + masterId, null);

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

        return l;
    }

    public long delete_table_temp() {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            l = db.delete(CommonString.Table_Temp_Temp_Promo_AplyDefinition, null, null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }

    public long delete_table_tempforsameproduct() {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            l = db.delete(CommonString.Table_Temp_Promotion_OffSameProduct, null, null);
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return l;
    }


    public long delete_table_tempfor_andpromo() {
        long l = 0;
        try {
            if (db.isOpen()) {
            } else {
                open();
            }

            l = db.delete(CommonString.Table_Temp_Temp_Promo_AplyDefinitionfor_and, null, null);

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

        return l;
    }

    public ArrayList<MasterPromotionSetEntityItem> getsetintitiytemId(int promoId) {
        ArrayList<MasterPromotionSetEntityItem> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select distinct Id,ItemCount,PromoId from Master_PromotionSetEntityItem where PromoId =" + promoId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    MasterPromotionSetEntityItem sb = new MasterPromotionSetEntityItem();
                    sb.setId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Id")));
                    sb.setPromoId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("PromoId")));
                    sb.setItemCount(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ItemCount")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    @SuppressLint("Recycle")
    public int getPromotiongetProductforAndPromo(int andId, String promoId, boolean flag_for_qty, String userId, String visit_date, String counterId) {
        int value = 0;
        Cursor dbcursor = null;
        Cursor dbcursor1 = null;
        try {

            dbcursor1 = db.rawQuery("Select * from Master_PromotionSetEntityItem where PromoId =" + promoId + " and Id=" + andId, null);

            if (dbcursor1 != null) {
                dbcursor1.moveToFirst();
                while (!dbcursor1.isAfterLast()) {
                    String setentitiy_listType = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListType"));
                    String setEntityListItem = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListItem"));
                    String val_str = "";
                    if (flag_for_qty) {
                        val_str = "Quantity";
                    } else {
                        val_str = "Quantity * Amount";
                    }
                    if (db.isOpen()) {
                    } else {
                        open();
                    }
                    if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("ProductGroup")) {
                        ////change by mahesh sir.........
                        db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity," + " a.Amount from (select *  from Temp_Consumer_Sale " + "where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId");

                        dbcursor = db.rawQuery("   select ifnull(sum(" + val_str + "),0) as Total_Value from (select *  from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                " ) as  a inner join " + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId", null);

                    } else if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("Catalog")) {
                        if (!db.isOpen()) {
                            open();
                        }
                        db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity, a.Amount from (select *  from Temp_Consumer_Sale " + " where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductCatalog where" + " CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId");

                        dbcursor = db.rawQuery("select ifnull(sum(Quantity),0) as Total_Value from (select *  from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                " ) as  a inner join " + "(WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "select * from Master_PromotionSetProductCatalog where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) " + "b on a.ProductId = b.ProductId", null);

                    } else {
                        ///Checked Setentity list item for product
                        if (!db.isOpen()) {
                            open();
                        }

                        if (setEntityListItem != null && setEntityListItem.equalsIgnoreCase("All")) {
                            db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity, a.Amount from (select *  from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a");

                            dbcursor = db.rawQuery("select ifnull(sum(" + val_str + "),0) as Total_Value from (select *  from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                    " )", null);

                        } else {
                            db.execSQL("Insert into Temp_Promo_AplyDefinitionfor_and(COUNTER_ID,Visit_Date,USER_ID,MasterId,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + andId + "','" + promoId + "'," + " a.ProductId, a.Quantity, a.Amount from (select *  from Temp_Consumer_Sale" + " where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                    " ) as a inner join" + " (WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId");

                            dbcursor = db.rawQuery("select ifnull(sum(" + val_str + "),0) as Total_Value from (select *  from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promoId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                    " ) as  a inner join " + "(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promoId + " and Id=" + andId + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b " + "on a.ProductId = b.ProductId", null);

                        }
                    }

                    if (dbcursor != null) {
                        dbcursor.moveToFirst();
                        while (!dbcursor.isAfterLast()) {
                            value = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Total_Value"));
                            dbcursor.moveToNext();
                        }

                        dbcursor.close();
                        return value;
                    }

                }
            }
        } catch (Exception e) {
            ////////test("Exception", " answer " + e);
            return value;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return value;
    }

    public long inserttemp_promo_data(String counterId, String visit_date, String userId, MasterPromotion promotionOb) {
        long l = 0;
        try {
            if (!db.isOpen()) open();

            db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Rate from (select *  from Temp_Promo_AplyDefinitionfor_and " + "where  PromoId=" + promotionOb.getPromoId() + " and COUNTER_ID=" + counterId + " ) as a");

            if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) {
                db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Rate from (select *  from Temp_Promo_AplyDefinitionfor_and " + "where  PromoId=" + promotionOb.getPromoId() + " and COUNTER_ID=" + counterId + " ) as a");

            }
        } catch (SQLException e) {
            e.fillInStackTrace();
        }
        return l;
    }

    @SuppressLint("Recycle")
    public int getPromotiongetProductall(MasterPromotion promotionOb, boolean flag_for_qty, String userId, String visit_date, String counterId) {
        int value = 0;
        Cursor dbcursor = null;
        Cursor dbcursor1 = null;
        try {

            dbcursor1 = db.rawQuery("Select * from Master_PromotionSetEntityItem where PromoId =" + promotionOb.getPromoId(), null);

            if (dbcursor1 != null) {
                dbcursor1.moveToFirst();
                while (!dbcursor1.isAfterLast()) {
                    String setentitiy_listType = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListType"));
                    String setEntityListItem = dbcursor1.getString(dbcursor1.getColumnIndexOrThrow("SetEntityListItem"));
                    String val_str = "";
                    if (flag_for_qty) {
                        val_str = "Quantity";
                    } else {
                        val_str = "Quantity * Amount";
                    }
                    if (db.isOpen()) {
                    } else {
                        open();
                    }
                    if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("ProductGroup")) {
                        ////change by mahesh sir.........
                        db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select *  from Temp_Consumer_Sale " + "where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT" + " id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b on a.ProductId = b.ProductId");

                        if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) {
                            db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select *  from Temp_Consumer_Sale " + "where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                    " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT" + " id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b on a.ProductId = b.ProductId");
                        }

                        dbcursor = db.rawQuery("   select ifnull(sum(" + val_str + "),0) as Total_Value from (select *  from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as  a inner join " + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + " select * from Master_PromotionSetProductGroup where" + " ProductGroupId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b on a.ProductId = b.ProductId", null);

                    } else if (setentitiy_listType != null && !setentitiy_listType.isEmpty() && setentitiy_listType.trim().equalsIgnoreCase("Catalog")) {
                        db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select *  from Temp_Consumer_Sale " + "where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' " + "FROM Master_PromotionSetEntityItem WHERE PromoId=" + promotionOb.getPromoId() + "" + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductCatalog where" + " CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId");

                        if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) {
                            db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate)" + "select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount" + " from (select *  from Temp_Consumer_Sale " + "where  USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                    " ) as a inner join" + " (WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' " + "FROM Master_PromotionSetEntityItem WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + " select * from Master_PromotionSetProductCatalog where" + " CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) b " + "on a.ProductId = b.ProductId");
                        }

                        dbcursor = db.rawQuery("select ifnull(sum(Quantity),0) as Total_Value from (select *  from Temp_Consumer_Sale " + "where USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                " ) as  a inner join " + "(WITH RECURSIVE neat( id, tag, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "select * from Master_PromotionSetProductCatalog where CatalogId in(SELECT tag FROM neat WHERE tag <> '' ORDER BY id ASC , tag ASC) ) " + "b on a.ProductId = b.ProductId", null);

                    } else {
                        if (!db.isOpen()) {
                            open();
                        }

                        if (setEntityListItem != null && setEntityListItem.equalsIgnoreCase("All")) {
                            db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Amount from (select *  from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a");

                            if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) {
                                db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity," + " a.Amount from (select *  from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a");
                            }
                            dbcursor = db.rawQuery("  select ifnull(sum(" + val_str + "),0) as Total_Value from (select *  from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "' and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " )", null);

                        } else {

                            db.execSQL("Insert into Temp_Promo_AplyDefinition(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount from (select *  from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                    " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as a inner join" + " (WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId");

                            if (promotionOb.getPromotionGetEntityType().equalsIgnoreCase("OffSameProduct")) {
                                db.execSQL("Insert into Temp_Promotion_OffSameProduct(COUNTER_ID,Visit_Date,USER_ID,PromoId,ProductId, Quantity,Rate) " + " select '" + counterId + "','" + visit_date + "','" + userId + "','" + promotionOb.getPromoId() + "'," + " a.ProductId, a.Quantity, a.Amount from (select *  from Temp_Consumer_Sale where " + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId +

                                        " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" +

                                        " ) as a inner join" + " (WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem " + "WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '') " + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId");

                            }

                            dbcursor = db.rawQuery("  select ifnull(sum(" + val_str + "),0) as Total_Value from (select *  from Temp_Consumer_Sale where" + " USER_ID='" + userId + "'AND Visit_Date='" + visit_date + "'and COUNTER_ID=" + counterId + " and ProductId not in(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetExclusionList || ','" + " FROM Master_PromotionSetExclusionList WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '')" + " ) as  a inner join " + "(WITH RECURSIVE neat( id, ProductId, etc) AS(SELECT PromoId, '' , SetEntityListItem || ',' FROM Master_PromotionSetEntityItem" + " WHERE PromoId=" + promotionOb.getPromoId() + " UNION ALL SELECT  id, SUBSTR(etc, 0, INSTR(etc, ',')) , SUBSTR(etc, INSTR(etc, ',')+1) FROM neat WHERE etc <> '')" + "SELECT ProductId FROM neat WHERE ProductId <> '' ORDER BY id ASC , ProductId ASC) as b on a.ProductId = b.ProductId", null);

                        }
                    }

                    if (dbcursor != null) {
                        dbcursor.moveToFirst();
                        while (!dbcursor.isAfterLast()) {
                            value = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Total_Value"));
                            dbcursor.moveToNext();
                        }

                        dbcursor.close();
                        return value;
                    }
                }
            }

        } catch (Exception e) {
            ////////test("Exception", " answer " + e.toString());
            return value;
        }

        ////////test("Fetching", " audit answer-->Stop<-");
        return value;
    }


    public int checked_applyied_promo(String promoId, String userId, String visit_date, String counterId, String check_promoId) {
        int value = 0;
        Cursor dbcursor = null;
        try {
            dbcursor = db.rawQuery("select ifnull(count(*),0) as TotalCount from " + "(select * from Temp_Promo_AplyDefinition where COUNTER_ID =" + counterId + "  and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + promoId + ") as Ck_promoId " + "Inner join " + "(select * from Temp_Promo_AplyDefinition where COUNTER_ID =" + counterId + "  and User_Id = '" + userId + "' and Visit_Date ='" + visit_date + "' and PromoId =" + check_promoId + ") as tick_promoid " + "on Ck_promoId.ProductId = tick_promoid.ProductId", null);
            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    value = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalCount"));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return value;
            }

        } catch (Exception e) {
            ////////test("Exception", " answer " + e);
            return value;
        }
        ////////test("Fetching", " audit answer-->Stop<-");
        return value;
    }

    public ArrayList<ProductMaster> gettransaction_date(int master_transaction_id) {
        Cursor cursordata = null;
        ArrayList<ProductMaster> auditData = new ArrayList<>();
        try {
            String str_data = "MASTER_TRANSACTION_ID,User_Id,COUNTER_ID,UUID_ID,STOCK_TYPE,ProductId,REASON_ID,STORE_IMAGE,STOCK,ENTRY_TYPE";
            cursordata = db.rawQuery("select distinct " + str_data + " from TABLE_TRANSACTION_DATA  where MASTER_TRANSACTION_ID =" + master_transaction_id + "", null);

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setMaster_transaction_id(cursordata.getInt(cursordata.getColumnIndexOrThrow("MASTER_TRANSACTION_ID")));
                    sb.setUser_id(cursordata.getString(cursordata.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    sb.setCounter_id(cursordata.getString(cursordata.getColumnIndexOrThrow("COUNTER_ID")));
                    sb.setTransaction_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("UUID_ID")));
                    sb.setStock_type(cursordata.getString(cursordata.getColumnIndexOrThrow("STOCK_TYPE")));
                    sb.setProductId(cursordata.getInt(cursordata.getColumnIndexOrThrow("ProductId")));
                    sb.setReasonId(cursordata.getInt(cursordata.getColumnIndexOrThrow("REASON_ID")));
                    sb.setImagePath(cursordata.getString(cursordata.getColumnIndexOrThrow("STORE_IMAGE")));
                    sb.setStock(cursordata.getInt(cursordata.getColumnIndexOrThrow("STOCK")));
                    String stock_entry_type = cursordata.getString(cursordata.getColumnIndexOrThrow("ENTRY_TYPE"));
                    if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Draft")) {
                        sb.setEntry_type(CommonString.KEY_DRAFT);
                    } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Comp")) {
                        sb.setEntry_type(CommonString.KEY_COMPLETE);
                    } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        sb.setEntry_type(CommonString.KEY_REGULAR);
                    }

                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }
        } catch (Exception ex) {
            ////////test("Exception ", " in  Master_Survey" + ex.toString());
        }

        return auditData;

    }


    public ArrayList<ProductMaster> getInwardStockTransactionData(String uuid_id) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_INWARD_STOCK_TRANSACTION + " where " + CommonString.KEY_TRANSACTION_ID + " = '" + uuid_id + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    String checkVal1 = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SKU_CONFIRMATION_CHECK));
                    sb.setCounter_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID)));
                    sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY)));
                    sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY)));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId)));
                    sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_REASON_ID)));
                    sb.setUser_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    sb.setInvId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_ID)));
                    sb.setInvoice_Status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS)));
                    sb.setInvoice_number(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER)));
                    sb.setInvoice_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE)));
                    sb.setInvoice_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE)));
                    sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID)));
                    sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE)));

                    if (checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) {
                        sb.setConfirmChecked(false);
                    } else {
                        sb.setConfirmChecked(true);
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }

        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public ArrayList<ProductMaster> getManualInwardStock(String uuid_Id) {
        ArrayList<ProductMaster> list = new ArrayList<>();
        Cursor dbcursor = null;

        try {
            dbcursor = db.rawQuery("select * from " + CommonString.TABLE_INSERT_MANUAL_INWARD_TRANSACTION + " where " + CommonString.KEY_TRANSACTION_ID + " ='" + uuid_Id + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    String checkVal1 = dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_CONFIRM));
                    sb.setVisit_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_VISIT_DATE)));
                    sb.setCounter_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID)));
                    sb.setConsumer_qty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_QTY)));
                    sb.setActualQty(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ACTUAL_QTY)));
                    sb.setProductId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_ProductId)));
                    sb.setReasonId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(CommonString.KEY_REASON_ID)));
                    sb.setUser_id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_USER_ID)));
                    sb.setInvId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_ID)));
                    sb.setInvoice_Status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_STATUS)));
                    sb.setInvoice_number(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_NUMBER)));
                    sb.setInvoice_type(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_TYPE)));
                    sb.setInvoice_date(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_DATE)));
                    sb.setTransaction_Id(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_TRANSACTION_ID)));
                    sb.setSource(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_SOURCE)));
                    sb.setDraft_status(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_DRAFT_STATUS)));
                    sb.setInvoice_img(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_INVOICE_IMG)));

                    if (checkVal1 != null && !checkVal1.equals("") && checkVal1.equals("0")) {
                        sb.setConfirmChecked(false);
                    } else {
                        sb.setConfirmChecked(true);
                    }

                    list.add(sb);
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return list;
            }
        } catch (Exception e) {

            return list;
        }

        return list;
    }


    public ArrayList<ProductMaster> getmasterTransaction(String visit_date, String counterId, boolean previous_date) {
        Cursor cursordata = null;
        ArrayList<ProductMaster> auditData = new ArrayList<>();
        try {

            if (previous_date) {
                cursordata = db.rawQuery("select distinct t1.MASTER_TRANSACTION_ID as MASTER_TRANSACTION_ID,t1.UUID_ID as UUID_ID," + "t1.STOCK_TYPE as STOCK_TYPE,t1.ENTRY_TYPE as ENTRY_TYPE,t1.Visit_Date as Visit_Date,t1.STATUS as STATUS" + " from DR_TABLE_TRANSACTION_WISE_MASTER t1" + " where t1.Visit_Date <>'" + visit_date + "'and t1.COUNTER_ID=" + counterId + " and t1.STATUS <>'Y' order by t1.MASTER_TRANSACTION_ID asc", null);

            } else {
                cursordata = db.rawQuery("select distinct t1.MASTER_TRANSACTION_ID as MASTER_TRANSACTION_ID,t1.UUID_ID as UUID_ID,t1.STOCK_TYPE as STOCK_TYPE," + "t1.ENTRY_TYPE as ENTRY_TYPE,t1.Visit_Date as Visit_Date,t1.STATUS as STATUS" + " from DR_TABLE_TRANSACTION_WISE_MASTER t1" + " where t1.Visit_Date ='" + visit_date + "'and t1.COUNTER_ID=" + counterId + " and t1.STATUS <>'Y' order by t1.MASTER_TRANSACTION_ID asc", null);

            }

            if (cursordata != null) {
                cursordata.moveToFirst();
                while (!cursordata.isAfterLast()) {
                    ProductMaster sb = new ProductMaster();
                    sb.setMaster_transaction_id(cursordata.getInt(cursordata.getColumnIndexOrThrow("MASTER_TRANSACTION_ID")));
                    sb.setTransaction_Id(cursordata.getString(cursordata.getColumnIndexOrThrow("UUID_ID")));
                    sb.setStock_type(cursordata.getString(cursordata.getColumnIndexOrThrow("STOCK_TYPE")));
                    sb.setVisit_date(cursordata.getString(cursordata.getColumnIndexOrThrow("Visit_Date")));
                    sb.setUpload_status(cursordata.getString(cursordata.getColumnIndexOrThrow("STATUS")));
                    String stock_entry_type = cursordata.getString(cursordata.getColumnIndexOrThrow("ENTRY_TYPE"));
                    if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Draft")) {
                        sb.setEntry_type(CommonString.KEY_DRAFT);
                    } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase("FirstTime_Stock_Comp")) {
                        sb.setEntry_type(CommonString.KEY_COMPLETE);
                    } else if (stock_entry_type != null && !stock_entry_type.equals("") && stock_entry_type.equalsIgnoreCase(CommonString.KEY_REGULAR)) {
                        sb.setEntry_type(CommonString.KEY_REGULAR);
                    }

                    auditData.add(sb);
                    cursordata.moveToNext();
                }

                cursordata.close();
            }
        } catch (Exception ex) {
            ////////test("Exception ", " in  Master_Survey" + ex.toString());
        }

        return auditData;

    }


    public long update_skinGenius_Category(String counterId, String user_Id, String keyId, String table_name) {
        long l = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            ContentValues values = new ContentValues();
            values.put("UPLOAD_STATUS", CommonString.KEY_Y);

            l = db.update(table_name, values, CommonString.KEY_COUNTER_ID + "=" + counterId + " AND UNIQUE_CODE='" + keyId + "'", null);

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

        return l;
    }

    public long update_visibility(String counterId, String user_Id, String keyId, String table_name) {
        long l = 0;
        try {

            ContentValues values = new ContentValues();
            values.put(CommonString.KEY_STATUS, CommonString.KEY_Y);
            if (!db.isOpen()) {
                open();
            }
            l = db.update(table_name, values, CommonString.KEY_COUNTER_ID + "='" + counterId + "' AND " + CommonString.KEY_UUID + "='" + keyId + "'", null);

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

        return l;
    }


    public long insertSkinGeniusdata(String user_Id, String visit_date, String counter_Id, String UID_code, String skingenius_img, String current_tyme) {
        db.delete(CommonString.Table_Skin_Genius_Table, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues finalvalues = new ContentValues();
        ContentValues values = new ContentValues();
        long l2 = 0, masterreturn = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, UID_code);
            finalvalues.put(CommonString.KEY_USER_ID, user_Id);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.SKINGENIUS);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);


            values.put("USER_ID", user_Id);
            values.put("UNIQUE_CODE", UID_code);
            values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
            values.put(CommonString.KEY_COUNTER_ID, counter_Id);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("SKIN_GENIUS_IMG", skingenius_img);
            values.put("UPLOAD_STATUS", CommonString.KEY_N);
            values.put("CAPTURED_TIME", current_tyme);
            if (db.isOpen()) {
            } else {
                open();
            }

            l2 = db.insert(CommonString.Table_Skin_Genius_Table, null, values);
            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Skin Genius Data " + ex.toString());
        }

        return l2;
    }


    public long insertOpenSkinGeniusdata(String user_Id, String visit_date, String counter_Id, String UID_code, int openskingenius_count) {
        db.delete(CommonString.Table_Open_Skin_Genius_Table, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues finalvalues = new ContentValues();
        ContentValues values = new ContentValues();
        long l2 = 0, masterreturn = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, UID_code);
            finalvalues.put(CommonString.KEY_USER_ID, user_Id);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.OPEN_SKINGENIUS);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);
            if (!db.isOpen()) {
                open();
            }
            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);


            values.put("USER_ID", user_Id);
            values.put("UNIQUE_CODE", UID_code);
            values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
            values.put(CommonString.KEY_COUNTER_ID, counter_Id);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("OPENSKIN_GENIUS_COUNT", openskingenius_count);
            values.put("UPLOAD_STATUS", CommonString.KEY_N);
            if (db.isOpen()) {
            } else {
                open();
            }

            l2 = db.insert(CommonString.Table_Open_Skin_Genius_Table, null, values);

            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Skin Genius Data " + ex.toString());
        }

        return l2;
    }

    public long insertOpenMaybellineNVdata(String user_Id, String visit_date, String counter_Id, String UID_code, int open_maybelline_count) {
        db.delete(CommonString.Table_Open_Maybelline_Table, CommonString.KEY_VISIT_DATE + "<>'" + visit_date + "'", null);
        db.delete(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, CommonString.KEY_VISIT_DATE + " <>'" + visit_date + "'", null);
        ContentValues finalvalues = new ContentValues();
        ContentValues values = new ContentValues();
        long l2 = 0, masterreturn = 0;
        try {
            if (!db.isOpen()) {
                open();
            }
            db.beginTransaction();
            finalvalues.put(CommonString.KEY_UUID, UID_code);
            finalvalues.put(CommonString.KEY_USER_ID, user_Id);
            finalvalues.put(CommonString.KEY_COUNTER_ID, counter_Id);
            finalvalues.put(CommonString.KEY_VISIT_DATE, visit_date);
            finalvalues.put(CommonString.KEY_STOCK_TYPE, CommonString.OPEN_MAYBELLINE);
            finalvalues.put(CommonString.KEY_ENTRY_TYPE, CommonString.KEY_REGULAR);
            finalvalues.put(CommonString.KEY_STATUS, CommonString.KEY_N);

            masterreturn = db.insert(CommonString.TABLE_TRANSACTION_WISE_MASTER_TABLE, null, finalvalues);


            values.put("USER_ID", user_Id);
            values.put("UNIQUE_CODE", UID_code);
            values.put(CommonString.KEY_MASTER_TRANSACTION_ID, masterreturn);
            values.put(CommonString.KEY_COUNTER_ID, counter_Id);
            values.put(CommonString.KEY_VISIT_DATE, visit_date);
            values.put("OPEN_MAYBELLINE_COUNT", open_maybelline_count);
            values.put("UPLOAD_STATUS", CommonString.KEY_N);
            if (db.isOpen()) {
            } else {
                open();
            }

            l2 = db.insert(CommonString.Table_Open_Maybelline_Table, null, values);

            closeDb();
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception", " while Insert Skin Genius Data " + ex.toString());
        }

        return l2;
    }

    public boolean insertMasterCompetitionOffer(ResponseResult cst) {
        db.delete("Master_CompetitionOffer", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitionOffer> data = cst.getMastercompetitionoffer();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CompOfferId", data.get(i).getCompOfferId());
                values.put("CompOffer", data.get(i).getCompOffer());
                values.put("CompBuyTypeId", data.get(i).getCompBuyTypeId());
                values.put("CompBuyType", data.get(i).getCompBuyType());
                values.put("CompSetId", data.get(i).getCompSetId());
                values.put("CompSetName", data.get(i).getCompSetName());
                values.put("CompGetId", data.get(i).getCompGetId());
                values.put("CompGetName", data.get(i).getCompGetName());

                long id = db.insert("Master_CompetitionOffer", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterCompetitionOfferSaleRange(ResponseResult cst) {
        db.delete("Master_CompetitionOfferSaleRange", null, null);
        ContentValues values = new ContentValues();
        List<MasterCompetitionOfferSaleRange> data = cst.getMasterCompetitionOfferSaleRange();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("SaleRange", data.get(i).getSaleRange());

                long id = db.insert("Master_CompetitionOfferSaleRange", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertMasterRetailExcellence(ResponseResult cst) {
        db.delete("Master_RetailExcellence_Item", null, null);
        ContentValues values = new ContentValues();
        List<MasterRetailExcellence> data = cst.getMasterRetailExcellenceList();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("ItemCategoryId", data.get(i).getItemCatId());
                values.put("ItemCategoryName", data.get(i).getItemCatName());
                values.put("ItemId", data.get(i).getItemId());
                values.put("ItemName", data.get(i).getItemName());

                long id = db.insert("Master_RetailExcellence_Item", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ex.fillInStackTrace();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertDashTVA(ResponseResult cst) {
        db.delete("AppDashboard_TVA", null, null);
        ContentValues values = new ContentValues();
        List<AppDashboardTVA> data = cst.getAppDashboardTVA();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getkPI());
                values.put("Graph", data.get(i).getGraph());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("Target", data.get(i).getTarget());
                values.put("TotalSale", data.get(i).getTotalSale());
                values.put("Per", data.get(i).getPer());

                long id = db.insert("AppDashboard_TVA", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertDashTVADrillDown(ResponseResult cst) {
        db.delete("AppDashboard_TVADrillDown", null, null);
        ContentValues values = new ContentValues();
        List<AppDashboardTVADrillDown> data = cst.getAppDashboardTVADrillDown();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getkPI());
                values.put("Graph", data.get(i).getGraph());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("Target", data.get(i).getTarget());
                values.put("TotalSale", data.get(i).getTotalSale());
                values.put("Per", data.get(i).getPer());
                values.put("ProductGroupId", data.get(i).getProductGroupId());
                values.put("ProductGroupName", data.get(i).getProductGroupName());

                long id = db.insert("AppDashboard_TVADrillDown", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public AppDashboardTVA getDashboardTVA(String CounterId) {
        AppDashboardTVA sb = null;
        Cursor dbcursor = null;

        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_TVA where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new AppDashboardTVA();
                    sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Graph")));
                    sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target")));
                    sb.setTotalSale(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalSale")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public ArrayList<AppDashboardTVADrillDown> getDashboardTVADrillDown(String CounterId) {
        ArrayList<AppDashboardTVADrillDown> list = new ArrayList<>();
       /* AppDashboardTVADrillDown sb = new AppDashboardTVADrillDown();
        sb.setTarget(120000.0);
        sb.setTotalSale(2300.0);
        sb.setPer(6.8);
        sb.setProductGroupName("tr");
        list.add(sb);
        sb = new AppDashboardTVADrillDown();
        sb.setTarget(120000.0);
        sb.setTotalSale(2300.0);
        sb.setPer(6.8);
        sb.setProductGroupName("tr");
        list.add(sb);*/

        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_TVADrillDown where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    AppDashboardTVADrillDown sb = new AppDashboardTVADrillDown();
                    sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Graph")));
                    sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target")));
                    sb.setTotalSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalSale")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    sb.setProductGroupId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ProductGroupId")));
                    sb.setProductGroupName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ProductGroupName")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }


    public boolean insertDashLeaderBoard(ResponseResult cst) {
        db.delete("AppDashboard_LeaderBoard", null, null);
        ContentValues values = new ContentValues();
        List<AppDashboardLeaderBoard> data = cst.getAppDashboardLeaderBoard();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("Graph", data.get(i).getGraph());
                values.put("EmpId", data.get(i).getEmpId());
                values.put("EmpName", data.get(i).getEmpName());
                values.put("EmpCode", data.get(i).getEmpCode());
                values.put("TotalSale", data.get(i).getTotalSale());
                values.put("Target", data.get(i).getTarget());
                values.put("Per", data.get(i).getPer());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());

                long id = db.insert("AppDashboard_LeaderBoard", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public AppDashboardTVA getLeaderDashboard() {
        AppDashboardTVA sb = null;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_LeaderBoard ORDER by Per DESC", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new AppDashboardTVA();
                    sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpName")));
                    sb.setCounter_name(dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName")));
                    int counterId = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId"));
                    String counterCode = dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterCode"));
                    sb.setCounter_code(counterCode + "/" + counterId);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public ArrayList<AppDashboardTVA> getDashboardInfo(String counterId, String _userId) {
        ArrayList<AppDashboardTVA> list = new ArrayList<>();
        try {
            if (!db.isOpen()) open();
            if (getDashboardTVA(counterId) != null) list.add(getDashboardTVA(counterId));
            if (getLeaderDashboard() != null) list.add(getLeaderDashboard());
            if (getDashboardIncentive(counterId, _userId) != null)
                list.add(getDashboardIncentive(counterId, _userId));

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

    public ArrayList<AppDashboardTVADrillDown> getLeaderDashboards() {
        ArrayList<AppDashboardTVADrillDown> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_LeaderBoard ORDER by Per DESC", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    AppDashboardTVADrillDown sb = new AppDashboardTVADrillDown();
                    sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    sb.setGraph(dbcursor.getString(dbcursor.getColumnIndexOrThrow("EmpName")));
                    String countername = dbcursor.getString(dbcursor.getColumnIndexOrThrow("CounterName"));
                    int counterId = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("CounterId"));
                    sb.setProductGroupName(countername + "/" + counterId);
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public boolean insertDashIncentive(ResponseResult cst) {
        db.delete("AppDashboard_Incentive", null, null);
        ContentValues values = new ContentValues();
        List<AppDashboardIncentive> data = cst.getAppDashboardIncentive();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Per", data.get(i).getPer());
                values.put("KPI", data.get(i).getKpi());
                values.put("Tier", data.get(i).getTier());
                values.put("UserId", data.get(i).getUserId());
                values.put("ChannelName", data.get(i).getChannelName());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("Offtake", data.get(i).getOfftake());

                values.put("LY_AVG_Sale", data.get(i).getLYAVGSale());
                values.put("MJF_AVG_Sale", data.get(i).getMJFAVGSale());
                values.put("SL_Incentive", data.get(i).getSLIncentive());
                values.put("Flat_Incentive", data.get(i).getFlatIncentive());
                values.put("ToatlIncentive", data.get(i).getToatlIncentive());
                values.put("MaximumIncentive", data.get(i).getMaximumIncentive());

                long id = db.insert("AppDashboard_Incentive", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public AppDashboardTVA getDashboardIncentive(String CounterId, String userId) {
        AppDashboardTVA sb = null;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_Incentive where CounterId =" + CounterId + " and UserId = '" + userId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new AppDashboardTVA();
                    sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MaximumIncentive")));
                    double totalIncentive = dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("ToatlIncentive"));
                    sb.setkPI(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    sb.setTotalSale((int) totalIncentive);
                    sb.setGraph("");
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }


    public AppDashboardIncentive getDashboardIncentiveDetail(String CounterId, String userId) {
        AppDashboardIncentive sb = null;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_Incentive where CounterId =" + CounterId + " and UserId = '" + userId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new AppDashboardIncentive();
                    sb.setMaximumIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MaximumIncentive")));
                    sb.setToatlIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("ToatlIncentive")));
                    sb.setOfftake(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Offtake")));
                    sb.setLYAVGSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("LY_AVG_Sale")));
                    sb.setMJFAVGSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("MJF_AVG_Sale")));
                    sb.setSLIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("SL_Incentive")));
                    sb.setFlatIncentive(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Flat_Incentive")));
                    sb.setTier(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Tier")));
                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }


    public boolean insertDashOffTakeCounter(ResponseResult cst) {
        db.delete("AppDashboard_L3MOffTake_Counter", null, null);
        ContentValues values = new ContentValues();
        List<L3MOffTakeCounter> data = cst.getL3MOffTakeCounter();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("Data", new Gson().toJson(data.get(i).getData()));
                long id = db.insert("AppDashboard_L3MOffTake_Counter", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public ArrayList<L3MOffTakeCounter> getL3OffTakeCounter(String CounterId) {
        ArrayList<L3MOffTakeCounter> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From AppDashboard_L3MOffTake_Counter where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    L3MOffTakeCounter sb = new L3MOffTakeCounter();
                    OffTakeData offTakeData = new Gson().fromJson(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Data")), OffTakeData.class);
                    sb.setData(offTakeData);
                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public boolean insertDashOffTakeNuance(ResponseResult cst) {
        db.delete("AppDashboard_L3MOffTake_Nuance", null, null);
        ContentValues values = new ContentValues();
        List<L3MOffTakeNuance> data = cst.getL3MOffTakeNuance();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("NuanceId", data.get(i).getNuanceId());
                values.put("NuanceName", data.get(i).getNuanceName());
                values.put("Month_Year", data.get(i).getMonthYear());
                values.put("OffTake", data.get(i).getOffTake());
                long id = db.insert("AppDashboard_L3MOffTake_Nuance", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertDashOffTakeSubAxe(ResponseResult cst) {
        db.delete("AppDashboard_L3MOffTake_SubAxe", null, null);
        ContentValues values = new ContentValues();
        List<L3MOffTakeSubAxe> data = cst.getL3MOffTakeSubAxe();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("SubAxeId", data.get(i).getSubAxeId());
                values.put("SubAxeName", data.get(i).getSubAxeName());
                values.put("Month_Year", data.get(i).getMonthYear());
                values.put("OffTake", data.get(i).getOffTake());
                long id = db.insert("AppDashboard_L3MOffTake_SubAxe", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertDailyTVA(ResponseResult cst) {
        db.delete("ReportDaily_TVA", null, null);
        ContentValues values = new ContentValues();
        List<DailyTVA> data = cst.getReportDailyTVA();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("UserId", data.get(i).getUserId());
                values.put("Target", data.get(i).getTarget());
                values.put("TotalSale", data.get(i).getTotalSale());
                values.put("Per", data.get(i).getPer());
                long id = db.insert("ReportDaily_TVA", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<DailyTVA> getDailyTVAReport(String CounterId, String _UserId) {
        ArrayList<DailyTVA> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From ReportDaily_TVA where CounterId =" + CounterId + " and UserId ='" + _UserId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    DailyTVA sb = new DailyTVA();
                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setVisitDate(dbcursor.getString(dbcursor.getColumnIndexOrThrow("VisitDate")));
                    sb.setTotalSale(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalSale")));
                    sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public DailyTVA getTotalDailyTVA(String CounterId, String _UserId) {
        DailyTVA sb = null;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("SELECT DISTINCT sum(ifnull(TotalSale,0))as TotalSale,sum(ifnull(Target,0))as Target ,((sum(ifnull(TotalSale,0))/sum(ifnull(Target,0)))*100)as Per From ReportDaily_TVA where CounterId =" + CounterId + " and UserId ='" + _UserId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new DailyTVA();
                    sb.setTotalSale(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TotalSale")));
                    sb.setTarget(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Target")));
                    sb.setPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Per")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public boolean insertReportSalesGrowthCounter(ResponseResult cst) {
        db.delete("Report_SalesGrowth_Counter", null, null);
        ContentValues values = new ContentValues();
        List<SalesGrowthCounter> data = cst.getReportSalesGrowthCounter();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("Last_Year_SameMonthSale", data.get(i).getLastYearSameMonthSale());
                values.put("L3M_Avg_Sale", data.get(i).getL3MAvgSale());
                values.put("Current_Month_Sale", data.get(i).getCurrentMonthSale());
                values.put("Growth_over_Last_Year_Per", data.get(i).getGrowthOverLastYearPer());
                values.put("Growth_over_L3M_Per", data.get(i).getGrowthOverL3MPer());
                values.put("Closing_Stock_LastMonth", data.get(i).getClosingStockLastMonth());
                values.put("NOD", data.get(i).getNod());
                long id = db.insert("Report_SalesGrowth_Counter", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertSalesGrowthCounterSubAxe(ResponseResult cst) {
        db.delete("Report_SalesGrowth_CounterDetail", null, null);
        ContentValues values = new ContentValues();
        List<SalesGrowthSubAxe> data = cst.getReportSalesGrowthSubAxe();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("ParamCode", data.get(i).getParamCode());
                values.put("ParamName", data.get(i).getParamName());
                values.put("Last_Year_SameMonthSale", data.get(i).getLastYearSameMonthSale());
                values.put("L3M_Avg_Sale", data.get(i).getL3MAvgSale());
                values.put("Current_Month_Sale", data.get(i).getCurrentMonthSale());
                values.put("Growth_over_Last_Year_Per", data.get(i).getGrowthOverLastYearPer());
                values.put("Growth_over_L3M_Per", data.get(i).getGrowthOverL3MPer());
                values.put("Closing_Stock_LastMonth", data.get(i).getClosingStockLastMonth());
                values.put("NOD", data.get(i).getNod());
                long id = db.insert("Report_SalesGrowth_CounterDetail", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<SalesGrowthSubAxe> getSalesGrowthReport(String CounterId, boolean details) {
        ArrayList<SalesGrowthSubAxe> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = "Report_SalesGrowth_Counter";
            if (details) table = "Report_SalesGrowth_CounterDetail";
            dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    SalesGrowthSubAxe sb = new SalesGrowthSubAxe();
                    if (details) {
                        sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode")));
                        sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName")));
                    } else {
                        sb.setParamCode(null);
                        sb.setParamName(null);
                    }
                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setLastYearSameMonthSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Last_Year_SameMonthSale")));
                    sb.setL3MAvgSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("L3M_Avg_Sale")));
                    sb.setCurrentMonthSale(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Current_Month_Sale")));
                    sb.setGrowthOverLastYearPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Growth_over_Last_Year_Per")));
                    sb.setGrowthOverL3MPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Growth_over_L3M_Per")));
                    sb.setClosingStockLastMonth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Closing_Stock_LastMonth")));
                    sb.setNod(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("NOD")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public boolean insertTesterCounter(TesterCounter cst) {
        db.delete("Report_TesterCounter", null, null);
        ContentValues values = new ContentValues();
        List<ReportTesterCounter> data = cst.getReportTesterCounter();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKPI());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("OpeningStock", data.get(i).getOpeningStock());
                values.put("InvoicedQty", data.get(i).getInvoicedQty());
                values.put("ReceivedQty", data.get(i).getReceivedQty());
                values.put("TesterStockAvailable", data.get(i).getTesterStockAvailable());
                values.put("TesterUsed", data.get(i).getTesterUsed());
                values.put("TesterUsedPer", data.get(i).getTesterUsedPer());
                long id = db.insert("Report_TesterCounter", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }


    public boolean insertTesterCounterDetail(ResponseResult cst) {
        db.delete("Report_TesterCounterDetail", null, null);
        ContentValues values = new ContentValues();
        List<ReportTesterCounterDetail> data = cst.getReportTesterCounterDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());

                values.put("ParamId", data.get(i).getParamId());
                values.put("ParamCode", data.get(i).getParamCode());
                values.put("ParamName", data.get(i).getParamName());

                values.put("CounterName", data.get(i).getCounterName());
                values.put("OpeningStock", data.get(i).getOpeningStock());
                values.put("InvoicedQty", data.get(i).getInvoicedQty());
                values.put("ReceivedQty", data.get(i).getReceivedQty());
                values.put("TesterStockAvailable", data.get(i).getTesterStockAvailable());
                values.put("TesterUsed", data.get(i).getTesterUsed());
                values.put("TesterUsedPer", data.get(i).getTesterUsedPer());
                long id = db.insert("Report_TesterCounterDetail", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertCounterVolume(ResponseResult cst) {
        db.delete("Report_CounterVolume", null, null);
        ContentValues values = new ContentValues();
        List<ReportCounterVolume> data = cst.getReportCounterVolume();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("MTDVolume", data.get(i).getMTDVolume());
                values.put("AvgPerDayVolume", data.get(i).getAvgPerDayVolume());
                long id = db.insert("Report_CounterVolume", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportTesterCounterDetail> getTesterCounterUsageReport(String CounterId, boolean detail) {
        ArrayList<ReportTesterCounterDetail> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = "Report_TesterCounter";
            if (detail) table = "Report_TesterCounterDetail";
            dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ReportTesterCounterDetail sb = new ReportTesterCounterDetail();
                    if (detail) {
                        sb.setParamId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ParamId")));
                        sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode")));
                        sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName")));
                    } else {
                        sb.setParamId(null);
                        sb.setParamCode(null);
                        sb.setParamName(null);
                    }

                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));
                    sb.setInvoicedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("InvoicedQty")));
                    sb.setReceivedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ReceivedQty")));
                    sb.setTesterUsed(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TesterUsed")));
                    sb.setOpeningStock(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("OpeningStock")));
                    sb.setTesterStockAvailable(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("TesterStockAvailable")));
                    sb.setTesterUsedPer(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TesterUsedPer")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public boolean insertCounterVolumeDetail(ResponseResult cst) {
        db.delete("Report_CounterVolumeDetail", null, null);
        ContentValues values = new ContentValues();
        List<ReportCounterVolumeDetail> data = cst.getReportCounterVolumeDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("MTDVolume", data.get(i).getMTDVolume());
                values.put("AvgPerDayVolume", data.get(i).getAvgPerDayVolume());
                values.put("ParamId", data.get(i).getParamId());
                values.put("ParamCode", data.get(i).getParamCode());
                values.put("ParamName", data.get(i).getParamName());


                long id = db.insert("Report_CounterVolumeDetail", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertCounterValue(ResponseResult cst) {
        db.delete("Report_ConterValue", null, null);
        ContentValues values = new ContentValues();
        List<ReportConterValue> data = cst.getReportConterValue();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("MTDValue", data.get(i).getMTDValue());
                values.put("AvgPerDayValue", data.get(i).getAvgPerDayValue());
                long id = db.insert("Report_ConterValue", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertCounterValueDetail(ResponseResult cst) {
        db.delete("Report_ConterValueDetail", null, null);
        ContentValues values = new ContentValues();
        List<ReportConterValueDetail> data = cst.getReportConterValueDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("MTDValue", data.get(i).getMTDValue());
                values.put("AvgPerDayValue", data.get(i).getAvgPerDayValue());
                values.put("ParamId", data.get(i).getParamId());
                values.put("ParamCode", data.get(i).getParamCode());
                values.put("ParamName", data.get(i).getParamName());


                long id = db.insert("Report_ConterValueDetail", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertCounterInwardStockDetail(ResponseResult cst) {
        db.delete("Report_CounterInwardStockDetail", null, null);
        ContentValues values = new ContentValues();
        List<ReportCounterInwardStockDetail> data = cst.getReportCounterInwardStockDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("ParamId", data.get(i).getParamId());
                values.put("ParamCode", data.get(i).getParamCode());
                values.put("ParamName", data.get(i).getParamName());
                values.put("InvoiceQty", data.get(i).getInvoiceQty());
                values.put("ActualQty", data.get(i).getActualQty());
                values.put("DamageQty", data.get(i).getDamageQty());
                values.put("MissedQty", data.get(i).getMissedQty());

                long id = db.insert("Report_CounterInwardStockDetail", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertCounterStockLedgerDetail(ResponseResult cst) {
        db.delete("Report_CounterStockLedgerDetail", null, null);
        ContentValues values = new ContentValues();
        List<ReportCounterStockLedgerDetail> data = cst.getReportCounterStockLedgerDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("ParamId", data.get(i).getParamId());
                values.put("ParamCode", data.get(i).getParamCode());
                values.put("ParamName", data.get(i).getParamName());
                values.put("OpeningStock", data.get(i).getOpeningStock());
                values.put("StockIn", data.get(i).getStockIn());
                values.put("SaleOut", data.get(i).getSaleOut());
                values.put("SaleableBalance", data.get(i).getSaleableBalance());

                long id = db.insert("Report_CounterStockLedgerDetail", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ArrayList<ReportCounterInwardStockDetail> getCounterInwordStkDetails(String CounterId, boolean inward_detail) {
        ArrayList<ReportCounterInwardStockDetail> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = "Report_CounterInwardStockDetail";
            if (!inward_detail) table = "Report_CounterStockLedgerDetail";
            dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ReportCounterInwardStockDetail sb = new ReportCounterInwardStockDetail();
                    sb.setParamId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ParamId")));
                    sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode")));
                    sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName")));
                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));

                    sb.setInvoiceQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "InvoiceQty" : "OpeningStock")));
                    sb.setActualQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "ActualQty" : "StockIn")));
                    sb.setDamageQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "DamageQty" : "SaleOut")));
                    sb.setMissedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "MissedQty" : "SaleableBalance")));
                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public ArrayList<ReportCounterVolumeDetail> getCounterVolumeDetails(String CounterId, boolean value) {
        ArrayList<ReportCounterVolumeDetail> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String table = "Report_CounterVolumeDetail";
            if (value) table = "Report_ConterValueDetail";
            dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    ReportCounterVolumeDetail sb = new ReportCounterVolumeDetail();
                    sb.setParamId(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("ParamId")));
                    sb.setParamCode(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamCode")));
                    sb.setParamName(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ParamName")));
                    sb.setKpi(dbcursor.getString(dbcursor.getColumnIndexOrThrow("KPI")));

                    sb.setMTDVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "MTDValue" : "MTDVolume")));
                    sb.setAvgPerDayVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "AvgPerDayValue" : "AvgPerDayVolume")));

                    list.add(sb);
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public ReportCounterVolume getCounterVolume(String CounterId, boolean value) {
        ReportCounterVolume sb = null;
        Cursor dbcursor = null;
        try {
            String table = "Report_CounterVolume";
            if (value) table = "Report_ConterValue";
            dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new ReportCounterVolume();
                    sb.setMTDVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "MTDValue" : "MTDVolume")));

                    sb.setAvgPerDayVolume(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow(value ? "AvgPerDayValue" : "AvgPerDayVolume")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public boolean insertCounterInwardStock(ResponseResult cst) {
        db.delete("Report_CounterInwardStock", null, null);
        ContentValues values = new ContentValues();
        List<ReportCounterInwardStock> data = cst.getReportCounterInwardStock();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("InvoiceQty", data.get(i).getInvoiceQty());
                values.put("ActualQty", data.get(i).getActualQty());
                values.put("DamageQty", data.get(i).getDamageQty());
                values.put("MissedQty", data.get(i).getMissedQty());
                long id = db.insert("Report_CounterInwardStock", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public ReportCounterInwardStock getCounterInwordStk(String CounterId, boolean inward_detail) {
        ReportCounterInwardStock sb = null;
        Cursor dbcursor = null;
        try {
            String table = "Report_CounterInwardStock";
            if (!inward_detail) table = "Report_CounterStockLedger";

            dbcursor = db.rawQuery("Select * From " + table + " where CounterId =" + CounterId, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new ReportCounterInwardStock();
                    sb.setInvoiceQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "InvoiceQty" : "OpeningStock")));
                    sb.setActualQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "ActualQty" : "StockIn")));
                    sb.setDamageQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "DamageQty" : "SaleOut")));
                    sb.setMissedQty(dbcursor.getInt(dbcursor.getColumnIndexOrThrow(inward_detail ? "MissedQty" : "SaleableBalance")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public boolean insertCounterStockledger(ResponseResult cst) {
        db.delete("Report_CounterStockLedger", null, null);
        ContentValues values = new ContentValues();
        List<ReportCounterStockLedger> data = cst.getReportCounterStockLedger();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("KPI", data.get(i).getKpi());
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("CounterName", data.get(i).getCounterName());
                values.put("OpeningStock", data.get(i).getOpeningStock());
                values.put("StockIn", data.get(i).getStockIn());
                values.put("SaleOut", data.get(i).getSaleOut());
                values.put("SaleableBalance", data.get(i).getSaleableBalance());
                long id = db.insert("Report_CounterStockLedger", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertBaTbaSales(ResponseResult cst) {
        db.delete("Report_BA_TBASale", null, null);
        ContentValues values = new ContentValues();
        List<BATBASale> data = cst.gettBATBASale();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("ProductId", data.get(i).getProductId());
                values.put("ProductCode", data.get(i).getProductCode());
                values.put("ProductName", data.get(i).getProductName());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("SaleQty", data.get(i).getSaleQty());
                values.put("SaleValues", data.get(i).getSaleValues());
                long id = db.insert("Report_BA_TBASale", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertBaTbaPromoSales(ResponseResult cst) {
        db.delete("Report_BA_TBAPromoSale", null, null);
        ContentValues values = new ContentValues();
        List<BATBAPromoSale> data = cst.gettBATBAPromoSale();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("CounterId", data.get(i).getCounterId());
                values.put("CounterCode", data.get(i).getCounterCode());
                values.put("ProductId", data.get(i).getProductId());
                values.put("ProductCode", data.get(i).getProductCode());
                values.put("ProductName", data.get(i).getProductName());
                values.put("VisitDate", data.get(i).getVisitDate());
                values.put("SaleQty", data.get(i).getSaleQty());
                values.put("SaleValues", data.get(i).getSaleValues());
                values.put("PromoType", data.get(i).getpromoType());
                long id = db.insert("Report_BA_TBAPromoSale", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertLeaveDetails(ResponseResult cst) {
        db.delete("T_LeaveRequestDetail", null, null);
        ContentValues values = new ContentValues();
        List<TLeaveRequestDetail> data = cst.getTLeaveRequestDetail();
        try {
            if (data.isEmpty()) {
                return false;
            }
            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Id", data.get(i).getId());
                values.put("UserId", data.get(i).getUserId());
                values.put("Year", data.get(i).getYear());
                values.put("Month", data.get(i).getMonth());
                values.put("Day", data.get(i).getDay());
                values.put("LeaveType", data.get(i).getLeaveType());
                values.put("LeaveSubType", data.get(i).getLeaveSubType());
                values.put("Reason", data.get(i).getReason());
                values.put("ApprovedStatus", data.get(i).getApprovedStatus());
                long id = db.insert("T_LeaveRequestDetail", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public TLeaveRequestDetail getLeaveDetails(String _userId, String status, int year, int month, int day) {
        TLeaveRequestDetail sb = null;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From T_LeaveRequestDetail where UserId ='" + _userId + "' And ApprovedStatus ='" + status + "'And Year=" + year + " And Month=" + month + " And Day=" + day, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new TLeaveRequestDetail();
                    sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")));
                    sb.setLeaveSubType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveSubType")));
                    sb.setApprovedStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ApprovedStatus")));
                    sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public ArrayList<TLeaveRequestDetail> getHolidaysOrLeaves(String _userId, String type) {
        ArrayList<TLeaveRequestDetail> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            String query = "Select * From T_LeaveRequestDetail where UserId ='" + _userId + "' Order by Id and ApprovedStatus";
            if (type.equals("GovtHolidays")) {
                query = "Select * from Master_HolidayList";
            }
            dbcursor = db.rawQuery(query, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    TLeaveRequestDetail sb = new TLeaveRequestDetail();
                    if (type.equals("GovtHolidays")) {
                        sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Date")));
                        sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Occasion")));
                    } else {
                        sb.setYear(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Year")));
                        sb.setMonth(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Month")));
                        sb.setDay(dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Day")));
                        sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")));
                        sb.setLeaveSubType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveSubType")));
                        sb.setApprovedStatus(dbcursor.getString(dbcursor.getColumnIndexOrThrow("ApprovedStatus")));
                        sb.setReason(dbcursor.getString(dbcursor.getColumnIndexOrThrow("Reason")));
                    }
                    list.add(sb);

                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }
        return list;
    }

    public List<CalendarDay> getLeaveDetails(String _userId, String status) {
        ArrayList<CalendarDay> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select * From T_LeaveRequestDetail where UserId ='" + _userId + "' And ApprovedStatus ='" + status + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    int year = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Year"));
                    int month = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Month"));
                    int day = dbcursor.getInt(dbcursor.getColumnIndexOrThrow("Day"));
                    list.add(CalendarDay.from(year, month, day));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return list;
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    public boolean insertHolidays(ResponseResult cst) {
        db.delete("Master_HolidayList", null, null);
        ContentValues values = new ContentValues();
        List<MasterHoliday> data = cst.getMasterHolidayList();
        try {
            if (data.isEmpty()) {
                return false;
            }

            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("Id", data.get(i).getId());
                values.put("Date", data.get(i).getDate());
                values.put("Occasion", data.get(i).getOccasion());
                long id = db.insert("Master_HolidayList", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public boolean insertLeaveLedger(ResponseResult cst) {
        db.delete("T_LeaveLedgerSummary", null, null);
        ContentValues values = new ContentValues();
        List<TLeaveLedgerSummary> data = cst.getTLeaveLedgerSummary();
        try {
            if (data.isEmpty()) {
                return false;
            }

            db.beginTransaction();
            for (int i = 0; i < data.size(); i++) {
                values.put("UserId", data.get(i).getEmpId());
                values.put("LeaveType", data.get(i).getLeaveType());
                values.put("Earned", data.get(i).getEarned());
                values.put("TakenThisMonth", data.get(i).getTakenThisMonth());
                values.put("TotalLeavesTaken", data.get(i).getTotalLeavesTaken());
                values.put("Balance", data.get(i).getBalance());
                long id = db.insert("T_LeaveLedgerSummary", null, values);
                //test("JeevanP", "" + id);
                if (id == -1) {
                    throw new Exception();
                }
            }
            closeDb();
            return true;
        } catch (Exception ex) {
            closeDb();
            ////////test("Database Exception  ", ex.toString());
            return false;
        }
    }

    public TLeaveLedgerSummary getLeaveLedger(String _userId, boolean personal) {
        TLeaveLedgerSummary sb = null;
        Cursor dbcursor = null;
        try {

            String query = "LeaveType != 'Personal Leave'";
            if (personal) {
                query = "LeaveType = 'Personal Leave'";
            }

            dbcursor = db.rawQuery("Select * from T_LeaveLedgerSummary Where UserId='" + _userId +
                    "' and " + query, null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new TLeaveLedgerSummary();
                    sb.setLeaveType(dbcursor.getString(dbcursor.getColumnIndexOrThrow("LeaveType")));
                    sb.setEarned(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Earned")));
                    sb.setTakenThisMonth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TakenThisMonth")));
                    sb.setTotalLeavesTaken(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalLeavesTaken")));
                    sb.setBalance(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Balance")));
                    dbcursor.moveToNext();
                }
                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public TLeaveLedgerSummary getLeaveLedgerTotal(String _userId) {
        TLeaveLedgerSummary sb = null;
        Cursor dbcursor = null;
        try {

            dbcursor = db.rawQuery("Select distinct sum(Earned)as Earned,sum(TakenThisMonth)as TakenThisMonth,sum(TotalLeavesTaken)as TotalLeavesTaken,sum(Balance)as Balance from T_LeaveLedgerSummary Where UserId='" + _userId + "'", null);

            if (dbcursor != null) {
                dbcursor.moveToFirst();
                while (!dbcursor.isAfterLast()) {
                    sb = new TLeaveLedgerSummary();
                    sb.setEarned(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Earned")));
                    sb.setTakenThisMonth(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TakenThisMonth")));
                    sb.setTotalLeavesTaken(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("TotalLeavesTaken")));
                    sb.setBalance(dbcursor.getDouble(dbcursor.getColumnIndexOrThrow("Balance")));
                    dbcursor.moveToNext();
                }

                dbcursor.close();
                return sb;
            }
        } catch (Exception e) {
            return sb;
        }
        return sb;
    }

    public void updateStatus(String id, String counterId, String bID, String status, double latitude, double longitude) {
        ContentValues values = new ContentValues();
        try {
            values.put("GeoTag", status);
            values.put("Latitude", latitude);
            values.put("Longitude", longitude);
            db.update("Mapping_JourneyPlan", values, "StoreId" + " = " + id + " And BID = " + bID + " And CounterId = " + counterId, null);
        } catch (Exception ignored) {
        }
    }


    public long InsertSTOREgeotag(String storeid, String counterId, String bId, String userId, double lat, double longitude, String path) {
        db.delete(CommonString.TABLE_STORE_GEOTAGGING, "STORE_ID = " + storeid + " And "
                + CommonString.KEY_COUNTER_ID + "=" + counterId + " And BiD = " + bId, null);

        ContentValues values = new ContentValues();
        try {
            values.put("STORE_ID", storeid);
            values.put(CommonString.KEY_COUNTER_ID, counterId);
            values.put(CommonString.KEY_USERNAME, userId);
            values.put("BiD", bId);
            values.put("LATITUDE", Double.toString(lat));
            values.put("LONGITUDE", Double.toString(longitude));
            values.put("GEO_IMG", path);
            values.put("GEOTAG", CommonString.KEY_N);
            return db.insert(CommonString.TABLE_STORE_GEOTAGGING, null, values);

        } catch (Exception ex) {
            return 0;
        }
    }

    public long updateInsertedGeoTagStatus(String storeId, String counterId, String useriD, String status) {
        ContentValues values = new ContentValues();
        try {
            values.put("GEOTAG", status);
            return db.update(CommonString.TABLE_STORE_GEOTAGGING, values, "STORE_ID = " + storeId + " And "
                    + CommonString.KEY_COUNTER_ID + "= " + counterId + " and " + CommonString.KEY_USERNAME + "='" + useriD + "'", null);
        } catch (Exception ex) {
            return 0;
        }
    }

    public ArrayList<GeotaggingBeans> getinsertGeotaggingData(String storeid, String counterId, String userId, String status) {
        ArrayList<GeotaggingBeans> list = new ArrayList<>();
        Cursor dbcursor = null;
        try {
            if (status != null) {
                dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_STORE_GEOTAGGING +
                        " where " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' and GEOTAG = '" + status + "' And STORE_ID = " + storeid +
                        " And " + CommonString.KEY_USERNAME + "='" + userId + "'", null);
            } else {
                dbcursor = db.rawQuery("Select * from " + CommonString.TABLE_STORE_GEOTAGGING +
                        " where " + CommonString.KEY_COUNTER_ID + " ='" + counterId + "' And STORE_ID = " + storeid +
                        " And " + CommonString.KEY_USERNAME + "='" + userId + "'", null);
            }
            dbcursor.moveToFirst();
            while (!dbcursor.isAfterLast()) {
                GeotaggingBeans geoTag = new GeotaggingBeans();
                geoTag.setBid(dbcursor.getString(dbcursor.getColumnIndexOrThrow("BiD")));
                geoTag.setStoreid(dbcursor.getString(dbcursor.getColumnIndexOrThrow("STORE_ID")));
                geoTag.setCounterId(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_COUNTER_ID)));
                geoTag.setLatitude(Double.parseDouble(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_LATITUDE))));
                geoTag.setLongitude(Double.parseDouble(dbcursor.getString(dbcursor.getColumnIndexOrThrow(CommonString.KEY_LONGITUDE))));
                geoTag.setImage(dbcursor.getString(dbcursor.getColumnIndexOrThrow("GEO_IMG")));
                list.add(geoTag);
                dbcursor.moveToNext();
            }

            dbcursor.close();
            return list;

        } catch (Exception e) {
            return list;
        }

    }
    @SuppressLint("LongLogTag")
    public boolean insertMappingAppRestrictedKPI(MasterBAProfileGetterSetter data) {
        db.delete("Mapping_AppRestrictedKPI", null, null);
        List<MappingAppRestrictedKPI> mappingAppRestrictedKPIList = data.getMappingAppRestrictedKPI();
        ContentValues values = new ContentValues();
        try {
            db.beginTransaction();
            if (mappingAppRestrictedKPIList.isEmpty()) {
                return false;
            }
            for (MappingAppRestrictedKPI mappingAppRestrictedKPI : mappingAppRestrictedKPIList) {
                values.put("KPIName", mappingAppRestrictedKPI.getKPIName());
                values.put("FieldValueType", mappingAppRestrictedKPI.getFieldValueType());
                values.put("FieldValue", mappingAppRestrictedKPI.getFieldValue());
                values.put("KPIFieldEnable", mappingAppRestrictedKPI.getKPIFieldEnable());
                if (!db.isOpen()) {
                    open();
                }
                long id = db.insert("Mapping_AppRestrictedKPI", null, values);
                if (id == -1) {
                    throw new Exception();
                }
            }
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            return true;
        } catch (Exception ex) {
            ex.fillInStackTrace();
            // do ALL your inserts here
            db.setTransactionSuccessful();
            db.endTransaction();
            Log.d("Exception in Mapping_AppRestrictedKPI", ex.toString());
            return false;
        }
    }

    public boolean getHideManualInwordCount() {
        int count = 0;
        boolean status = false;
        Cursor outerCursor = null;
        Cursor countCursor = null;
        try {
            outerCursor = db.rawQuery("SELECT DISTINCT FieldValueType, FieldValue, KPIFieldEnable FROM Mapping_AppRestrictedKPI", null);
            if (outerCursor != null && outerCursor.moveToFirst()) {
                do {
                    String fieldValueType = outerCursor.getString(outerCursor.getColumnIndexOrThrow("FieldValueType"));
                    String fieldValue = outerCursor.getString(outerCursor.getColumnIndexOrThrow("FieldValue"));
                    String kpiFieldEnable = outerCursor.getString(outerCursor.getColumnIndexOrThrow("KPIFieldEnable"));
                    // Construct query dynamically, make sure field names and values are safe
                    String query = "SELECT COUNT(*) FROM Mapping_JourneyPlan WHERE " + fieldValueType + " IN (?)";

                    countCursor = db.rawQuery(query, new String[]{fieldValue});

                    if (countCursor != null && countCursor.moveToFirst()) {
                        count += countCursor.getInt(0);  // Accumulate count
                        if (count>0) {
                            status = kpiFieldEnable!=null && !kpiFieldEnable.isEmpty() && kpiFieldEnable.equals("1")?true:false;
                        }
                        countCursor.close();
                    }

                } while (outerCursor.moveToNext());

                outerCursor.close();
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        } finally {
            if (outerCursor != null && !outerCursor.isClosed()) outerCursor.close();
            if (countCursor != null && !countCursor.isClosed()) countCursor.close();
        }

        return status;
    }
}

