package com.example.bdkipoc;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.net.URI;

public class ReceiptActivity extends AppCompatActivity {

    // Views
    private LinearLayout backNavigation;
    private ImageView backArrow;
    private TextView toolbarTitle;
    
    // Receipt details
    private TextView merchantName;
    private TextView merchantLocation;
    private TextView midText;
    private TextView tidText;
    private TextView transactionNumber;
    private TextView transactionDate;
    private TextView paymentMethod;
    private TextView cardType;
    private TextView transactionTotal;
    private TextView taxPercentage;
    private TextView serviceFee;
    private TextView finalTotal;
    
    // Action buttons
    private LinearLayout printButton;
    private LinearLayout emailButton;
    private Button finishButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set status bar color
        setStatusBarColor();
        
        setContentView(R.layout.activity_receipt);
        
        initializeViews();
        setupClickListeners();
        loadTransactionData();
    }

    private void setStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#E31937")); // Red color
            
            // Make status bar icons white (for dark red background)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                View decorView = window.getDecorView();
                decorView.setSystemUiVisibility(0); // Clear light status bar flag
            }
        }
    }

    private void initializeViews() {
        // Navigation
        backNavigation = findViewById(R.id.back_navigation);
        backArrow = findViewById(R.id.backArrow);
        toolbarTitle = findViewById(R.id.toolbarTitle);
        
        // Receipt details
        merchantName = findViewById(R.id.merchant_name);
        merchantLocation = findViewById(R.id.merchant_location);
        midText = findViewById(R.id.mid_text);
        tidText = findViewById(R.id.tid_text);
        transactionNumber = findViewById(R.id.transaction_number);
        transactionDate = findViewById(R.id.transaction_date);
        paymentMethod = findViewById(R.id.payment_method);
        cardType = findViewById(R.id.card_type);
        transactionTotal = findViewById(R.id.transaction_total);
        taxPercentage = findViewById(R.id.tax_percentage);
        serviceFee = findViewById(R.id.service_fee);
        finalTotal = findViewById(R.id.final_total);
        
        // Action buttons
        printButton = findViewById(R.id.print_button);
        emailButton = findViewById(R.id.email_button);
        finishButton = findViewById(R.id.finish_button);
    }

    private void setupClickListeners() {
        // Back navigation - Goes back to previous activity
        backNavigation.setOnClickListener(v -> handleBackNavigation());
        backArrow.setOnClickListener(v -> handleBackNavigation());
        toolbarTitle.setOnClickListener(v -> handleBackNavigation());
        
        // Action buttons
        printButton.setOnClickListener(v -> handlePrintReceipt());
        emailButton.setOnClickListener(v -> handleEmailReceipt());
        finishButton.setOnClickListener(v -> handleFinish());
    }

    private void loadTransactionData() {
        Intent intent = getIntent();
        if (intent != null) {
            Log.d("ReceiptActivity", "=== LOADING TRANSACTION DATA ===");
            
            // Get all available data from intent
            String amount = intent.getStringExtra("transaction_amount");
            String grossAmount = intent.getStringExtra("gross_amount");
            String merchantNameStr = intent.getStringExtra("merchant_name");
            String merchantLocationStr = intent.getStringExtra("merchant_location");
            String transactionId = intent.getStringExtra("transaction_id");
            String referenceId = intent.getStringExtra("reference_id");
            String orderId = intent.getStringExtra("order_id");
            String transactionDateStr = intent.getStringExtra("transaction_date");
            String createdAt = intent.getStringExtra("created_at");
            String paymentMethodStr = intent.getStringExtra("payment_method");
            String cardTypeStr = intent.getStringExtra("card_type");
            String channelCode = intent.getStringExtra("channel_code");
            String channelCategory = intent.getStringExtra("channel_category");
            String acquirer = intent.getStringExtra("acquirer");
            String mid = intent.getStringExtra("mid");
            String tid = intent.getStringExtra("tid");
            
            // Log received data for debugging
            Log.d("ReceiptActivity", "🔍 RECEIVED DATA:");
            Log.d("ReceiptActivity", "   amount: " + amount);
            Log.d("ReceiptActivity", "   referenceId: " + referenceId);
            Log.d("ReceiptActivity", "   orderId: " + orderId);
            Log.d("ReceiptActivity", "   channelCode: " + channelCode);
            Log.d("ReceiptActivity", "   acquirer (from intent): " + acquirer);
            Log.d("ReceiptActivity", "   createdAt: " + createdAt);
            
            // 1. Set merchant data with defaults
            merchantName.setText(merchantNameStr != null ? merchantNameStr : "Marcel Panjaitan");
            merchantLocation.setText(merchantLocationStr != null ? merchantLocationStr : "Jakarta, Indonesia");
            
            // 2. Set MID and TID
            midText.setText(mid != null ? mid : "71000026521");
            tidText.setText(tid != null ? tid : "73001500");
            
            // 3. Set transaction number
            String displayTransactionNumber = null;
            if (referenceId != null && !referenceId.isEmpty()) {
                displayTransactionNumber = referenceId;
            } else if (transactionId != null && !transactionId.isEmpty()) {
                displayTransactionNumber = transactionId;
            } else if (orderId != null && !orderId.isEmpty()) {
                displayTransactionNumber = orderId;
            }
            transactionNumber.setText(displayTransactionNumber != null ? displayTransactionNumber : "N/A");
            
            // 4. Set transaction date
            String displayDate = null;
            if (createdAt != null && !createdAt.isEmpty()) {
                displayDate = formatDateFromCreatedAt(createdAt);
            } else if (transactionDateStr != null && !transactionDateStr.isEmpty()) {
                displayDate = transactionDateStr;
            } else {
                displayDate = getCurrentDateTime();
            }
            transactionDate.setText(displayDate);
            
            // 5. Set payment method
            String displayPaymentMethod = getPaymentMethodFromChannelCode(channelCode, paymentMethodStr);
            paymentMethod.setText(displayPaymentMethod);
            
            // 6. ✅ IMPROVED: Enhanced card type detection for QRIS
            String displayCardType = null;
            
            if (channelCode != null && channelCode.equalsIgnoreCase("QRIS")) {
                Log.d("ReceiptActivity", "🔍 QRIS transaction detected - searching for real acquirer");
                
                // For QRIS, try to get real acquirer from webhook data
                if (referenceId != null && !referenceId.isEmpty()) {
                    String realAcquirer = fetchRealAcquirerSync(referenceId);
                    if (realAcquirer != null && !realAcquirer.isEmpty() && !realAcquirer.equalsIgnoreCase("qris")) {
                        displayCardType = getCardTypeFromAcquirer(realAcquirer, null, null);
                        Log.d("ReceiptActivity", "✅ QRIS real acquirer found: " + realAcquirer + " -> " + displayCardType);
                    } else {
                        Log.w("ReceiptActivity", "⚠️ QRIS real acquirer not found, using generic QRIS");
                        displayCardType = "QRIS";
                        
                        // Start async search for better results
                        fetchRealAcquirerFromWebhook(referenceId);
                    }
                } else {
                    displayCardType = "QRIS";
                }
            } else {
                // Non-QRIS transaction
                displayCardType = getCardTypeFromAcquirer(acquirer, channelCode, cardTypeStr);
            }
            
            cardType.setText(displayCardType);
            Log.d("ReceiptActivity", "💳 FINAL CARD TYPE: " + displayCardType);
            
            // 7. Format and set amounts
            setAmountData(amount, grossAmount);
            
            Log.d("ReceiptActivity", "=== TRANSACTION DATA LOADED ===");
        }
    }
    
    private String formatDateFromCreatedAt(String createdAt) {
        try {
            // Input format from database: "yyyy-MM-dd HH:mm:ss"
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            
            // Output format for receipt: "dd/MM/yyyy HH:mm"
            SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", new Locale("id", "ID"));
            
            Date date = inputFormat.parse(createdAt);
            String formatted = outputFormat.format(date);
            
            Log.d("ReceiptActivity", "Date formatting: '" + createdAt + "' -> '" + formatted + "'");
            return formatted;
            
        } catch (Exception e) {
            Log.e("ReceiptActivity", "Error formatting date: " + createdAt, e);
            // Fallback: try alternative formats or return as-is
            return createdAt;
        }
    }

    /**
     * Get payment method name from channel_code with comprehensive mapping
     */
    private String getPaymentMethodFromChannelCode(String channelCode, String fallbackPaymentMethod) {
        if (channelCode != null && !channelCode.isEmpty()) {
            String code = channelCode.toUpperCase();
            
            switch (code) {
                case "QRIS":
                    return "QRIS";
                case "DEBIT":
                    return "Kartu Debit";
                case "CREDIT":
                    return "Kartu Kredit";
                case "BCA":
                    return "BCA";
                case "MANDIRI":
                    return "Bank Mandiri";
                case "BNI":
                    return "Bank BNI";
                case "BRI":
                    return "Bank BRI";
                case "PERMATA":
                    return "Bank Permata";
                case "CIMB":
                    return "CIMB Niaga";
                case "DANAMON":
                    return "Bank Danamon";
                case "BSI":
                    return "Bank Syariah Indonesia";
                case "CASH":
                    return "Tunai";
                case "EDC":
                    return "EDC";
                case "ALFAMART":
                    return "Alfamart";
                case "INDOMARET":
                    return "Indomaret";
                case "AKULAKU":
                    return "Akulaku";
                default:
                    return code; // Return the code as-is if not mapped
            }
        }
        
        // Fallback to provided payment method or default
        return fallbackPaymentMethod != null ? fallbackPaymentMethod : "QRIS";
    }

    private String getCardTypeFromAcquirer(String acquirer, String channelCode, String fallbackCardType) {
        // STEP 1: If we have a valid acquirer that's not generic "qris", use it
        if (acquirer != null && !acquirer.isEmpty() && !acquirer.equalsIgnoreCase("qris")) {
            String acq = acquirer.toLowerCase().trim();
            
            Log.d("ReceiptActivity", "🔍 Mapping acquirer: '" + acquirer + "' -> '" + acq + "'");
            
            // ✅ COMPREHENSIVE acquirer mapping (case-insensitive)
            switch (acq) {
                // E-Wallet acquirers (most common for QRIS)
                case "gopay": 
                case "go-pay": 
                case "gojek": return "GoPay";
                
                case "shopeepay": 
                case "shopee_pay": 
                case "shopee": return "ShopeePay";
                
                case "ovo": return "OVO";
                
                case "dana": return "DANA";
                
                case "linkaja": 
                case "link_aja": 
                case "tcash": return "LinkAja";
                
                case "jenius": 
                case "btpn": return "Jenius";
                
                case "kaspro": 
                case "kas_pro": return "KasPro";
                
                case "sakuku": 
                case "saku_ku": return "SakuKu";
                
                case "doku": 
                case "doku_wallet": return "DOKU";
                
                case "paymi": 
                case "pay_mi": return "PayMi";
                
                case "isaku": 
                case "i_saku": return "i.Saku";
                
                // Bank acquirers
                case "bca": 
                case "bank_bca": return "BCA";
                
                case "mandiri":
                case "bank_mandiri":
                case "mandiri_bill": return "Mandiri";
                
                case "bni":
                case "bank_bni":
                case "bni_va": return "BNI";
                
                case "bri":
                case "bank_bri":
                case "bri_va": return "BRI";
                
                case "permata":
                case "bank_permata":
                case "permata_va": return "Permata";
                
                case "cimb":
                case "cimb_niaga":
                case "bank_cimb":
                case "cimb_va": return "CIMB Niaga";
                
                case "danamon":
                case "bank_danamon":
                case "danamon_va": return "Danamon";
                
                case "bsi":
                case "bank_bsi":
                case "bsi_va": 
                case "syariah_indonesia": return "BSI";
                
                case "maybank":
                case "bank_maybank": return "Maybank";
                
                case "bca_digital":
                case "blu": return "BCA Digital";
                
                case "jago":
                case "bank_jago": return "Bank Jago";
                
                case "seabank":
                case "sea_bank": return "SeaBank";
                
                // Credit card acquirers
                case "visa": return "Visa";
                case "mastercard": 
                case "master_card": return "Mastercard";
                case "jcb": return "JCB";
                case "amex":
                case "american_express": return "American Express";
                case "discover": return "Discover";
                case "unionpay":
                case "union_pay": return "UnionPay";
                
                // Over-the-counter
                case "alfamart": 
                case "alfa_mart": return "Alfamart";
                case "indomaret": 
                case "indo_maret": return "Indomaret";
                case "pos_indonesia": return "Pos Indonesia";
                
                // Buy now pay later
                case "akulaku": return "Akulaku";
                case "kredivo": return "Kredivo";
                case "indodana": 
                case "indo_dana": return "Indodana";
                case "traveloka_paylater": 
                case "traveloka": return "Traveloka PayLater";
                case "atome": return "Atome";
                
                default:
                    // Return capitalized version of acquirer if not in mapping
                    String capitalized = capitalizeFirstLetter(acquirer);
                    Log.d("ReceiptActivity", "🔤 Using capitalized acquirer: " + capitalized);
                    return capitalized;
            }
        }
        
        // STEP 2: Fallback based on channel code
        if (channelCode != null && !channelCode.isEmpty()) {
            String code = channelCode.toUpperCase();
            Log.d("ReceiptActivity", "🔍 Using channel code fallback: " + code);
            
            switch (code) {
                case "QRIS": return "QRIS"; // Generic QRIS
                case "DEBIT": return "Debit";
                case "CREDIT": return "Credit";
                case "BCA": return "BCA";
                case "MANDIRI": return "Mandiri";
                case "BNI": return "BNI";
                case "BRI": return "BRI";
                default: return code;
            }
        }
        
        // STEP 3: Final fallback
        String result = fallbackCardType != null ? fallbackCardType : "Unknown";
        Log.d("ReceiptActivity", "🔍 Using final fallback: " + result);
        return result;
    }
    
    private String fetchRealAcquirerSync(String referenceId) {
        try {
            Log.d("ReceiptActivity", "🔍 Sync search for acquirer: " + referenceId);
            
            // ✅ IMPROVED: Search with broader scope for better matches
            String queryUrl = "https://be-edc.msvc.app/api-logs?limit=100&sortOrder=DESC&sortColumn=created_at";
            
            URL url = new URL(queryUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("User-Agent", "BDKIPOCApp/1.0");
            conn.setConnectTimeout(8000); // Slightly longer timeout for better results
            conn.setReadTimeout(8000);
            
            if (conn.getResponseCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                
                org.json.JSONObject json = new org.json.JSONObject(response.toString());
                org.json.JSONArray results = json.optJSONArray("results");
                
                if (results != null && results.length() > 0) {
                    Log.d("ReceiptActivity", "📊 Sync analyzing " + results.length() + " webhook logs");
                    
                    // ✅ PRIORITY SEARCH: Look for settlement first, then pending, then any
                    String[] searchPriority = {"settlement", "capture", "success", "pending", ""};
                    
                    for (String status : searchPriority) {
                        String[] targetStatuses = status.isEmpty() ? new String[]{} : new String[]{status};
                        String foundAcquirer = searchLogsByStatus(results, referenceId, targetStatuses);
                        
                        if (foundAcquirer != null && !foundAcquirer.isEmpty() && !foundAcquirer.equalsIgnoreCase("qris")) {
                            Log.d("ReceiptActivity", "🎯 Sync found acquirer: " + foundAcquirer + 
                                " (priority: " + (status.isEmpty() ? "any" : status) + ")");
                            return foundAcquirer;
                        }
                    }
                    
                    Log.w("ReceiptActivity", "⚠️ Sync search completed but no valid acquirer found");
                }
                
            } else {
                Log.w("ReceiptActivity", "⚠️ Sync API call failed with code: " + conn.getResponseCode());
            }
            
        } catch (Exception e) {
            Log.e("ReceiptActivity", "❌ Sync acquirer fetch error: " + e.getMessage());
        }
        
        return null; // No acquirer found
    }

    private void fetchRealAcquirerFromWebhook(String referenceId) {
        new Thread(() -> {
            try {
                Log.d("ReceiptActivity", "🔍 Async search for real acquirer: " + referenceId);
                
                String queryUrl = "https://be-edc.msvc.app/api-logs?limit=200&sortOrder=DESC&sortColumn=created_at";
                
                URL url = new URL(queryUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("User-Agent", "BDKIPOCApp/1.0");
                conn.setConnectTimeout(15000);
                conn.setReadTimeout(15000);
                
                if (conn.getResponseCode() == 200) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                    
                    org.json.JSONObject json = new org.json.JSONObject(response.toString());
                    org.json.JSONArray results = json.optJSONArray("results");
                    
                    if (results != null && results.length() > 0) {
                        Log.d("ReceiptActivity", "📊 Async analyzing " + results.length() + " webhook logs");
                        
                        String realAcquirer = searchForRealAcquirer(results, referenceId);
                        
                        if (realAcquirer != null && !realAcquirer.isEmpty() && !realAcquirer.equalsIgnoreCase("qris")) {
                            Log.d("ReceiptActivity", "✅ Async found real acquirer: " + realAcquirer);
                            
                            // Update UI on main thread
                            final String displayAcquirer = getCardTypeFromAcquirer(realAcquirer, null, null);
                            runOnUiThread(() -> {
                                if (cardType != null) {
                                    cardType.setText(displayAcquirer);
                                    Log.d("ReceiptActivity", "🎨 UI UPDATED: QRIS -> " + displayAcquirer);
                                    
                                    // Show a subtle indication that the data was updated
                                    showToast("Card type updated: " + displayAcquirer);
                                }
                            });
                        } else {
                            Log.w("ReceiptActivity", "⚠️ Async search found no valid acquirer for: " + referenceId);
                        }
                    } else {
                        Log.w("ReceiptActivity", "⚠️ Async search returned no results");
                    }
                } else {
                    Log.w("ReceiptActivity", "⚠️ Async API call failed with code: " + conn.getResponseCode());
                }
                
            } catch (Exception e) {
                Log.e("ReceiptActivity", "❌ Async acquirer fetch error: " + e.getMessage(), e);
            }
        }).start();
    }
    
    private String searchForRealAcquirer(org.json.JSONArray results, String referenceId) {
        try {
            Log.d("ReceiptActivity", "🔍 Analyzing " + results.length() + " webhook logs for acquirer");
            Log.d("ReceiptActivity", "🎯 Target reference ID: " + referenceId);
            
            // Get order_id from intent for additional matching
            String orderId = getIntent().getStringExtra("order_id");
            Log.d("ReceiptActivity", "🎯 Target order ID: " + orderId);
            
            // Strategy 1: Look for settlement/success transactions first (highest priority)
            Log.d("ReceiptActivity", "🔍 Strategy 1: Searching for settlement/success status");
            String acquirerFromSettlement = searchLogsByStatus(results, referenceId, new String[]{"settlement", "capture", "success"});
            if (acquirerFromSettlement != null) {
                Log.d("ReceiptActivity", "🎯 SUCCESS: Found acquirer from settlement: " + acquirerFromSettlement);
                return acquirerFromSettlement;
            }
            
            // Strategy 2: Look for pending transactions
            Log.d("ReceiptActivity", "🔍 Strategy 2: Searching for pending status");
            String acquirerFromPending = searchLogsByStatus(results, referenceId, new String[]{"pending"});
            if (acquirerFromPending != null) {
                Log.d("ReceiptActivity", "🎯 SUCCESS: Found acquirer from pending: " + acquirerFromPending);
                return acquirerFromPending;
            }
            
            // Strategy 3: Look for any transaction with this reference (broadest search)
            Log.d("ReceiptActivity", "🔍 Strategy 3: Searching for any status");
            String acquirerFromAny = searchLogsByStatus(results, referenceId, new String[]{});
            if (acquirerFromAny != null) {
                Log.d("ReceiptActivity", "🎯 SUCCESS: Found acquirer from any status: " + acquirerFromAny);
                return acquirerFromAny;
            }
            
            Log.w("ReceiptActivity", "❌ FAILED: No acquirer found in webhook logs for reference: " + referenceId);
            
            // Strategy 4: Debug logging - show what we actually found
            Log.d("ReceiptActivity", "🔍 DEBUG: Showing first 5 log entries for analysis:");
            for (int i = 0; i < Math.min(5, results.length()); i++) {
                try {
                    org.json.JSONObject log = results.getJSONObject(i);
                    org.json.JSONObject reqBody = log.optJSONObject("request_body");
                    if (reqBody != null) {
                        String logOrderId = reqBody.optString("order_id", "");
                        String logRefId = reqBody.optString("reference_id", "");
                        String logStatus = reqBody.optString("transaction_status", "");
                        String logAcquirer = reqBody.optString("acquirer", "");
                        String logIssuer = reqBody.optString("issuer", "");
                        
                        Log.d("ReceiptActivity", "   Log " + (i+1) + ": " +
                            "order_id=" + logOrderId + 
                            ", ref_id=" + logRefId +
                            ", status=" + logStatus +
                            ", acquirer=" + logAcquirer +
                            ", issuer=" + logIssuer);
                    }
                } catch (Exception e) {
                    Log.w("ReceiptActivity", "Error parsing debug log " + i + ": " + e.getMessage());
                }
            }
            
            return null;
            
        } catch (Exception e) {
            Log.e("ReceiptActivity", "❌ Error analyzing webhook logs: " + e.getMessage(), e);
            return null;
        }
    }

    private String searchLogsByStatus(org.json.JSONArray results, String referenceId, String[] targetStatuses) {
        try {
            for (int i = 0; i < results.length(); i++) {
                org.json.JSONObject log = results.getJSONObject(i);
                org.json.JSONObject reqBody = log.optJSONObject("request_body");
                
                if (reqBody != null) {
                    String logReferenceId = reqBody.optString("reference_id", "");
                    String logTransactionStatus = reqBody.optString("transaction_status", "");
                    String logAcquirer = reqBody.optString("acquirer", "");
                    String logIssuer = reqBody.optString("issuer", "");
                    String logOrderId = reqBody.optString("order_id", "");
                    
                    Log.d("ReceiptActivity", "🔍 Checking log: order_id=" + logOrderId + 
                        ", status=" + logTransactionStatus + 
                        ", acquirer=" + logAcquirer + 
                        ", issuer=" + logIssuer);
                    
                    // Check for direct reference match
                    boolean isDirectMatch = referenceId.equals(logReferenceId);
                    
                    // ✅ IMPROVED: Also check order_id match from QrisResultActivity
                    boolean isOrderMatch = false;
                    String orderId = getIntent().getStringExtra("order_id");
                    if (orderId != null && !orderId.isEmpty() && orderId.equals(logOrderId)) {
                        isOrderMatch = true;
                        Log.d("ReceiptActivity", "✅ Found order_id match: " + orderId);
                    }
                    
                    // Check custom_field1 for refresh tracking
                    boolean isRefreshMatch = false;
                    String customField1 = reqBody.optString("custom_field1", "");
                    if (!customField1.isEmpty()) {
                        try {
                            org.json.JSONObject customData = new org.json.JSONObject(customField1);
                            String originalReference = customData.optString("original_reference", "");
                            String appReferenceId = customData.optString("app_reference_id", "");
                            if (referenceId.equals(originalReference) || referenceId.equals(appReferenceId)) {
                                isRefreshMatch = true;
                            }
                        } catch (org.json.JSONException e) {
                            // Ignore parsing errors
                        }
                    }
                    
                    // Check if this log matches our reference
                    if (isDirectMatch || isRefreshMatch || isOrderMatch) {
                        Log.d("ReceiptActivity", "🎯 TRANSACTION MATCH FOUND!");
                        Log.d("ReceiptActivity", "   Match type: " + 
                            (isDirectMatch ? "DIRECT " : "") + 
                            (isRefreshMatch ? "REFRESH " : "") + 
                            (isOrderMatch ? "ORDER" : ""));
                        
                        // If target statuses specified, check status
                        if (targetStatuses.length > 0) {
                            boolean statusMatches = false;
                            for (String targetStatus : targetStatuses) {
                                if (logTransactionStatus.equalsIgnoreCase(targetStatus)) {
                                    statusMatches = true;
                                    break;
                                }
                            }
                            if (!statusMatches) {
                                Log.d("ReceiptActivity", "   Status doesn't match target: " + logTransactionStatus);
                                continue; // Skip if status doesn't match
                            }
                        }
                        
                        // ✅ CRITICAL FIX: For QRIS transactions, prioritize issuer over acquirer
                        String foundAcquirer = null;
                        
                        // Check if this is a QRIS transaction by payment_type
                        String paymentType = reqBody.optString("payment_type", "");
                        boolean isQrisTransaction = "qris".equalsIgnoreCase(paymentType);
                        
                        if (isQrisTransaction) {
                            // For QRIS: issuer contains the actual payment provider (LinkAja, DANA, etc.)
                            // acquirer is usually just "gopay" (the QRIS aggregator)
                            if (!logIssuer.isEmpty() && !logIssuer.equalsIgnoreCase("qris")) {
                                foundAcquirer = logIssuer;
                                Log.d("ReceiptActivity", "📱 QRIS: Using issuer as acquirer: " + foundAcquirer);
                            } else if (!logAcquirer.isEmpty() && !logAcquirer.equalsIgnoreCase("qris")) {
                                foundAcquirer = logAcquirer;
                                Log.d("ReceiptActivity", "📱 QRIS: Fallback to acquirer: " + foundAcquirer);
                            }
                        } else {
                            // For non-QRIS: prefer acquirer over issuer (traditional behavior)
                            if (!logAcquirer.isEmpty() && !logAcquirer.equalsIgnoreCase("qris")) {
                                foundAcquirer = logAcquirer;
                                Log.d("ReceiptActivity", "💳 Non-QRIS: Using acquirer: " + foundAcquirer);
                            } else if (!logIssuer.isEmpty() && !logIssuer.equalsIgnoreCase("qris")) {
                                foundAcquirer = logIssuer;
                                Log.d("ReceiptActivity", "💳 Non-QRIS: Fallback to issuer: " + foundAcquirer);
                            }
                        }
                        
                        if (foundAcquirer != null && !foundAcquirer.isEmpty()) {
                            Log.d("ReceiptActivity", "✅ FINAL ACQUIRER FOUND: " + foundAcquirer + 
                                " (status: " + logTransactionStatus + 
                                ", payment_type: " + paymentType + ")");
                            return foundAcquirer;
                        } else {
                            Log.w("ReceiptActivity", "⚠️ Transaction matched but no valid acquirer found");
                        }
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e("ReceiptActivity", "❌ Error searching logs by status: " + e.getMessage(), e);
        }
        
        return null; // No acquirer found for specified criteria
    }

    private String capitalizeFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        
        // Handle special cases
        String cleaned = input.trim();
        
        // Special handling for common patterns
        if (cleaned.toLowerCase().contains("pay")) {
            // Keep "Pay" capitalized in payment methods
            return cleaned.substring(0, 1).toUpperCase() + cleaned.substring(1).toLowerCase()
                .replace("pay", "Pay");
        }
        
        return cleaned.substring(0, 1).toUpperCase() + cleaned.substring(1).toLowerCase();
    }

    private void setAmountData(String amount, String grossAmount) {
        // Prioritize 'amount' over 'grossAmount' for transaction data
        String amountToUse = amount != null ? amount : grossAmount;
        
        Log.d("ReceiptActivity", "Setting amount data - amount: " + amount + 
            ", grossAmount: " + grossAmount + ", using: " + amountToUse);
        
        if (amountToUse != null) {
            try {
                // Clean and parse the amount
                String cleanAmount = cleanAmountString(amountToUse);
                Log.d("ReceiptActivity", "Cleaned amount: " + cleanAmount);
                
                // Parse as long integer (Indonesian Rupiah doesn't use decimal cents)
                long amountLong = Long.parseLong(cleanAmount);
                
                // Set transaction total
                transactionTotal.setText("Rp " + formatCurrency(amountLong));
                
                // Calculate tax and service fee (for QRIS, typically no additional fees)
                long tax = 0; // QRIS usually doesn't have tax
                long serviceFeeValue = 0; // QRIS usually doesn't have service fee
                long total = amountLong + tax + serviceFeeValue;
                
                // Set calculated values
                taxPercentage.setText("Rp 0");
                serviceFee.setText("Rp 0");
                finalTotal.setText("Rp " + formatCurrency(total));
                
                Log.d("ReceiptActivity", "Amount formatting successful: " + amountLong + " -> Rp " + formatCurrency(total));
                
            } catch (NumberFormatException e) {
                Log.e("ReceiptActivity", "Error parsing amount: " + amountToUse, e);
                // Fallback if parsing fails
                transactionTotal.setText("Rp " + amountToUse);
                taxPercentage.setText("Rp 0");
                serviceFee.setText("Rp 0");
                finalTotal.setText("Rp " + amountToUse);
            }
        } else {
            // Default values if no amount provided
            transactionTotal.setText("Rp 0");
            taxPercentage.setText("Rp 0");
            serviceFee.setText("Rp 0");
            finalTotal.setText("Rp 0");
        }
    }

    /**
     * Clean amount string to extract raw number correctly
     * Input examples: "1000", "1000.00", "Rp 1.000", "1.000"
     * Output: "1000"
     */
    private String cleanAmountString(String amount) {
        if (amount == null || amount.isEmpty()) {
            return "0";
        }
        
        // Remove currency symbols and spaces first
        String cleaned = amount
                .replace("Rp. ", "")
                .replace("Rp ", "")
                .replace("IDR ", "")
                .replace(" ", "")
                .trim();
        
        Log.d("ReceiptActivity", "After currency removal: '" + cleaned + "'");
        
        // Handle decimal cases properly
        if (cleaned.contains(".")) {
            // Check if it contains decimal cents (like "1000.00") or thousand separator (like "1.000")
            String[] parts = cleaned.split("\\.");
            
            if (parts.length == 2) {
                String beforeDot = parts[0];
                String afterDot = parts[1];
                
                // If after dot is "00" or "0", it's decimal cents - remove it
                if (afterDot.equals("00") || afterDot.equals("0")) {
                    cleaned = beforeDot;
                    Log.d("ReceiptActivity", "Removed decimal cents: '" + cleaned + "'");
                }
                // If after dot has 3 digits, it's thousand separator - combine them
                else if (afterDot.length() == 3) {
                    cleaned = beforeDot + afterDot;
                    Log.d("ReceiptActivity", "Combined thousand separator: '" + cleaned + "'");
                }
                // For other cases, try to determine based on length
                else {
                    // If beforeDot is short (1-3 digits) and afterDot is 3 digits, it's thousand separator
                    if (beforeDot.length() <= 3 && afterDot.length() == 3) {
                        cleaned = beforeDot + afterDot;
                    } else {
                        // Otherwise, it's likely decimal - remove the decimal part
                        cleaned = beforeDot;
                    }
                    Log.d("ReceiptActivity", "Processed mixed format: '" + cleaned + "'");
                }
            } else {
                // Multiple dots - remove all dots (treat as thousand separators)
                cleaned = cleaned.replace(".", "");
                Log.d("ReceiptActivity", "Removed multiple dots: '" + cleaned + "'");
            }
        }
        
        // Remove any remaining commas (some locales use comma as thousand separator)
        cleaned = cleaned.replace(",", "");
        
        Log.d("ReceiptActivity", "Final cleaned amount: '" + amount + "' -> '" + cleaned + "'");
        return cleaned;
    }

    private String formatCurrency(long amount) {
        // Use Indonesian locale formatting with dots as thousand separators
        return String.format("%,d", amount).replace(',', '.');
    }

    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", new Locale("id", "ID"));
        return sdf.format(new Date());
    }

    private void handlePrintReceipt() {
        // Handle print receipt action
        // In real app, this would integrate with printer
        showToast("Mencetak struk...");
    }

    private void handleEmailReceipt() {
        // Handle email receipt action
        // In real app, this would open email intent
        showToast("Mengirim email...");
    }

    private void handleFinish() {
        // Navigate to MainActivity/Home Page when "Selesai" button is pressed
        navigateToHomePage();
    }

    private void handleBackNavigation() {
        // Smart back navigation - go to the actual previous activity
        // Check if we have a calling activity in the intent
        String callingActivity = getIntent().getStringExtra("calling_activity");
        
        if (callingActivity != null) {
            switch (callingActivity) {
                case "TransactionActivity":
                    // Go back to transaction list
                    Intent transactionIntent = new Intent(this, TransactionActivity.class);
                    transactionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(transactionIntent);
                    break;
                    
                case "QrisResultActivity":
                    // Go back to main menu since QrisResultActivity is typically finished
                    navigateToHomePage();
                    break;
                    
                case "PaymentActivity":
                case "QrisActivity":
                    // Go back to payment/qris activity
                    Intent paymentIntent = new Intent(this, QrisActivity.class);
                    paymentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(paymentIntent);
                    break;
                    
                default:
                    // Default: use system back navigation
                    super.onBackPressed();
                    break;
            }
        } else {
            // No calling activity specified, use system back navigation
            super.onBackPressed();
        }
        
        finish();
    }

    private void navigateToHomePage() {
        // Navigate to MainActivity/Home Page
        Intent intent = new Intent(this, MainActivity.class);
        
        // Clear all previous activities from the stack and start fresh
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        
        // Optional: Add success message to show in MainActivity
        intent.putExtra("transaction_completed", true);
        intent.putExtra("transaction_amount", getIntent().getStringExtra("transaction_amount"));
        
        startActivity(intent);
        finish();
        
        // Show success message
        showToast("Transaksi berhasil diselesaikan!");
    }

    private void showToast(String message) {
        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {
        // Use the smart back navigation
        handleBackNavigation();
        super.onBackPressed();
    }
}