package com.example.bdkipoc.cetakulang;

import com.example.bdkipoc.R;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream; // ✅ ADDED: Missing import
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import com.example.bdkipoc.StyleHelper;

public class ReprintAdapterActivity extends RecyclerView.Adapter<ReprintAdapterActivity.TransactionViewHolder> {
    private List<ReprintActivity.Transaction> transactionList;
    private OnPrintClickListener printClickListener;

    public interface OnPrintClickListener {
        void onPrintClick(ReprintActivity.Transaction transaction);
    }

    public ReprintAdapterActivity(List<ReprintActivity.Transaction> transactionList) {
        this.transactionList = transactionList;
    }

    public void setPrintClickListener(OnPrintClickListener listener) {
        this.printClickListener = listener;
    }

    /**
     * Update data without numbering (removed as per request)
     */
    public void updateData(List<ReprintActivity.Transaction> newData, int startIndex) {
        this.transactionList = newData;
        notifyDataSetChanged();
        
        Log.d("ReprintAdapterActivity", "📋 Data updated: " + newData.size() + " items");
    }

    @NonNull
    @Override
    public TransactionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_reprint, parent, false);
        return new TransactionViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TransactionViewHolder holder, int position) {
        ReprintActivity.Transaction t = transactionList.get(position);
        
        // ✅ STRIPE TABLE: Set alternating row colors
        LinearLayout itemContainer = holder.itemView.findViewById(R.id.itemContainer);
        if (position % 2 == 0) {
            // Even rows - white background
            itemContainer.setBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), android.R.color.white));
        } else {
            // Odd rows - light gray background  
            itemContainer.setBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), android.R.color.background_light));
        }
        
        Log.d("ReprintAdapterActivity", "📋 Binding transaction " + position + ":");
        Log.d("ReprintAdapterActivity", "   Reference: " + t.referenceId);
        Log.d("ReprintAdapterActivity", "   Status: " + t.status);
        Log.d("ReprintAdapterActivity", "   Amount: " + t.amount);
        
        // Set reference ID
        holder.referenceId.setText(t.referenceId);
        
        // Format the amount as Indonesian Rupiah
        try {
            String cleanAmount = cleanAmountString(t.amount);
            long amountValue = Long.parseLong(cleanAmount);
            String formattedAmount = formatRupiah(amountValue);
            holder.amount.setText(formattedAmount);
            
            Log.d("ReprintAdapterActivity", "💰 Amount processed: '" + t.amount + "' -> '" + formattedAmount + "'");
            
        } catch (NumberFormatException e) {
            Log.e("ReprintAdapterActivity", "❌ Amount format error: " + t.amount, e);
            String fallback = t.amount.startsWith("Rp") ? t.amount : "Rp " + t.amount;
            holder.amount.setText(fallback);
        }

        // ✅ ENHANCED STATUS HANDLING dengan comprehensive checking
        String displayStatus = t.status;
        
        Log.d("ReprintAdapterActivity", "🔍 Checking status for: " + t.referenceId + " (current: " + displayStatus + ")");
        
        // Jika status adalah INIT atau PENDING, lakukan comprehensive check
        if ("INIT".equalsIgnoreCase(t.status) || "PENDING".equalsIgnoreCase(t.status)) {
            if (t.referenceId != null && !t.referenceId.isEmpty()) {
                // Show checking state
                holder.status.setText("CHECKING...");
                StyleHelper.applyStatusTextColor(holder.status, holder.itemView.getContext(), "CHECKING");
                
                Log.d("ReprintAdapterActivity", "🔄 Starting comprehensive check for: " + t.referenceId);
                
                // Check real status dari semua kemungkinan sources
                checkMidtransStatus(t.referenceId, holder.status);
            } else {
                // No reference ID to check
                holder.status.setText(displayStatus.toUpperCase());
                StyleHelper.applyStatusTextColor(holder.status, holder.itemView.getContext(), displayStatus);
                Log.w("ReprintAdapterActivity", "⚠️ No reference ID for status check");
            }
        } else {
            // Use existing status yang sudah confirmed
            holder.status.setText(displayStatus.toUpperCase());
            StyleHelper.applyStatusTextColor(holder.status, holder.itemView.getContext(), displayStatus);
            Log.d("ReprintAdapterActivity", "✅ Using confirmed status: " + displayStatus);
        }

        // Set payment method
        String paymentMethod = getPaymentMethodName(t.channelCode, t.channelCategory);
        holder.paymentMethod.setText(paymentMethod);

        // ✅ FORMAT AND DISPLAY CREATED AT
        String formattedDate = formatCreatedAtDate(t.createdAt);
        holder.createdAt.setText(formattedDate);
        
        Log.d("ReprintAdapterActivity", "📅 Created at: " + t.createdAt + " -> " + formattedDate);

        // Set click listeners
        holder.itemView.setOnClickListener(v -> {
            if (printClickListener != null) {
                printClickListener.onPrintClick(t);
            }
        });

        holder.printSection.setOnClickListener(v -> {
            if (printClickListener != null) {
                printClickListener.onPrintClick(t);
            }
        });
        
        Log.d("ReprintAdapterActivity", "✅ Transaction binding complete for: " + t.referenceId);
    }

    private String cleanAmountString(String amount) {
        if (amount == null || amount.isEmpty()) {
            return "0";
        }
        
        Log.d("ReprintAdapterActivity", "Cleaning amount: '" + amount + "'");
        
        // Remove currency symbols and spaces
        String cleaned = amount
                .replace("Rp. ", "")
                .replace("Rp ", "")
                .replace("IDR ", "")
                .replace(" ", "")
                .trim();
        
        // Handle dots properly
        if (cleaned.contains(".")) {
            // Split by dots
            String[] parts = cleaned.split("\\.");
            
            if (parts.length == 2) {
                String beforeDot = parts[0];
                String afterDot = parts[1];
                
                // Check if it's decimal format (like "1000.00") or thousand separator (like "1.000")
                if (afterDot.length() <= 2 && (afterDot.equals("00") || afterDot.equals("0"))) {
                    // It's decimal format - keep only the integer part
                    cleaned = beforeDot;
                } else if (afterDot.length() == 3) {
                    // It's thousand separator format - combine parts
                    cleaned = beforeDot + afterDot;
                } else {
                    // Ambiguous case - assume thousand separator if beforeDot is short
                    if (beforeDot.length() <= 3) {
                        cleaned = beforeDot + afterDot;
                    } else {
                        cleaned = beforeDot; // Assume decimal
                    }
                }
            } else if (parts.length > 2) {
                // Multiple dots - assume all are thousand separators
                cleaned = String.join("", parts);
            }
        }
        
        // Remove any commas
        cleaned = cleaned.replace(",", "");
        
        Log.d("ReprintAdapterActivity", "Cleaned result: '" + cleaned + "'");
        return cleaned;
    }

    /**
     * Format long amount to Indonesian Rupiah format
     */
    private String formatRupiah(long amount) {
        // Use dots as thousand separators (Indonesian format)
        String formatted = String.format("%,d", amount).replace(',', '.');
        return "Rp. " + formatted;
    }

    // ✅ FIXED: Enhanced status checking with comprehensive search
    private void checkMidtransStatus(String referenceId, TextView statusTextView) {
        new Thread(() -> {
            try {
                Log.d("ReprintAdapterActivity", "🔍 Comprehensive status check for reference: " + referenceId);
                
                // STEP 1: Query webhook logs untuk semua order_id yang terkait
                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.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                
                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);
                    }
                    
                    JSONObject json = new JSONObject(response.toString());
                    JSONArray results = json.optJSONArray("results");
                    
                    String finalStatus = "INIT"; // Default
                    String foundOrderId = null;
                    String foundAcquirer = null;
                    
                    if (results != null && results.length() > 0) {
                        Log.d("ReprintAdapterActivity", "📊 Processing " + results.length() + " log entries");
                        
                        // STEP 2: Comprehensive search dengan multiple matching strategies
                        for (int i = 0; i < results.length(); i++) {
                            JSONObject log = results.getJSONObject(i);
                            JSONObject reqBody = log.optJSONObject("request_body");
                            
                            if (reqBody != null) {
                                String logOrderId = reqBody.optString("order_id", "");
                                String logTransactionStatus = reqBody.optString("transaction_status", "");
                                String logReferenceId = reqBody.optString("reference_id", "");
                                String logAcquirer = reqBody.optString("acquirer", "");
                                
                                // ✅ METHOD 1: Direct reference_id match
                                boolean isDirectMatch = referenceId.equals(logReferenceId);
                                
                                // ✅ METHOD 2: Check custom_field1 untuk QR refresh tracking
                                boolean isRefreshMatch = false;
                                String customField1 = reqBody.optString("custom_field1", "");
                                if (!customField1.isEmpty()) {
                                    try {
                                        JSONObject customData = new JSONObject(customField1);
                                        String originalReference = customData.optString("original_reference", "");
                                        String appReferenceId = customData.optString("app_reference_id", "");
                                        if (referenceId.equals(originalReference) || referenceId.equals(appReferenceId)) {
                                            isRefreshMatch = true;
                                            Log.d("ReprintAdapterActivity", "🔄 Found refresh match: " + logOrderId);
                                        }
                                    } catch (JSONException e) {
                                        // Ignore custom field parsing errors
                                    }
                                }
                                
                                // ✅ METHOD 3: Check item details untuk backup tracking
                                boolean isItemMatch = false;
                                JSONArray itemDetails = reqBody.optJSONArray("item_details");
                                if (itemDetails != null && itemDetails.length() > 0) {
                                    for (int j = 0; j < itemDetails.length(); j++) {
                                        JSONObject item = itemDetails.optJSONObject(j);
                                        if (item != null) {
                                            String itemName = item.optString("name", "");
                                            if (itemName.contains("(Ref: " + referenceId + ")") || 
                                                itemName.contains("- " + referenceId)) {
                                                isItemMatch = true;
                                                Log.d("ReprintAdapterActivity", "📦 Found item match: " + logOrderId);
                                                break;
                                            }
                                        }
                                    }
                                }
                                
                                // ✅ COMPREHENSIVE MATCH: Any of the three methods
                                boolean isRelatedTransaction = isDirectMatch || isRefreshMatch || isItemMatch;
                                
                                if (isRelatedTransaction) {
                                    Log.d("ReprintAdapterActivity", "🎯 MATCH FOUND!");
                                    Log.d("ReprintAdapterActivity", "   Order ID: " + logOrderId);
                                    Log.d("ReprintAdapterActivity", "   Status: " + logTransactionStatus);
                                    Log.d("ReprintAdapterActivity", "   Acquirer: " + logAcquirer);
                                    Log.d("ReprintAdapterActivity", "   Match Type: " + 
                                        (isDirectMatch ? "DIRECT " : "") + 
                                        (isRefreshMatch ? "REFRESH " : "") + 
                                        (isItemMatch ? "ITEM" : ""));
                                    
                                    // ✅ PRIORITY SYSTEM: settlement > capture > success > pending > init
                                    if (logTransactionStatus.equals("settlement") || 
                                        logTransactionStatus.equals("capture") ||
                                        logTransactionStatus.equals("success")) {
                                        finalStatus = "PAID";
                                        foundOrderId = logOrderId;
                                        foundAcquirer = logAcquirer;
                                        Log.d("ReprintAdapterActivity", "✅ PAYMENT CONFIRMED: " + logOrderId + " -> " + logTransactionStatus);
                                        break; // Found paid status, stop searching
                                    } else if (logTransactionStatus.equals("pending") && finalStatus.equals("INIT")) {
                                        finalStatus = "PENDING";
                                        foundOrderId = logOrderId;
                                        foundAcquirer = logAcquirer;
                                        Log.d("ReprintAdapterActivity", "⏳ PENDING found: " + logOrderId);
                                    } else if (logTransactionStatus.equals("expire") || logTransactionStatus.equals("cancel")) {
                                        if (finalStatus.equals("INIT")) { // Only update if no better status found
                                            finalStatus = "FAILED";
                                            foundOrderId = logOrderId;
                                            foundAcquirer = logAcquirer;
                                            Log.d("ReprintAdapterActivity", "❌ FAILED status: " + logOrderId + " -> " + logTransactionStatus);
                                        }
                                    }
                                }
                            }
                        }
                        
                        Log.d("ReprintAdapterActivity", "🔍 FINAL RESULT for " + referenceId + ":");
                        Log.d("ReprintAdapterActivity", "   Status: " + finalStatus);
                        Log.d("ReprintAdapterActivity", "   Order ID: " + (foundOrderId != null ? foundOrderId : "N/A"));
                        Log.d("ReprintAdapterActivity", "   Acquirer: " + (foundAcquirer != null ? foundAcquirer : "N/A"));
                    }
                    
                    // STEP 3: Update UI di main thread
                    final String displayStatus = finalStatus;
                    final String detectedAcquirer = foundAcquirer;
                    
                    statusTextView.post(() -> {
                        statusTextView.setText(displayStatus);
                        StyleHelper.applyStatusTextColor(statusTextView, statusTextView.getContext(), displayStatus);
                        
                        Log.d("ReprintAdapterActivity", "🎨 UI UPDATED:");
                        Log.d("ReprintAdapterActivity", "   Reference: " + referenceId);
                        Log.d("ReprintAdapterActivity", "   Display Status: " + displayStatus);
                        Log.d("ReprintAdapterActivity", "   Detected Acquirer: " + (detectedAcquirer != null ? detectedAcquirer : "Unknown"));
                    });
                    
                    // ✅ BONUS: Update backend jika status berubah ke PAID
                    if (finalStatus.equals("PAID")) {
                        updateBackendTransactionStatus(referenceId, finalStatus, foundOrderId, detectedAcquirer);
                    }
                    
                } else {
                    Log.w("ReprintAdapterActivity", "⚠️ API call failed with code: " + conn.getResponseCode());
                    statusTextView.post(() -> {
                        statusTextView.setText("ERROR");
                        StyleHelper.applyStatusTextColor(statusTextView, statusTextView.getContext(), "ERROR");
                    });
                }
                
            } catch (IOException | JSONException e) {
                Log.e("ReprintAdapterActivity", "❌ Comprehensive status check error: " + e.getMessage(), e);
                statusTextView.post(() -> {
                    statusTextView.setText("INIT");
                    StyleHelper.applyStatusTextColor(statusTextView, statusTextView.getContext(), "INIT");
                });
            }
        }).start();
    }

    /**
     * ✅ NEW METHOD: Update backend transaction status when payment confirmed
     */
    private void updateBackendTransactionStatus(String referenceId, String status, String orderId, String acquirer) {
        new Thread(() -> {
            try {
                Log.d("ReprintAdapterActivity", "🔄 Updating backend status for reference: " + referenceId);
                
                JSONObject updatePayload = new JSONObject();
                updatePayload.put("status", status);
                updatePayload.put("payment_status", status);
                updatePayload.put("paid_order_id", orderId);
                updatePayload.put("detected_acquirer", acquirer);
                updatePayload.put("updated_at", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
                updatePayload.put("settlement_time", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
                
                String updateUrl = "https://be-edc.msvc.app/transactions/update-by-reference";
                URL url = new URL(updateUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("User-Agent", "BDKIPOCApp/1.0");
                conn.setDoOutput(true);
                conn.setConnectTimeout(15000);
                conn.setReadTimeout(15000);
                
                JSONObject requestBody = new JSONObject();
                requestBody.put("reference_id", referenceId);
                requestBody.put("update_data", updatePayload);
                
                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = requestBody.toString().getBytes("utf-8");
                    os.write(input, 0, input.length);
                }
                
                int responseCode = conn.getResponseCode();
                Log.d("ReprintAdapterActivity", "📥 Backend update response: " + responseCode);
                
                if (responseCode == 200 || responseCode == 201) {
                    Log.d("ReprintAdapterActivity", "✅ Backend status updated successfully");
                } else {
                    Log.e("ReprintAdapterActivity", "❌ Backend update failed: " + responseCode);
                }
                
            } catch (Exception e) {
                Log.e("ReprintAdapterActivity", "❌ Backend update error: " + e.getMessage(), e);
            }
        }).start();
    }

    /**
     * Format created_at date to readable format
     */
    private String formatCreatedAtDate(String rawDate) {
        if (rawDate == null || rawDate.isEmpty()) {
            return "N/A";
        }
        
        Log.d("ReprintAdapterActivity", "📅 Input date: '" + rawDate + "'");
        
        try {
            // Handle different possible input formats from API
            SimpleDateFormat inputFormat;
            String cleanedDate = rawDate;
            
            if (rawDate.contains("T")) {
                // ISO format: "2025-06-10T04:31:19.565Z"
                cleanedDate = rawDate.replace("T", " ").replace("Z", "");
                // Remove microseconds if present
                if (cleanedDate.contains(".")) {
                    cleanedDate = cleanedDate.substring(0, cleanedDate.indexOf("."));
                }
                inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            } else if (rawDate.length() > 19 && rawDate.contains(".")) {
                // Format with microseconds: "2025-06-10 04:31:19.565"
                cleanedDate = rawDate.substring(0, 19); // Cut off microseconds
                inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            } else {
                // Standard format: "2025-06-10 04:31:19"
                inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            }
            
            Log.d("ReprintAdapterActivity", "📅 Cleaned date: '" + cleanedDate + "'");
            
            // Output format: d/M/yyyy H:mm:ss
            SimpleDateFormat outputFormat = new SimpleDateFormat("d/M/yyyy H:mm:ss", Locale.getDefault());
            
            Date date = inputFormat.parse(cleanedDate);
            if (date != null) {
                String formatted = outputFormat.format(date);
                Log.d("ReprintAdapterActivity", "📅 Date formatted: " + rawDate + " -> " + formatted);
                return formatted;
            }
        } catch (Exception e) {
            Log.e("ReprintAdapterActivity", "❌ Date formatting error for: " + rawDate, e);
        }
        
        // Fallback: Manual parsing
        try {
            // Handle format like "2025-06-10T04:31:19.565Z" manually
            String workingDate = rawDate.replace("T", " ").replace("Z", "");
            
            // Remove microseconds if present
            if (workingDate.contains(".")) {
                workingDate = workingDate.substring(0, workingDate.indexOf("."));
            }
            
            Log.d("ReprintAdapterActivity", "📅 Manual parsing attempt: '" + workingDate + "'");
            
            // Split into date and time parts
            String[] parts = workingDate.split(" ");
            if (parts.length >= 2) {
                String datePart = parts[0]; // "2025-06-10"
                String timePart = parts[1]; // "04:31:19"
                
                String[] dateComponents = datePart.split("-");
                if (dateComponents.length == 3) {
                    String year = dateComponents[0];
                    String month = dateComponents[1];
                    String day = dateComponents[2];
                    
                    // Remove leading zeros and format as d/M/yyyy H:mm:ss
                    int dayInt = Integer.parseInt(day);
                    int monthInt = Integer.parseInt(month);
                    
                    // Parse time to remove leading zeros from hour
                    String[] timeComponents = timePart.split(":");
                    if (timeComponents.length >= 3) {
                        int hour = Integer.parseInt(timeComponents[0]);
                        String minute = timeComponents[1];
                        String second = timeComponents[2];
                        
                        String result = dayInt + "/" + monthInt + "/" + year + " " + hour + ":" + minute + ":" + second;
                        Log.d("ReprintAdapterActivity", "📅 Manual format result: " + result);
                        return result;
                    }
                }
            }
        } catch (Exception e) {
            Log.w("ReprintAdapterActivity", "❌ Manual date formatting failed: " + e.getMessage());
        }
        
        Log.w("ReprintAdapterActivity", "📅 Using fallback - returning original date: " + rawDate);
        return rawDate;
    }

    private String getPaymentMethodName(String channelCode, String channelCategory) {
        Log.d("ReprintAdapterActivity", "🔍 Mapping payment method - channelCode: " + channelCode + ", channelCategory: " + channelCategory);
        
        // Priority 1: Use channelCode for specific mapping
        if (channelCode != null && !channelCode.isEmpty()) {
            String code = channelCode.toUpperCase().trim();
            
            switch (code) {
                case "QRIS":
                    return "QRIS";
                case "DEBIT":
                case "DEBIT_CARD":
                    return "Kartu Debit";
                case "CREDIT":
                case "CREDIT_CARD":
                    return "Kartu Kredit";
                case "BCA":
                    return "BCA";
                case "MANDIRI":
                    return "Mandiri";
                case "BNI":
                    return "BNI";
                case "BRI":
                    return "BRI";
                case "PERMATA":
                    return "Permata";
                case "CIMB":
                    return "CIMB Niaga";
                case "DANAMON":
                    return "Danamon";
                case "BSI":
                    return "BSI";
                case "CASH":
                    return "Tunai";
                case "EDC":
                    return "EDC";
                case "RETAIL_OUTLET":
                    // ✅ SPECIAL HANDLING: For RETAIL_OUTLET, determine by context
                    return determinePaymentMethodFromCategory(channelCategory);
                default:
                    Log.d("ReprintAdapterActivity", "🔍 Unknown channelCode: " + code + ", trying channelCategory");
                    break;
            }
        }
        
        // Priority 2: Use channelCategory as fallback
        if (channelCategory != null && !channelCategory.isEmpty()) {
            return mapChannelCategoryToPaymentMethod(channelCategory);
        }
        
        // Final fallback
        Log.w("ReprintAdapterActivity", "⚠️ No valid payment method found, using default");
        return "Unknown";
    }

    private String determinePaymentMethodFromCategory(String channelCategory) {
        if (channelCategory == null || channelCategory.isEmpty()) {
            return "QRIS"; // Default assumption for RETAIL_OUTLET
        }
        
        String category = channelCategory.toUpperCase().trim();
        Log.d("ReprintAdapterActivity", "🔍 Mapping channelCategory: " + category);
        
        switch (category) {
            case "RETAIL_OUTLET":
                return "QRIS"; // Most RETAIL_OUTLET transactions are QRIS
            case "DEBIT":
            case "DEBIT_CARD":
                return "Kartu Debit";
            case "CREDIT":
            case "CREDIT_CARD":
                return "Kartu Kredit";
            case "E_MONEY":
            case "EMONEY":
                return "E-Money";
            case "BANK_TRANSFER":
                return "Transfer Bank";
            case "VIRTUAL_ACCOUNT":
                return "Virtual Account";
            default:
                Log.d("ReprintAdapterActivity", "🔍 Unknown channelCategory: " + category + ", defaulting to QRIS");
                return "QRIS";
        }
    }

    private String mapChannelCategoryToPaymentMethod(String channelCategory) {
        if (channelCategory == null || channelCategory.isEmpty()) {
            return "Unknown";
        }
        
        String category = channelCategory.toUpperCase().trim();
        
        switch (category) {
            case "RETAIL_OUTLET":
                return "QRIS";
            case "DEBIT":
            case "DEBIT_CARD":
                return "Kartu Debit";
            case "CREDIT":
            case "CREDIT_CARD":
                return "Kartu Kredit";
            case "E_MONEY":
            case "EMONEY":
                return "E-Money";
            case "BANK_TRANSFER":
                return "Transfer Bank";
            case "VIRTUAL_ACCOUNT":
                return "Virtual Account";
            case "QRIS":
                return "QRIS";
            default:
                // Capitalize first letter for unknown categories
                return capitalizeFirstLetter(channelCategory);
        }
    }

    private String capitalizeFirstLetter(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
    }

    @Override
    public int getItemCount() {
        return transactionList.size();
    }

    static class TransactionViewHolder extends RecyclerView.ViewHolder {
        TextView amount, referenceId, status, paymentMethod, createdAt; // ✅ Added createdAt
        LinearLayout printSection;

        public TransactionViewHolder(@NonNull View itemView) {
            super(itemView);
            amount = itemView.findViewById(R.id.textAmount);
            referenceId = itemView.findViewById(R.id.textReferenceId);
            status = itemView.findViewById(R.id.textStatus);
            paymentMethod = itemView.findViewById(R.id.textPaymentMethod);
            createdAt = itemView.findViewById(R.id.textCreatedAt); // ✅ Added createdAt
            printSection = itemView.findViewById(R.id.printSection);
        }
    }
}