package com.example.bdkipoc.kredit;

import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.bdkipoc.MyApplication;
import com.example.bdkipoc.R;
import com.example.bdkipoc.utils.ByteUtil;
import com.example.bdkipoc.utils.Utility;
import com.sunmi.emv.l2.utils.iso8583.TLV;
import com.sunmi.emv.l2.utils.iso8583.TLVUtils;
import com.sunmi.pay.hardware.aidlv2.AidlConstantsV2;
import com.sunmi.pay.hardware.aidlv2.emv.EMVOptV2;

import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.bdkipoc.transaction.CreateTransactionActivity;

/**
 * CreditCardActivity - Display detailed transaction results and TLV data
 */
public class CreditCardActivity extends AppCompatActivity {
    private static final String TAG = "CreditCard";
    
    // UI Components
    private TextView tvTransactionSummary;
    private TextView tvCardData;
    private Button btnCopyData;
    private Button btnNewTransaction;
    private Button btnPrintReceipt;
    
    // Transaction Data
    private String transactionAmount;
    private String cardType;
    private boolean isEMVMode;
    private String cardNo;
    private Bundle cardData;
    
    // EMV Components
    private EMVOptV2 mEMVOptV2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credit_card);
        
        getIntentData();
        initViews();
        initEMVComponents();
        loadCardData();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        transactionAmount = intent.getStringExtra("TRANSACTION_AMOUNT");
        cardType = intent.getStringExtra("CARD_TYPE");
        isEMVMode = intent.getBooleanExtra("EMV_MODE", true);
        cardNo = intent.getStringExtra("CARD_NO");
        cardData = intent.getBundleExtra("CARD_DATA");
        
        if (transactionAmount == null) {
            transactionAmount = "0";
        }
    }

    private void initViews() {
        // Setup Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Detail Transaksi");
        }
        
        tvTransactionSummary = findViewById(R.id.tv_transaction_summary);
        tvCardData = findViewById(R.id.tv_card_data);
        btnCopyData = findViewById(R.id.btn_copy_data);
        btnNewTransaction = findViewById(R.id.btn_new_transaction);
        btnPrintReceipt = findViewById(R.id.btn_print_receipt);
        
        btnCopyData.setOnClickListener(v -> copyCardDataToClipboard());
        btnNewTransaction.setOnClickListener(v -> startNewTransaction());
        btnPrintReceipt.setOnClickListener(v -> printReceipt());
    }

    private void initEMVComponents() {
        if (MyApplication.app != null) {
            mEMVOptV2 = MyApplication.app.emvOptV2;
            android.util.Log.d(TAG, "EMV components initialized for TLV data retrieval");
        }
    }

    private void loadCardData() {
        if (isEMVMode && mEMVOptV2 != null) {
            loadEMVTlvData();
        } else {
            loadSimpleCardData();
        }
    }

    private void loadEMVTlvData() {
        android.util.Log.d(TAG, "======== RETRIEVING COMPLETE EMV CARD DATA ========");
        
        try {
            String[] standardTagList = {
                    "4F", "50", "57", "5A", "5F20", "5F24", "5F25", "5F28", "5F2A", "5F2D", "5F30", "5F34",
                    "82", "84", "87", "88", "8A", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95",
                    "9A", "9B", "9C", "9D", "9F01", "9F02", "9F03", "9F04", "9F05", "9F06", "9F07", "9F08", "9F09",
                    "9F0D", "9F0E", "9F0F", "9F10", "9F11", "9F12", "9F13", "9F14", "9F15", "9F16", "9F17", "9F18",
                    "9F1A", "9F1B", "9F1C", "9F1D", "9F1E", "9F1F", "9F20", "9F21", "9F22", "9F23", "9F26", "9F27",
                    "9F2D", "9F2E", "9F2F", "9F32", "9F33", "9F34", "9F35", "9F36", "9F37", "9F38", "9F39", "9F3A",
                    "9F3B", "9F3C", "9F3D", "9F40", "9F41", "9F42", "9F43", "9F44", "9F45", "9F46", "9F47", "9F48",
                    "9F49", "9F4A", "9F4B", "9F4C", "9F4D", "9F4E", "9F53", "9F54", "9F55", "9F56", "9F57", "9F58",
                    "9F59", "9F5A", "9F5B", "9F5C", "9F5D", "9F5E", "9F61", "9F62", "9F63", "9F64", "9F65", "9F66",
                    "9F67", "9F68", "9F69", "9F6A", "9F6B", "9F6C", "9F6D", "9F6E", "9F70", "9F71", "9F72", "9F73",
                    "9F74", "9F75", "9F76", "9F77", "9F78", "9F79", "9F7A", "9F7B", "9F7C", "9F7D", "9F7E", "9F7F"
            };
            
            String[] payPassTagList = {
                    "DF810C", "DF8117", "DF8118", "DF8119", "DF811A", "DF811B", "DF811C", "DF811D", "DF811E", "DF811F",
                    "DF8120", "DF8121", "DF8122", "DF8123", "DF8124", "DF8125", "DF8126", "DF8127", "DF8128", "DF8129",
                    "DF812A", "DF812B", "DF812C", "DF812D", "DF812E", "DF812F", "DF8130", "DF8131", "DF8132", "DF8133",
                    "DF8134", "DF8135", "DF8136", "DF8137", "DF8138", "DF8139", "DF813A", "DF813B", "DF813C", "DF813D",
                    "DF8161", "DF8167", "DF8168", "DF8169", "DF8170"
            };
            
            byte[] outData = new byte[4096];
            Map<String, TLV> allTlvMap = new TreeMap<>();
            
            int tlvOpCode = AidlConstantsV2.EMV.TLVOpCode.OP_NORMAL;
            if ("NFC".equals(cardType)) {
                tlvOpCode = AidlConstantsV2.EMV.TLVOpCode.OP_PAYPASS;
            }
            
            android.util.Log.d(TAG, "Using TLV OpCode: " + tlvOpCode);
            android.util.Log.d(TAG, "Requesting " + standardTagList.length + " standard tags");
            
            int len = mEMVOptV2.getTlvList(tlvOpCode, standardTagList, outData);
            if (len > 0) {
                byte[] bytes = Arrays.copyOf(outData, len);
                String hexStr = ByteUtil.bytes2HexStr(bytes);
                android.util.Log.d(TAG, "Retrieved " + len + " bytes of standard TLV data");
                
                Map<String, TLV> tlvMap = TLVUtils.buildTLVMap(hexStr);
                allTlvMap.putAll(tlvMap);
                android.util.Log.d(TAG, "Parsed " + tlvMap.size() + " standard TLV tags");
            }

            if ("NFC".equals(cardType)) {
                android.util.Log.d(TAG, "Requesting " + payPassTagList.length + " PayPass specific tags");
                
                len = mEMVOptV2.getTlvList(AidlConstantsV2.EMV.TLVOpCode.OP_PAYPASS, payPassTagList, outData);
                if (len > 0) {
                    byte[] bytes = Arrays.copyOf(outData, len);
                    String hexStr = ByteUtil.bytes2HexStr(bytes);
                    android.util.Log.d(TAG, "Retrieved " + len + " bytes of PayPass TLV data");
                    
                    Map<String, TLV> payPassTlvMap = TLVUtils.buildTLVMap(hexStr);
                    allTlvMap.putAll(payPassTlvMap);
                    android.util.Log.d(TAG, "Parsed " + payPassTlvMap.size() + " PayPass TLV tags");
                }
            }

            displayEMVData(allTlvMap);
            
            android.util.Log.d(TAG, "Total TLV tags retrieved: " + allTlvMap.size());
            android.util.Log.d(TAG, "==================================");
            
        } catch (Exception e) {
            android.util.Log.e(TAG, "Error retrieving TLV data: " + e.getMessage());
            e.printStackTrace();
            showSimpleError("Error retrieving EMV data: " + e.getMessage());
        }
    }

    private void loadSimpleCardData() {
        StringBuilder summary = new StringBuilder();
        StringBuilder cardInfo = new StringBuilder();
        
        // Transaction Summary
        summary.append("==== TRANSACTION COMPLETED ====\n");
        summary.append("Amount: ").append(formatAmount(Long.parseLong(transactionAmount))).append("\n");
        summary.append("Payment Method: ").append(getCardTypeDisplay()).append("\n");
        summary.append("Status: SUCCESS\n");
        
        // Card Information
        if (cardData != null) {
            cardInfo.append("==== CARD INFORMATION ====\n");
            
            if ("MAGNETIC".equals(cardType)) {
                String track1 = Utility.null2String(cardData.getString("TRACK1"));
                String track2 = Utility.null2String(cardData.getString("TRACK2"));
                String track3 = Utility.null2String(cardData.getString("TRACK3"));
                
                cardInfo.append("Track1: ").append(track1.isEmpty() ? "N/A" : track1).append("\n");
                cardInfo.append("Track2: ").append(track2.isEmpty() ? "N/A" : track2).append("\n");
                cardInfo.append("Track3: ").append(track3.isEmpty() ? "N/A" : track3).append("\n");
                
            } else if ("IC".equals(cardType)) {
                String atr = cardData.getString("atr", "");
                cardInfo.append("ATR: ").append(atr.isEmpty() ? "N/A" : atr).append("\n");
                
            } else if ("NFC".equals(cardType)) {
                String uuid = cardData.getString("uuid", "");
                String ats = cardData.getString("ats", "");
                int sak = cardData.getInt("sak", -1);
                
                cardInfo.append("UUID: ").append(uuid.isEmpty() ? "N/A" : uuid).append("\n");
                if (!ats.isEmpty()) {
                    cardInfo.append("ATS: ").append(ats).append("\n");
                }
                if (sak != -1) {
                    cardInfo.append("SAK: ").append(String.format("0x%02X", sak)).append("\n");
                    cardInfo.append("Type: ").append(analyzeCardTypeBySAK(sak)).append("\n");
                }
            }
        }
        
        tvTransactionSummary.setText(summary.toString());
        tvCardData.setText(cardInfo.toString());
    }

    private void displayEMVData(Map<String, TLV> allTlvMap) {
        StringBuilder summary = new StringBuilder();
        StringBuilder cardInfo = new StringBuilder();
        
        // Transaction Summary
        summary.append("==== TRANSACTION COMPLETED ====\n");
        summary.append("Amount: ").append(formatAmount(Long.parseLong(transactionAmount))).append("\n");
        summary.append("Payment Method: EMV ").append(cardType).append("\n");
        summary.append("Status: SUCCESS\n");
        
        // Card Summary
        summary.append("\n==== CARD SUMMARY ====\n");
        
        TLV panTlv = allTlvMap.get("5A");
        if (panTlv != null && !TextUtils.isEmpty(panTlv.getValue())) {
            summary.append("Card Number: ").append(panTlv.getValue()).append("\n");
        }
        
        TLV labelTlv = allTlvMap.get("50");
        if (labelTlv != null && !TextUtils.isEmpty(labelTlv.getValue())) {
            summary.append("App Label: ").append(hexToString(labelTlv.getValue())).append("\n");
        }
        
        TLV nameTlv = allTlvMap.get("5F20");
        if (nameTlv != null && !TextUtils.isEmpty(nameTlv.getValue())) {
            summary.append("Cardholder: ").append(hexToString(nameTlv.getValue()).trim()).append("\n");
        }
        
        TLV expiryTlv = allTlvMap.get("5F24");
        if (expiryTlv != null && !TextUtils.isEmpty(expiryTlv.getValue())) {
            String expiry = expiryTlv.getValue();
            if (expiry.length() == 6) {
                summary.append("Expiry: ").append(expiry.substring(2, 4)).append("/").append(expiry.substring(0, 2)).append("\n");
            }
        }
        
        TLV aidTlv = allTlvMap.get("9F06");
        if (aidTlv != null && !TextUtils.isEmpty(aidTlv.getValue())) {
            summary.append("Scheme: ").append(identifyPaymentScheme(aidTlv.getValue())).append("\n");
        }
        
        // Detailed TLV Data
        cardInfo.append("==== DETAILED TLV DATA ====\n");
        
        Set<String> keySet = allTlvMap.keySet();
        for (String key : keySet) {
            TLV tlv = allTlvMap.get(key);
            String value = tlv != null ? tlv.getValue() : "";
            String description = getTlvDescription(key);
            
            cardInfo.append(key);
            if (!description.equals("Unknown")) {
                cardInfo.append(" (").append(description).append(")");
            }
            cardInfo.append(": ");
            
            if (key.equals("5A") && !value.isEmpty()) {
                cardInfo.append(value);
            } else if (key.equals("50") && !value.isEmpty()) {
                String decodedLabel = hexToString(value);
                cardInfo.append(value).append(" (").append(decodedLabel).append(")");
            } else if (key.equals("5F20") && !value.isEmpty()) {
                String decodedName = hexToString(value);
                cardInfo.append(value).append(" (").append(decodedName.trim()).append(")");
            } else if (key.equals("9F06") && !value.isEmpty()) {
                String scheme = identifyPaymentScheme(value);
                cardInfo.append(value).append(" (").append(scheme).append(")");
            } else if (key.equals("5F24") && !value.isEmpty()) {
                cardInfo.append(value);
                if (value.length() == 6) {
                    cardInfo.append(" (").append(value.substring(2, 4)).append("/").append(value.substring(0, 2)).append(")");
                }
            } else if (key.equals("9F02") && !value.isEmpty()) {
                cardInfo.append(value);
                try {
                    long amount = Long.parseLong(value, 16);
                    cardInfo.append(" (").append(String.format("%.2f", amount / 100.0)).append(")");
                } catch (Exception e) {
                    // Keep original value
                }
            } else {
                cardInfo.append(value);
            }
            
            cardInfo.append("\n");
        }
        
        cardInfo.append("\nTotal TLV tags retrieved: ").append(keySet.size());
        
        tvTransactionSummary.setText(summary.toString());
        tvCardData.setText(cardInfo.toString());
    }

    private void showSimpleError(String error) {
        StringBuilder summary = new StringBuilder();
        summary.append("==== TRANSACTION ERROR ====\n");
        summary.append("Amount: ").append(formatAmount(Long.parseLong(transactionAmount))).append("\n");
        summary.append("Status: FAILED\n");
        
        tvTransactionSummary.setText(summary.toString());
        tvCardData.setText(error);
    }

    private String getCardTypeDisplay() {
        switch (cardType) {
            case "MAGNETIC": return "Magnetic Card";
            case "IC": return "IC Card";
            case "NFC": return "NFC/RF Card";
            default: return cardType;
        }
    }

    private String formatAmount(long amountCents) {
        double amountRupiah = amountCents / 100.0;
        NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("id", "ID"));
        return formatter.format(amountRupiah);
    }

    private void copyCardDataToClipboard() {
        String summary = tvTransactionSummary.getText().toString();
        String cardData = tvCardData.getText().toString();
        String fullData = summary + "\n\n" + cardData;
        
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("Transaction Data", fullData);
        clipboard.setPrimaryClip(clip);
        showToast("Transaction data copied to clipboard");
    }

    private void startNewTransaction() {
        Intent intent = new Intent(this, CreateTransactionActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void printReceipt() {
        // TODO: Implement print functionality
        showToast("Print functionality to be implemented");
    }

    // ====== HELPER METHODS ======
    private String getTlvDescription(String tag) {
        switch (tag.toUpperCase()) {
            case "4F": return "Application Identifier";
            case "50": return "Application Label";
            case "57": return "Track 2 Equivalent Data";
            case "5A": return "Application PAN";
            case "5F20": return "Cardholder Name";
            case "5F24": return "Application Expiry Date";
            case "5F25": return "Application Effective Date";
            case "5F28": return "Issuer Country Code";
            case "5F2A": return "Transaction Currency Code";
            case "5F2D": return "Language Preference";
            case "5F30": return "Service Code";
            case "5F34": return "PAN Sequence Number";
            case "82": return "Application Interchange Profile";
            case "84": return "Dedicated File Name";
            case "87": return "Application Priority Indicator";
            case "88": return "Short File Identifier";
            case "8A": return "Authorization Response Code";
            case "8C": return "Card Risk Management Data Object List 1";
            case "8D": return "Card Risk Management Data Object List 2";
            case "8E": return "Cardholder Verification Method List";
            case "8F": return "Certification Authority Public Key Index";
            case "90": return "Issuer Public Key Certificate";
            case "91": return "Issuer Authentication Data";
            case "92": return "Issuer Public Key Remainder";
            case "93": return "Signed Static Application Data";
            case "94": return "Application File Locator";
            case "95": return "Terminal Verification Results";
            case "9A": return "Transaction Date";
            case "9B": return "Transaction Status Information";
            case "9C": return "Transaction Type";
            case "9D": return "Directory Definition File Name";
            case "9F01": return "Acquirer Identifier";
            case "9F02": return "Amount Authorized";
            case "9F03": return "Amount Other";
            case "9F04": return "Amount Other (Binary)";
            case "9F05": return "Application Discretionary Data";
            case "9F06": return "Application Identifier";
            case "9F07": return "Application Usage Control";
            case "9F08": return "Application Version Number";
            case "9F09": return "Application Version Number";
            case "9F0D": return "Issuer Action Code - Default";
            case "9F0E": return "Issuer Action Code - Denial";
            case "9F0F": return "Issuer Action Code - Online";
            case "9F10": return "Issuer Application Data";
            case "9F11": return "Issuer Code Table Index";
            case "9F12": return "Application Preferred Name";
            case "9F13": return "Last Online Application Transaction Counter";
            case "9F14": return "Lower Consecutive Offline Limit";
            case "9F15": return "Merchant Category Code";
            case "9F16": return "Merchant Identifier";
            case "9F17": return "PIN Try Counter";
            case "9F18": return "Issuer Script Identifier";
            case "9F1A": return "Terminal Country Code";
            case "9F1B": return "Terminal Floor Limit";
            case "9F1C": return "Terminal Identification";
            case "9F1D": return "Terminal Risk Management Data";
            case "9F1E": return "Interface Device Serial Number";
            case "9F1F": return "Track 1 Discretionary Data";
            case "9F20": return "Track 2 Discretionary Data";
            case "9F21": return "Transaction Time";
            case "9F22": return "Certification Authority Public Key Index";
            case "9F23": return "Upper Consecutive Offline Limit";
            case "9F26": return "Application Cryptogram";
            case "9F27": return "Cryptogram Information Data";
            case "9F2D": return "ICC PIN Encipherment Public Key Certificate";
            case "9F2E": return "ICC PIN Encipherment Public Key Exponent";
            case "9F2F": return "ICC PIN Encipherment Public Key Remainder";
            case "9F32": return "Issuer Public Key Exponent";
            case "9F33": return "Terminal Capabilities";
            case "9F34": return "CVM Results";
            case "9F35": return "Terminal Type";
            case "9F36": return "Application Transaction Counter";
            case "9F37": return "Unpredictable Number";
            case "9F38": return "Processing Options Data Object List";
            case "9F39": return "Point-of-Service Entry Mode";
            case "9F3A": return "Amount Reference Currency";
            case "9F3B": return "Currency Code Application";
            case "9F3C": return "Transaction Reference Currency Code";
            case "9F3D": return "Transaction Reference Currency Exponent";
            case "9F40": return "Additional Terminal Capabilities";
            case "9F41": return "Transaction Sequence Counter";
            case "9F42": return "Application Currency Code";
            case "9F43": return "Application Reference Currency Exponent";
            case "9F44": return "Application Currency Exponent";
            case "9F45": return "Data Authentication Code";
            case "9F46": return "ICC Public Key Certificate";
            case "9F47": return "ICC Public Key Exponent";
            case "9F48": return "ICC Public Key Remainder";
            case "9F49": return "Dynamic Data Authentication Data Object List";
            case "9F4A": return "Static Data Authentication Tag List";
            case "9F4B": return "Signed Dynamic Application Data";
            case "9F4C": return "ICC Dynamic Number";
            case "9F4D": return "Log Entry";
            case "9F4E": return "Merchant Name and Location";
            case "9F53": return "Transaction Category Code";
            case "9F54": return "Cumulative Total Transaction Amount Limit";
            case "9F55": return "Geographic Indicator";
            case "9F56": return "Issuer Authentication Indicator";
            case "9F57": return "Issuer Country Code";
            case "9F58": return "Lower Cumulative Offline Transaction Amount Limit";
            case "9F59": return "Upper Cumulative Offline Transaction Amount Limit";
            case "9F5A": return "Application Program Identifier";
            case "9F5B": return "Issuer Script Results";
            case "9F5C": return "Cumulative Total Transaction Amount Upper Limit";
            case "9F5D": return "Available Offline Spending Amount";
            case "9F5E": return "Consecutive Transaction Limit (International)";
            case "9F61": return "Point-of-Service Environment";
            case "9F62": return "PCVC3 Track1";
            case "9F63": return "PUNATC Track1";
            case "9F64": return "NATC Track1";
            case "9F65": return "PCVC3 Track2";
            case "9F66": return "Terminal Transaction Qualifiers";
            case "9F67": return "NATC Track2";
            case "9F68": return "Mag Stripe CVM List";
            case "9F69": return "Unpredictable Number Data Object List";
            case "9F6A": return "Unpredictable Number";
            case "9F6B": return "Track 2 Data";
            case "9F6C": return "Card Transaction Qualifiers";
            case "9F6D": return "Mag Stripe Application Version Number";
            case "9F6E": return "Unknown";
            case "9F70": return "Protected Data Envelope 1";
            case "9F71": return "Protected Data Envelope 2";
            case "9F72": return "Protected Data Envelope 3";
            case "9F73": return "Protected Data Envelope 4";
            case "9F74": return "Protected Data Envelope 5";
            case "9F75": return "Unprotected Data Envelope 1";
            case "9F76": return "Unprotected Data Envelope 2";
            case "9F77": return "Unprotected Data Envelope 3";
            case "9F78": return "Unprotected Data Envelope 4";
            case "9F79": return "Unprotected Data Envelope 5";
            case "9F7A": return "VLP Issuer Authorization Code";
            case "9F7B": return "VLP Terminal Transaction Limit";
            case "9F7C": return "Customer Exclusive Data";
            case "9F7D": return "Unknown";
            case "9F7E": return "Application Life Cycle Data";
            case "9F7F": return "Card Production Life Cycle Data";
            
            // PayPass/Contactless specific tags (DF81xx range)
            case "DF810C": return "PayPass - Mag Stripe CVM Capability No CVM Required";
            case "DF8117": return "PayPass - Terminal Capabilities";
            case "DF8118": return "PayPass - Additional Terminal Capabilities";
            case "DF8119": return "PayPass - Terminal Type";
            case "DF811A": return "PayPass - Kernel Configuration";
            case "DF811B": return "PayPass - Mag Stripe Application Version Number";
            case "DF811C": return "PayPass - Mag Stripe CVM Capability CVM Required";
            case "DF811D": return "PayPass - Mag Stripe CVM Capability No CVM Required";
            case "DF811E": return "PayPass - Message Hold Time";
            case "DF811F": return "PayPass - Security Capability";
            case "DF8120": return "PayPass - Kernel Identifier";
            case "DF8121": return "PayPass - Kernel Configuration";
            case "DF8122": return "PayPass - Maximum Torn Transaction Log Records";
            case "DF8123": return "PayPass - Torn Transaction Log Data Element";
            case "DF8124": return "PayPass - Max Lifetime of Torn Transaction Log Record";
            case "DF8125": return "PayPass - Max Number of Torn Transaction Log Records";
            case "DF8126": return "PayPass - Mag Stripe CVM Capability";
            case "DF8127": return "PayPass - CVM Capability - CVM Required";
            case "DF8128": return "PayPass - CVM Capability - No CVM Required";
            case "DF8129": return "PayPass - Card Data Input Capability";
            case "DF812A": return "PayPass - CVM Required Limit";
            case "DF812B": return "PayPass - No CVM Required Limit";
            case "DF812C": return "PayPass - Transaction Limit (No On-device CVM)";
            case "DF812D": return "PayPass - Transaction Limit (On-device CVM)";
            case "DF812E": return "PayPass - CVM Required Limit";
            case "DF812F": return "PayPass - No CVM Required Limit";
            case "DF8130": return "PayPass - Floor Limit Check";
            case "DF8131": return "PayPass - Terminal Action Code - Default";
            case "DF8132": return "PayPass - Terminal Action Code - Denial";
            case "DF8133": return "PayPass - Terminal Action Code - Online";
            case "DF8134": return "PayPass - Reader Contactless Transaction Limit (No On-device CVM)";
            case "DF8135": return "PayPass - Reader Contactless Transaction Limit (On-device CVM)";
            case "DF8136": return "PayPass - Reader CVM Required Limit";
            case "DF8137": return "PayPass - Reader Contactless Floor Limit";
            case "DF8138": return "PayPass - Max Torn Record Lifetime";
            case "DF8139": return "PayPass - Mag-stripe CVM Capability - CVM Required";
            case "DF813A": return "PayPass - Mag-stripe CVM Capability - No CVM Required";
            case "DF813B": return "PayPass - Kernel Configuration";
            case "DF813C": return "PayPass - Mag Stripe Application Version Number";
            case "DF813D": return "PayPass - Mag Stripe CVM Capability";
            case "DF8161": return "JCB - Terminal Transaction Qualifiers";
            case "DF8167": return "AMEX - Terminal Capabilities";
            case "DF8168": return "AMEX - Additional Terminal Capabilities";
            case "DF8169": return "AMEX - Terminal Type";
            case "DF8170": return "AMEX - Message Hold Time";
            
            default: return "Unknown";
        }
    }
    
    private String identifyPaymentScheme(String aid) {
        if (aid == null) return "Unknown";
        
        if (aid.startsWith("A000000333")) return "UnionPay";
        else if (aid.startsWith("A000000003")) return "Visa";
        else if (aid.startsWith("A000000004") || aid.startsWith("A000000005")) return "MasterCard";
        else if (aid.startsWith("A000000025")) return "American Express";
        else if (aid.startsWith("A000000065")) return "JCB";
        else if (aid.startsWith("A000000524")) return "RuPay";
        else return "Unknown (" + aid + ")";
    }

    private String hexToString(String hex) {
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hex.length(); i += 2) {
                String str = hex.substring(i, i + 2);
                sb.append((char) Integer.parseInt(str, 16));
            }
            return sb.toString().trim();
        } catch (Exception e) {
            return hex;
        }
    }

    private String analyzeCardTypeBySAK(int sak) {
        switch (sak & 0xFF) {
            case 0x00: return "MIFARE Ultralight";
            case 0x04: return "MIFARE Classic 1K";
            case 0x08: return "MIFARE Classic 1K";
            case 0x09: return "MIFARE Mini";
            case 0x18: return "MIFARE Classic 4K";
            case 0x20: return "MIFARE Plus/DESFire";
            case 0x28: return "JCOP 30";
            case 0x38: return "MIFARE DESFire";
            case 0x88: return "Infineon my-d move";
            case 0x98: return "Gemplus MPCOS";
            default: return "Unknown card type (SAK: 0x" + String.format("%02X", sak) + ")";
        }
    }

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

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}