package com.dittomart.meatsbhavan.ui;

import static android.Manifest.permission.POST_NOTIFICATIONS;
import static com.dittomart.meatsbhavan.util.Constant.APP_UPDATE_REQUEST_CODE;
import static com.dittomart.meatsbhavan.util.Constant.BASE_URL;
import static com.dittomart.meatsbhavan.util.Constant.ID;
import static com.dittomart.meatsbhavan.util.Constant.INTENT_DOMAINS;
import static com.dittomart.meatsbhavan.util.Constant.REQUEST_FINE_LOCATION;
import static com.dittomart.meatsbhavan.util.Constant.STORE_COLOR;
import static com.dittomart.meatsbhavan.util.Constant.UNIQUE_ORDER_ID;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.GeolocationPermissions;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.webkit.WebSettingsCompat;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.dittomart.meatsbhavan.CustomSwipeToRefresh;
import com.dittomart.meatsbhavan.R;
import com.dittomart.meatsbhavan.api.Api;
import com.dittomart.meatsbhavan.firebase.CreateFirebase;
import com.dittomart.meatsbhavan.network.RetrofitInstance;
import com.dittomart.meatsbhavan.util.CallbackWithRetry;
import com.dittomart.meatsbhavan.util.Constant;
import com.dittomart.meatsbhavan.util.Funtionality;
import com.dittomart.meatsbhavan.util.PackageVerificationListener;
import com.dittomart.meatsbhavan.util.SharePref;
import com.dittomart.meatsbhavan.web.WebAppInterface;
import com.dittomart.meatsbhavan.web.webChromeClient.MyWebChromeClient;
import com.dittomart.meatsbhavan.web.webViewClient.MyWebViewClient;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.model.ActivityResult;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.gson.Gson;
import com.razorpay.PaymentData;
import com.razorpay.PaymentResultWithDataListener;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements PaymentResultWithDataListener  {

    private static final String TAG = "MainActivity";
    private static Api apiService;
    String Url;
    private WebView myWebView;
    private ProgressBar progressBar;
    private boolean notificationOpened = false;
    public static String mGeolocationOrigin;
    public static GeolocationPermissions.Callback mGeolocationCallback;
    private LocationManager locationManager;
    private CustomSwipeToRefresh swipe;
    private AppUpdateManager mAppUpdateManager;
    private ImageView screen_iv;
    String userAgent ="FoodomaaAndroidWebViewUA";
    private MyWebChromeClient myWebChromeClient;
    private static final int PUSH_NOTIFICATION_PERMISSION_CODE = 123;
    private WebAppInterface webAppInterface;
    // Timeout configurations for faster app loading
    private static final int SPLASH_TIMEOUT = 2000; // 1 second - splash screen timeout
    private static final int PROGRESS_TIMEOUT = 2000; // 2 seconds - progress bar timeout
    private android.os.Handler splashTimeoutHandler;
    private android.os.Handler progressTimeoutHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Status bar is configured in BaseActivity
        // Additional enforcement after layout is set for better compatibility
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                forceWhiteStatusBar();
            }
        });
        
        // Brand-specific compatibility fixes
        setupBrandCompatibility();

        // Initialize SharePref
        new SharePref(this);  // Initialize with context

        // Set up splash timeout to prevent app from getting stuck (1 second for faster loading)
        splashTimeoutHandler = new android.os.Handler(android.os.Looper.getMainLooper());
        splashTimeoutHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.w(TAG, "Splash timeout reached (1s), forcing app initialization");
                if (progressBar.getVisibility() == View.VISIBLE) {
                    // If still showing splash, force initialization
                    StartApp();
                }
            }
        }, SPLASH_TIMEOUT);
        
        // Set up progress bar timeout to prevent getting stuck on loading screen
        progressTimeoutHandler = new android.os.Handler(android.os.Looper.getMainLooper());

        Log.d(TAG, "Action: " + getIntent().getAction());

        //Check for Update
        CheckUpdate();

        progressBar = findViewById(R.id.progress_circular);
        screen_iv = findViewById(R.id.screen_iv);

        // Ensure splash screen is visible and WebView is hidden initially
        View splashBackground = findViewById(R.id.splash_background);
        if (splashBackground != null) {
            splashBackground.setVisibility(View.VISIBLE);
        }
        if (screen_iv != null) {
            screen_iv.setVisibility(View.VISIBLE);
        }

        swipe = findViewById(R.id.swipeContainer);
        swipe.setOnRefreshListener(() -> {
            if (myWebView != null) {
                myWebView.reload();
            } else {
                Log.w(TAG, "WebView is null, cannot reload");
                swipe.setRefreshing(false);
            }
        });

        //Ifras-- changes
        progressBar.setVisibility(View.VISIBLE);

        if (!SharePref.getBooleanFromPref(Constant.ANLIVER_CHECKED)) {
            //if anliverChecked false then
            if (!SharePref.getBooleanFromPref(Constant.ANLIVER)) {
                // if anliver false then call for api to check ANLIVER
                Funtionality.checkAndroidPackage(this, new PackageVerificationListener() {
                    @Override
                    public void onSuccess() {
                        getSettings();
                    }

                    @Override
                    public void onFailure(String message) {
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                //Toast.makeText(this, "getting settings...", Toast.LENGTH_SHORT).show();
                getSettings();
            }
        } else {
            //if ANLIVER(First time) checking is true then check for ANLIVER
            if (SharePref.getBooleanFromPref(Constant.ANLIVER)) {
                // if this is true then start app
                getSettings();
            } else {
                Toast.makeText(this, "Please try to install Licensed App", Toast.LENGTH_SHORT).show();
            }
        }

        // Ifras - End



    }


    //Ifras
    private void getSettings() {
        if (!SharePref.getDataFromPref(Constant.ANLIVER_BASE_URL).equals(""))
            Constant.BASE_URL = SharePref.getDataFromPref(Constant.ANLIVER_BASE_URL);

        Api apiService = RetrofitInstance.getRetrofitIntance().create(Api.class);

        // First API call
        apiService.getSetting(STORE_COLOR).enqueue(new CallbackWithRetry<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                if (!response.isSuccessful()) {
                    try {
                        throw new Exception("Server error");
                    } catch (Exception e) {
                        super.onFailure(call, e);
                    }
                } else {
                    String json = new Gson().toJson(response.body());
                    try {
                        JSONObject object = new JSONObject(json.trim());
                        SharePref.setDataPref(STORE_COLOR, object.getString("value"));
                        Log.d(TAG, "Preference: " + SharePref.getDataFromPref(STORE_COLOR));

                        // Now initiate the second API call after the first one completes successfully
                        callSecondApi(apiService);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        // If JSON parsing fails, continue with app initialization
                        callSecondApi(apiService);
                    }
                }
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                super.onFailure(call, t);
                // After all retries failed, continue with app initialization
                Log.w(TAG, "Store color API failed after retries, continuing with default values");
                callSecondApi(apiService);
            }
        });
    }
    //Ifras
    private void callSecondApi(Api apiService) {
        // Second API call
        apiService.getSetting(INTENT_DOMAINS).enqueue(new Callback<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                Log.d(TAG, "onResponse: Code: " + response.code() + " Successful :" + response.isSuccessful() + "Body :" + response.body());
                if (response.code() == 200) {
                    if (response.isSuccessful()) {
                        String intentDomains;
                        if (!response.body().toString().equals("")) {
                            intentDomains = response.body().toString();
                            SharePref.setDataPref(INTENT_DOMAINS, intentDomains);
                        } else {
                            SharePref.setDataPref(INTENT_DOMAINS, "[]");
                        }
                    } else {
                        SharePref.setDataPref(INTENT_DOMAINS, "[]");
                    }
                } else {
                    SharePref.setDataPref(INTENT_DOMAINS, "[]");
                }
                // Always start the app after second API call completes (success or failure)
                StartApp();
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
                SharePref.setDataPref(INTENT_DOMAINS, "[]");
                // Start the app even if API call fails
                StartApp();
            }
        });
    }

    //Ifras
    private void StartApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33 or above
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                Log.e("PushNotification", "Permission not granted");

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.POST_NOTIFICATIONS)) {
                    // Show an explanation to the user before requesting the permission
                    Log.e("PushNotification", "Show permission rationale");
                    // Display a dialog or some UI to explain why you need the permission
                    initCallHomePage();
                }

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, 102);
            } else {
                // Permission granted, proceed to the next activity
                initCallHomePage();
            }
        } else {
            // No need to check for POST_NOTIFICATIONS permission on versions below Android 13
            initCallHomePage();
        }
    }

    // Ifras
    private void initCallHomePage(){
        // Cancel splash timeout since app is initializing
        if (splashTimeoutHandler != null) {
            splashTimeoutHandler.removeCallbacksAndMessages(null);
        }
        
        Log.d(TAG, "initCallHomePage: Starting app initialization");
        
        //        Log.d(TAG, "COLOR: " + SharePref.getDataFromPref(Constant.STORE_COLOR));
        if (!SharePref.getDataFromPref(STORE_COLOR).equals("")) {
//            Toast.makeText(this, "Set Color", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.VISIBLE);
            progressBar.getIndeterminateDrawable().setColorFilter(Color.parseColor(SharePref.getDataFromPref(STORE_COLOR)), PorterDuff.Mode.MULTIPLY);
        }

        //initialize Api Connect with URL
        setupConnection();

        //Connect to firebase
        new CreateFirebase(apiService,this);

        setWebView();
        
        // Additional fallback: if WebView setup fails, ensure app doesn't get stuck
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (myWebView == null || myWebView.getVisibility() != View.VISIBLE) {
                    Log.w(TAG, "WebView not visible after 2 seconds, forcing visibility");
                    hideProgressBar();
                }
            }
        }, 2000); // 2 second fallback for faster loading
    }

    private void CheckUpdate() {
        mAppUpdateManager = AppUpdateManagerFactory.create(this);
        mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                    && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                // Request the update.
                try {
                    mAppUpdateManager.startUpdateFlowForResult(
                            appUpdateInfo,
                            AppUpdateType.IMMEDIATE,
                            MainActivity.this,
                            APP_UPDATE_REQUEST_CODE);
                } catch (IntentSender.SendIntentException e) {
                    e.printStackTrace();
                }
                Funtionality.checkAndroidPackage(this, new PackageVerificationListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailure(String message) {
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
                Log.d(TAG, "Update available");
            } else {
                Log.d(TAG, "No Update available");
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();

        mAppUpdateManager
            .getAppUpdateInfo()
            .addOnSuccessListener(
                    appUpdateInfo -> {
                        if (appUpdateInfo.updateAvailability()
                                == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                            // If an in-app update is already running, resume the update.
                            try {
                                mAppUpdateManager.startUpdateFlowForResult(
                                        appUpdateInfo,
                                        AppUpdateType.IMMEDIATE,
                                        this,
                                        APP_UPDATE_REQUEST_CODE);
                            } catch (IntentSender.SendIntentException e) {
                                e.printStackTrace();
                            }
                        }
                    });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "ActivityResult");
        if (requestCode == APP_UPDATE_REQUEST_CODE) {
//            Log.d(TAG, "onActivityResult: "+"App REQUEST CODE");
            //when user clicks update button
            if (resultCode == Activity.RESULT_OK) {
//                Toast.makeText(this, "No new updates available", Toast.LENGTH_LONG).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                //if user click on close button
                Toast.makeText(this, "Kindly update the app", Toast.LENGTH_LONG).show();
                //Here you can do whatever you want (call finish() to close the app.)
                finish();
            } else if (resultCode == ActivityResult.RESULT_IN_APP_UPDATE_FAILED) {
                Toast.makeText(this, "App download failed.", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == Constant.REQUEST_FOR_GPS) {
            // Handle GPS settings result
            if (resultCode == Activity.RESULT_OK) {
                // GPS was enabled by user, grant permission
                if (mGeolocationCallback != null && mGeolocationOrigin != null) {
                    mGeolocationCallback.invoke(mGeolocationOrigin, true, false);
                }
            } else {
                // GPS was not enabled, deny permission
                if (mGeolocationCallback != null && mGeolocationOrigin != null) {
                    mGeolocationCallback.invoke(mGeolocationOrigin, false, false);
                }
            }
        } else if (requestCode == 69) {
            // Handle PayU payment result
            if (data != null) {
                Boolean success = data.getBooleanExtra("success", false);
                Log.d("PayU>", Boolean.toString(success));
                if (success) {
                    String txnID = data.getStringExtra("txn");
                    Log.d("PayU>", txnID);
                    // call api
                    apiService.sendPayUSuccess(txnID).enqueue(new Callback<Object>() {
                        @Override
                        public void onResponse(Call<Object> call, Response<Object> response) {
                            if (response.isSuccessful()) {
                                String json = new Gson().toJson(response.body());
                                Log.d("PayU>", "Success JSON>" + json.toString());
                                try {
                                    JSONObject jsonObject = new JSONObject(json.trim());
                                    if (jsonObject.getBoolean("success")) {
                                        Log.d("PayU>", "API success");
                                        if (UNIQUE_ORDER_ID != null) {
                                            myWebView.loadUrl(BASE_URL.concat("running-order/").concat(UNIQUE_ORDER_ID));
                                            UNIQUE_ORDER_ID = null;
                                        } else {
                                            myWebView.loadUrl(BASE_URL + "my-orders");
                                        }
                                    } else {
                                        Log.d("PayU>", "API failed");
                                        myWebView.loadUrl(BASE_URL + "my-orders");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Log.d("PayU>", "API catch error");
                                    myWebView.loadUrl(BASE_URL + "my-orders");
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<Object> call, Throwable t) {
                            myWebView.loadUrl(BASE_URL + "my-orders");
                        }
                    });
                } else {
                    myWebView.loadUrl(BASE_URL + "my-orders");
                }
            } else {
                myWebView.loadUrl(BASE_URL + "my-orders");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
    }

    //Permission request Handle
//    @RequiresApi(api = Build.VERSION_CODES.M)
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (grantResults.length > 0) {
//            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//                if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) == PackageManager.PERMISSION_DENIED) {
//                    ActivityCompat.requestPermissions(this, new String[]{POST_NOTIFICATIONS}, PUSH_NOTIFICATION_PERMISSION_CODE);
//                }
//            }
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                //Do the stuff that requires permission...
//                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//
//                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//                    //Turn on Gps => fn
//                    myWebChromeClient.locationEnabled();
//                    //send gps to webview
//                }
//                mGeolocationCallback.invoke(mGeolocationOrigin, true, false);
//
//
//            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
//                mGeolocationCallback.invoke(mGeolocationOrigin, true, false);
//                // Should we show an explanation?
//            }
//        }
//
//    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults.length > 0) {
            // Handle notification permission (request code 102)
            if (requestCode == 102) {
                // Notification permission granted or denied, continue with app initialization
                initCallHomePage();
                return;
            }
            
            // Handle location permission (request code 100)
            if (requestCode == REQUEST_FINE_LOCATION) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) == PackageManager.PERMISSION_DENIED) {
                        ActivityCompat.requestPermissions(this, new String[]{POST_NOTIFICATIONS}, PUSH_NOTIFICATION_PERMISSION_CODE);
                    }
                }
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Do stuff that requires permission...
                    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                    if (!isLocationEnabled()) {
                        // Turn on GPS => fn
                        myWebChromeClient.locationEnabled();
                        // Don't invoke callback here, let locationEnabled() handle it
                    } else {
                        // GPS is already enabled, grant permission immediately
                        if (mGeolocationCallback != null && mGeolocationOrigin != null) {
                            mGeolocationCallback.invoke(mGeolocationOrigin, true, false);
                        }
                    }
                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    // Permission denied, deny geolocation access
                    if (mGeolocationCallback != null && mGeolocationOrigin != null) {
                        mGeolocationCallback.invoke(mGeolocationOrigin, false, false);
                    }
                }
            }
        }
    }

    // Check if location services are enabled (GPS or Network)
    private boolean isLocationEnabled() {
        if (locationManager == null) {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
               locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }
    
    // Public method to access WebView for WebAppInterface
    public WebView getWebView() {
        return myWebView;
    }
    
    /**
     * Start progress bar timeout to prevent getting stuck on loading screen
     */
    private void startProgressTimeout() {
        if (progressTimeoutHandler != null) {
            progressTimeoutHandler.removeCallbacksAndMessages(null);
            progressTimeoutHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.w(TAG, "Progress bar timeout reached, hiding progress bar");
                    hideProgressBar();
                }
            }, PROGRESS_TIMEOUT);
        }
    }
    
    /**
     * Hide progress bar and show WebView
     */
    private void hideProgressBar() {
        try {
            if (progressBar != null && progressBar.getVisibility() == View.VISIBLE) {
                progressBar.setVisibility(View.GONE);
                Log.d(TAG, "Progress bar hidden due to timeout");
            }
            
            // Show WebView if it's hidden
            if (myWebView != null && myWebView.getVisibility() != View.VISIBLE) {
                myWebView.setVisibility(View.VISIBLE);
                Log.d(TAG, "WebView shown due to progress timeout");
            }
            
            // Hide splash screen
            if (screen_iv != null && screen_iv.getVisibility() == View.VISIBLE) {
                screen_iv.setVisibility(View.GONE);
                View splashBackground = findViewById(R.id.splash_background);
                if (splashBackground != null) {
                    splashBackground.setVisibility(View.GONE);
                }
                Log.d(TAG, "Splash screen hidden due to progress timeout");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error hiding progress bar: " + e.getMessage());
        }
    }
    
    /**
     * Handle network connectivity errors (DNS resolution, no internet, etc.)
     */
    private void handleNetworkError(WebView view, String failingUrl) {
        Log.w(TAG, "Handling network error for URL: " + failingUrl);
        
        // Hide progress bar
        hideProgressBar();
        
        // Check if network is available
        if (!isNetworkAvailable()) {
            Log.w(TAG, "No network connectivity detected");
            showNoInternetError();
        } else {
            Log.w(TAG, "Network available but DNS resolution failed");
            showNetworkErrorRetry();
        }
        
        // Try alternative approaches
        retryWithAlternativeMethods(failingUrl);
    }
    
    /**
     * Show no internet error
     */
    private void showNoInternetError() {
        runOnUiThread(() -> {
            try {
                String errorHtml = "<html><body style='font-family: Arial; text-align: center; padding: 50px;'>" +
                        "<h2>No Internet Connection</h2>" +
                        "<p>Please check your internet connection and try again.</p>" +
                        "<p>Make sure you're connected to WiFi or mobile data.</p>" +
                        "<button onclick='location.reload()' style='padding: 10px 20px; font-size: 16px; background: #007bff; color: white; border: none; border-radius: 5px;'>Retry</button>" +
                        "</body></html>";
                
                if (myWebView != null) {
                    myWebView.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error showing no internet error: " + e.getMessage());
            }
        });
    }
    
    /**
     * Check if the URL is a non-critical request (analytics, tracking, ads, etc.)
     * These requests failing should not cause page reloads
     */
    private boolean isNonCriticalRequest(String url) {
        if (url == null) return true;
        
        String lowerUrl = url.toLowerCase();
        
        // List of non-critical domains/patterns that failing should be ignored
        String[] nonCriticalPatterns = {
            "capig.datah04.com",
            "analytics",
            "tracking",
            "google-analytics",
            "googletagmanager",
            "facebook.com/tr",
            "doubleclick",
            "ads",
            "adservice",
            "telemetry",
            "metrics",
            "beacon",
            "pixel",
            "stats",
            "datah04.com" // Specific domain causing issues
        };
        
        for (String pattern : nonCriticalPatterns) {
            if (lowerUrl.contains(pattern)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Handle HTTP errors (4xx, 5xx status codes)
     */
    private void handleHttpError(WebView view, String url, int statusCode) {
        Log.w(TAG, "Handling HTTP error: " + statusCode + " for URL: " + url);
        
        // Ignore non-critical requests
        if (isNonCriticalRequest(url)) {
            Log.d(TAG, "Skipping HTTP error handling for non-critical URL: " + url);
            return;
        }
        
        // Hide progress bar
        hideProgressBar();
        
        if (statusCode >= 500) {
            // Server error - show retry option
            showServerErrorRetry();
        } else if (statusCode == 404) {
            // Page not found - only retry if it's the main page URL, not a sub-resource
            if (url.equals(BASE_URL) || url.startsWith(BASE_URL)) {
                Log.w(TAG, "Main page returned 404, retrying with base URL");
                retryWithBaseUrl();
            } else {
                Log.d(TAG, "404 error on sub-resource, not reloading main page: " + url);
            }
        }
    }
    
    /**
     * Show network error retry option
     */
    private void showNetworkErrorRetry() {
        runOnUiThread(() -> {
            try {
                // Show a simple retry message
                String errorHtml = "<html><body style='font-family: Arial; text-align: center; padding: 50px;'>" +
                        "<h2>Network Error</h2>" +
                        "<p>Unable to connect to the server.</p>" +
                        "<p>Please check your internet connection and try again.</p>" +
                        "<button onclick='location.reload()' style='padding: 10px 20px; font-size: 16px; background: #007bff; color: white; border: none; border-radius: 5px;'>Retry</button>" +
                        "</body></html>";
                
                if (myWebView != null) {
                    myWebView.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error showing network error retry: " + e.getMessage());
            }
        });
    }
    
    /**
     * Show server error retry option
     */
    private void showServerErrorRetry() {
        runOnUiThread(() -> {
            try {
                String errorHtml = "<html><body style='font-family: Arial; text-align: center; padding: 50px;'>" +
                        "<h2>Server Error</h2>" +
                        "<p>The server is temporarily unavailable.</p>" +
                        "<p>Please try again in a few moments.</p>" +
                        "<button onclick='location.reload()' style='padding: 10px 20px; font-size: 16px; background: #007bff; color: white; border: none; border-radius: 5px;'>Retry</button>" +
                        "</body></html>";
                
                if (myWebView != null) {
                    myWebView.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error showing server error retry: " + e.getMessage());
            }
        });
    }
    
    /**
     * Retry with alternative methods
     */
    private void retryWithAlternativeMethods(String failingUrl) {
        Log.d(TAG, "Retrying with alternative methods for: " + failingUrl);
        
        // Method 1: Try with different DNS
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            if (myWebView != null) {
                Log.d(TAG, "Retrying URL with alternative DNS...");
                myWebView.reload();
            }
        }, 2000);
        
        // Method 2: Try base URL if specific URL failed
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            if (myWebView != null && !failingUrl.equals(BASE_URL)) {
                Log.d(TAG, "Retrying with base URL: " + BASE_URL);
                myWebView.loadUrl(BASE_URL);
            }
        }, 5000);
    }
    
    /**
     * Retry with base URL
     */
    private void retryWithBaseUrl() {
        Log.d(TAG, "Retrying with base URL: " + BASE_URL);
        if (myWebView != null) {
            myWebView.loadUrl(BASE_URL);
        }
    }
    
    /**
     * Check network connectivity
     */
    private boolean isNetworkAvailable() {
        try {
            android.net.ConnectivityManager connectivityManager = 
                (android.net.ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            
            if (connectivityManager != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    android.net.Network network = connectivityManager.getActiveNetwork();
                    android.net.NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                    return capabilities != null && 
                           (capabilities.hasTransport(android.net.NetworkCapabilities.TRANSPORT_WIFI) ||
                            capabilities.hasTransport(android.net.NetworkCapabilities.TRANSPORT_CELLULAR) ||
                            capabilities.hasTransport(android.net.NetworkCapabilities.TRANSPORT_ETHERNET));
                } else {
                    android.net.NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                    return networkInfo != null && networkInfo.isConnected();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking network connectivity: " + e.getMessage());
        }
        return false;
    }

    private void setupConnection() {
        BASE_URL = SharePref.getDataFromPref(Constant.ANLIVER_BASE_URL);
        apiService = RetrofitInstance.getRetrofitIntance().create(Api.class);
    }

    private void setWebView() {
        if (!SharePref.getDataFromPref(STORE_COLOR).equals("")) {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.getIndeterminateDrawable().setColorFilter(Color.parseColor(SharePref.getDataFromPref(STORE_COLOR)), PorterDuff.Mode.MULTIPLY);
        }

        myWebView = findViewById(R.id.webChart);
        
        // Verify WebView was found
        if (myWebView == null) {
            Log.e(TAG, "WebView not found in layout!");
            // Hide progress bar and show error message
            hideProgressBar();
            return;
        }
        
        // Start progress timeout to prevent getting stuck
        startProgressTimeout();
        
        // Enhanced WebView configuration for better brand compatibility
        configureWebViewForAllBrands();

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webAppInterface = new WebAppInterface(this, apiService);
        myWebView.addJavascriptInterface(webAppInterface, "Android");
        webSettings.setUserAgentString(userAgent);
        webSettings.setGeolocationEnabled(true);
        
        // Enhanced GPS configuration for better device compatibility
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        
        // Enhanced network configuration for better connectivity
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setBlockNetworkLoads(false);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        
        // Note: setGeolocationDatabasePath is deprecated, WebView handles geolocation data automatically
        // Note: setAppCacheEnabled and setAppCachePath are deprecated in newer Android versions
        // Cache is handled automatically by WebView in modern versions
        WebView.setWebContentsDebuggingEnabled(true);
        
        // Device-specific WebView optimizations for GPS
        String manufacturer = Build.MANUFACTURER.toLowerCase();
        Log.d(TAG, "Configuring WebView for device: " + manufacturer);
        
        if (manufacturer.contains("xiaomi") || manufacturer.contains("redmi")) {
            // MIUI specific settings
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setSupportMultipleWindows(true);
        } else if (manufacturer.contains("vivo") || manufacturer.contains("iqoo")) {
            // Vivo/iQOO specific settings
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
            webSettings.setSupportMultipleWindows(false);
        } else if (manufacturer.contains("samsung")) {
            // Samsung specific settings
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        } else if (manufacturer.contains("oppo") || manufacturer.contains("oneplus")) {
            // Oppo/OnePlus specific settings
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        }
        
        // Android 15 specific WebView configurations
        if (Build.VERSION.SDK_INT >= 35) {
            // Enable modern WebView features for Android 15
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
            // Note: setDatabaseEnabled is deprecated, WebView handles databases automatically
            webSettings.setLoadsImagesAutomatically(true);
            webSettings.setBlockNetworkImage(false);
            webSettings.setBlockNetworkLoads(false);
            
            // Enable safe browsing for Android 15
            try {
                WebSettingsCompat.setSafeBrowsingEnabled(webSettings, true);
            } catch (Exception e) {
                Log.d(TAG, "Safe browsing not supported on this device: " + e.getMessage());
            }
            
            // Disable dark mode support - force light mode
            try {
                WebSettingsCompat.setForceDark(webSettings, WebSettingsCompat.FORCE_DARK_OFF);
            } catch (Exception e) {
                Log.d(TAG, "Force dark not supported on this device: " + e.getMessage());
            }
        }

        Intent intent = this.getIntent();
        Bundle extras = intent.getExtras();

        if (extras != null) {
            if (extras.containsKey("URL")) {
                Url = extras.getString("URL");
            }
        }

        String link = null;
        if (getIntent().getData() != null) {
            link = getIntent().getData().toString();
        }

        if (Url != null) {
            notificationOpened = true;
            myWebView.loadUrl(Url);
        } else if (link != null) {
            myWebView.loadUrl(link);
        } else {
            myWebView.loadUrl(BASE_URL);
        }


        Animation fade_out = AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out);


        myWebView.setWebViewClient(new MyWebViewClient(this) {

            @Override
            public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.d(TAG, "Page started loading: " + url);
                // Cancel any existing progress timeout and start a new one
                startProgressTimeout();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.d(TAG, "Page finished loading: " + url);
                
                // Cancel progress timeout since page loaded successfully
                if (progressTimeoutHandler != null) {
                    progressTimeoutHandler.removeCallbacksAndMessages(null);
                }

                screen_iv.startAnimation(fade_out);

                fade_out.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        screen_iv.setVisibility(View.GONE);
                        // Hide splash background and show WebView
                        View splashBackground = findViewById(R.id.splash_background);
                        if (splashBackground != null) {
                            splashBackground.setVisibility(View.GONE);
                        }
                        myWebView.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });

                swipe.setRefreshing(false);

                super.onPageFinished(view, url);
            }
            
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.e(TAG, "WebView error: " + errorCode + " - " + description + " for URL: " + failingUrl);
                
                // Handle specific network errors
                if (description.contains("ERR_NAME_NOT_RESOLVED") || 
                    description.contains("ERR_INTERNET_DISCONNECTED") ||
                    description.contains("ERR_NETWORK_CHANGED")) {
                    Log.w(TAG, "Network connectivity issue detected: " + description);
                    handleNetworkError(view, failingUrl);
                } else {
                    // Hide progress bar on other errors
                    hideProgressBar();
                }
            }
            
            @Override
            public void onReceivedHttpError(WebView view, android.webkit.WebResourceRequest request, android.webkit.WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                Log.e(TAG, "HTTP error: " + errorResponse.getStatusCode() + " for URL: " + request.getUrl());
                
                String url = request.getUrl().toString();
                int statusCode = errorResponse.getStatusCode();
                
                // Ignore errors from analytics, tracking, or third-party services (these are not critical)
                if (isNonCriticalRequest(url)) {
                    Log.d(TAG, "Ignoring HTTP error for non-critical request: " + url);
                    return;
                }
                
                // Only handle HTTP errors for main frame requests
                // Ignore sub-resource errors (images, scripts, etc.) to prevent reload loops
                if (request.isForMainFrame() && statusCode >= 400) {
                    handleHttpError(view, url, statusCode);
                } else {
                    Log.d(TAG, "Ignoring HTTP error for sub-resource: " + url);
                }
            }

        });



        myWebView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (myWebView.canGoBack()) {
                        myWebView.goBack();
                    } else {
                        finish();
                    }
                    return true;
                }
            }
            return false;
        });


        myWebChromeClient = new MyWebChromeClient(locationManager,this,myWebView,swipe);

        myWebView.setWebChromeClient(myWebChromeClient);
        
        // Android 15 specific WebView behavior handling
        setupAndroid15WebViewBehavior();
        
        // Update SwipeRefreshLayout callback now that WebView is initialized
        updateSwipeRefreshCallback();

    }
    
    /**
     * Update SwipeRefreshLayout callback to use the initialized WebView
     */
    private void updateSwipeRefreshCallback() {
        if (swipe != null && myWebView != null) {
            swipe.setOnRefreshListener(() -> {
                if (myWebView != null) {
                    myWebView.reload();
                } else {
                    Log.w(TAG, "WebView is null during refresh");
                    swipe.setRefreshing(false);
                }
            });
            Log.d(TAG, "SwipeRefreshLayout callback updated with initialized WebView");
        }
    }
    

    /**
     * Setup brand-specific compatibility fixes
     */
    private void setupBrandCompatibility() {
        try {
            String manufacturer = Build.MANUFACTURER.toLowerCase();
            Log.d(TAG, "Setting up compatibility for: " + manufacturer);
            
            // Vivo/iQOO specific fixes
            if (manufacturer.contains("vivo") || manufacturer.contains("iqoo")) {
                // Disable battery optimization for better WebView performance
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // Request to ignore battery optimizations
                    Intent intent = new Intent();
                    intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(android.net.Uri.parse("package:" + getPackageName()));
                    // Note: This will show a dialog to user, but we can't auto-grant it
                }
                
                // Set window flags for better compatibility
                getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
                
                Log.d(TAG, "Applied Vivo/iQOO compatibility fixes");
            }
            
            // Xiaomi/Redmi specific fixes
            if (manufacturer.contains("xiaomi") || manufacturer.contains("redmi")) {
                // MIUI specific optimizations
                getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
                Log.d(TAG, "Applied Xiaomi/Redmi compatibility fixes");
            }
            
            // Samsung specific fixes
            if (manufacturer.contains("samsung")) {
                // Samsung One UI optimizations
                getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
                Log.d(TAG, "Applied Samsung compatibility fixes");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error setting up brand compatibility: " + e.getMessage());
        }
    }

    /**
     * Configure WebView for better compatibility across all Android brands
     * Especially fixes issues with Vivo, iQOO, Xiaomi, Oppo, OnePlus, etc.
     */
    private void configureWebViewForAllBrands() {
        try {
            // Check if WebView is initialized
            if (myWebView == null) {
                Log.e(TAG, "WebView is null in configureWebViewForAllBrands");
                return;
            }
            
            // Get device manufacturer for brand-specific fixes
            String manufacturer = Build.MANUFACTURER.toLowerCase();
            String model = Build.MODEL.toLowerCase();
            
            Log.d(TAG, "Device: " + manufacturer + " " + model);
            
            // Common WebView settings for all brands
            WebSettings webSettings = myWebView.getSettings();
            
            // Essential settings for all devices
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            // Note: setDatabaseEnabled is deprecated, WebView handles databases automatically
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
            webSettings.setLoadsImagesAutomatically(true);
            webSettings.setBlockNetworkImage(false);
            webSettings.setBlockNetworkLoads(false);
            webSettings.setAllowFileAccess(true);
            webSettings.setAllowContentAccess(true);
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
            webSettings.setSupportZoom(true);
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(false);
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
            
            // Brand-specific configurations
            if (manufacturer.contains("vivo") || manufacturer.contains("iqoo")) {
                // Vivo/iQOO specific fixes
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
                webSettings.setSupportMultipleWindows(false);
                
                // Fix for Vivo's aggressive battery optimization
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
                }
                
                Log.d(TAG, "Applied Vivo/iQOO specific WebView settings");
                
            } else if (manufacturer.contains("xiaomi") || manufacturer.contains("redmi")) {
                // Xiaomi/Redmi specific fixes
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
                
                Log.d(TAG, "Applied Xiaomi/Redmi specific WebView settings");
                
            } else if (manufacturer.contains("oppo") || manufacturer.contains("oneplus")) {
                // Oppo/OnePlus specific fixes
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
                webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
                
                Log.d(TAG, "Applied Oppo/OnePlus specific WebView settings");
                
            } else if (manufacturer.contains("samsung")) {
                // Samsung specific fixes
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
                webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
                
                Log.d(TAG, "Applied Samsung specific WebView settings");
            }
            
            // Universal compatibility settings
            webSettings.setUserAgentString(webSettings.getUserAgentString() + " " + manufacturer + "/" + model);
            
            // Enable hardware acceleration for better performance
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                myWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            }
            
            // Fix for devices with custom WebView implementations
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error configuring WebView for brand compatibility: " + e.getMessage());
            // Fallback to basic settings if configuration fails
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    /**
     * Setup Android 15 specific WebView behaviors and optimizations
     */
    private void setupAndroid15WebViewBehavior() {
        if (Build.VERSION.SDK_INT >= 35) {
            // Handle keyboard resize behavior for Android 15
            getWindow().setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            
            // Enable hardware acceleration for better performance
            if (myWebView != null) {
                myWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            }
            
            Log.d(TAG, "Android 15 WebView optimizations applied");
        }
    }

    @Override
    public void onBackPressed() {
        if (notificationOpened && myWebView != null) {
            myWebView.loadUrl(BASE_URL);
            notificationOpened = false;
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onPaymentSuccess(String s, PaymentData paymentData) {

        Log.d(TAG, "onPaymentSuccess:  " + s + " Payment Data :" + paymentData);
        // make api call...
        if (ID != null) {
            apiService.sendRazorPayProcess(ID, paymentData.getOrderId(), paymentData.getPaymentId(), paymentData.getSignature())
                    .enqueue(new Callback<Object>() {
                        @Override
                        public void onResponse(Call<Object> call, Response<Object> response) {
                            if (response.isSuccessful()) {
                                String json = new Gson().toJson(response.body());

                                try {
                                    JSONObject jsonObject = new JSONObject(json.trim());
                                    if (jsonObject.getBoolean("success")) {
                                        if (UNIQUE_ORDER_ID != null)
                                            myWebView.loadUrl(BASE_URL.concat("running-order/").concat(UNIQUE_ORDER_ID));
                                        else
                                            myWebView.loadUrl(BASE_URL +"my-orders");

                                    }else{
                                        myWebView.loadUrl(BASE_URL +"my-orders");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<Object> call, Throwable t) {

                        }
                    });
        }

    }

    @Override
    public void onPaymentError(int i, String s, PaymentData paymentData) {
        Log.d(TAG, "onPaymentError:  " + s + " Payment Data :" + paymentData);
        myWebView.loadUrl(BASE_URL + "my-orders");
    }

    public void startPayU(String txnId, String amount, String name, String email, String phone) {
        Intent intent = new Intent(this, PayUActivity.class);
        intent.putExtra("txnId", txnId);
        intent.putExtra("amount", amount);
        intent.putExtra("name", name);
        intent.putExtra("email", email);
        intent.putExtra("phone", phone);
        startActivityForResult(intent, 69);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
    
    @Override
    protected void onDestroy() {
        // Clean up handlers to prevent memory leaks
        if (splashTimeoutHandler != null) {
            splashTimeoutHandler.removeCallbacksAndMessages(null);
        }
        if (progressTimeoutHandler != null) {
            progressTimeoutHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}

