package com.cpm.lorealbaautomation;

import android.Manifest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.SettingsClient;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.InputFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.adapter.LeaveDetailAdapter;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.dailyactivity.BAProfileActivity;
import com.cpm.lorealbaautomation.dailyactivity.CounterImageActivity;
import com.cpm.lorealbaautomation.dailyactivity.CounterProfileActivity;
import com.cpm.lorealbaautomation.dailyactivity.GroomedActivity;
import com.cpm.lorealbaautomation.dailyactivity.NotificationsActivity;
import com.cpm.lorealbaautomation.dailyactivity.RetailExcellenceActivity;
import com.cpm.lorealbaautomation.dailyactivity.ServiceActivity;
import com.cpm.lorealbaautomation.databinding.DialogApplyLeaveBinding;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.download.DownloadActivity;
import com.cpm.lorealbaautomation.download.Downloader;
import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.GroomingGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPromoOffer;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaautomation.leavemanagement.LeaveManagemntActivity;
import com.cpm.lorealbaautomation.password.ChangePasswordActivity;
import com.cpm.lorealbaautomation.pinviewactivity.PinViewActivity;
import com.cpm.lorealbaautomation.promooffer.PromoOffersActivity;
import com.cpm.lorealbaautomation.reports.MeSaleReport;
import com.cpm.lorealbaautomation.reports.PerformanceHistoryActivity;
import com.cpm.lorealbaautomation.reports.ReportsActivity;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.tbaleavemodel.Common;
import com.cpm.lorealbaautomation.tbaleavemodel.TBAMESearch;
import com.cpm.lorealbaautomation.upload.CommonUpload;
import com.cpm.lorealbaautomation.upload.UploadKeyData;
import com.cpm.lorealbaautomation.utils.DrawableClickListener;

import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.checkincomplete_upload_data;
import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCroppedBitmap;
import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime_only;
import static com.cpm.lorealbaautomation.constant.CommonFunctions.getResizedBitmap;
import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

