package com.hs.sosnow;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import com.google.android.material.card.MaterialCardView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;

public class DashboardActivity extends AppCompatActivity {

    private SharedPreferences prefs;
    private LinearLayout containerCircle, containerEvidenceList, layoutAuthChecking;
    private ScrollView scrollDashboardContent;
    private MaterialCardView cardActiveRecordingBanner;
    private View viewStatusDotIndicator;
    private TextView tvProfileName, tvProfileMobile, tvProfileEmail;
    private TextView tvRecordingStatusLabel, tvRecordingSubLabel;
    private TextView tabCategoryVideo, tabCategoryImage, tabCategoryAudio;

    private String selectedCategory = "IMAGE";
    private JSONArray fullEvidenceArray = new JSONArray();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        prefs = getSharedPreferences("SosNowPrefs", Context.MODE_PRIVATE);

        Toolbar toolbar = findViewById(R.id.toolbarDash);
        setSupportActionBar(toolbar);
        if (toolbar != null) toolbar.setNavigationOnClickListener(v -> finish());

        containerCircle = findViewById(R.id.containerCircle);
        containerEvidenceList = findViewById(R.id.containerEvidenceList);
        cardActiveRecordingBanner = findViewById(R.id.cardActiveRecordingBanner);
        viewStatusDotIndicator = findViewById(R.id.viewStatusDotIndicator);
        tvProfileName = findViewById(R.id.tvProfileName);
        tvProfileMobile = findViewById(R.id.tvProfileMobile);
        tvProfileEmail = findViewById(R.id.tvProfileEmail);
        tvRecordingStatusLabel = findViewById(R.id.tvRecordingStatusLabel);
        tvRecordingSubLabel = findViewById(R.id.tvRecordingSubLabel);
        layoutAuthChecking = findViewById(R.id.layoutAuthChecking);
        scrollDashboardContent = findViewById(R.id.scrollDashboardContent);

        tabCategoryVideo = findViewById(R.id.tabCategoryVideo);
        tabCategoryImage = findViewById(R.id.tabCategoryImage);
        tabCategoryAudio = findViewById(R.id.tabCategoryAudio);

        findViewById(R.id.btnAddGuardian).setOnClickListener(v -> showAddGuardianDialog());
        findViewById(R.id.btnLogout).setOnClickListener(v -> logout());
        findViewById(R.id.btnViewAccessLogs).setOnClickListener(v -> showAccessLogsDialog());
        findViewById(R.id.btnRefreshVault).setOnClickListener(v -> loadEvidenceVault());
        findViewById(R.id.btnStopRecordingPinProtected).setOnClickListener(v -> showStopRecordingPinPrompt());

