package cpm.com.gskmtorange;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;

import org.json.JSONObject;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GeoTag.GeoTagStoreList;
import cpm.com.gskmtorange.GetterSetter.CoverageBean;
import cpm.com.gskmtorange.GetterSetter.StoreBean;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.dailyentry.CounterfeitIndicatorWebActivity;
import cpm.com.gskmtorange.dailyentry.DeliveryCallActivity;
import cpm.com.gskmtorange.dailyentry.FutureJCPActivity;
import cpm.com.gskmtorange.dailyentry.PlanogramPDFActivity;
import cpm.com.gskmtorange.dailyentry.ServiceActivity;
import cpm.com.gskmtorange.dailyentry.SettingsActivity;
import cpm.com.gskmtorange.dailyentry.StoreListActivity;
import cpm.com.gskmtorange.dailyentry.WebViewActivity;
import cpm.com.gskmtorange.download.DownloadActivity;
import cpm.com.gskmtorange.password.ChangePasswordActivity;
import cpm.com.gskmtorange.upload.PreviousDataUploadActivity;
import cpm.com.gskmtorange.upload.UploadActivity;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.NoticeItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private Context context;
    WebView webView;
    ImageView imageView;
    ViewPager2 viewPager;
    private Handler sliderHandler = new Handler();
    private Runnable sliderRunnable;
    private List<ImageView> dots = new ArrayList<>();
    List<NoticeItem>bannerlist = null;
    String date;
    String app_ver;
    private SharedPreferences preferences = null;
    GSKOrangeDB db;
    String user_name, country_id;
    ArrayList<StoreBean> storelist = new ArrayList<StoreBean>();
    View headerView;
    ArrayList<CoverageBean> coverageList;
    String error_msg;
    Toolbar toolbar;
    LinearLayout dotsLayout;
    NavigationView navigationView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        viewPager = findViewById(R.id.viewPager);
        setSupportActionBar(toolbar);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        context = this;
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        date = preferences.getString(CommonString.KEY_DATE, null);
        imageView = (ImageView) findViewById(R.id.img_main);
        dotsLayout = findViewById(R.id.dotsLayout);
        webView = (WebView) findViewById(R.id.webview);
        String url = preferences.getString(CommonString.KEY_NOTICE_BOARD_LINK, "");
      //  String url = "https://dle.parinaam.in/OneApp/Dabur/brand-spiels/dabur-brand-spiels.html";
        user_name = preferences.getString(CommonString.KEY_USERNAME, null);
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, null);
        db = new GSKOrangeDB(MainActivity.this);
        db.open();
        webView.setWebViewClient(new MyWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        String json = preferences.getString("NOTICEBOARD_DATA", null) != null
                ? preferences.getString("NOTICEBOARD_DATA", null)
                : "";
        Log.d("noticejsondata",json);
        if (!json.isEmpty()) {
            Gson gson = new Gson();
            NoticeResponse response =
                    gson.fromJson(json, NoticeResponse.class);
           bannerlist = response.Mer_NoticeBoard;
           Log.d("SIZE", String.valueOf(bannerlist.size()));
        }


        if(bannerlist!=null && bannerlist.size()>0){
            setupDots(bannerlist.size());
            viewPager.setAdapter(new NoticeAdapter(bannerlist, this::handleClick));
        }
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);

                setActiveDot(position); // 👈 your dots logic
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);

                if (state == ViewPager2.SCROLL_STATE_DRAGGING) {
                    sliderHandler.removeCallbacks(sliderRunnable); // stop
                }
                else if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    startAutoSlide(); // 🔥 don't call postDelayed directly
                }
            }
        });
        viewPager.setClipToPadding(false);
        viewPager.setClipChildren(false);

        if (!url.isEmpty()) {
            webView.loadUrl(url);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        headerView = LayoutInflater.from(this).inflate(R.layout.nav_header_main, navigationView, false);
        TextView tv_username = (TextView) headerView.findViewById(R.id.nav_user_name);
        //tv_usertype = (TextView) headerView.findViewById(R.id.nav_user_type);
        ImageView img_change_password = (ImageView) headerView.findViewById(R.id.img_change_password);
        tv_username.setText(user_name);
        //tv_usertype.setText(user_type);

        img_change_password.setOnClickListener(v -> {
            Intent in = new Intent(context, ChangePasswordActivity.class);
            startActivity(in);
        });

        navigationView.addHeaderView(headerView);
        navigationView.setNavigationItemSelectedListener(this);
    }

    private void setupDots(int size) {
        dotsLayout.removeAllViews();
        dots.clear();

        for (int i = 0; i < size; i++) {
            ImageView dot = new ImageView(this);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(8, 0, 8, 0);
            dot.setLayoutParams(params);

            // default (inactive)
            dot.setImageResource(R.drawable.dot_inactive);

            dotsLayout.addView(dot);
            dots.add(dot);
        }

        // set first dot active
        if (size > 0) {
            setActiveDot(0);
        }
    }

    private void setActiveDot(int position) {

        for (int i = 0; i < dots.size(); i++) {
            ImageView dot = dots.get(i);

            if (i == position) {
                // Active dot (bigger + dark)
                dot.setImageResource(R.drawable.dot_active);

                dot.animate()
                        .scaleX(1f)
                        .scaleY(1f)
                        .setDuration(200)
                        .start();

            } else {
                // Inactive dot (small + light)
                dot.setImageResource(R.drawable.dot_inactive);

                dot.animate()
                        .scaleX(1f)
                        .scaleY(1f)
                        .setDuration(200)
                        .start();
            }
        }
    }

    private void handleClick(NoticeItem item) {

        String url = String.valueOf(item.getNoticeLink_FullPage());
        String type = String.valueOf(item.getFullPageTarget());
       // Log.d("clickdata",url + ","+type);
        Log.e("clickdata", "URL = " + url);
        System.out.println("FULL URL = " + url);

        if (type == null) return;

        switch (type.toLowerCase()) {
            case "html-webview":
                Log.d("itemdata", String.valueOf(item.getFullPageTarget()));
                Intent webIntent = new Intent(this, WebViewActivity.class);
                webIntent.putExtra("url", url);
                webIntent.putExtra("type", item.getFullPageTarget());
                webIntent.putExtra("dt_level", "");
                startActivity(webIntent);
                break;

            case "html-webbrowser":
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                break;

            case "video":
                Intent videoIntent = new Intent(this, WebViewActivity.class);
                videoIntent.putExtra("url", url);
                videoIntent.putExtra("type", item.getFullPageTarget());
                videoIntent.putExtra("dt_level", "");
                startActivity(videoIntent);
                break;

            case "image":
                Intent imageIntent = new Intent(this, WebViewActivity.class);
                imageIntent.putExtra("url", url);
                imageIntent.putExtra("type", item.getFullPageTarget());
                imageIntent.putExtra("dt_level", "");
                startActivity(imageIntent);
                break;

            case "deeplink":
                try {
                    Intent deepIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(deepIntent);
                } catch (Exception e) {
                    Toast.makeText(this, "Invalid deeplink", Toast.LENGTH_SHORT).show();
                }
                break;

            case "contact":
                handleContact(url);
                break;

            default:
                Toast.makeText(this, "Unsupported type", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleContact(String raw) {
        try {
            // remove query params
            String jsonPart = raw.split("\\?")[0];

            JSONObject obj = new JSONObject(jsonPart);

            String number = obj.getString("Value");

            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + number));
            startActivity(intent);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Invalid contact data", Toast.LENGTH_SHORT).show();
        }
    }

    private String loadJSONFromAsset() {
            String json = null;
            try {
                InputStream is = getAssets().open("notice.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return json;
        }


    @Override
    protected void onResume() {
        super.onResume();
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        toolbar.setTitle(getString(R.string.main_menu_activity_name));
        db.open();
        //usk
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        startAutoSlide();
        try {
            app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
            // login_version.setText("Parinaam Version " + app_ver);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // get menu from navigationView
        Menu menu = navigationView.getMenu();
        // find MenuItem you want to change
        MenuItem nav_route_plan = menu.findItem(R.id.nav_route_plan);
        nav_route_plan.setTitle(getResources().getString(R.string.menu_daily_route_plan));
        MenuItem nav_route_plan1 = menu.findItem(R.id.nav_download);
        nav_route_plan1.setTitle(getResources().getString(R.string.menu_daily_download));
        MenuItem nav_route_plan2 = menu.findItem(R.id.nav_upload);
        nav_route_plan2.setTitle(getResources().getString(R.string.menu_upload_data));
        MenuItem nav_route_plan3 = menu.findItem(R.id.nav_geotag);
        nav_route_plan3.setTitle(getResources().getString(R.string.menu_geotag));
        MenuItem nav_route_plan4 = menu.findItem(R.id.nav_deviation);
        nav_route_plan4.setTitle(getResources().getString(R.string.menu_deviation_data));
        MenuItem nav_route_plan5 = menu.findItem(R.id.nav_delivery_call);
        nav_route_plan5.setTitle(getResources().getString(R.string.delivery_call));
        MenuItem nav_route_plan6 = menu.findItem(R.id.nav_future_jcp);
        nav_route_plan6.setTitle(getResources().getString(R.string.future_route_plan));
        MenuItem nav_route_plan7 = menu.findItem(R.id.nav_planogram);
        nav_route_plan7.setTitle(getResources().getString(R.string.category_performance_PLANOGRAM));
        MenuItem nav_route_plan8 = menu.findItem(R.id.nav_pharmacy_stores);
        nav_route_plan8.setTitle(getResources().getString(R.string.pharma_stores));
        MenuItem nav_route_plan9 = menu.findItem(R.id.nav_additional_stores);
        nav_route_plan9.setTitle(getResources().getString(R.string.additional_stores));
        MenuItem nav_route_plan10 = menu.findItem(R.id.nav_additional_adhoc_stores);
        nav_route_plan10.setTitle(getResources().getString(R.string.additional_adhoc_stores));
        MenuItem nav_route_plan11 = menu.findItem(R.id.nav_counterfeit_indicator);
        nav_route_plan11.setTitle(getResources().getString(R.string.title_activity_counterfeit_indicator_web));
        MenuItem nav_route_plan12 = menu.findItem(R.id.nav_exit);
        nav_route_plan12.setTitle(getResources().getString(R.string.menu_exit));
        MenuItem nav_route_plan13 = menu.findItem(R.id.nav_setting);
        nav_route_plan13.setTitle(getResources().getString(R.string.menu_setting));
        MenuItem nav_route_plan14 = menu.findItem(R.id.nav_services);
        nav_route_plan14.setTitle(getResources().getString(R.string.menu_services));

        MenuItem nav_route_plan15 = menu.findItem(R.id.nav_version);
        nav_route_plan15.setTitle("Version/Versiyon - " + app_ver + "-T3");
        //Enable disable According to Configuration
        ArrayList<ConfigurationMasterGetterSetter> configurationData = db.getConfigurationMasterData(country_id);
        if (!configurationData.isEmpty()) {
            for (int i = 0; i < configurationData.size(); i++) {
                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("ADHOC REPORTING") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_deviation).setVisible(true);
                }
                //temp remove it
                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("PDF ALLOW") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_planogram).setVisible(true);
                }

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("DELIVERY CALLS") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_delivery_call).setVisible(true);
                }

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("ADDITIONAL STORE") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_additional_stores).setVisible(true);
                }

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("PHARMA STORE") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_pharmacy_stores).setVisible(true);
                }


                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("COUNTERFEIT INDICATORS") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_counterfeit_indicator).setVisible(true);
                }

            }
        }

        db.open();
        coverageList = db.getCoverageData(date, null);
        storelist = db.getStoreData(date, CommonString.KEY_JOURNEY_PLAN);
    }

    private void startAutoSlide() {

        if (sliderRunnable != null) {
            sliderHandler.removeCallbacks(sliderRunnable); // 🔥 prevent duplicate
        }

        sliderRunnable = new Runnable() {
            @Override
            public void run() {

                if (viewPager.getAdapter() == null) return;

                int nextItem = (viewPager.getCurrentItem() + 1) %
                        viewPager.getAdapter().getItemCount();

                viewPager.setCurrentItem(nextItem, true);

                sliderHandler.postDelayed(this, 3000); // 3 sec
            }
        };

        sliderHandler.postDelayed(sliderRunnable, 3000);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            // super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_route_plan) {
            Intent in_jcp = new Intent(this, StoreListActivity.class);
            in_jcp.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_JCP);
            startActivity(in_jcp);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_download) {
            downloadMethod();
        } else if (id == R.id.nav_upload) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(getResources().getString(R.string.dialog_title));
            builder.setMessage(getResources().getString(R.string.want_to_upload)).setCancelable(false)
                    .setPositiveButton(getResources().getString(R.string.ok), (dialog, id1) -> {
                        db.open();
                        if (checkNetIsAvailable()) {
                            if (db.getSKUMasterData(null).isEmpty()) {
                                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT)
                                        .setAction("Action", null).show();
                            } else {
                                if (coverageList.isEmpty()) {
                                    Snackbar.make(webView, R.string.no_data_for_upload, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                } else {
                                    if (isStoreCheckedIn() && isValid()) {
                                        Intent i = new Intent(getBaseContext(), UploadActivity.class);
                                        startActivity(i);
                                    } else {
                                        Snackbar.make(webView, error_msg, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                    }
                                }
                            }
                        } else {
                            Snackbar.make(webView, getResources().getString(R.string.nonetwork), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                        }
                    }).setNegativeButton(getResources().getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
            AlertDialog alert = builder.create();
            alert.show();

        } else if (id == R.id.nav_geotag) {
            if (!storelist.isEmpty()) {
                Intent startDownload = new Intent(this, GeoTagStoreList.class);
                startActivity(startDownload);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                Snackbar.make(headerView, R.string.title_store_list_download_data, Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }

        } else if (id == R.id.nav_exit) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(getResources().getString(R.string.dialog_title));
            builder.setMessage(getResources().getString(R.string.want_to_exit)).setCancelable(false)
                    .setPositiveButton(getResources().getString(R.string.ok), (dialog, id12) -> {
                        ActivityCompat.finishAffinity(MainActivity.this);
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }).setNegativeButton(getResources().getString(R.string.cancel), (dialog, which) -> {
                        dialog.dismiss();
                    });
            AlertDialog alert = builder.create();
            alert.show();

        } else if (id == R.id.nav_setting) {
            Intent startDownload = new Intent(this, SettingsActivity.class);
            startActivity(startDownload);
            finish();
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_services) {
            Intent startservice = new Intent(this, ServiceActivity.class);
            startActivity(startservice);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_future_jcp) {
            Intent startDownload = new Intent(this, FutureJCPActivity.class);
            startActivity(startDownload);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_planogram) {
            if (checkNetIsAvailable()) {
                Intent planogram_pdf = new Intent(this, PlanogramPDFActivity.class);
                startActivity(planogram_pdf);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                Snackbar.make(webView, getResources().getString(R.string.nonetwork), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            }

        } else if (id == R.id.nav_deviation) {
            db.open();
            if (db.getSKUMasterData(null).isEmpty()) {
                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            } else {
                Intent in = new Intent(this, StoreListActivity.class);
                in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_DEVIATION);
                startActivity(in);
            }
        } else if (id == R.id.nav_delivery_call) {
            Intent in = new Intent(this, DeliveryCallActivity.class);
            startActivity(in);

            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_pharmacy_stores) {
            Intent in = new Intent(this, StoreListActivity.class);
            in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_PHARMA);
            startActivity(in);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_additional_stores) {
            db.open();
            if (db.getSKUMasterData(null).isEmpty()) {
                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            } else {
                Intent in = new Intent(this, StoreListActivity.class);
                in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_ADDITIONAL);
                startActivity(in);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            }
        } else if (id == R.id.nav_additional_adhoc_stores) {
            db.open();
            if (db.getSKUMasterData(null).isEmpty()) {
                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            } else {
                Intent in = new Intent(this, StoreListActivity.class);
                in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_ADDITIONAL_ADHOC);
                startActivity(in);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            }
        } else if (id == R.id.nav_counterfeit_indicator) {
            Intent intent = new Intent(this, CounterfeitIndicatorWebActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

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

        @Override
        public void onPageFinished(WebView view, String url) {
            imageView.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
            view.clearCache(true);
        }

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

    }

    public boolean checkNetIsAvailable() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
        return isConnected;
    }

    public boolean isStoreCheckedIn() {

        boolean result_flag = true;
        for (int i = 0; i < coverageList.size(); i++) {

            String status = coverageList.get(i).getStatus();
            if (status.equals(CommonString.KEY_INVALID) || status.equals(CommonString.KEY_VALID)) {
                result_flag = false;
                error_msg = getResources().getString(R.string.title_store_list_checkout_current);
                break;
            }
        }

        return result_flag;
    }

    public boolean isValid() {
        boolean flag = false;
        String storestatus = "";
        for (int i = 0; i < coverageList.size(); i++) {

            StoreBean store_data = db.getSpecificStoreData(date, coverageList.get(i).getStoreId(), coverageList.get(i).getFlag_from());

            storestatus = store_data.getUPLOAD_STATUS();
            String coverage_status = store_data.getCHECKOUT_STATUS();

            if (!storestatus.equalsIgnoreCase(CommonString.KEY_U) && !storestatus.equalsIgnoreCase(CommonString.KEY_UN)) {
                if ((coverage_status.equalsIgnoreCase(CommonString.KEY_Y) || storestatus.equalsIgnoreCase(CommonString.KEY_P) ||
                        storestatus.equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE))) {
                    flag = true;
                    break;

                }
            }
        }

        if (!flag)
            error_msg = getResources().getString(R.string.no_data_for_upload);

        return flag;
    }

    public boolean isPreviousValid(String visit_date) {
        boolean isvalid = false;
        ArrayList<CoverageBean> coverage_list = db.getPreviousCoverageData(visit_date, null);
        for (int i = 0; i < coverage_list.size(); i++) {
            StoreBean storeData = db.getSpecificStoreData(coverage_list.get(i).getVisitDate(), coverage_list.get(i).getStoreId(), coverage_list.get(i).getFlag_from());
            if (storeData.getSTORE_ID() != null) {

                if (!storeData.getUPLOAD_STATUS().equals(CommonString.KEY_U) && !storeData.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_UN) && (storeData.getCHECKOUT_STATUS().equals(CommonString.KEY_Y) ||
                        storeData.getCHECKOUT_STATUS().equals(CommonString.KEY_L) || storeData.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_P))) {
                    isvalid = true;
                    break;
                }
            }
        }
        return isvalid;
    }

    //for download
    public void downloadMethod() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(getResources().getString(R.string.dialog_title));
        builder.setMessage(getResources().getString(R.string.want_to_download)).setCancelable(false)
                .setPositiveButton(getResources().getString(R.string.ok), (dialog, id) -> {
                    if (checkNetIsAvailable()) {
                        boolean previousflag = false;
                        if (db.isPreviousCoverageDataFilled(date)) {
                            if (isPreviousValid(date)) {
                                previousflag = true;
                            } else {
                                db.deletePreviousCoverageData(date);
                            }
                        }

                        if (previousflag) {
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                            builder1.setTitle("Parinaam");
                            builder1.setMessage(getResources().getString(R.string.previous_data_upload)).setCancelable(false)
                                    .setPositiveButton(getResources().getString(R.string.ok), (dialog1, id1) -> {
                                        Intent in = new Intent(context, PreviousDataUploadActivity.class);
                                        startActivity(in);
                                        //finish();
                                    });
                            AlertDialog alert = builder1.create();
                            alert.show();

                        } else {
                            Intent in = new Intent(context, DownloadActivity.class);
                            startActivity(in);
                        }
                    } else {
                        Snackbar.make(webView, getResources().getString(R.string.nonetwork), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                    }
                }).setNegativeButton(getResources().getString(R.string.cancel), (dialog, which) -> {
                    dialog.dismiss();
                });
        AlertDialog alert = builder.create();
        alert.show();


    }
    public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.ViewHolder> {

        private List<NoticeItem> list;
        private OnItemClickListener listener;

        // Interface for click handling
        public interface OnItemClickListener {
            void onClick(NoticeItem item);
        }

        public NoticeAdapter(List<NoticeItem> list, OnItemClickListener listener) {
            this.list = list;
            this.listener = listener;
        }

        public static class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;

            public ViewHolder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.bannerImage);
            }
        }

        @Override
        public NoticeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.banner_item, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(NoticeAdapter.ViewHolder holder, int position) {
            NoticeItem item = list.get(position);

            String url = String.valueOf(item.getNoticeLink_Thumbnail());
            Glide.with(holder.itemView.getContext())
                    .load(url)
                    .transform(new RoundedCorners(30))
                    .into(holder.image);

            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onClick(item);
                }
            });
        }

        @Override
        public int getItemCount() {
            return list != null ? list.size() : 0;
        }
    }

    /**
     * Append storeid and merid to the provided URL as query parameters.
     * If the URL already contains query params, append with '&', otherwise use '?'.
     */
    private String appendStoreMerQuery(String url, String storeId, String merId) {
        if (url == null) return null;
        try {
            StringBuilder sb = new StringBuilder(url);
            String separator = url.contains("?") ? "&" : "?";
            boolean appended = false;
            if (storeId != null && !storeId.isEmpty()) {
                sb.append(separator).append("storeid=").append(URLEncoder.encode(storeId, "UTF-8"));
                separator = "&";
                appended = true;
            }
            if (merId != null && !merId.isEmpty()) {
                sb.append(separator).append("merid=").append(URLEncoder.encode(merId, "UTF-8"));
                appended = true;
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return url;
        }
    }
}


