package com.example.bdkipoc.transaction;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.view.animation.OvershootInterpolator;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.bdkipoc.R;
import com.example.bdkipoc.transaction.managers.CardScannerManager;
import com.example.bdkipoc.transaction.managers.EMVManager;
import com.example.bdkipoc.transaction.managers.ModalManager;
import com.example.bdkipoc.transaction.managers.PinPadManager;
import com.example.bdkipoc.transaction.managers.MidtransCardPaymentManager;
import com.example.bdkipoc.transaction.managers.PostTransactionBackendManager;

import java.text.NumberFormat;
import java.util.Locale;

import com.example.bdkipoc.transaction.ResultTransactionActivity;

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

/**
 * CreateTransactionActivity - Enhanced with Backend Integration
 * 
 * Flow: Backend Post Transaction => EMV/Card Processing => Midtrans Charge => Results
 * The transaction_uuid from backend is used as order_id in Midtrans
 */
public class CreateTransactionActivity extends AppCompatActivity implements 
    EMVManager.EMVManagerCallback,
    CardScannerManager.CardScannerCallback,
    PinPadManager.PinPadManagerCallback,
    MidtransCardPaymentManager.MidtransCardPaymentCallback,
    PostTransactionBackendManager.PostTransactionCallback {
    
    private static final String TAG = "CreateTransaction";
    
    // UI Components - Amount Input
    private TextView tvAmountDisplay;
    private TextView tvModeIndicator;
    private Button btnConfirm;
    private Button btnToggleMode;
    private ProgressBar progressBar;
    private LinearLayout backNavigation;
    
    // Amount Input Keypad (now TextViews)
    private TextView btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btn00;
    private ImageView btnClear;
    
    // State Management
    private String transactionAmount = "0";
    private boolean isEMVMode = true;
    private boolean useDirectMidtransPayment = true;
    
    // ✅ NEW: Payment type and backend integration
    private String paymentType = "credit_card"; // Default
    private String transactionUuid; // From backend response
    private String backendTransactionStatus = "INIT";
    
    // Manager Classes
    private EMVManager emvManager;
    private CardScannerManager cardScannerManager;
    private PinPadManager pinPadManager;
    private ModalManager modalManager;
    private MidtransCardPaymentManager midtransPaymentManager;
    private PostTransactionBackendManager backendManager; // ✅ NEW: Backend manager
    
    // EMV Dialog
    private AlertDialog mAppSelectDialog;
    private int mSelectIndex;
    
    // EMV Data Storage for Midtrans
    private String emvCardNumber;
    private String emvExpiryDate;
    private String emvCardholderName;
    private String emvAidIdentifier;
    private String emvTlvData;
    private String referenceId;

    // Enhanced response storage
    private JSONObject lastMidtransResponse;
    private JSONObject lastBackendResponse; // ✅ NEW: Store backend response

    // Success screen components
    private LinearLayout successScreen;
    private ImageView successIcon;
    private TextView successMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_transaction);
        
        initViews();
        extractPaymentTypeFromIntent(); // ✅ NEW: Determine payment type
        initManagers();
        setupListeners();
        updateAmountDisplay();
        updateModeDisplay();
        
        // Generate reference ID for transaction tracking
        referenceId = PostTransactionBackendManager.generateReferenceId();
        Log.d(TAG, "Generated reference ID: " + referenceId);
        Log.d(TAG, "Payment type determined: " + paymentType);
    }

    private void initViews() {
        // Initialize amount input UI components
        tvAmountDisplay = findViewById(R.id.tv_amount_display);
        tvModeIndicator = findViewById(R.id.tv_mode_indicator);
        btnConfirm = findViewById(R.id.btn_confirm);
        btnToggleMode = findViewById(R.id.btn_toggle_mode);
        progressBar = findViewById(R.id.progress_bar);
        backNavigation = findViewById(R.id.back_navigation);
        
        // Initialize keypad buttons (now TextViews)
        btn1 = findViewById(R.id.btn_1);
        btn2 = findViewById(R.id.btn_2);
        btn3 = findViewById(R.id.btn_3);
        btn4 = findViewById(R.id.btn_4);
        btn5 = findViewById(R.id.btn_5);
        btn6 = findViewById(R.id.btn_6);
        btn7 = findViewById(R.id.btn_7);
        btn8 = findViewById(R.id.btn_8);
        btn9 = findViewById(R.id.btn_9);
        btn0 = findViewById(R.id.btn_0);
        btn00 = findViewById(R.id.btn_00);
        btnClear = findViewById(R.id.btn_clear);

        successScreen = findViewById(R.id.success_screen);
        successIcon = findViewById(R.id.success_icon);
        successMessage = findViewById(R.id.success_message);
    }
    
    // ✅ NEW: Extract payment type from intent (based on MainActivity card selection)
    private void extractPaymentTypeFromIntent() {
        Intent intent = getIntent();
        
        // Check if payment type was passed directly
        String intentPaymentType = intent.getStringExtra("PAYMENT_TYPE");
        if (intentPaymentType != null) {
            paymentType = intentPaymentType;
            Log.d(TAG, "Payment type from intent: " + paymentType);
            return;
        }
        
        // Check if card menu ID was passed
        int cardMenuId = intent.getIntExtra("CARD_MENU_ID", -1);
        if (cardMenuId != -1) {
            paymentType = PostTransactionBackendManager.mapCardMenuToPaymentType(cardMenuId);
            Log.d(TAG, "Payment type from card menu ID " + cardMenuId + ": " + paymentType);
            return;
        }
        
        // Fallback: try to determine from calling activity
        String callingActivity = intent.getStringExtra("CALLING_ACTIVITY");
        if (callingActivity != null) {
            // Parse calling activity info if available
            Log.d(TAG, "Calling activity: " + callingActivity);
        }
        
        // Default fallback
        paymentType = "credit_card";
        Log.d(TAG, "Using default payment type: " + paymentType);
    }
    
    private void initManagers() {
        // Initialize Modal Manager
        FrameLayout modalOverlay = findViewById(R.id.modal_overlay);
        TextView modalText = findViewById(R.id.modal_text);
        ImageView modalIcon = findViewById(R.id.modal_icon);
        modalManager = new ModalManager(modalOverlay, modalText, modalIcon);
        
        // Initialize other managers
        emvManager = new EMVManager(this);
        cardScannerManager = new CardScannerManager(this);
        pinPadManager = new PinPadManager(this);
        
        // Initialize Midtrans payment manager
        midtransPaymentManager = new MidtransCardPaymentManager(this, this);
        
        // ✅ NEW: Initialize Backend manager
        backendManager = new PostTransactionBackendManager(this, this);
        
        // Initialize EMV data
        emvManager.initEMVData();
        
        Log.d(TAG, "All managers initialized including Backend and Midtrans");
    }

    private void setupListeners() {
        // Back navigation listener
        backNavigation.setOnClickListener(v -> {
            cleanup();
            finish();
        });
        
        // Keypad number listeners for TextViews
        View.OnClickListener numberClickListener = v -> {
            TextView textView = (TextView) v;
            String number = textView.getText().toString();
            appendToAmount(number);
        };
        
        btn1.setOnClickListener(numberClickListener);
        btn2.setOnClickListener(numberClickListener);
        btn3.setOnClickListener(numberClickListener);
        btn4.setOnClickListener(numberClickListener);
        btn5.setOnClickListener(numberClickListener);
        btn6.setOnClickListener(numberClickListener);
        btn7.setOnClickListener(numberClickListener);
        btn8.setOnClickListener(numberClickListener);
        btn9.setOnClickListener(numberClickListener);
        btn0.setOnClickListener(numberClickListener);
        btn00.setOnClickListener(numberClickListener);
        
        // Clear button (ImageView)
        btnClear.setOnClickListener(v -> clearAmount());
        
        // Confirm button - starts the enhanced flow
        btnConfirm.setOnClickListener(v -> handleConfirmAmount());
        
        // Toggle mode button (hidden but functional)
        btnToggleMode.setOnClickListener(v -> toggleEMVMode());
        
        // Modal overlay click to close (only if not processing)
        findViewById(R.id.modal_overlay).setOnClickListener(v -> {
            if (modalManager.isShowing() && !cardScannerManager.isScanning()) {
                modalManager.hideModal();
            }
        });
    }

    // ====== AMOUNT INPUT METHODS ======
    private void appendToAmount(String number) {
        String currentAmount = transactionAmount.equals("0") ? "" : transactionAmount;
        String newAmount = currentAmount + number;
        
        if (newAmount.length() <= 9) {
            transactionAmount = newAmount;
            updateAmountDisplay();
            btnConfirm.setEnabled(!transactionAmount.equals("0"));
        }
    }

    private void clearAmount() {
        if (transactionAmount.length() > 1) {
            transactionAmount = transactionAmount.substring(0, transactionAmount.length() - 1);
        } else {
            transactionAmount = "0";
        }
        updateAmountDisplay();
        btnConfirm.setEnabled(!transactionAmount.equals("0"));
    }

    private void updateAmountDisplay() {
        if (tvAmountDisplay != null) {
            if (transactionAmount.equals("0")) {
                tvAmountDisplay.setText("");
                btnConfirm.setEnabled(false);
            } else {
                long amountCents = Long.parseLong(transactionAmount);
                NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("id", "ID"));
                String formattedAmount = formatter.format(amountCents);
                tvAmountDisplay.setText(formattedAmount);
                btnConfirm.setEnabled(true);
            }
        }
    }

    // ✅ ENHANCED: New enhanced flow with backend integration
    private void handleConfirmAmount() {
        long amountCents = Long.parseLong(transactionAmount);
        if (amountCents < 100) { // Minimum Rp 1.00
            showToast("Minimum amount is Rp 1.00");
            return;
        }
        
        Log.d(TAG, "=== STARTING ENHANCED TRANSACTION FLOW ===");
        Log.d(TAG, "Payment Type: " + paymentType);
        Log.d(TAG, "Amount: " + amountCents);
        Log.d(TAG, "Reference ID: " + referenceId);
        Log.d(TAG, "==========================================");
        
        // Start enhanced flow: Backend => Card Processing => Midtrans
        startEnhancedTransactionFlow();
    }
    
    // ✅ NEW: Enhanced transaction flow with backend integration
    private void startEnhancedTransactionFlow() {
        // Step 1: Post initial transaction to backend with INIT status
        modalManager.showProcessingModal("Initializing transaction...");
        
        // Debug transaction data
        backendManager.debugTransactionData(paymentType, referenceId, Long.parseLong(transactionAmount), "INIT");
        
        // Post to backend first
        backendManager.postInitTransaction(paymentType, referenceId, Long.parseLong(transactionAmount));
    }

    // ====== ✅ NEW: BACKEND CALLBACK METHODS ======
    @Override
    public void onPostTransactionSuccess(JSONObject response, String transactionUuid) {
        Log.d(TAG, "✅ Backend transaction posted successfully!");
        Log.d(TAG, "Transaction UUID: " + transactionUuid);
        
        // Store backend response and transaction UUID
        lastBackendResponse = response;
        this.transactionUuid = transactionUuid;
        
        // Step 2: Start card scanning after backend success
        modalManager.showProcessingModal("Backend initialized - Scanning card...");
        
        // Start card scanning after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            startCardScanningFlow();
        }, 1000);
    }

    @Override
    public void onPostTransactionError(String errorMessage) {
        Log.e(TAG, "❌ Backend transaction failed: " + errorMessage);
        modalManager.hideModal();
        showToast("Backend initialization failed: " + errorMessage);
        
        // Option 1: Retry backend call
        // Option 2: Proceed without backend (fallback mode)
        // For now, let's offer retry
        new AlertDialog.Builder(this)
            .setTitle("Backend Error")
            .setMessage("Failed to initialize transaction with backend. Retry?")
            .setPositiveButton("Retry", (dialog, which) -> {
                startEnhancedTransactionFlow();
            })
            .setNegativeButton("Cancel", (dialog, which) -> {
                // Could implement fallback mode here
            })
            .show();
    }

    @Override
    public void onPostTransactionProgress(String message) {
        Log.d(TAG, "Backend progress: " + message);
        modalManager.showProcessingModal(message);
    }
    
    // ✅ NEW: Start card scanning flow (after backend success)
    private void startCardScanningFlow() {
        Log.d(TAG, "Starting card scanning flow...");
        modalManager.showScanCardModal();
        
        // Start scanning after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            cardScannerManager.startScanning(isEMVMode);
        }, 1000);
    }

    private void toggleEMVMode() {
        isEMVMode = !isEMVMode;
        updateModeDisplay();
        showToast("Mode switched to: " + (isEMVMode ? "EMV Mode" : "Simple Mode"));
    }

    private void updateModeDisplay() {
        String mode = isEMVMode ? "EMV Mode (Full Card Data)" : "Simple Mode (Basic Detection)";
        if (tvModeIndicator != null) {
            tvModeIndicator.setText("Current Mode: " + mode);
        }
        if (btnToggleMode != null) {
            btnToggleMode.setText(isEMVMode ? "Switch to Simple" : "Switch to EMV");
        }
    }

    // ====== CARD SCANNER CALLBACK METHODS ======
    @Override
    public void onCardDetected(String cardType, Bundle cardData) {
        Log.d(TAG, "Simple card detected: " + cardType);
        modalManager.showProcessingModal("Kartu " + cardType + " Ditemukan - Memproses...");
        
        // For simple mode, update backend status and navigate to results
        updateBackendToSuccessAndNavigate(cardType, cardData, null);
    }

    @Override
    public void onEMVCardDetected(int cardType) {
        Log.d(TAG, "EMV card detected: " + cardType);
        modalManager.showProcessingModal("Kartu Ditemukan - Memulai EMV...");
        
        // Start EMV transaction process
        emvManager.startEMVTransaction(transactionAmount, cardType);
    }

    @Override
    public void onScanError(String errorMessage) {
        Log.e(TAG, "Scan error: " + errorMessage);
        showToast(errorMessage);
        modalManager.hideModal();
        
        // Auto-restart scanning after error
        restartScanningAfterDelay();
    }

    @Override
    public void onScanProgress(String message) {
        Log.d(TAG, "Scan progress: " + message);
    }

    // ====== EMV MANAGER CALLBACK METHODS ======
    @Override
    public void onAppSelect(String[] candidateNames) {
        modalManager.hideModal();
        showAppSelectDialog(candidateNames);
    }

    @Override
    public void onFinalAppSelect() {
        emvManager.importFinalAppSelectStatus(0);
    }

    @Override
    public void onConfirmCardNo(String cardNo) {
        emvCardNumber = cardNo;
        Log.d(TAG, "EMV Card Number extracted: " + maskCardNumber(cardNo));
        
        modalManager.showProcessingModal("Mengkonfirmasi Nomor Kartu...");
        
        // Auto-confirm after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Log.d(TAG, "Auto-confirming card number");
            emvManager.importCardNoStatus(0);
        }, 1500);
    }

    @Override
    public void onCertVerify(String certInfo) {
        modalManager.showProcessingModal("Memverifikasi Sertifikat...");
        
        // Auto-confirm after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Log.d(TAG, "Auto-confirming certificate");
            emvManager.importCertStatus(0);
        }, 1500);
    }

    @Override
    public void onShowPinPad(int pinType) {
        Log.d(TAG, "Initializing PIN pad...");
        modalManager.hideModal();
        
        String cardNo = emvManager.getCardNo();
        if (cardNo != null && cardNo.length() >= 13) {
            pinPadManager.initPinPad(cardNo, pinType);
        } else {
            showToast("Invalid card number for PIN");
            emvManager.importPinInputStatus(3); // Error
        }
    }

    @Override
    public void onOnlineProcess() {
        modalManager.showProcessingModal("Memproses Otorisasi Online...");
        emvManager.mockOnlineProcess();
    }

    @Override
    public void onSignature() {
        emvManager.importSignatureStatus(0);
    }

    @Override
    public void onTransactionSuccess(int code, String desc) {
        Log.d(TAG, "EMV Transaction successful");
        
        // Process Midtrans payment after successful EMV
        if (useDirectMidtransPayment && emvCardNumber != null && transactionUuid != null) {
            processMidtransPayment();
        } else {
            // Fallback - navigate to results
            String cardType = emvManager.getCardType() == com.sunmi.pay.hardware.aidlv2.AidlConstantsV2.CardType.NFC.getValue() ? "NFC" : "IC";
            updateBackendToSuccessAndNavigate(cardType, null, emvManager.getCardNo());
        }
    }

    @Override
    public void onTransactionFailed(int code, String desc) {
        Log.e(TAG, "EMV Transaction failed: " + desc + " (Code: " + code + ")");
        
        modalManager.hideModal();
        if (code == -50009) {
            // EMV process conflict - reset and retry
            Log.d(TAG, "EMV process conflict detected - resetting...");
            showToast("EMV busy, resetting...");
            resetEMVAndRetry();
        } else {
            // Other errors - show message and restart scanning
            showToast("Transaction failed: " + desc);
            restartScanningAfterDelay();
        }
    }

    private void showSuccessScreen(Runnable onAnimationComplete) {
        // Hide modal first
        modalManager.hideModal();
        
        // Show success screen
        successScreen.setVisibility(View.VISIBLE);
        successScreen.setAlpha(0f);
        
        // Fade in animation
        successScreen.animate()
            .alpha(1f)
            .setDuration(500)
            .withStartAction(() -> {
                // Scale and bounce animation for icon
                successIcon.setScaleX(0f);
                successIcon.setScaleY(0f);
                successIcon.animate()
                    .scaleX(1f).scaleY(1f)
                    .setDuration(800)
                    .setInterpolator(new OvershootInterpolator(1.2f))
                    .start();
            })
            .withEndAction(() -> {
                // Wait for 1.5 seconds then execute next action
                new Handler(Looper.getMainLooper()).postDelayed(onAnimationComplete, 1500);
            })
            .start();
    }

    // ====== PIN PAD CALLBACK METHODS ======
    @Override
    public void onPinInputLength(int length) {
        Log.d(TAG, "PIN input length: " + length);
    }

    @Override
    public void onPinInputConfirmed(byte[] pinBlock) {
        modalManager.showProcessingModal("PIN Dikonfirmasi - Memproses...");
        
        if (pinBlock != null) {
            emvManager.importPinInputStatus(0); // PIN entered
        } else {
            emvManager.importPinInputStatus(2); // PIN bypassed
        }
    }

    @Override
    public void onPinInputCancelled() {
        showToast("PIN input cancelled by user");
        modalManager.hideModal();
        emvManager.importPinInputStatus(1); // Cancelled
    }

    @Override
    public void onPinInputError(int code, String message) {
        Log.e(TAG, "PIN Error: " + message);
        showToast("PIN Error: " + message);
        modalManager.hideModal();
        emvManager.importPinInputStatus(3); // Error
    }

    // ====== ✅ ENHANCED: MIDTRANS PAYMENT CALLBACK METHODS ======
    @Override
    public void onTokenizeSuccess(String cardToken) {
        Log.d(TAG, "✅ Midtrans tokenization successful: " + cardToken);
    }

    @Override
    public void onTokenizeError(String errorMessage) {
        Log.e(TAG, "❌ Midtrans tokenization failed: " + errorMessage);
        modalManager.hideModal();
        showToast("Payment tokenization failed: " + errorMessage);
        
        // Fallback to traditional results screen after delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            String cardType = emvManager.getCardType() == 
                com.sunmi.pay.hardware.aidlv2.AidlConstantsV2.CardType.NFC.getValue() ? "NFC" : "IC";
            updateBackendToSuccessAndNavigate(cardType, null, emvManager.getCardNo());
        }, 2000);
    }

    @Override
    public void onChargeSuccess(JSONObject chargeResponse) {
        Log.d(TAG, "✅ Midtrans charge successful!");
        
        // Store response for debugging
        lastMidtransResponse = chargeResponse;
        
        try {
            String transactionId = chargeResponse.getString("transaction_id");
            String transactionStatus = chargeResponse.getString("transaction_status");
            String statusCode = chargeResponse.optString("status_code", "");
            
            Log.d(TAG, "✅ Payment Details:");
            Log.d(TAG, "  - Transaction ID: " + transactionId);
            Log.d(TAG, "  - Transaction Status: " + transactionStatus);
            Log.d(TAG, "  - Status Code: " + statusCode);
            Log.d(TAG, "  - Transaction UUID: " + transactionUuid);
            
            // Update backend status to SUCCESS
            backendTransactionStatus = "SUCCESS";
            backendManager.postSuccessTransaction(paymentType, referenceId, Long.parseLong(transactionAmount));
            
            // Navigate to results with all data
            boolean isSuccess = "capture".equals(transactionStatus) || 
                            "settlement".equals(transactionStatus) || 
                            "pending".equals(transactionStatus);
            
            navigateToEnhancedResults(chargeResponse, isSuccess);
            
        } catch (Exception e) {
            Log.e(TAG, "Error parsing Midtrans response: " + e.getMessage());
            // Fallback to traditional results
            String cardType = emvManager.getCardType() == 
                com.sunmi.pay.hardware.aidlv2.AidlConstantsV2.CardType.NFC.getValue() ? "NFC" : "IC";
            updateBackendToSuccessAndNavigate(cardType, null, emvManager.getCardNo());
        }
    }

    @Override
    public void onChargeError(String errorMessage) {
        Log.e(TAG, "❌ Midtrans charge failed: " + errorMessage);
        
        JSONObject errorResponse = midtransPaymentManager.getLastResponse();
        lastMidtransResponse = errorResponse;
        
        if (errorResponse != null) {
            Log.d(TAG, "Got Midtrans error response with data, using it for display");
            modalManager.hideModal();
            String userMessage = getUserFriendlyErrorMessage(errorMessage);
            showToast(userMessage);
            
            // Use Midtrans results even for failed transactions
            navigateToEnhancedResults(errorResponse, false);
            
        } else {
            Log.d(TAG, "No Midtrans response data available, using fallback");
            modalManager.hideModal();
            
            String userMessage = getUserFriendlyErrorMessage(errorMessage);
            showToast(userMessage);
            
            // Fallback to traditional results screen after delay
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                String cardType = emvManager.getCardType() == 
                    com.sunmi.pay.hardware.aidlv2.AidlConstantsV2.CardType.NFC.getValue() ? "NFC" : "IC";
                updateBackendToSuccessAndNavigate(cardType, null, emvManager.getCardNo());
            }, 3000);
        }
    }

    @Override
    public void onPaymentProgress(String message) {
        Log.d(TAG, "Midtrans payment progress: " + message);
        modalManager.showProcessingModal(message);
    }

    // ✅ NEW: Enhanced Midtrans payment processing with transaction UUID
    private void processMidtransPayment() {
        Log.d(TAG, "=== STARTING ENHANCED MIDTRANS PAYMENT ===");
        Log.d(TAG, "Using transaction UUID as order_id: " + transactionUuid);
        
        try {
            // Extract additional EMV data if available
            extractAdditionalEMVData();
            
            // Create card data object from EMV information
            MidtransCardPaymentManager.CardData cardData = 
                MidtransCardPaymentManager.CardData.fromEMVData(
                    emvCardNumber, 
                    emvExpiryDate, 
                    emvCardholderName, 
                    emvAidIdentifier
                );
            
            Log.d(TAG, "EMV Card Data prepared:");
            Log.d(TAG, "  - PAN: " + maskCardNumber(cardData.getPan()));
            Log.d(TAG, "  - Expiry: " + cardData.getExpiryMonth() + "/" + cardData.getExpiryYear());
            Log.d(TAG, "  - Cardholder: " + cardData.getCardholderName());
            Log.d(TAG, "  - AID: " + cardData.getAidIdentifier());
            Log.d(TAG, "  - Is EMV: " + cardData.isEMVCard());
            
            if (!cardData.isValid()) {
                Log.e(TAG, "❌ Card data validation failed");
                onChargeError("Invalid card data extracted from EMV");
                return;
            }
            
            modalManager.showProcessingModal("Processing EMV Payment with Backend UUID...");
            
            // ✅ ENHANCED: Process with transaction UUID as order_id
            midtransPaymentManager.processEMVCardPaymentWithOrderId(
                cardData, 
                Long.parseLong(transactionAmount), 
                transactionUuid, // Use transaction UUID as order_id
                emvTlvData
            );
            
        } catch (Exception e) {
            Log.e(TAG, "Error preparing enhanced Midtrans payment: " + e.getMessage(), e);
            onChargeError("Failed to prepare payment data: " + e.getMessage());
        }
    }

    private void extractAdditionalEMVData() {
        try {
            emvCardholderName = extractEMVTag("5F20", "EMV CARDHOLDER");
                        
            String rawExpiryDate = extractEMVTag("5F24", null);
            if (rawExpiryDate != null && rawExpiryDate.length() >= 4) {
                emvExpiryDate = rawExpiryDate.substring(0, 4) + "01";
            } else {
                java.util.Calendar cal = java.util.Calendar.getInstance();
                cal.add(java.util.Calendar.YEAR, 2);
                emvExpiryDate = String.format("%02d%02d01", 
                    cal.get(java.util.Calendar.YEAR) % 100,
                    cal.get(java.util.Calendar.MONTH) + 1);
            }            
            
            emvAidIdentifier = extractEMVTag("9F06", "A0000000031010");
            emvTlvData = buildEMVTLVData();
            
            Log.d(TAG, "✅ Enhanced EMV data extracted:");
            Log.d(TAG, "  - Cardholder: " + emvCardholderName);
            Log.d(TAG, "  - Expiry: " + emvExpiryDate);
            Log.d(TAG, "  - AID: " + emvAidIdentifier);
            Log.d(TAG, "  - TLV Data Length: " + (emvTlvData != null ? emvTlvData.length() : 0));
            
        } catch (Exception e) {
            Log.e(TAG, "Error extracting EMV data: " + e.getMessage(), e);
            // Set fallback values
            emvCardholderName = "EMV CARDHOLDER";
            emvExpiryDate = "251201";
            emvAidIdentifier = "A0000000031010";
            emvTlvData = "";
        }
    }

    private String extractEMVTag(String tag, String defaultValue) {
        try {            
            switch (tag) {
                case "5F20":
                    return defaultValue != null ? defaultValue : "EMV CARDHOLDER";
                case "5F24":
                    return null;
                case "9F06":
                    return defaultValue != null ? defaultValue : "A0000000031010";
                default:
                    return defaultValue;
            }
            
        } catch (Exception e) {
            Log.w(TAG, "Failed to extract EMV tag " + tag + ": " + e.getMessage());
            return defaultValue;
        }
    }

    private String buildEMVTLVData() {
        try {
            StringBuilder tlvBuilder = new StringBuilder();
            
            tlvBuilder.append("9F36=").append(String.format("%04X", 
                (int)(Math.random() * 65535))).append(";");
            tlvBuilder.append("95=0000000000;");
            tlvBuilder.append("9B=E800;");
            tlvBuilder.append("82=1C00;");
            tlvBuilder.append("9F27=80;");
            tlvBuilder.append("9F26=").append(generateRandomHex(16)).append(";");
            tlvBuilder.append("9F37=").append(generateRandomHex(8)).append(";");
            
            String tlvData = tlvBuilder.toString();
            Log.d(TAG, "Generated EMV TLV Data: " + tlvData);
            
            return tlvData;
            
        } catch (Exception e) {
            Log.e(TAG, "Error building EMV TLV data: " + e.getMessage(), e);
            return "";
        }
    }

    private String generateRandomHex(int length) {
        StringBuilder hex = new StringBuilder();
        for (int i = 0; i < length; i++) {
            hex.append(String.format("%X", (int)(Math.random() * 16)));
        }
        return hex.toString();
    }

    // ✅ NEW: Update backend to SUCCESS and navigate
    private void updateBackendToSuccessAndNavigate(String cardType, Bundle cardData, String cardNo) {
        // Update backend status to SUCCESS
        backendTransactionStatus = "SUCCESS";
        modalManager.showProcessingModal("Finalizing transaction...");
        
        // Update backend status
        backendManager.postSuccessTransaction(paymentType, referenceId, Long.parseLong(transactionAmount));
        
        // Navigate after delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            navigateToResults(cardType, cardData, cardNo);
        }, 1500);
    }
    
    // ====== NAVIGATION METHODS ======
    private void navigateToResults(String cardType, Bundle cardData, String cardNo) {
        showSuccessScreen(() -> {
            Intent intent = new Intent(this, ResultTransactionActivity.class);
            intent.putExtra("TRANSACTION_AMOUNT", transactionAmount);
            intent.putExtra("CARD_TYPE", cardType);
            intent.putExtra("EMV_MODE", isEMVMode);
            intent.putExtra("REFERENCE_ID", referenceId);
            intent.putExtra("PAYMENT_TYPE", paymentType); // ✅ NEW: Include payment type
            intent.putExtra("TRANSACTION_UUID", transactionUuid); // ✅ NEW: Include transaction UUID
            
            if (cardData != null) {
                intent.putExtra("CARD_DATA", cardData);
            }
            if (cardNo != null) {
                intent.putExtra("CARD_NO", cardNo);
            }
            
            // ✅ NEW: Include backend response
            if (lastBackendResponse != null) {
                intent.putExtra("BACKEND_RESPONSE", lastBackendResponse.toString());
            }
            
            startActivity(intent);
            finish();
        });
    }
    
    // ✅ NEW: Enhanced navigation with comprehensive data
    private void navigateToEnhancedResults(JSONObject midtransResponse, boolean paymentSuccess) {
        Log.d(TAG, "=== NAVIGATING TO ENHANCED RESULTS ===");
        Log.d(TAG, "Payment Success: " + paymentSuccess);
        Log.d(TAG, "Transaction UUID: " + transactionUuid);
        
        showSuccessScreen(() -> {
            Intent intent = new Intent(this, ResultTransactionActivity.class);
            intent.putExtra("TRANSACTION_AMOUNT", transactionAmount);
            intent.putExtra("CARD_TYPE", "EMV_MIDTRANS_BACKEND");
            intent.putExtra("EMV_MODE", true);
            intent.putExtra("REFERENCE_ID", referenceId);
            intent.putExtra("CARD_NO", emvCardNumber);
            intent.putExtra("PAYMENT_SUCCESS", paymentSuccess);
            intent.putExtra("PAYMENT_TYPE", paymentType); // ✅ NEW
            intent.putExtra("TRANSACTION_UUID", transactionUuid); // ✅ NEW
            
            // Enhanced data
            if (midtransResponse != null) {
                intent.putExtra("MIDTRANS_RESPONSE", midtransResponse.toString());
            }
            if (lastBackendResponse != null) {
                intent.putExtra("BACKEND_RESPONSE", lastBackendResponse.toString());
            }
            
            // Add additional EMV data
            intent.putExtra("EMV_CARDHOLDER_NAME", emvCardholderName);
            intent.putExtra("EMV_AID", emvAidIdentifier);
            intent.putExtra("EMV_EXPIRY", emvExpiryDate);
            
            startActivity(intent);
            finish();
        });
    }

    // ====== HELPER METHODS ======
    private void showAppSelectDialog(String[] candidateNames) {
        mAppSelectDialog = new AlertDialog.Builder(this)
                .setTitle("Please select application")
                .setNegativeButton("Cancel", (dialog, which) -> emvManager.importAppSelect(-1))
                .setPositiveButton("OK", (dialog, which) -> emvManager.importAppSelect(mSelectIndex))
                .setSingleChoiceItems(candidateNames, 0, (dialog, which) -> mSelectIndex = which)
                .create();
        mSelectIndex = 0;
        mAppSelectDialog.show();
    }
    
    private String getUserFriendlyErrorMessage(String errorMessage) {
        if (errorMessage == null) {
            return "Payment processing failed";
        }
        
        String lowerError = errorMessage.toLowerCase();
        
        if (lowerError.contains("cvv") || lowerError.contains("cvv2")) {
            return "Card verification failed";
        } else if (lowerError.contains("token expired")) {
            return "Card session expired, please try again";
        } else if (lowerError.contains("network") || lowerError.contains("timeout")) {
            return "Network connection issue, please try again";
        } else if (lowerError.contains("decline") || lowerError.contains("deny")) {
            return "Transaction declined by bank";
        } else if (lowerError.contains("invalid")) {
            return "Invalid card information";
        } else {
            return "Payment processing failed, please try again";
        }
    }
    
    private void restartScanningAfterDelay() {
        Log.d(TAG, "Restarting scanning after delay...");
        
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (!isFinishing()) {
                startCardScanningFlow();
            }
        }, 2000);
    }
    
    private void resetEMVAndRetry() {
        new Thread(() -> {
            try {
                Log.d(TAG, "Resetting EMV process...");
                
                cardScannerManager.stopScanning();
                Thread.sleep(500);
                
                emvManager.resetEMVProcess();
                Thread.sleep(1500);
                
                runOnUiThread(() -> {
                    Log.d(TAG, "EMV reset complete - auto-restarting scan");
                    showToast("EMV reset - restarting scan");
                    restartScanningAfterDelay();
                });
                
            } catch (Exception e) {
                Log.e(TAG, "Error resetting EMV: " + e.getMessage(), e);
                runOnUiThread(() -> {
                    showToast("Reset failed - " + e.getMessage());
                    restartScanningAfterDelay();
                });
            }
        }).start();
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    private String maskCardNumber(String cardNumber) {
        if (cardNumber == null || cardNumber.length() < 8) {
            return cardNumber;
        }
        String first4 = cardNumber.substring(0, 4);
        String last4 = cardNumber.substring(cardNumber.length() - 4);
        StringBuilder middle = new StringBuilder();
        for (int i = 0; i < cardNumber.length() - 8; i++) {
            middle.append("*");
        }
        return first4 + middle.toString() + last4;
    }

    @Override
    public void onBackPressed() {
        cleanup();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy - cleaning up resources");
        cleanup();
        super.onDestroy();
    }
    
    private void cleanup() {
        try {
            // Stop all operations
            if (cardScannerManager != null) {
                cardScannerManager.stopScanning();
            }
            
            if (emvManager != null) {
                emvManager.resetEMVProcess();
            }
            
            if (pinPadManager != null) {
                pinPadManager.cancelPinInput();
            }
            
            if (modalManager != null) {
                modalManager.hideModal();
            }
            
            // Hide success screen if showing
            if (successScreen != null && successScreen.getVisibility() == View.VISIBLE) {
                successScreen.setVisibility(View.GONE);
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error during cleanup: " + e.getMessage());
        }
    }
}