        setupCategoryPillListeners();
        ensureSecurityPinInitialized();
        verifyLoginSession();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateRecordingStatusVisuals();
    }

    private void updateRecordingStatusVisuals() {
        boolean active = SmartEvidenceService.isServiceRunning;
        if (active) {
            // Emerald Green Active Badge
            cardActiveRecordingBanner.setCardBackgroundColor(0xFFECFDF5);
            cardActiveRecordingBanner.setStrokeColor(0xFFA7F3D0);
            viewStatusDotIndicator.setBackgroundTintList(ColorStateList.valueOf(0xFF10B981));
            tvRecordingStatusLabel.setText("Evidence Stream: ACTIVE (Dual Cam & Audio)");
            tvRecordingStatusLabel.setTextColor(0xFF065F46);
            tvRecordingSubLabel.setText("Logging background proof • PIN required to stop");
            tvRecordingSubLabel.setTextColor(0xFF047857);
            findViewById(R.id.btnStopRecordingPinProtected).setVisibility(View.VISIBLE);
        } else {
            // Soft Crimson Stopped Badge
            cardActiveRecordingBanner.setCardBackgroundColor(0xFFFEF2F2);
            cardActiveRecordingBanner.setStrokeColor(0xFFFECACA);
            viewStatusDotIndicator.setBackgroundTintList(ColorStateList.valueOf(0xFFEF4444));
            tvRecordingStatusLabel.setText("Evidence Stream: STOPPED");
            tvRecordingStatusLabel.setTextColor(0xFF991B1B);
            tvRecordingSubLabel.setText("Background logging inactive • System armed for next SOS");
            tvRecordingSubLabel.setTextColor(0xFFB91C1C);
            findViewById(R.id.btnStopRecordingPinProtected).setVisibility(View.GONE);
        }
    }

    private void ensureSecurityPinInitialized() {
        String savedPin = prefs.getString("SECURITY_MASTER_PIN", "");
        if (savedPin.isEmpty()) {
            showSetInitialPinDialog();
        }
    }

    private void showSetInitialPinDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Set Master Security PIN");
        builder.setMessage("Create a 4-digit PIN to stop evidence recording securely.");
        builder.setCancelable(false);

        final EditText etPin = new EditText(this);
        etPin.setInputType(android.text.InputType.TYPE_CLASS_NUMBER | android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        etPin.setHint("Enter 4-Digit PIN");
        etPin.setPadding(40, 30, 40, 30);
        builder.setView(etPin);

        builder.setPositiveButton("Save PIN", (dialog, which) -> {
            String p = etPin.getText().toString().trim();
            if (p.length() >= 4) {
                prefs.edit().putString("SECURITY_MASTER_PIN", p).apply();
                Toast.makeText(this, "Master PIN saved successfully!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "PIN must be at least 4 digits!", Toast.LENGTH_SHORT).show();
                showSetInitialPinDialog();
            }
        });
        builder.show();
    }

    private void showStopRecordingPinPrompt() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Verify PIN to Stop");
        builder.setMessage("Enter Master PIN to safely stop background recording.");

        final EditText etPin = new EditText(this);
        etPin.setInputType(android.text.InputType.TYPE_CLASS_NUMBER | android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        etPin.setHint("Enter PIN");
        etPin.setPadding(40, 30, 40, 30);
        builder.setView(etPin);

        builder.setPositiveButton("Verify & Stop", (dialog, which) -> {
            String entered = etPin.getText().toString().trim();
            String correct = prefs.getString("SECURITY_MASTER_PIN", "1234");

            if (entered.equals(correct)) {
                Intent stopIntent = new Intent(this, SmartEvidenceService.class);
                stopService(stopIntent);
                SmartEvidenceService.isServiceRunning = false;
                updateRecordingStatusVisuals();
                Toast.makeText(this, "Evidence recording safely stopped.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Incorrect PIN! Stop denied.", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("Cancel", null);
        builder.show();
    }

    private void setupCategoryPillListeners() {
        tabCategoryVideo.setOnClickListener(v -> {
            selectedCategory = "VIDEO";
            updatePillStyling();
            filterAndDisplayEvidence();
        });

        tabCategoryImage.setOnClickListener(v -> {
            selectedCategory = "IMAGE";
            updatePillStyling();
            filterAndDisplayEvidence();
        });

        tabCategoryAudio.setOnClickListener(v -> {
            selectedCategory = "AUDIO";
            updatePillStyling();
            filterAndDisplayEvidence();
        });
    }

    private void updatePillStyling() {
        tabCategoryVideo.setBackgroundResource("VIDEO".equals(selectedCategory) ? R.drawable.btn_3d_primary : R.drawable.bg_dark_button);
        tabCategoryImage.setBackgroundResource("IMAGE".equals(selectedCategory) ? R.drawable.btn_3d_primary : R.drawable.bg_dark_button);
        tabCategoryAudio.setBackgroundResource("AUDIO".equals(selectedCategory) ? R.drawable.btn_3d_primary : R.drawable.bg_dark_button);
    }

    private void verifyLoginSession() {
        String token = prefs.getString("AUTH_TOKEN", "");
        long expiryTime = prefs.getLong("TOKEN_EXPIRY_MILLIS", 0);

        if (token.isEmpty() || System.currentTimeMillis() > expiryTime) {
            layoutAuthChecking.setVisibility(View.GONE);
            scrollDashboardContent.setVisibility(View.GONE);
            showLoginDialog();
        } else {
            layoutAuthChecking.setVisibility(View.GONE);
            scrollDashboardContent.setVisibility(View.VISIBLE);

            tvProfileName.setText("Name: " + prefs.getString("USER_NAME", "User"));
            tvProfileMobile.setText("Mobile: +91 " + prefs.getString("USER_MOBILE", "---"));
            tvProfileEmail.setText("Email: " + prefs.getString("USER_EMAIL", "---"));

            updatePillStyling();
            updateRecordingStatusVisuals();
            loadDashboardData();
        }
    }

    private void showLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_login, null);
        builder.setView(view);
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();

        EditText etIdentifier = view.findViewById(R.id.etIdentifier);
        EditText etPassword = view.findViewById(R.id.etPassword);

        view.findViewById(R.id.btnCloseModal).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        view.findViewById(R.id.btnLoginSubmit).setOnClickListener(v -> {
            String idn = etIdentifier.getText().toString().trim();
            String pwd = etPassword.getText().toString().trim();

            if (idn.isEmpty() || pwd.isEmpty()) {
                Toast.makeText(this, "Please enter all fields", Toast.LENGTH_SHORT).show();
                return;
            }

            performNetworkCall("action=login", "identifier=" + enc(idn) + "&password=" + enc(pwd), response -> {
                try {
                    JSONObject res = new JSONObject(response);
                    if ("success".equals(res.optString("status"))) {
                        String token = res.getString("auth_token");
                        JSONObject user = res.getJSONObject("user");
                        long threeDays = System.currentTimeMillis() + (3L * 24 * 60 * 60 * 1000);

                        prefs.edit()
                                .putString("AUTH_TOKEN", token)
                                .putLong("TOKEN_EXPIRY_MILLIS", threeDays)
                                .putString("USER_NAME", user.getString("username"))
                                .putString("USER_EMAIL", user.getString("email"))
                                .putString("USER_MOBILE", user.getString("mobile"))
                                .apply();

                        dialog.dismiss();
                        layoutAuthChecking.setVisibility(View.GONE);
                        scrollDashboardContent.setVisibility(View.VISIBLE);

                        tvProfileName.setText("Name: " + user.getString("username"));
                        tvProfileMobile.setText("Mobile: +91 " + user.getString("mobile"));
                        tvProfileEmail.setText("Email: " + user.getString("email"));

                        updateRecordingStatusVisuals();
                        loadDashboardData();
                        Toast.makeText(this, "Login Successful!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, res.getString("message"), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(this, "Connection error", Toast.LENGTH_SHORT).show();
                }
            });
        });

        view.findViewById(R.id.btnGoToRegister).setOnClickListener(v -> {
            dialog.dismiss();
            showRegisterDialog();
        });

        dialog.show();
    }

    private void showRegisterDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_register, null);
        builder.setView(view);
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();

        EditText etUsername = view.findViewById(R.id.etRegUsername);
        EditText etEmail = view.findViewById(R.id.etRegEmail);
        EditText etMobile = view.findViewById(R.id.etRegMobile);
        EditText etPassword = view.findViewById(R.id.etRegPassword);

        view.findViewById(R.id.btnCloseRegModal).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        view.findViewById(R.id.btnRegisterSubmit).setOnClickListener(v -> {
            String u = etUsername.getText().toString().trim();
            String e = etEmail.getText().toString().trim();
            String m = etMobile.getText().toString().trim();
            String p = etPassword.getText().toString().trim();

            if (!m.matches("^[6-9]\\d{9}$")) {
                Toast.makeText(this, "Enter valid 10-digit Indian mobile number", Toast.LENGTH_SHORT).show();
                return;
            }

            String params = "username=" + enc(u) + "&email=" + enc(e) + "&mobile=" + enc(m) + "&password=" + enc(p);
            performNetworkCall("action=register", params, response -> {
                try {
                    JSONObject res = new JSONObject(response);
                    if ("success".equals(res.optString("status"))) {
                        Toast.makeText(this, "OTP sent successfully!", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        showOtpDialog(e);
                    } else {
                        Toast.makeText(this, res.getString("message"), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception err) {
                    Toast.makeText(this, "Registration error", Toast.LENGTH_SHORT).show();
                }
            });
        });

        view.findViewById(R.id.btnBackToLogin).setOnClickListener(v -> {
            dialog.dismiss();
            showLoginDialog();
        });

        dialog.show();
    }

    private void showOtpDialog(String email) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_otp, null);
        builder.setView(view);
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();

        EditText etOtp = view.findViewById(R.id.etOtpCode);

        view.findViewById(R.id.btnVerifyOtp).setOnClickListener(v -> {
            String otp = etOtp.getText().toString().trim();
            if (otp.length() != 6) {
                Toast.makeText(this, "Enter complete 6-digit OTP code", Toast.LENGTH_SHORT).show();
                return;
            }

            performNetworkCall("action=verify_otp", "email=" + enc(email) + "&otp=" + enc(otp), response -> {
                try {
                    JSONObject res = new JSONObject(response);
                    if ("success".equals(res.optString("status"))) {
                        Toast.makeText(this, "Registration Successful! Please Login.", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                        showLoginDialog();
                    } else {
                        Toast.makeText(this, res.getString("message"), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(this, "Verification error", Toast.LENGTH_SHORT).show();
                }
            });
        });

        dialog.show();
    }

    private void showAccessLogsDialog() {
        String token = prefs.getString("AUTH_TOKEN", "");
        performNetworkCall("action=get_access_logs&auth_token=" + enc(token), "", res -> {
            try {
                JSONObject o = new JSONObject(res);
                JSONArray logs = o.getJSONArray("logs");

                StringBuilder sb = new StringBuilder();
                if (logs.length() == 0) {
                    sb.append("No one has accessed your tracking link yet.");
                } else {
                    for (int i = 0; i < logs.length(); i++) {
                        JSONObject l = logs.getJSONObject(i);
                        sb.append("• ").append(l.getString("viewer_email"))
                                .append("\n  Timestamp: ").append(l.getString("accessed_at"))
                                .append("\n  IP Address: ").append(l.getString("viewer_ip"))
                                .append("\n\n");
                    }
                }

                new AlertDialog.Builder(this)
                        .setTitle("Access History")
                        .setMessage(sb.toString().trim())
                        .setPositiveButton("Close", null)
                        .show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load logs", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadDashboardData() {
        loadEvidenceVault();
        loadSafetyCircle();
    }

    private void loadEvidenceVault() {
        String token = prefs.getString("AUTH_TOKEN", "");
        performNetworkCall("action=get_user_evidence&auth_token=" + enc(token), "", res -> {
            try {
                JSONObject o = new JSONObject(res);
                fullEvidenceArray = o.optJSONArray("evidence");
                if (fullEvidenceArray == null) fullEvidenceArray = new JSONArray();
                filterAndDisplayEvidence();
            } catch (Exception ignored) {}
        });
    }

    private void filterAndDisplayEvidence() {
        containerEvidenceList.removeAllViews();
        int matchedCount = 0;

        try {
            for (int i = 0; i < fullEvidenceArray.length(); i++) {
                JSONObject ev = fullEvidenceArray.getJSONObject(i);
                String type = ev.optString("evidence_type", "").toUpperCase();
                String url = ev.optString("file_url", "");
                String time = ev.optString("created_at", "");
                String serverHash = ev.optString("sha256_hash", "");

                if (!type.contains(selectedCategory)) {
                    continue;
                }

                matchedCount++;
                renderEvidenceCard(type, url, time, serverHash);
            }
        } catch (Exception ignored) {}

        if (matchedCount == 0) {
            TextView tv = new TextView(this);
            tv.setText("No evidence records found in " + selectedCategory + ".");
            tv.setTextColor(0xFF64748B);
            tv.setTextSize(13);
            containerEvidenceList.addView(tv);
        }
    }

    private void renderEvidenceCard(String type, String serverUrl, String timestamp, String serverHash) {
        View card = LayoutInflater.from(this).inflate(R.layout.item_vault_evidence, containerEvidenceList, false);

        TextView tvType = card.findViewById(R.id.tvEvidenceType);
        TextView tvSource = card.findViewById(R.id.tvStorageSourceBadge);
        TextView tvTime = card.findViewById(R.id.tvEvidenceTimestamp);
        TextView tvHash = card.findViewById(R.id.tvEvidenceHash);
        TextView btnOpen = card.findViewById(R.id.btnOpenFile);

        String fileName = serverUrl.substring(serverUrl.lastIndexOf("/") + 1);
        File localFile = new File(getExternalFilesDir(null), fileName);

        boolean isLocal = localFile.exists();

        if (isLocal) {
            tvSource.setText("LOCAL STORAGE (OFFLINE VERIFIED)");
            tvSource.setTextColor(0xFF166534);
            tvSource.setBackgroundTintList(ColorStateList.valueOf(0xFFDCFCE7));

            String localComputed = calculateFileSHA256(localFile);
            if (serverHash.equalsIgnoreCase(localComputed)) {
                tvHash.setText("SHA-256 Match: " + serverHash.substring(0, 16) + "... (100% Authentic)");
            } else {
                tvHash.setText("Warning: Local file modified! Cloud Backup Available.");
                tvHash.setTextColor(0xFFDC2626);
            }
        } else {
            tvSource.setText("CLOUD VAULT BACKUP");
            tvSource.setTextColor(0xFF0369A1);
            tvSource.setBackgroundTintList(ColorStateList.valueOf(0xFFE0F2FE));
            tvHash.setText("SHA-256 (Server): " + serverHash.substring(0, 16) + "...");
        }

        tvType.setText(type);
        tvTime.setText(timestamp);

        btnOpen.setOnClickListener(v -> {
            // Check for Dual Front + Back pair
            String companionFileName = fileName.contains("BACK_")
                    ? fileName.replace("BACK_", "FRONT_")
                    : fileName.replace("FRONT_", "BACK_");
            File companionFile = new File(getExternalFilesDir(null), companionFileName);

            if (companionFile.exists()) {
                // Open Split-Screen Dual Synced Player
                Intent dual = new Intent(this, DualPlayerActivity.class);
                dual.putExtra("FRONT_URI", fileName.contains("FRONT_") ? localFile.getAbsolutePath() : companionFile.getAbsolutePath());
                dual.putExtra("BACK_URI", fileName.contains("BACK_") ? localFile.getAbsolutePath() : companionFile.getAbsolutePath());
                dual.putExtra("IS_VIDEO", type.contains("VIDEO"));
                startActivity(dual);
            } else if (isLocal) {
                openSingleLocalMedia(localFile, type);
            } else {
                Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(serverUrl));
                startActivity(browser);
            }
        });

        containerEvidenceList.addView(card);
    }

    private void openSingleLocalMedia(File file, String type) {
        try {
            Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            if (type.contains("IMAGE")) {
                intent.setDataAndType(uri, "image/*");
            } else if (type.contains("AUDIO")) {
                intent.setDataAndType(uri, "audio/*");
            } else {
                intent.setDataAndType(uri, "video/*");
            }
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Opening media...", Toast.LENGTH_SHORT).show();
        }
    }

    private String calculateFileSHA256(File file) {
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] buf = new byte[8192];
            int read;
            while ((read = fis.read(buf)) != -1) digest.update(buf, 0, read);
            byte[] hash = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }

    private void loadSafetyCircle() {
        String token = prefs.getString("AUTH_TOKEN", "");
        performNetworkCall("action=get_my_circle&auth_token=" + enc(token), "", response -> {
            try {
                JSONObject res = new JSONObject(response);
                containerCircle.removeAllViews();
                JSONArray circle = res.getJSONArray("circle");

                if (circle.length() == 0) {
                    TextView tv = new TextView(this);
                    tv.setText("No guardians added yet. Tap + Add Member to add your circle.");
                    tv.setTextColor(0xFF64748B);
                    tv.setTextSize(13);
                    containerCircle.addView(tv);
                    return;
                }

                for (int i = 0; i < circle.length(); i++) {
                    JSONObject c = circle.getJSONObject(i);
                    int contactId = c.getInt("id");
                    String gName = c.getString("guardian_name");
                    String gPhone = c.getString("guardian_mobile");
                    String gEmail = c.getString("guardian_email");

                    View card = LayoutInflater.from(this).inflate(R.layout.item_circle_member, containerCircle, false);
                    TextView tvName = card.findViewById(R.id.tvMemberName);
                    TextView tvDetails = card.findViewById(R.id.tvMemberDetails);
                    View btnDelete = card.findViewById(R.id.btnDeleteMember);

                    tvName.setText(gName);
                    tvDetails.setText(gPhone + " • " + gEmail);

                    btnDelete.setOnClickListener(v -> deleteGuardianMember(contactId));
                    containerCircle.addView(card);
                }
            } catch (Exception ignored) {}
        });
    }

    private void deleteGuardianMember(int contactId) {
        new AlertDialog.Builder(this)
                .setTitle("Delete Member")
                .setMessage("Are you sure you want to remove this member from your safety circle?")
                .setPositiveButton("Delete", (d, w) -> {
                    String token = prefs.getString("AUTH_TOKEN", "");
                    performNetworkCall("action=delete_circle_contact", "auth_token=" + enc(token) + "&contact_id=" + contactId, res -> {
                        loadSafetyCircle();
                        Toast.makeText(this, "Member removed", Toast.LENGTH_SHORT).show();
                    });
                })
                .setNegativeButton("Cancel", null)
                .show();
    }

    private void showAddGuardianDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_add_guardian, null);
        builder.setView(view);
        AlertDialog dialog = builder.create();

        EditText etName = view.findViewById(R.id.etGName);
        EditText etEmail = view.findViewById(R.id.etGEmail);
        EditText etMobile = view.findViewById(R.id.etGMobile);

        view.findViewById(R.id.btnSaveG).setOnClickListener(v -> {
            String n = etName.getText().toString().trim();
            String e = etEmail.getText().toString().trim();
            String m = etMobile.getText().toString().trim();

            if (!m.matches("^[6-9]\\d{9}$")) {
                Toast.makeText(this, "Enter valid 10-digit mobile number", Toast.LENGTH_SHORT).show();
                return;
            }

            String token = prefs.getString("AUTH_TOKEN", "");
            String params = "auth_token=" + enc(token) + "&name=" + enc(n) + "&email=" + enc(e) + "&mobile=" + enc(m);
            performNetworkCall("action=add_circle_contact", params, res -> {
                dialog.dismiss();
                loadSafetyCircle();
                Toast.makeText(this, "Safety Member Added!", Toast.LENGTH_SHORT).show();
            });
        });

        dialog.show();
    }

    private void logout() {
        prefs.edit().remove("AUTH_TOKEN").remove("TOKEN_EXPIRY_MILLIS").apply();
        Toast.makeText(this, "Logged out", Toast.LENGTH_SHORT).show();
        verifyLoginSession();
    }

    private String enc(String val) {
        try { return URLEncoder.encode(val, "UTF-8"); } catch (Exception e) { return ""; }
    }

    private void performNetworkCall(String actionQuery, String postData, ResponseListener listener) {
        new Thread(() -> {
            try {
                URL url = new URL(AppConfig.SERVER_BASE_URL + "?" + actionQuery);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod(postData.isEmpty() ? "GET" : "POST");
                conn.setConnectTimeout(8000);

                if (!postData.isEmpty()) {
                    conn.setDoOutput(true);
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    OutputStream os = conn.getOutputStream();
                    os.write(postData.getBytes());
                    os.flush();
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) sb.append(line);
                reader.close();

                new Handler(Looper.getMainLooper()).post(() -> listener.onResponse(sb.toString()));
            } catch (Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> listener.onResponse("{\"status\":\"error\",\"message\":\"Network error\"}"));
            }
        }).start();
    }

    interface ResponseListener {
        void onResponse(String response);
    }
}