<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Fiuu cloudECR - Sale Terminal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card-shadow {
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        }
        .pulse-animation {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: .5; }
        }
        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <!-- Header -->
    <nav class="gradient-bg text-white shadow-lg">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16 items-center">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-credit-card text-2xl"></i>
                    <span class="font-bold text-xl">Fiuu cloudECR</span>
                    <span class="text-sm opacity-75">Sale Terminal Demo</span>
                </div>
                <div class="flex items-center space-x-4">
                    <div id="auth-status" class="flex items-center space-x-2">
                        <span class="w-3 h-3 rounded-full {{ $isAuthenticated ? 'bg-green-400' : 'bg-red-400' }}"></span>
                        <span class="text-sm">{{ $isAuthenticated ? 'Connected' : 'Disconnected' }}</span>
                    </div>
                    @if($isAuthenticated)
                        <button onclick="logout()" class="bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg text-sm transition">
                            <i class="fas fa-sign-out-alt mr-2"></i>Logout
                        </button>
                    @endif
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Authentication Section (shown when not authenticated) -->
        <div id="auth-section" class="{{ $isAuthenticated ? 'hidden' : '' }}">
            <div class="bg-white rounded-2xl card-shadow p-8 max-w-md mx-auto">
                <div class="text-center mb-6">
                    <div class="w-16 h-16 bg-gradient-to-r from-purple-500 to-indigo-600 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-lock text-white text-2xl"></i>
                    </div>
                    <h2 class="text-2xl font-bold text-gray-800">Connect to Terminal</h2>
                    <p class="text-gray-500 mt-2">Authenticate with Fiuu cloudECR to start accepting payments</p>
                </div>

                <div class="bg-gray-50 rounded-lg p-4 mb-6">
                    <h3 class="text-sm font-semibold text-gray-700 mb-3">Demo Credentials</h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-gray-500">POS ID:</span>
                            <span class="font-mono text-gray-800">{{ $posId }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Merchant ID:</span>
                            <span class="font-mono text-gray-800">{{ $merchantId }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Device ID:</span>
                            <span class="font-mono text-gray-800">{{ $deviceId }}</span>
                        </div>
                    </div>
                </div>

                <button onclick="authenticate()" id="auth-btn" class="w-full gradient-bg text-white py-3 rounded-xl font-semibold hover:opacity-90 transition flex items-center justify-center space-x-2">
                    <i class="fas fa-plug"></i>
                    <span>Connect & Authenticate</span>
                </button>
            </div>
        </div>

        <!-- Main Content (shown when authenticated) -->
        <div id="main-section" class="{{ $isAuthenticated ? '' : 'hidden' }}">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- Sale Form -->
                <div class="lg:col-span-2">
                    <div class="bg-white rounded-2xl card-shadow p-6">
                        <div class="flex items-center justify-between mb-6">
                            <h2 class="text-xl font-bold text-gray-800">
                                <i class="fas fa-shopping-cart text-indigo-600 mr-2"></i>
                                New Sale Transaction
                            </h2>
                            <span class="text-sm text-gray-500">API v1</span>
                        </div>

                        <form id="sale-form" class="space-y-6">
                            <!-- Amount -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Transaction Amount (MYR)
                                </label>
                                <div class="relative">
                                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 text-lg font-semibold">RM</span>
                                    <input type="number" name="amount" id="amount" step="0.01" min="0.01" value="1.00"
                                           class="w-full pl-14 pr-4 py-4 text-2xl font-bold border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-0 transition"
                                           placeholder="0.00" required>
                                </div>
                            </div>

                            <!-- Payment Method -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Payment Method
                                </label>
                                <div class="grid grid-cols-3 gap-3">
                                    <label class="relative">
                                        <input type="radio" name="payment_method" value="bankCard" class="peer sr-only" checked>
                                        <div class="p-4 border-2 rounded-xl cursor-pointer transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 hover:border-gray-300">
                                            <div class="text-center">
                                                <i class="fas fa-credit-card text-2xl text-gray-600 peer-checked:text-indigo-600"></i>
                                                <p class="mt-2 text-sm font-medium">Bank Card</p>
                                            </div>
                                        </div>
                                    </label>
                                    <label class="relative">
                                        <input type="radio" name="payment_method" value="qrCustScan" class="peer sr-only">
                                        <div class="p-4 border-2 rounded-xl cursor-pointer transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 hover:border-gray-300">
                                            <div class="text-center">
                                                <i class="fas fa-qrcode text-2xl text-gray-600 peer-checked:text-indigo-600"></i>
                                                <p class="mt-2 text-sm font-medium">QR (Merchant)</p>
                                                <p class="text-xs text-gray-400">Customer Scan</p>
                                            </div>
                                        </div>
                                    </label>
                                    <label class="relative">
                                        <input type="radio" name="payment_method" value="qrMerchScan" class="peer sr-only">
                                        <div class="p-4 border-2 rounded-xl cursor-pointer transition-all peer-checked:border-indigo-500 peer-checked:bg-indigo-50 hover:border-gray-300">
                                            <div class="text-center">
                                                <i class="fas fa-mobile-alt text-2xl text-gray-600 peer-checked:text-indigo-600"></i>
                                                <p class="mt-2 text-sm font-medium">QR (Customer)</p>
                                                <p class="text-xs text-gray-400">Merchant Scan</p>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>

                            <!-- E-Wallet Channel (shown for qrCustScan) -->
                            <div id="channel-section" class="hidden">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    E-Wallet Channel
                                </label>
                                <select name="payment_channel" id="payment_channel" 
                                        class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-0 transition">
                                    <option value="">Select e-wallet...</option>
                                    <option value="tng">Touch 'n Go eWallet</option>
                                    <option value="boost">Boost</option>
                                    <option value="grabpay">GrabPay</option>
                                    <option value="shopeepay">ShopeePay</option>
                                    <option value="duitNowQr">DuitNow QR</option>
                                    @foreach($ewalletChannels as $channel)
                                        @if(($channel['status'] ?? 0) == 1)
                                            <option value="{{ $channel['name'] }}">{{ ucfirst($channel['name']) }}</option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>

                            <!-- Optional Fields Toggle -->
                            <div>
                                <button type="button" onclick="toggleOptionalFields()" class="text-indigo-600 text-sm font-medium hover:text-indigo-700">
                                    <i class="fas fa-cog mr-1"></i>
                                    <span id="optional-toggle-text">Show Optional Fields</span>
                                </button>
                            </div>

                            <!-- Optional Fields -->
                            <div id="optional-fields" class="hidden space-y-4 border-t pt-4">
                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Reference Label (max 10 chars)
                                        </label>
                                        <input type="text" name="reference_label" maxlength="10"
                                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-0 transition"
                                               placeholder="e.g., Order ID">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            Print Count
                                        </label>
                                        <select name="print_count" class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-0 transition">
                                            <option value="2">Merchant + Customer</option>
                                            <option value="1">Merchant Only</option>
                                            <option value="0">No Receipt</option>
                                        </select>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">
                                        Note (printed on receipt, max 128 chars)
                                    </label>
                                    <textarea name="note" maxlength="128" rows="2"
                                              class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-0 transition resize-none"
                                              placeholder="Additional note for the receipt..."></textarea>
                                </div>
                            </div>

                            <!-- Submit Button -->
                            <button type="submit" id="sale-btn" 
                                    class="w-full gradient-bg text-white py-4 rounded-xl font-bold text-lg hover:opacity-90 transition flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed">
                                <i class="fas fa-paper-plane"></i>
                                <span>Process Sale</span>
                            </button>
                        </form>
                    </div>

                    <!-- Quick Actions -->
                    <div class="mt-6 grid grid-cols-2 gap-4">
                        <button onclick="getLastTransaction()" class="bg-white rounded-xl p-4 card-shadow hover:bg-gray-50 transition text-left">
                            <i class="fas fa-history text-indigo-600 text-xl mb-2"></i>
                            <h3 class="font-semibold text-gray-800">Get Last Transaction</h3>
                            <p class="text-sm text-gray-500">Retrieve the last transaction result</p>
                        </button>
                        <button onclick="showVoidModal()" class="bg-white rounded-xl p-4 card-shadow hover:bg-gray-50 transition text-left">
                            <i class="fas fa-undo text-red-500 text-xl mb-2"></i>
                            <h3 class="font-semibold text-gray-800">Void Transaction</h3>
                            <p class="text-sm text-gray-500">Cancel a previous transaction</p>
                        </button>
                    </div>
                </div>

                <!-- Right Sidebar -->
                <div class="space-y-6">
                    <!-- Terminal Status -->
                    <div class="bg-white rounded-2xl card-shadow p-6">
                        <h3 class="font-bold text-gray-800 mb-4">
                            <i class="fas fa-tablet-alt text-indigo-600 mr-2"></i>
                            Terminal Status
                        </h3>
                        <div id="terminal-list" class="space-y-3">
                            @forelse($terminals as $terminal)
                                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                    <div class="flex items-center space-x-3">
                                        <i class="fas fa-{{ $terminal['isVT'] ? 'laptop' : 'credit-card' }} text-gray-600"></i>
                                        <div>
                                            <p class="font-medium text-sm">{{ $terminal['terminalId'] }}</p>
                                            <p class="text-xs text-gray-400">{{ $terminal['isVT'] ? 'Fiuu VT+' : 'Physical Terminal' }}</p>
                                        </div>
                                    </div>
                                    <span class="flex items-center space-x-1">
                                        <span class="w-2 h-2 rounded-full {{ $terminal['connected'] ? 'bg-green-500' : 'bg-gray-400' }}"></span>
                                        <span class="text-xs {{ $terminal['connected'] ? 'text-green-600' : 'text-gray-400' }}">
                                            {{ $terminal['connected'] ? 'Online' : 'Offline' }}
                                        </span>
                                    </span>
                                </div>
                            @empty
                                <div class="text-center py-4 text-gray-400">
                                    <i class="fas fa-plug text-2xl mb-2"></i>
                                    <p class="text-sm">No terminals connected</p>
                                </div>
                            @endforelse
                        </div>
                        <button onclick="refreshTerminals()" class="mt-4 w-full text-center text-indigo-600 text-sm font-medium hover:text-indigo-700">
                            <i class="fas fa-sync-alt mr-1"></i>
                            Refresh Terminals
                        </button>
                    </div>

                    <!-- Transaction Response -->
                    <div class="bg-white rounded-2xl card-shadow p-6">
                        <h3 class="font-bold text-gray-800 mb-4">
                            <i class="fas fa-receipt text-indigo-600 mr-2"></i>
                            Last Response
                        </h3>
                        <div id="response-container" class="min-h-[200px]">
                            <div class="text-center py-8 text-gray-400">
                                <i class="fas fa-inbox text-3xl mb-2"></i>
                                <p class="text-sm">No transaction yet</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Void Modal -->
    <div id="void-modal" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div class="bg-white rounded-2xl p-6 w-full max-w-md mx-4">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-800">
                    <i class="fas fa-undo text-red-500 mr-2"></i>
                    Void Transaction
                </h3>
                <button onclick="hideVoidModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="void-form" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Transaction ID</label>
                    <input type="text" name="trans_id" id="void_trans_id" required
                           class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-red-500 focus:ring-0 transition"
                           placeholder="e.g., 1516809">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Invoice Number (Optional)</label>
                    <input type="text" name="inv_no" id="void_inv_no"
                           class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-red-500 focus:ring-0 transition"
                           placeholder="e.g., 000001">
                </div>
                <button type="submit" class="w-full bg-red-500 text-white py-3 rounded-xl font-semibold hover:bg-red-600 transition">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    Confirm Void
                </button>
            </form>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="loading-overlay" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div class="bg-white rounded-2xl p-8 text-center">
            <div class="loading-spinner mx-auto mb-4"></div>
            <p id="loading-text" class="text-gray-600 font-medium">Processing transaction...</p>
            <p class="text-sm text-gray-400 mt-2">Please wait for terminal response</p>
        </div>
    </div>

    <script>
        // CSRF Token setup
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        // Toggle payment channel visibility based on payment method
        document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const channelSection = document.getElementById('channel-section');
                if (this.value === 'qrCustScan') {
                    channelSection.classList.remove('hidden');
                } else {
                    channelSection.classList.add('hidden');
                }
            });
        });

        // Toggle optional fields
        function toggleOptionalFields() {
            const fields = document.getElementById('optional-fields');
            const text = document.getElementById('optional-toggle-text');
            if (fields.classList.contains('hidden')) {
                fields.classList.remove('hidden');
                text.textContent = 'Hide Optional Fields';
            } else {
                fields.classList.add('hidden');
                text.textContent = 'Show Optional Fields';
            }
        }

        // Show/hide loading overlay
        function showLoading(text = 'Processing...') {
            document.getElementById('loading-text').textContent = text;
            document.getElementById('loading-overlay').classList.remove('hidden');
        }

        function hideLoading() {
            document.getElementById('loading-overlay').classList.add('hidden');
        }

        // Authenticate
        async function authenticate() {
            const btn = document.getElementById('auth-btn');
            btn.disabled = true;
            btn.innerHTML = '<div class="loading-spinner"></div><span class="ml-2">Connecting...</span>';

            try {
                const response = await fetch('/public/api/fiuu/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                });

                const data = await response.json();

                if (data.success) {
                    showNotification('Connected successfully!', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showNotification(data.message || 'Authentication failed', 'error');
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-plug"></i><span>Connect & Authenticate</span>';
                }
            } catch (error) {
                showNotification('Connection error: ' + error.message, 'error');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-plug"></i><span>Connect & Authenticate</span>';
            }
        }

        // Logout
        async function logout() {
            try {
                await fetch('/public/api/fiuu/logout', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                    },
                });
                location.reload();
            } catch (error) {
                console.error('Logout error:', error);
            }
        }

        // Process Sale
        document.getElementById('sale-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData.entries());
            
            // Validate payment channel for qrCustScan
            if (data.payment_method === 'qrCustScan' && !data.payment_channel) {
                showNotification('Please select an e-wallet channel', 'error');
                return;
            }

            showLoading('Processing sale transaction...');
            const btn = document.getElementById('sale-btn');
            btn.disabled = true;

            try {
                const response = await fetch('/public/api/fiuu/sale', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                    body: JSON.stringify(data),
                });

                const result = await response.json();
                displayResponse(result);

                if (result.success) {
                    showNotification('Transaction completed!', 'success');
                } else {
                    showNotification(result.message || 'Transaction failed', 'error');
                }
            } catch (error) {
                showNotification('Error: ' + error.message, 'error');
                displayResponse({ success: false, error: error.message });
            } finally {
                hideLoading();
                btn.disabled = false;
            }
        });

        // Get Last Transaction
        async function getLastTransaction() {
            showLoading('Fetching last transaction...');

            try {
                const response = await fetch('/public/api/fiuu/get-last', {
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                    },
                });

                const result = await response.json();
                displayResponse(result);
            } catch (error) {
                showNotification('Error: ' + error.message, 'error');
            } finally {
                hideLoading();
            }
        }

        // Void Modal
        function showVoidModal() {
            document.getElementById('void-modal').classList.remove('hidden');
        }

        function hideVoidModal() {
            document.getElementById('void-modal').classList.add('hidden');
        }

        // Process Void
        document.getElementById('void-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData.entries());

            hideVoidModal();
            showLoading('Processing void transaction...');

            try {
                const response = await fetch('/public/api/fiuu/void', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                    body: JSON.stringify(data),
                });

                const result = await response.json();
                displayResponse(result);

                if (result.success) {
                    showNotification('Transaction voided!', 'success');
                } else {
                    showNotification(result.message || 'Void failed', 'error');
                }
            } catch (error) {
                showNotification('Error: ' + error.message, 'error');
            } finally {
                hideLoading();
            }
        });

        // Refresh Terminals
        async function refreshTerminals() {
            try {
                const response = await fetch('/public/api/fiuu/terminals', {
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                    },
                });

                const result = await response.json();
                
                if (result.success && result.data.data) {
                    const container = document.getElementById('terminal-list');
                    if (result.data.data.length === 0) {
                        container.innerHTML = `
                            <div class="text-center py-4 text-gray-400">
                                <i class="fas fa-plug text-2xl mb-2"></i>
                                <p class="text-sm">No terminals connected</p>
                            </div>
                        `;
                    } else {
                        container.innerHTML = result.data.data.map(t => `
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center space-x-3">
                                    <i class="fas fa-${t.isVT ? 'laptop' : 'credit-card'} text-gray-600"></i>
                                    <div>
                                        <p class="font-medium text-sm">${t.terminalId}</p>
                                        <p class="text-xs text-gray-400">${t.isVT ? 'Fiuu VT+' : 'Physical Terminal'}</p>
                                    </div>
                                </div>
                                <span class="flex items-center space-x-1">
                                    <span class="w-2 h-2 rounded-full ${t.connected ? 'bg-green-500' : 'bg-gray-400'}"></span>
                                    <span class="text-xs ${t.connected ? 'text-green-600' : 'text-gray-400'}">
                                        ${t.connected ? 'Online' : 'Offline'}
                                    </span>
                                </span>
                            </div>
                        `).join('');
                    }
                    showNotification('Terminals refreshed', 'success');
                }
            } catch (error) {
                showNotification('Error refreshing terminals', 'error');
            }
        }

        // Display Response
        function displayResponse(result) {
            const container = document.getElementById('response-container');
            
            if (result.success && result.data) {
                const data = result.data;
                const transData = data.transData || {};
                const statusClass = data.statusCode === '00' ? 'bg-green-100 text-green-800' : 
                                   data.statusCode === '22' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800';

                container.innerHTML = `
                    <div class="space-y-3">
                        <div class="flex items-center justify-between">
                            <span class="px-3 py-1 rounded-full text-sm font-medium ${statusClass}">
                                ${data.statusCode === '00' ? 'Success' : data.statusCode === '22' ? 'Pending' : 'Failed'}
                            </span>
                            <span class="text-sm text-gray-500">${data.transType || 'N/A'}</span>
                        </div>
                        
                        ${transData.transAmt ? `
                        <div class="text-center py-2">
                            <p class="text-3xl font-bold text-gray-800">RM ${transData.transAmt}</p>
                            <p class="text-sm text-gray-500">${transData.currency || 'MYR'}</p>
                        </div>
                        ` : ''}

                        <div class="border-t pt-3 space-y-2 text-sm">
                            ${transData.transId ? `<div class="flex justify-between"><span class="text-gray-500">Trans ID</span><span class="font-mono">${transData.transId}</span></div>` : ''}
                            ${transData.invNo ? `<div class="flex justify-between"><span class="text-gray-500">Invoice No</span><span class="font-mono">${transData.invNo}</span></div>` : ''}
                            ${transData.paymentChannel ? `<div class="flex justify-between"><span class="text-gray-500">Channel</span><span class="capitalize">${transData.paymentChannel}</span></div>` : ''}
                            ${transData.cardNo ? `<div class="flex justify-between"><span class="text-gray-500">Card</span><span class="font-mono">${transData.cardNo}</span></div>` : ''}
                            ${transData.apprCode ? `<div class="flex justify-between"><span class="text-gray-500">Appr Code</span><span class="font-mono">${transData.apprCode}</span></div>` : ''}
                            ${transData.rrn ? `<div class="flex justify-between"><span class="text-gray-500">RRN</span><span class="font-mono">${transData.rrn}</span></div>` : ''}
                            ${transData.transDateTime ? `<div class="flex justify-between"><span class="text-gray-500">Date/Time</span><span>${transData.transDateTime}</span></div>` : ''}
                            ${data.responseText ? `<div class="flex justify-between"><span class="text-gray-500">Message</span><span>${data.responseText}</span></div>` : ''}
                        </div>

                        <button onclick="copyResponse()" class="w-full mt-3 text-center text-indigo-600 text-sm font-medium hover:text-indigo-700">
                            <i class="fas fa-copy mr-1"></i>
                            Copy Full Response
                        </button>
                    </div>
                `;

                // Store for copy
                window.lastResponse = result;

                // If successful sale, populate void form
                if (data.statusCode === '00' && data.transType === 'sale' && transData.transId) {
                    document.getElementById('void_trans_id').value = transData.transId;
                    document.getElementById('void_inv_no').value = transData.invNo || '';
                }
            } else {
                container.innerHTML = `
                    <div class="p-4 bg-red-50 rounded-lg">
                        <p class="text-red-700 font-medium mb-2">
                            <i class="fas fa-exclamation-circle mr-1"></i>
                            ${result.message || 'Error'}
                        </p>
                        <pre class="text-xs text-red-600 overflow-auto max-h-32">${JSON.stringify(result.error || result, null, 2)}</pre>
                    </div>
                `;
                window.lastResponse = result;
            }
        }

        // Copy Response
        function copyResponse() {
            if (window.lastResponse) {
                navigator.clipboard.writeText(JSON.stringify(window.lastResponse, null, 2))
                    .then(() => showNotification('Response copied to clipboard', 'success'))
                    .catch(() => showNotification('Failed to copy', 'error'));
            }
        }

        // Notification
        function showNotification(message, type = 'info') {
            const colors = {
                success: 'bg-green-500',
                error: 'bg-red-500',
                info: 'bg-blue-500',
            };

            const notification = document.createElement('div');
            notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-lg z-50 transition-all transform translate-x-0`;
            notification.innerHTML = `
                <div class="flex items-center space-x-2">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                    <span>${message}</span>
                </div>
            `;

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.classList.add('translate-x-full', 'opacity-0');
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        }
    </script>
</body>
</html>