public class DealarBoardActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
    private SharedPreferences preferences = null;
    int downloadindex = 0;
    Lorealba_Database db;
    View headerView;
    Context context;
    private String counterId = "", visitDate = "";
    NavigationView navigationView;
    String user_name, user_type, loginTym = "", serverTym = "", DASHBOARD_REFRESH_TIME = "";
    ArrayList<LoginGetterSetter> allLoginListData = new ArrayList<>();
    public static final String PROGRESS_UPDATE = "progress_update";
    ProgressDialog loading;
    TextView txt_dashboard, txt_more;
    private double lat = 0.0;
    private double lon = 0.0;
    private static final int REQUEST_LOCATION = 1;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    Location mLastLocation;
    LocationRequest mLocationRequest;
    SharedPreferences.Editor editor = null;
    LinearLayout rl_pending_data;
    TextView textCartItemCount;
    int mCartItemCount = 0;
    CircleImageView circleView;
    TextView version_code;
    private FusedLocationProviderClient fusedLocationClient;

    public BaMenuRefreshListener getBaMenuRefreshListener() {
        return baMenuRefreshListener;
    }

    public void setBaMenuRefreshListener(BaMenuRefreshListener baMenuRefreshListener) {
        this.baMenuRefreshListener = baMenuRefreshListener;
    }

    private BaMenuRefreshListener baMenuRefreshListener;

    public CounterMenuRefreshListener getCounterMenuRefreshListener() {
        return counterMenuRefreshListener;
    }

    public void setCounterMenuRefreshListener(CounterMenuRefreshListener counterMenuRefreshListener) {
        this.counterMenuRefreshListener = counterMenuRefreshListener;
    }

    private CounterMenuRefreshListener counterMenuRefreshListener;

    public DealarBoardActivity.OfferMenuRefreshListener getOfferMenuRefreshListener() {
        return OfferMenuRefreshListener;
    }

    public void setOfferMenuRefreshListener(DealarBoardActivity.OfferMenuRefreshListener offerMenuRefreshListener) {
        OfferMenuRefreshListener = offerMenuRefreshListener;
    }

    private OfferMenuRefreshListener OfferMenuRefreshListener;

    public DashboardRefreshListener getDashboardRefreshListener() {
        return dashboardRefreshListener;
    }

    public void setDashboardRefreshListener(DashboardRefreshListener dashboardRefreshListener) {
        this.dashboardRefreshListener = dashboardRefreshListener;
    }

    private DashboardRefreshListener dashboardRefreshListener;
    LinearLayout rl_ba, rl_me, rl_ba2, no_data_lay;
    NestedScrollView dealerb_scroll_view;
    FloatingActionButton fab_download;

    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    private TBAMESearch tbameSearch = null;
    private CustomDialogLeaveApply customDialogLeave = null;
    String blockCharacterSet = "[';:-+{('}<!>@=#$%^&*?)\"]";
    InputFilter filter = (source, start, end, dest, dstart, dend) -> {
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dealar_board);
        context = this;
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        CommonFunctions.hideKeyboard(this);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        downloadindex = preferences.getInt(CommonString.KEY_DOWNLOAD_INDEX, 0);
        DASHBOARD_REFRESH_TIME = preferences.getString(CommonString.KEY_DASHBOARD_REFRESH_TIME, "");
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        version_code = (TextView) findViewById(R.id.version_code);
        rl_pending_data = (LinearLayout) findViewById(R.id.rl_pending_data);
        txt_dashboard = (TextView) findViewById(R.id.txt_dashboard);
        txt_more = (TextView) findViewById(R.id.txt_more);
        no_data_lay = (LinearLayout) findViewById(R.id.no_data_lay);
        dealerb_scroll_view = (NestedScrollView) findViewById(R.id.dealerb_scroll_view);
        fab_download = (FloatingActionButton) findViewById(R.id.fab_download);
        rl_ba = (LinearLayout) findViewById(R.id.rl_ba);
        rl_ba2 = (LinearLayout) findViewById(R.id.rl_ba2);
        rl_me = (LinearLayout) findViewById(R.id.rl_me);
        navigationView = findViewById(R.id.nav_view);
        try {
            if (!CommonFunctions.isTablet(context)) {
                navigationView.setItemIconSize(58);
            }
        } catch (Exception ignored) {
        }
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle((Activity) context, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
        headerView = LayoutInflater.from(this).inflate(R.layout.nav_header_dealar_board, navigationView, false);
        checkAndRequestPermissions();
        createLocationRequest();
        getLastLocation();
        //find location

        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visitDate = preferences.getString(CommonString.KEY_DATE, "");
        user_name = preferences.getString(CommonString.KEY_USERNAME, "");
        user_type = preferences.getString(CommonString.KEY_USER_TYPE, "");
        //  //test("usertype",user_type);

        TextView tv_username = (TextView) headerView.findViewById(R.id.nav_user_name);
        TextView tv_usertype = (TextView) headerView.findViewById(R.id.nav_user_type);
        circleView = (CircleImageView) headerView.findViewById(R.id.circleView);
        tv_username.setText(user_name);
        navigationView.addHeaderView(headerView);

        db = new Lorealba_Database(context);
        db.open();
        ArrayList<LoginGetterSetter> allLoginData = db.getlistAllData(visitDate, user_name);
        if (!allLoginData.isEmpty() && allLoginData.get(0).getUserType() != null) {
            tv_usertype.setText(allLoginData.get(0).getUserType());
        }

        setTitle(user_name);
        registerReceiver();
//        checkRunTimePermission();
        serverTym = db.getserverTym(visitDate).getServerTime();
        ////update device time from server time.............
        if (CommonFunctions.checkNetIsAvailable(context)) {
            CommonFunctions.GetServerTym(context, user_name, db);
        }

        download_data();
        fab_download.setOnClickListener(view -> {
            // Handle the camera action
            if (CommonFunctions.checkNetIsAvailable(context)) {
                startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0));
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
            }
        });

        txt_dashboard.setText(getString(R.string.dashboard) + "  Last Updated at - " + DASHBOARD_REFRESH_TIME + " - " + visitDate);
        txt_more.setOnClickListener(this);

        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counterId);
    }


    private void registerReceiver() {
        LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PROGRESS_UPDATE);
        bManager.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), PROGRESS_UPDATE)) {
                db.open();
                mCartItemCount = db.getNotificationList(user_name).size();
                setupBadge(mCartItemCount);
            }
        }
    };

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

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.txt_more) {
            final ArrayList<MasterPromoOffer>[] masterPromoOffers = new ArrayList[]{new ArrayList<>()};
            final ArrayList<MasterPromoOffer>[] finalPromoOffers = new ArrayList[]{new ArrayList<>()};
            masterPromoOffers[0] = db.getmaterPromoOffers();
            if (!masterPromoOffers[0].isEmpty()) {
                finalPromoOffers[0] = new ArrayList<>();
                for (int k = 0; k < masterPromoOffers[0].size(); k++) {
                    if (CommonFunctions.isTablet(context)) {
                        String path = CommonString.getPromosFolder(context) + masterPromoOffers[0].get(k).getPromoOfferTab();
                        File dir = new File(path);
                        if (dir.exists()) {
                            finalPromoOffers[0].add(masterPromoOffers[0].get(k));
                        }
                    } else {
                        String path = CommonString.getPromosFolder(context) + masterPromoOffers[0].get(k).getPromoOfferMobile();
                        File dir = new File(path);
                        if (dir.exists()) {
                            finalPromoOffers[0].add(masterPromoOffers[0].get(k));
                        }
                    }
                }
            }

            if (!finalPromoOffers[0].isEmpty()) {
                startActivity(new Intent(context, PromoOffersActivity.class));
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                AlertandMessages.showToastMsg(context, "Promotion Banner Not Available");
            }
        }
    }


    public interface BaMenuRefreshListener {
        void onRefresh(String value);
    }

    public interface CounterMenuRefreshListener {
        void onRefresh(String value);
    }

    public interface DashboardRefreshListener {
        void onRefresh(String value);
    }

    public interface OfferMenuRefreshListener {
        void onRefresh();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.findItem(R.id.user_info);
        Menu subMenu = menuItem.getSubMenu();
        assert subMenu != null;
        subMenu.clear();
        MenuItem profilemenuItem = menu.findItem(R.id.user_logout);
        Menu profilesubMenu = profilemenuItem.getSubMenu();
        assert profilesubMenu != null;
        profilesubMenu.clear();
        MenuItem break_menuitem = menu.findItem(R.id.take_break_nav);
        db.open();
        break_menuitem.setVisible(db.isBreakManagmentEndTymChecked(visitDate, user_name, counterId));
        if (!allLoginListData.isEmpty()) {
            for (int i = 0; i < allLoginListData.size(); i++) {
                if (!allLoginListData.get(i).getUserId().equals(user_name) && allLoginListData.get(i).getUser_checkout().equals("0")) {
                    Bitmap bitmp = null;
                    Drawable drawable = null;
                    db.open();
                    MasterProfile baProfileGetterSetter = db.getBaProfileData(allLoginListData.get(i).getUserId(), visitDate, false);
                    if (baProfileGetterSetter != null && baProfileGetterSetter.getProfilePic() != null) {
                        if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) {
                            bitmp = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic());
                            if (bitmp != null) {
                                if (CommonFunctions.isTablet(context)) {
                                    bitmp = getResizedBitmap(bitmp, 70);
                                } else {
                                    bitmp = getResizedBitmap(bitmp, 240);
                                }
                                bitmp = getCroppedBitmap(bitmp);

                                if (bitmp != null) {
                                    drawable = new BitmapDrawable(getResources(), bitmp);
                                }
                            }
                        }
                    } else if (allLoginListData != null && allLoginListData.get(i).getProfile_Pic() != null && !allLoginListData.get(i).getProfile_Pic().equals("")) {
                        if (new File(CommonString.getProfileFolder(context) + allLoginListData.get(i).getProfile_Pic()).exists()) {
                            bitmp = convertBitmap(CommonString.getProfileFolder(context) + allLoginListData.get(i).getProfile_Pic());
                            if (bitmp != null) {
                                if (CommonFunctions.isTablet(context)) {
                                    bitmp = getResizedBitmap(bitmp, 70);
                                } else {
                                    bitmp = getResizedBitmap(bitmp, 240);
                                }
                                bitmp = getCroppedBitmap(bitmp);
                                if (bitmp != null) {
                                    drawable = new BitmapDrawable(getResources(), bitmp);
                                }
                            }
                        }
                    }
                    if (drawable == null) {
                        assert allLoginListData != null;
                        subMenu.add(0, i, 0, allLoginListData.get(i).getUserId()).setShortcut('3', 'c').setIcon(R.mipmap.user_for_menu);
                    } else {
                        subMenu.add(0, i, 0, allLoginListData.get(i).getUserId()).setShortcut('3', 'c').setIcon(drawable);
                    }
                }
            }
        }

        subMenu.add(0, 112, 0, "New User").setShortcut('4', 's').setIcon(R.mipmap.user_for_menu);

        Bitmap bitmpprofile = null;
        Drawable drawableprofile = null;
        db.open();
        MasterProfile baProfileGetterSetter = db.getBaProfileData(user_name, visitDate, false);
        if (baProfileGetterSetter != null && baProfileGetterSetter.getProfilePic() != null) {
            if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) {
                bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic());
                if (bitmpprofile != null) {
                    if (CommonFunctions.isTablet(context)) {
                        bitmpprofile = getResizedBitmap(bitmpprofile, 70);
                    } else {
                        bitmpprofile = getResizedBitmap(bitmpprofile, 240);
                    }

                    bitmpprofile = getCroppedBitmap(bitmpprofile);
                    if (bitmpprofile != null) {
                        drawableprofile = new BitmapDrawable(getResources(), bitmpprofile);
                    }
                }
            }

        } else if (!db.getlistLoginData(visitDate, user_name, counterId).isEmpty() && !db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic().isEmpty()) {
            if (new File(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic()).exists()) {
                bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic());
                if (bitmpprofile != null) {
                    if (CommonFunctions.isTablet(context)) {
                        bitmpprofile = getResizedBitmap(bitmpprofile, 70);
                    } else {
                        bitmpprofile = getResizedBitmap(bitmpprofile, 240);
                    }
                    bitmpprofile = getCroppedBitmap(bitmpprofile);
                    if (bitmpprofile != null) {
                        drawableprofile = new BitmapDrawable(getResources(), bitmpprofile);
                    }
                }
            }
        }

        if (drawableprofile == null) {
            profilesubMenu.add(0, 10, 0, R.string.Profile).setShortcut('3', 'c').setIcon(R.mipmap.profile);
        } else {
            profilesubMenu.add(0, 10, 0, R.string.Profile).setShortcut('3', 'c').setIcon(drawableprofile);
        }

        profilesubMenu.add(0, 11, 0, "Logout").setShortcut('3', 'c').setIcon(R.mipmap.logout_item);

        MenuItem profile = menu.findItem(10);
        profile.setEnabled(!db.isBreakManagmentEndTymChecked(visitDate, user_name, counterId));
        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.dealar_board, menu);
        final MenuItem menuItem = menu.findItem(R.id.notification_img_nav);
        View actionView = (View) menuItem.getActionView();
        assert actionView != null;
        textCartItemCount = (TextView) actionView.findViewById(R.id.cart_badge);
        db.open();
        mCartItemCount = db.getNotificationList(user_name).size();
        setupBadge(mCartItemCount);
        actionView.setOnClickListener(v -> onOptionsItemSelected(menuItem));
        return super.onCreateOptionsMenu(menu);
    }

    private void setupBadge(int mCartItemCount) {
        if (textCartItemCount != null) {
            if (this.mCartItemCount == 0) {
                if (textCartItemCount.getVisibility() != View.GONE) {
                    textCartItemCount.setVisibility(View.GONE);
                }
            } else {
                textCartItemCount.setText(String.valueOf(mCartItemCount));
                if (textCartItemCount.getVisibility() != View.VISIBLE) {
                    textCartItemCount.setVisibility(View.VISIBLE);
                }
            }
        }
    }

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

        if (id == 112) {//for New User Login
            Intent in = new Intent(context, UserLoginActivity.class);
            in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            in.putExtra("Previous_Login", "Previous_Login");
            startActivity(in);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            DealarBoardActivity.this.finish();
        } else if (id == 10) {//for Profile
            db.open();
            if (!db.getlistAllData(visitDate, user_name).isEmpty()) {
                if (!db.getBAProfileListAllData(user_name, visitDate).isEmpty()) {
                    Intent profile = new Intent(context, BAProfileActivity.class);
                    startActivity(profile);
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                } else {
                    AlertandMessages.showToastMsg(context, " Profile  Data Not Found");
                }
            }

        } else if (id == 11) {//for logout
            ////upload data if not upload
            if (checkNetIsAvailable()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertlogout);
                builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                    if (!db.getmasterTransaction(visitDate, counterId, false).isEmpty()) {
                        CommonFunctions.call_upload(context);
                    } else {
                        if (checkincomplete_upload_data(visitDate, counterId, db, false)) {
                            CommonUpload.Checkout_service(loading, context, lat, lon, user_name, counterId, visitDate, db, true);
                        } else {
                            CommonUpload downloadData = new CommonUpload(context, db, loading, counterId, visitDate, user_name, lat, lon);
                            downloadData.CommonUploadwithrecursive(context, db, false);
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
                builder.show();
            } else {
                AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
            }

        } else if (id == R.id.notification_img_nav) {
            if (!db.getNotificationList().isEmpty()) {
                startActivity(new Intent(context, NotificationsActivity.class));
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                AlertandMessages.showToastMsg(context, getResources().getString(R.string.notification_error_msg));
            }

        } else {

            String userId = Objects.requireNonNull(item.getTitle()).toString();
            String mpin = preferences.getString(userId, null);
            if (mpin != null) {
                Intent in1 = new Intent(context, PinViewActivity.class);
                in1.putExtra(CommonString.IS_PASSWORD_CHECK, true);
                in1.putExtra(CommonString.KEY_USERNAME, userId.toLowerCase());
                startActivity(in1);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                finish();
            } else if (userId != null && !userId.isEmpty()) {
                startActivity(new Intent(context, UserLoginActivity.class));
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                DealarBoardActivity.this.finish();
            }

        }

        return super.onOptionsItemSelected(item);
    }


    private void hideItem() {
        Menu nav_Menu = navigationView.getMenu();
        if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
            nav_Menu.findItem(R.id.nav_reset_password).setVisible(true);
            nav_Menu.findItem(R.id.nav_report).setVisible(true);
            nav_Menu.findItem(R.id.nav_me_report).setVisible(false);
            nav_Menu.findItem(R.id.nav_per_history).setVisible(false);
            nav_Menu.findItem(R.id.nav_per_history).setVisible(false);
        } else {
            nav_Menu.findItem(R.id.nav_reset_password).setVisible(true);
            nav_Menu.findItem(R.id.nav_report).setVisible(true);
            nav_Menu.findItem(R.id.nav_me_report).setVisible(false);
            nav_Menu.findItem(R.id.nav_per_history).setVisible(false);
        }

        /////new change for leave apply
        if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) {
            nav_Menu.findItem(R.id.nav_apply_leave).setVisible(false);
            nav_Menu.findItem(R.id.nav_leave_detail).setVisible(false);
            nav_Menu.findItem(R.id.nav_leave_ledger).setVisible(false);
        } else {
            nav_Menu.findItem(R.id.nav_apply_leave).setVisible(true);
            nav_Menu.findItem(R.id.nav_leave_detail).setVisible(true);
            nav_Menu.findItem(R.id.nav_leave_ledger).setVisible(true);
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.sync_data_nav) {
            // Handle the camera action
            startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_ba_profile) {
            Intent profile = new Intent(context, BAProfileActivity.class);
            startActivity(profile);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);

        } else if (id == R.id.nav_counter_menu) {
            Intent profile = new Intent(context, CounterProfileActivity.class);
            startActivity(profile);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_services) {
            startActivity(new Intent(context, ServiceActivity.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_reset_password) {
            startActivity(new Intent(context, ChangePasswordActivity.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_logout) {
            if (checkNetIsAvailable()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertlogout);
                builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                    if (!db.getmasterTransaction(visitDate, counterId, false).isEmpty()) {
                        CommonFunctions.call_upload(context);
                    } else {
                        if (checkincomplete_upload_data(visitDate, counterId, db, false)) {
                            CommonUpload.Checkout_service(loading, context, lat, lon, user_name, counterId, visitDate, db, true);
                        } else {
                            CommonUpload downloadData = new CommonUpload(context, db, loading, counterId, visitDate, user_name, lat, lon);
                            downloadData.CommonUploadwithrecursive(context, db, false);
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
                builder.show();
            } else {
                AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
            }

            /*Intent intent = new Intent(context, UserLoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);*/
        } else if (id == R.id.nav_report) {
            startActivity(new Intent(context, ReportsActivity.class).putExtra("from", user_type));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_d2d_ars) {
            String url = preferences.getString(CommonString.KEY_D2D_ARS_URL, "");
            if (!url.isEmpty()) {
                openurlinchrome(url);
            } else {
                Toast.makeText(context, "Url not available", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.nav_per_history) {
            startActivity(new Intent(context, PerformanceHistoryActivity.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_me_report) {
            startActivity(new Intent(context, MeSaleReport.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_manual_upload) {
            startActivity(new Intent(context, UploadKeyData.class));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_apply_leave) {
            customDialogLeave = new CustomDialogLeaveApply((AppCompatActivity) context, true);
            customDialogLeave.show();
        } else if (id == R.id.nav_leave_detail) {
            customDialogLeave = new CustomDialogLeaveApply((AppCompatActivity) context, false);
            customDialogLeave.show();
        } else if (id == R.id.nav_leave_ledger) {
            startActivity(new Intent(context, LeaveManagemntActivity.class).putExtra(CommonString.TAG_FROM, "TBA/ME"));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        }
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    private void openurlinchrome(String url) {
        try {
            Uri uri = Uri.parse("googlechrome://navigate?url=" + url);
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        } catch (ActivityNotFoundException e) {
            Uri uri = Uri.parse(url);
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        context = this;
        editor = preferences.edit();
        visitDate = preferences.getString(CommonString.KEY_DATE, "");
        user_type = preferences.getString(CommonString.KEY_USER_TYPE, "");
        downloadindex = preferences.getInt(CommonString.KEY_DOWNLOAD_INDEX, 0);
        db.open();
        if (!db.isProductMasterFilled(visitDate)) {
            no_data_lay.setVisibility(View.VISIBLE);
            fab_download.show();
            dealerb_scroll_view.setVisibility(View.GONE);
        } else {
            no_data_lay.setVisibility(View.GONE);
            fab_download.hide();
            dealerb_scroll_view.setVisibility(View.VISIBLE);
        }

        checkAndRequestPermissions();
        createLocationRequest();
        getLastLocation();
        //find location

        checkgpsEnableDevice();
        /////set picture current user
        Bitmap bitmpprofile = null;
        db.open();
        MasterProfile baProfileGetterSetter = db.getBaProfileData(user_name, visitDate, false);
        if (baProfileGetterSetter != null && baProfileGetterSetter.getProfilePic() != null) {
            if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) {
                bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic());
            }
            db.open();
        } else if (!db.getlistLoginData(visitDate, user_name, counterId).isEmpty() && !db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic().isEmpty()) {
            db.open();
            if (new File(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic()).exists()) {
                db.open();
                bitmpprofile = convertBitmap(CommonString.getProfileFolder(context) + db.getlistLoginData(visitDate, user_name, counterId).get(0).getProfile_Pic());
            }
        }

        if (bitmpprofile != null) {
            circleView.setImageBitmap(bitmpprofile);
        } else {
            circleView.setImageResource(R.mipmap.user_100);
        }
        if (user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
            calculateme_counter();
        } else {
            callall_method();
        }
        db.open();
        allLoginListData = db.getlistLoginData(visitDate, null, counterId);

        if (user_type != null && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
            rl_me.setVisibility(View.VISIBLE);
            rl_ba.setVisibility(View.GONE);
            rl_ba2.setVisibility(View.GONE);
        } else {
            rl_me.setVisibility(View.GONE);
            rl_ba2.setVisibility(View.VISIBLE);
            rl_ba.setVisibility(View.VISIBLE);
        }

        hideItem();
        //UploadKeyData image service
        File f = new File(CommonString.getImagesFolder(context));
        if (!getFileNames(Objects.requireNonNull(f.listFiles())).isEmpty()) {
            ArrayList<String> finalList = new ArrayList<>();
            for (int k = 0; k < getFileNames(Objects.requireNonNull(f.listFiles())).size(); k++) {
                if (!db.ischeck_uploaded_image(visitDate, getFileNames(Objects.requireNonNull(f.listFiles())).get(k))) {
                    finalList.add(getFileNames(Objects.requireNonNull(f.listFiles())).get(k));
                }
            }

            if (!finalList.isEmpty()) {
                Intent intentu = new Intent(context, Downloader.class);
                intentu.putExtra(CommonString.KEY_UPLOADIMAGE, "1");
                Downloader.enqueueWork(context, intentu);
            }
        }

        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;
            version_code.setText("Version : " + version);
        } catch (PackageManager.NameNotFoundException e) {
            e.fillInStackTrace();
            version_code.setText("Version : 0.0");
        }

        alert_for_date(context, visitDate);
        updateuserInterface();
        invalidateOptionsMenu();
        ///Dashboard Ui Report Updated
        //checkNDownloadSalesReport();
        DASHBOARD_REFRESH_TIME = preferences.getString(CommonString.KEY_DASHBOARD_REFRESH_TIME, "");
        txt_dashboard.setText(getString(R.string.dashboard) + "  Last Updated at - " + DASHBOARD_REFRESH_TIME + " - " + visitDate);
        checkpending_datafor_upload();
    }

    public void alert_for_date(final Context context, final String visit_date) {
        @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date date_device = new Date();
        if (!dateFormat.format(date_device).equalsIgnoreCase(visit_date)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("Alert Dialog").setMessage("Your Device date does not match login Date. You will be logged out now").setPositiveButton(android.R.string.ok, (dialog, which) -> {
                startActivity(new Intent(context, IMEILoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                DealarBoardActivity.this.finish();
                dialog.dismiss();
            });
            builder.show();
        }
    }


    @SuppressLint("VisibleForTests")
    protected void createLocationRequest() {
        LocationRequest mLocationRequest = new LocationRequest();
        // Location updates intervals in sec
        // 5 sec
        int UPDATE_INTERVAL = 5000;
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        // 1 sec
        int FATEST_INTERVAL = 1000;
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // 10 meters
        int DISPLACEMENT = 5;
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private void checkgpsEnableDevice() {
        if (!hasGPSDevice(context)) {
            Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show();
        }

        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
            enableLocationSettings();
        } else {
            if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                hasGPSDevice(context);
            }
        }
    }

    private void enableLocationSettings() {
        @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant
                .setInterval(30 * 1000)
                .setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
                .setAlwaysShow(true); // show dialog if GPS is off

        SettingsClient settingsClient = LocationServices.getSettingsClient(this);

        settingsClient.checkLocationSettings(builder.build())
                .addOnSuccessListener(locationSettingsResponse -> {
                    // All location settings are satisfied. You can request location updates here.
                }).addOnFailureListener(e -> {
                    if (e instanceof ResolvableApiException) {
                        try {
                            ResolvableApiException resolvable = (ResolvableApiException) e;
                            resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                            sendEx.fillInStackTrace();
                        }
                    }
                });
    }

    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null)
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }


    private boolean checkNetIsAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    private void updateuserInterface() {
        /////Only for Dashboard data................
        if (getDashboardRefreshListener() != null) {
            getDashboardRefreshListener().onRefresh("");
        }

        /////Only for offers data................
        if (getOfferMenuRefreshListener() != null) {
            getOfferMenuRefreshListener().onRefresh();
        }

        /////for counter images disable icon.............
        db.open();
        if (!db.getinserted_counter_images(counterId, visitDate).getCounter_img_two_for_ba().isEmpty() || !db.getinserted_counter_images(counterId, visitDate).getCounter_img_onefor_ba().isEmpty()) {
            if (getBaMenuRefreshListener() != null) {
                getBaMenuRefreshListener().onRefresh("0");
            }
            if (getCounterMenuRefreshListener() != null) {
                getCounterMenuRefreshListener().onRefresh("0");
            }
        } else {
            if (getBaMenuRefreshListener() != null) {
                getBaMenuRefreshListener().onRefresh("1");
            }
            if (getCounterMenuRefreshListener() != null) {
                getCounterMenuRefreshListener().onRefresh("1");
            }
        }
        /////Only for break managment
        db.open();
        if (db.isBreakManagmentEndTymChecked(visitDate, user_name, counterId)) {
            if (getBaMenuRefreshListener() != null) {
                getBaMenuRefreshListener().onRefresh("2");
            }
            if (getCounterMenuRefreshListener() != null) {
                getCounterMenuRefreshListener().onRefresh("2");
            }
        }
    }

    private void uploadGroomedData() {
        db.open();
        loginTym = db.get_baLoginTym(visitDate, user_name).getUserLoginTym();
        loginTym = CommonFunctions.setTimeFormat(loginTym);
        if (loginTym != null && !loginTym.isEmpty()) {
            if (calculateTotalDuration(loginTym) > 8) {
                GroomingGetterSetter groomedList = db.getGroomedList(counterId, user_name, visitDate);
                if (groomedList != null && !groomedList.getMorning_groom_img_str().isEmpty() || groomedList != null && !groomedList.getNoon_groom_img_str().isEmpty() || groomedList != null && !groomedList.getEvenning_groom_img_str().isEmpty()) {
                    //download service
                    Intent intent = new Intent(context, Downloader.class);
                    intent.putExtra(CommonString.KEY_Groomed_Image, groomedList);
                    Downloader.enqueueWork(context, intent);
                }
            }
        }
    }


    private void calculateloginTym() {
        try {
            boolean flag = true;
            if (db.isCounterChecked(visitDate, counterId)) {
                loginTym = db.get_baLoginTym(visitDate, user_name).getUserLoginTym();
                loginTym = CommonFunctions.setTimeFormat(loginTym);
                SimpleDateFormat simpleDateFormat = null;
                ////for morning tym after Added 45 minutes
                String morngTym = addtime_str(loginTym, 45, 0);
                String morngEndTym = addtime_str(loginTym, 0, 3);
                simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
                Date date1 = simpleDateFormat.parse(morngTym);
                Date date2 = simpleDateFormat.parse(getTime());
                Date date3 = simpleDateFormat.parse(morngEndTym);
                assert date2 != null;
                if (date2.after(date1) && date2.before(date3)) {
                    db.open();
                    if (!db.isGroomedCheckedfornotification(visitDate, counterId, user_name, "Mornning_groomed_img")) {
                        flag = false;
                        showCommentforGrooming(context);
                    } else if (!user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME) && !db.getRetailExcellenceData().isEmpty()) {
                        if (!db.isRetailExcellenceFilled(visitDate, counterId, user_name)) {
                            flag = false;
                            showCommentforRetailExcellence(context);
                        }
                    }
                }

                ////for nooo tym after adding 03:10
                String noonTym = addtime_str(loginTym, 10, 03);
                String endNoonTym = addtime_str(loginTym, 59, 05);
                simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
                date1 = simpleDateFormat.parse(noonTym);
                date2 = simpleDateFormat.parse(getTime());
                date3 = simpleDateFormat.parse(endNoonTym);
                if (flag) {
                    db.open();
                    assert date2 != null;
                    if (date2.after(date1) && date2.before(date3)) {
                        if (!db.isGroomedCheckedfornotification(visitDate, counterId, user_name, "Noon_groomed_img")) {
                            flag = false;
                            showCommentforGrooming(context);
                        } else if (!user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME) && !db.getRetailExcellenceData().isEmpty()) {
                            if (!db.isRetailExcellenceFilled(visitDate, counterId, user_name)) {
                                flag = false;
                                showCommentforRetailExcellence(context);
                            }
                        }
                    }
                }

                ////for evenning tym after adding 03:10
                String evngTym = addtime_str(loginTym, 10, 6);
                String EndevngTym = addtime_str(loginTym, 59, 8);
                simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
                date1 = simpleDateFormat.parse(evngTym);
                date2 = simpleDateFormat.parse(getTime());
                date3 = simpleDateFormat.parse(EndevngTym);
                if (flag) {
                    assert date2 != null;
                    db.open();
                    if (date2.after(date1) && date2.before(date3)) {
                        if (!db.isGroomedCheckedfornotification(visitDate, counterId, user_name, "Evening_groomed_img")) {
                            showCommentforGrooming(context);
                        } else if (!user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME) && !db.getRetailExcellenceData().isEmpty()) {
                            if (!db.isRetailExcellenceFilled(visitDate, counterId, user_name)) {
                                showCommentforRetailExcellence(context);
                            }
                        }
                    }
                }
            } else {
                db.open();
                if (db.isProductMasterFilled(visitDate)) {
                    showCommentforCounter(context);
                }
            }
        } catch (ParseException e) {
            e.fillInStackTrace();
        }
    }


    private String addtime_str(String str, int minuts, int hours) {
        SimpleDateFormat displayFormat = null;
        SimpleDateFormat parseFormat = null;
        Calendar calendar = null;
        Date date = null;

        try {
            if (str != null && !str.isEmpty()) {
                parseFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
                displayFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
                date = parseFormat.parse(str);
                calendar = Calendar.getInstance();
                assert date != null;
                calendar.setTime(date);
                calendar.add(Calendar.HOUR, hours);
                calendar.add(Calendar.MINUTE, minuts);
                //test(displayFormat.format(calendar.getTime()));
            }
        } catch (ParseException e) {
            e.fillInStackTrace();
        }

        assert displayFormat != null;
        assert calendar != null;
        return displayFormat.format(calendar.getTime());
    }


    private String getTime() {
        Calendar currnetDateTime = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
        return df.format(currnetDateTime.getTime());
    }


    public void showCommentforGrooming(final Context context) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        final Dialog dialog_for = new Dialog(context);
        Objects.requireNonNull(dialog_for.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog_for.setContentView(R.layout.comment_layout);

        Window window = dialog_for.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        window.setAttributes(wlp);
        RelativeLayout rl_dialog = dialog_for.findViewById(R.id.rl_dialog);
        rl_dialog.setOnClickListener(view -> {
            startActivity(new Intent(context, GroomedActivity.class));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            dialog_for.dismiss();
        });

        dialog_for.show();

    }

    public void showCommentforRetailExcellence(final Context context) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        final Dialog dialog_for = new Dialog(context);
        Objects.requireNonNull(dialog_for.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog_for.setContentView(R.layout.comment_retail_excellence);

        Window window = dialog_for.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        window.setAttributes(wlp);
        RelativeLayout rl_dialog = dialog_for.findViewById(R.id.rl_dialog);
        rl_dialog.setOnClickListener(view -> {
            startActivity(new Intent(context, RetailExcellenceActivity.class));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            dialog_for.dismiss();
        });

        dialog_for.show();

    }


    public void showCommentforCounter(final Context context) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        final Dialog dialogcounter = new Dialog(context);
        Objects.requireNonNull(dialogcounter.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialogcounter.setContentView(R.layout.commentfor_counter_layout);

        Window window = dialogcounter.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        window.setAttributes(wlp);
        dialogcounter.setCanceledOnTouchOutside(false);
        RelativeLayout rl_dialog = dialogcounter.findViewById(R.id.rl_dialog);
        rl_dialog.setOnClickListener(view -> {
            startActivity(new Intent(context, CounterImageActivity.class));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            dialogcounter.dismiss();
        });
        dialogcounter.show();

    }


    private int calculateTotalDuration(String loginTym) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
        int days = 0, hours = 0, min = 0;
        try {
            Date date1 = simpleDateFormat.parse(loginTym);
            Date date2 = simpleDateFormat.parse(getTime());
            assert date2 != null;
            assert date1 != null;
            long difference = date2.getTime() - date1.getTime();
            days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
            min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
        } catch (ParseException e) {
            e.fillInStackTrace();
        }

        return hours;
    }

    private int calculateTotalDurationinminutes(String currentTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss", Locale.ENGLISH);
        int days = 0, hours = 0, min = 0;
        try {
            Date date1 = simpleDateFormat.parse(currentTime);
            Date date2 = simpleDateFormat.parse(getCurrentTime_only());
            assert date2 != null;
            assert date1 != null;
            long difference = date2.getTime() - date1.getTime();
            days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
            min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
        } catch (ParseException e) {
            e.fillInStackTrace();
        }

        return min;
    }


    //--------------Download all data........................---------
    private void download_data() {
        int incorrect_tStockSummery = preferences.getInt(CommonString.KEY_INCORRECT_TSTOCK_SUMMERY + visitDate, 0);
        db.open();
        if (!db.isProductMasterFilled(visitDate)) {
            startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (incorrect_tStockSummery == 2) {
            startActivity(new Intent(context, DownloadActivity.class).putExtra(CommonString.TAG_FROM, 0));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        }
    }

    private void callall_method() {
        try {
            db.open();
            if (db.isProductMasterFilled(visitDate)) {
                uploadGroomedData();
                loginTym = db.get_baLoginTym(visitDate, user_name).getUserLoginTym();
                loginTym = CommonFunctions.setTimeFormat(loginTym);
                calculateloginTym();
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private void calculateme_counter() {
        db.open();
        if (!db.isCounterCheckedforme(visitDate, counterId)) {
            db.open();
            if (db.isProductMasterFilled(visitDate)) {
                db.open();
                showCommentforCounter(context);
            }
        }
    }

    private void checkAndRequestPermissions() {
        int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE);
        int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
        int locationPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
        int READ_PHONE_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
        List<String> listPermissionsNeeded = new ArrayList<>();

        if (CAMERA != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }

        if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE);
        }
        if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
        }


        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CommonString.PERMISSION_ALL);
        }
    }

    private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //test("", "Permission callback called-------");
        if (requestCode == CommonString.PERMISSION_ALL) {
            Map<String, Integer> perms = new HashMap<>();
            // Initialize the map with both permissions
            perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions
                boolean allPermissionsGranted =
                        Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) &&
                                Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE));

                if (allPermissionsGranted) {
                    getLastLocation();

                    createLocationRequest();
                }
            } else {
                //test("", "Some permissions are not granted ask again ");
                //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
//                        // shouldShowRequestPermissionRationale will return true
                //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
                    showDialogOK("Location,File,Call and Camera Services Permission required for this app", (dialog, which) -> {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                checkAndRequestPermissions();
                                break;
                            case DialogInterface.BUTTON_NEGATIVE:
                                // proceed with logic by disabling the related features or quit the app.
                                Intent startMain = new Intent(Intent.ACTION_MAIN);
                                startMain.addCategory(Intent.CATEGORY_HOME);
                                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(startMain);
                                break;
                        }
                    });
                } else {
                    Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void getLastLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Request location permissions
            return;
        }
        try {
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, location -> {
                        if (location != null) {
                            lat = location.getLatitude();
                            lon = location.getLongitude();
                            //test("Location", "Lat: " + lat + ", Lng: " + lon);
                        }
                    });
        } catch (Exception e) {
            e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);}
        }

    }

    public ArrayList<String> getFileNames(File[] file) {
        ArrayList<String> arrayFiles = new ArrayList<String>();
        for (File value : file) arrayFiles.add(value.getName());
        return arrayFiles;
    }

    private void checkpending_datafor_upload() {
        db.open();
        if (!db.getmasterTransaction(visitDate, counterId, false).isEmpty()) {
            rl_pending_data.setVisibility(View.VISIBLE);
        } else {
            rl_pending_data.setVisibility(View.GONE);
        }
    }

    public void downloadDataUniversalWithoutWait(final ArrayList<String> jsonStringList,
                                                 final ArrayList<String> KeyNames, int downloadindex, final ProgressDialog pd) {
        final String[] data_global = {""};
        String jsonString = "", KeyName = "";
        int jsonIndex = 0;

        if (!jsonStringList.isEmpty()) {
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build();
            jsonString = jsonStringList.get(downloadindex);
            KeyName = KeyNames.get(downloadindex);
            jsonIndex = downloadindex;
            pd.setMessage("Downloading Dashboard Data (" + downloadindex + "/" + jsonStringList.size() + ") \n" + KeyName);
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<String> call = api.getDownloadAll(jsonData);
            final int[] finalJsonIndex = {jsonIndex};
            final String finalKeyName = KeyName;
            call.enqueue(new Callback<String>() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (data.isEmpty()) {
                                data_global[0] = "";
                            } else {
                                data_global[0] = data;
                                {
                                    switch (finalKeyName) {
                                        ///jp_download Report
                                        case "Report_SalesValue":
                                            if (!data.contains("No Data")) {
                                                MasterProfileQuestionGetterSetter reportSaleValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                                db.open();
                                                if (reportSaleValueObject != null && !db.insertReportSaleValue(reportSaleValueObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_SalesValue not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_SalesValue");
                                            }

                                            break;

                                        case "Report_AvgTransactionPerDay":
                                            if (!data.contains("No Data")) {
                                                MasterProfileQuestionGetterSetter reportavGTransationValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                                db.open();
                                                if (reportavGTransationValueObject != null && !db.insertReportAvgTransationperDay(reportavGTransationValueObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_AvgTransactionPerDay not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_AvgTransactionPerDay");
                                            }


                                            break;

                                        case "Report_AvgUnitsPerBill":
                                            if (!data.contains("No Data")) {
                                                MasterProfileQuestionGetterSetter reportAvgUnitPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                                db.open();
                                                if (reportAvgUnitPerBillObject != null && !db.insertReportAvgPerBillDay(reportAvgUnitPerBillObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_AvgUnitsPerBill not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_AvgUnitsPerBill");
                                            }


                                            break;

                                        case "Report_AvgBillValue":
                                            if (!data.contains("No Data")) {
                                                MasterProfileQuestionGetterSetter reportAvgBillUnitObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                                db.open();
                                                if (reportAvgBillUnitObject != null && !db.insertReportAvgBillUnit(reportAvgBillUnitObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_AvgBillValue not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_AvgBillValue");
                                            }
                                            break;

                                        case "Report_AvgLinPerBill":
                                            if (!data.contains("No Data")) {
                                                MasterProfileQuestionGetterSetter reportAvgLinPerBillObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                                db.open();
                                                if (reportAvgLinPerBillObject != null && !db.insertReportAvgLinPerBill(reportAvgLinPerBillObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_AvgLinPerBill not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_AvgLinPerBill");
                                            }

                                            break;

                                        case "Report_SellingPrice":
                                            if (!data.contains("No Data")) {
                                                MasterProfileQuestionGetterSetter reportSalingPrizeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                                db.open();
                                                if (reportSalingPrizeObject != null && !db.insertReportSelingPrice(reportSalingPrizeObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_SellingPrice not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_SellingPrice");
                                            }
                                            break;
                                        case "Report_ProductGroupWiseSalesValue":
                                            if (!data.contains("No Data")) {
                                                ResponseResult productGroupwiseSaleObject = new Gson().fromJson(data, ResponseResult.class);
                                                db.open();
                                                if (productGroupwiseSaleObject != null && !db.insertGroupWiseSale(productGroupwiseSaleObject)) {
                                                    pd.dismiss();
                                                    AlertandMessages.showToastMsg(context, "Report_ProductGroupWiseSalesValue not saved");
                                                }
                                            } else {
                                                db.open();
                                                db.delete_table_data("Report_ProductGroupWiseSalesValue");
                                            }

                                            break;


                                    }
                                }
                            }

                            finalJsonIndex[0]++;
                            if (finalJsonIndex[0] != KeyNames.size()) {
                                downloadDataUniversalWithoutWait(jsonStringList, KeyNames, finalJsonIndex[0], pd);
                            } else {

                                /////update Dashboard UI reports.......
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_DASHBOARD_REFRESH_TIME, CommonFunctions.getCurrentTime_only());
                                editor.commit();
                                if (pd.isShowing()) {
                                    pd.dismiss();
                                }
                                /////Only for Dashboard data................
                                if (getDashboardRefreshListener() != null) {
                                    getDashboardRefreshListener().onRefresh("");
                                }

                                DASHBOARD_REFRESH_TIME = preferences.getString(CommonString.KEY_DASHBOARD_REFRESH_TIME, "");
                                txt_dashboard.setText(getString(R.string.dashboard) + "  Last Updated at - " + DASHBOARD_REFRESH_TIME + " - " + visitDate);
                            }

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

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    pd.dismiss();
                }
            });
        }
    }

    ////TBA/ME apply leave code
    public class CustomDialogLeaveApply extends Dialog {
        private CustomDialogLeaveApply oneButtonDialog;
        private DialogApplyLeaveBinding binding = null;
        private final boolean markleave;

        public CustomDialogLeaveApply(AppCompatActivity activity, boolean mark_leave) {
            super(activity);
            this.markleave = mark_leave;
        }

        public CustomDialogLeaveApply getInstance(AppCompatActivity activity, boolean mark_leave) {
            return oneButtonDialog = (oneButtonDialog == null) ? new CustomDialogLeaveApply(activity, mark_leave) : oneButtonDialog;
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            binding = DialogApplyLeaveBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            // Set the dialog window properties
            Window window = customDialogLeave.getWindow();
            if (window != null) {
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                // Adjust margins
                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) binding.getRoot().getLayoutParams();

                if (CommonFunctions.isTablet(context)) {
                    layoutParams.setMargins(75, 5, 75, 5); // Left, Top, Right, Bottom margins in pixels
                } else {
                    layoutParams.setMargins(15, 5, 15, 5); // Left, Top, Right, Bottom margins in pixels
                }
                binding.getRoot().setLayoutParams(layoutParams);
            }

            binding.edtapplyForleaveReason.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(550)});
            binding.imgClose.setOnClickListener(v -> dismiss());

            binding.etEmployeeCode.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // Your action on done
                    if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                        getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode,
                                binding.tvEmpDesignation);
                    }
                    return true;
                }
                return false;
            });

            binding.etEmployeeCode.setDrawableClickListener(target -> {
                if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) {
                    if (Objects.requireNonNull(binding.etEmployeeCode.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                        getEmployeeDetails(binding.etEmployeeCode.getText().toString(), binding.tvEmpName, binding.tvEmpCode, binding.tvEmpDesignation);
                    }
                }
            });

            binding.etEmployeeCodeforHistory.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // Your action on done
                    if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        ///API call
                        getLeaveHistory(binding);
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                    }
                    return true;
                }
                return false;
            });

            binding.etEmployeeCodeforHistory.setDrawableClickListener(target -> {
                if (Objects.requireNonNull(target) == DrawableClickListener.DrawablePosition.RIGHT) {
                    if (Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString().isEmpty()) {
                        AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                    } else {
                        ///API call
                        getLeaveHistory(binding);
                        CommonFunctions.dismissKeyboard(binding.getRoot());
                    }
                }
            });

            binding.rlFromDateInfo.setOnClickListener(v -> {
                if (binding.radioBFullday.isChecked() || binding.radioHalfDay.isChecked()) {
                    c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    // Launch Date Picker Dialog
                    dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
                        String month_of_year = "", start_day_Of_Month = "";
                        if ((monthOfYear + 1) < 10) {
                            month_of_year = "0" + (monthOfYear + 1);
                        } else {
                            month_of_year = String.valueOf(monthOfYear + 1);
                        }
                        if ((dayOfMonth) < 10) {
                            start_day_Of_Month = "0" + dayOfMonth;
                        } else {
                            start_day_Of_Month = String.valueOf(dayOfMonth);
                        }
                        String cmp_date = month_of_year + "/" + start_day_Of_Month + "/" + year;
                        binding.tvFromDate.setText(cmp_date);
                        binding.tvToDate.setText("");
                        if (binding.radioHalfDay.isChecked()) {
                            binding.tvToDate.setText(cmp_date);
                        }
                    }, mYear, mMonth, mDay);
                    Calendar calendar = Calendar.getInstance();
                    dpd.getDatePicker().setMinDate(calendar.getTimeInMillis() - 1000);
                    calendar = Calendar.getInstance();
                    calendar.add(Calendar.MONTH, 2);
                    dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());
                    dpd.show();
                }
            });

            binding.rlToDateInfo.setOnClickListener(v -> {
                if (binding.radioBFullday.isChecked() && !binding.tvFromDate.getText().toString().isEmpty()) {
                    c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    dpd = new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
                        try {
                            String month_of_year = "", day_Of_Month = "";
                            if ((monthOfYear + 1) < 10) {
                                month_of_year = "0" + (monthOfYear + 1);
                            } else {
                                month_of_year = String.valueOf(monthOfYear + 1);
                            }
                            if ((dayOfMonth) < 10) {
                                day_Of_Month = "0" + dayOfMonth;
                            } else {
                                day_Of_Month = String.valueOf(dayOfMonth);
                            }

                            binding.tvToDate.setText(month_of_year + "/" + day_Of_Month + "/" + year);

                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }, mYear, mMonth, mDay);
                    String[] fromDate = binding.tvFromDate.getText().toString().split("/");
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) - 1, Integer.parseInt(fromDate[1]));
                    dpd.getDatePicker().setMinDate(calendar.getTimeInMillis());
                    calendar = Calendar.getInstance();
                    calendar.set(Integer.parseInt(fromDate[2]), Integer.parseInt(fromDate[0]) + 1, Integer.parseInt(fromDate[1]));
                    dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());
                    dpd.show();
                }
            });
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onStart() {
            super.onStart();
            setCancelable(false);
            if (markleave) {
                binding.tvDialogTitle.setText("Apply For Leave");
                binding.btnSubmit.setVisibility(View.VISIBLE);
                binding.rlApplyLeaveDetail.setVisibility(View.VISIBLE);
                binding.rlLeaveHistory.setVisibility(View.GONE);
            } else {
                binding.tvDialogTitle.setText("Leave History");
                binding.btnSubmit.setVisibility(View.GONE);
                binding.rlApplyLeaveDetail.setVisibility(View.GONE);
                binding.rlLeaveHistory.setVisibility(View.VISIBLE);
            }

            binding.radioBFullday.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    binding.radioHalfDay.setChecked(false);
                    binding.radioBFullday.setChecked(true);
                    binding.tvFromDateInfo.setText("Date From");
                    binding.rlToDateInfo.setEnabled(true);
                    binding.tvFromDate.setText("");
                    binding.tvToDate.setText("");
                    binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.black));
                }
            });

            binding.radioHalfDay.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    binding.radioHalfDay.setChecked(true);
                    binding.radioBFullday.setChecked(false);
                    binding.tvFromDateInfo.setText("Select Date");
                    binding.rlToDateInfo.setEnabled(false);
                    binding.tvFromDate.setText("");
                    binding.tvToDate.setText("");
                    binding.tvTodatePlaceholder.setTextColor(ContextCompat.getColor(context, R.color.gray));
                }
            });
            binding.btnSubmit.setOnClickListener(v -> {
                if (tbameSearch == null && binding.tvEmpCode.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Employee/Legacy Code");
                } else if (!binding.radioBFullday.isChecked() && !binding.radioHalfDay.isChecked()) {
                    AlertandMessages.showToastMsg(context, "Please Select Leave Type(Full/Half day)");
                } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Select Date From");
                } else if (!binding.radioHalfDay.isChecked() && binding.radioBFullday.isChecked() && binding.tvToDate.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Select Date to");
                } else if (!binding.radioBFullday.isChecked() && binding.radioHalfDay.isChecked() && binding.tvFromDate.getText().toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Select Date");
                } else if (Objects.requireNonNull(binding.edtapplyForleaveReason.getText()).toString().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please Enter Reason");
                } else {
                    if (CommonFunctions.checkNetIsAvailable(context)) {
                        submitLeaveRequest(tbameSearch.getEmpId().toString(),
                                binding.radioBFullday.isChecked() ? binding.radioBFullday.getText().toString()
                                        : binding.radioHalfDay.getText().toString(),
                                binding.tvFromDate.getText().toString(), binding.tvToDate.getText().toString(),
                                binding.edtapplyForleaveReason.getText().toString());
                    } else {
                        AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
                    }
                }
            });
        }
    }

    private void submitLeaveRequest(String empId, String leaveType, String date_from, String
            date_to, String leaveReason) {
        ProgressDialog pd = null;
        try {
            pd = new ProgressDialog(context);
            pd.setTitle("Applying Leave Request");
            pd.setMessage("Please wait.....");
            pd.show();
            JSONObject json = new JSONObject().put("EmpId", empId)
                    .put("LeaveType", leaveType).put("FromDate", date_from).put("ToDate", leaveType.equals("Half Day") ? date_from : date_to)
                    .put("Reason", leaveReason).put("UserId", "");
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build();
            ProgressDialog finalPd = pd;
            adapter.create(PostApi.class).LeaveRequest(jsonData).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (!data.isEmpty() && !data.contains("No Data")) {
                                Common common = new Gson().fromJson(data, Common.class);
                                if (common != null && !common.getLeaveRequest().isEmpty()) {
                                    assert common.getLeaveRequest().get(0).getResult() != null;
                                    if (common.getLeaveRequest().get(0).getResult().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                        if (finalPd.isShowing()) finalPd.dismiss();
                                        showAlert(customDialogLeave, "Leave request applied successfully.");
                                    } else {
                                        if (finalPd.isShowing()) finalPd.dismiss();
                                        showAlert(customDialogLeave, common.getLeaveRequest().get(0).getResult());
                                    }
                                } else {
                                    if (finalPd.isShowing()) finalPd.dismiss();
                                    AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong));
                                }
                            } else {
                                if (finalPd.isShowing()) finalPd.dismiss();
                                AlertandMessages.showToastMsg(context, getString(R.string.something_went_wrong));
                            }
                            if (finalPd.isShowing()) finalPd.dismiss();
                        } catch (Exception e) {
                            if (finalPd.isShowing()) finalPd.dismiss();
                            AlertandMessages.showToastMsg(context, "Error in data.Please try again...");
                        }
                    } else {
                        if (finalPd.isShowing()) finalPd.dismiss();
                        AlertandMessages.showToastMsg(context, "Error in Data,Please try again...");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    if (finalPd.isShowing()) finalPd.dismiss();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });
        } catch (Exception ignored) {
            if (pd != null && pd.isShowing()) pd.dismiss();
        }

    }

    private void showAlert(CustomDialogLeaveApply customDialogLeave, String str) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(getString(R.string.parinaam));
            builder.setMessage(str).setCancelable(false)
                    .setPositiveButton(android.R.string.ok, (dialog, id) -> {
                        if (str.equals("Leave request applied successfully.")) {
                            if (customDialogLeave != null) customDialogLeave.cancel();
                        } else dialog.dismiss();
                    });
            AlertDialog alert = builder.create();
            alert.show();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private void getLeaveHistory(DialogApplyLeaveBinding binding) {
        ProgressDialog pd = null;
        try {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing");
            pd.setMessage("Please wait.....");
            pd.show();
            JSONObject json = new JSONObject().put("Downloadtype", "TBAME_LeaveHistory")
                    .put("Username", "").put("Param1", Objects.requireNonNull(binding.etEmployeeCodeforHistory.getText()).toString()).put("Param2", "");
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build();
            ProgressDialog finalPd = pd;
            adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (!data.isEmpty() && !data.contains("No Data")) {
                                Common common = new Gson().fromJson(data, Common.class);
                                if (common != null && !common.getTBAMELeaveHistory().isEmpty()) {
                                    runOnUiThread(() -> {
                                        binding.tvEmpNameHistory.setText(CommonFunctions.capitalizeFirstLetter(common.getTBAMELeaveHistory().get(0).getName()));
                                        binding.tvEmpDesignationHistory.setText(common.getTBAMELeaveHistory().get(0).getDesignation());
                                        binding.tvEmpCodeHistory.setText(common.getTBAMELeaveHistory().get(0).getEmpCode());
                                        binding.recyclerLeaveDetail.setAdapter(new LeaveDetailAdapter(context, common.getTBAMELeaveHistory()));
                                        binding.recyclerLeaveDetail.setLayoutManager(new LinearLayoutManager(context));
                                        binding.rlLeaveDetailItem.setVisibility(View.VISIBLE);
                                    });
                                }
                            } else {
                                runOnUiThread(() -> {
                                    binding.tvEmpNameHistory.setText("");
                                    binding.tvEmpCodeHistory.setText("");
                                    binding.tvEmpDesignationHistory.setText("");
                                    binding.rlLeaveDetailItem.setVisibility(View.GONE);
                                });
                                AlertandMessages.showToastMsg(context, "No Leave history found for this employee . Please check Employee code and re-sync");
                            }
                            if (finalPd.isShowing()) finalPd.dismiss();
                        } catch (Exception e) {
                            runOnUiThread(() -> {
                                binding.tvEmpNameHistory.setText("");
                                binding.tvEmpCodeHistory.setText("");
                                binding.tvEmpDesignationHistory.setText("");
                                binding.rlLeaveDetailItem.setVisibility(View.GONE);
                            });
                            if (finalPd.isShowing()) finalPd.dismiss();
                            AlertandMessages.showAlert((Activity) context, "Error in Leave history data.", true);
                        }
                    } else {
                        runOnUiThread(() -> {
                            binding.tvEmpNameHistory.setText("");
                            binding.tvEmpCodeHistory.setText("");
                            binding.tvEmpDesignationHistory.setText("");
                            binding.rlLeaveDetailItem.setVisibility(View.GONE);
                        });
                        if (finalPd.isShowing()) finalPd.dismiss();
                        AlertandMessages.showAlert((Activity) context, "Error in downloading Data,Please try again... ", true);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    runOnUiThread(() -> {
                        binding.tvEmpNameHistory.setText("");
                        binding.tvEmpCodeHistory.setText("");
                        binding.tvEmpDesignationHistory.setText("");
                        binding.rlLeaveDetailItem.setVisibility(View.GONE);
                    });
                    if (finalPd.isShowing()) finalPd.dismiss();
                    AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE, true);
                }
            });
        } catch (Exception ignored) {
            if (pd != null && pd.isShowing()) pd.dismiss();
        }
    }

    private void getEmployeeDetails(String empId, TextView tvEmpName, TextView
            tvEmpId, TextView empDesignation) {
        ProgressDialog pd = null;
        try {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing");
            pd.setMessage("Please wait.....");
            pd.show();
            JSONObject json = new JSONObject().put("Downloadtype", "TBAME_Search").put("Username", "").put("Param1", empId)
                    .put("Param2", "");
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), json.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build()).addConverterFactory(GsonConverterFactory.create()).build();
            ProgressDialog finalPd = pd;
            adapter.create(PostApi.class).getDownloadAll(jsonData).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            assert data != null;
                            if (!data.isEmpty() && !data.contains("No Data")) {
                                Common common = new Gson().fromJson(data, Common.class);
                                if (common != null && !common.getTBAMESearch().isEmpty()) {
                                    tbameSearch = common.getTBAMESearch().get(0);
                                    runOnUiThread(() -> {
                                        tvEmpName.setText(common.getTBAMESearch().get(0).getName());
                                        tvEmpId.setText(common.getTBAMESearch().get(0).getEmpCode());
                                        empDesignation.setText(common.getTBAMESearch().get(0).getDesignation());
                                    });
                                } else {
                                    tbameSearch = null;
                                    runOnUiThread(() -> {
                                        tvEmpName.setText("");
                                        tvEmpId.setText("");
                                        empDesignation.setText("");
                                    });
                                    AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync");
                                }
                            } else {
                                tbameSearch = null;
                                runOnUiThread(() -> {
                                    tvEmpName.setText("");
                                    tvEmpId.setText("");
                                    empDesignation.setText("");
                                });
                                AlertandMessages.showToastMsg(context, "Employee Detail not available. Please check Employee/Legacy code and re-sync");
                            }
                            if (finalPd.isShowing()) finalPd.dismiss();
                        } catch (Exception e) {
                            tbameSearch = null;
                            runOnUiThread(() -> {
                                tvEmpName.setText("");
                                tvEmpId.setText("");
                                empDesignation.setText("");
                            });
                            if (finalPd.isShowing()) finalPd.dismiss();
                            AlertandMessages.showToastMsg(context, "Error in data. " + e.getMessage());
                        }
                    } else {
                        tbameSearch = null;
                        runOnUiThread(() -> {
                            tvEmpName.setText("");
                            tvEmpId.setText("");
                            empDesignation.setText("");
                        });
                        if (finalPd.isShowing()) finalPd.dismiss();
                        AlertandMessages.showToastMsg(context, "Error in downloading Data,Please try again... ");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    tbameSearch = null;
                    runOnUiThread(() -> {
                        tvEmpName.setText("");
                        tvEmpId.setText("");
                        empDesignation.setText("");
                    });
                    if (finalPd.isShowing()) finalPd.dismiss();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });
        } catch (Exception ignored) {
            if (pd != null && pd.isShowing()) pd.dismiss();
        }
    }
}
