const express = require('express');
const router = express.Router();
const { makeQBOApiRequest, retryNetworkOperation, makeHttpsRequest } = require('../utils/network');
const { auditLog } = require('../utils/logging');
const config = require('../config/environment');

// Get transactions list with search and pagination
router.get('/api/transactions', async (req, res) => {
    try {
        auditLog('ADMIN_TRANSACTIONS_REQUEST', {}, req);
        
        // Get tokens from the main server context (we'll need to pass these)
        const { accessToken, refreshToken, tokenExpiresAt, realmId, refreshAccessToken } = req.qbTokens;
        
        if (!accessToken) {
            return res.status(401).json({
                success: false,
                message: 'QuickBooks not connected. Please connect QuickBooks first.',
                requestId: req.requestId
            });
        }

        // Check if token refresh needed
        if (Date.now() >= tokenExpiresAt - 300000) {
            const refreshed = await refreshAccessToken();
            if (!refreshed) {
                return res.status(401).json({
                    success: false,
                    message: 'Authentication failed. Please reconnect QuickBooks.',
                    requestId: req.requestId
                });
            }
        }

        // Check if realm ID is available
        if (!realmId) {
            return res.status(500).json({
                success: false,
                message: 'QuickBooks company not connected. Please reconnect QuickBooks.',
                requestId: req.requestId
            });
        }

        // Get pagination and search parameters
        const limit = parseInt(req.query.limit) || 100; // Default 100 transactions
        const search = req.query.search || '';
        const searchField = req.query.searchField || 'all';

        // HYBRID SOLUTION: Support multiple search methods
        // 1. Transaction ID (Payments API) - most reliable
        // 2. Customer name/email (QBO API) - find payments via customer lookup
        // 3. Amount (QBO API) - find payments by amount
        
        if (!search || search.length === 0) {
            // No search term provided
            return res.json({
                success: true,
                transactions: [],
                total: 0,
                totalFetched: 0,
                searchApplied: false,
                searchTerm: search,
                searchField: searchField,
                message: 'Please enter a search term to find transactions.',
                notice: 'You can search by Transaction ID, Customer Name, Email, or Amount.',
                requestId: req.requestId
            });
        }
        
        let apiUrl, searchMethod;
        const QB_PAYMENTS_BASE_URL = config.QB_ENVIRONMENT === 'production' 
            ? 'https://api.intuit.com' 
            : 'https://sandbox.api.intuit.com';
        const QB_QBO_BASE_URL = config.QB_ENVIRONMENT === 'production' 
            ? 'https://quickbooks.api.intuit.com' 
            : 'https://sandbox-quickbooks.api.intuit.com';
        
        // Use correct QuickBooks Payments API with proper filtering
        if (searchField === 'transactionId') {
            // Method 1: Direct transaction lookup OR filter by transaction ID
            if (search.length > 10) {
                // Looks like a full transaction ID - use direct lookup
                apiUrl = QB_PAYMENTS_BASE_URL + '/quickbooks/v4/payments/charges/' + search;
                searchMethod = 'direct_transaction';
                console.log('[DEBUG] Direct transaction search: ' + search);
            } else {
                // Use filter approach for partial transaction IDs
                apiUrl = QB_PAYMENTS_BASE_URL + '/quickbooks/v4/payments/charges?filter=transactionId=' + search;
                searchMethod = 'filtered_transaction';
                console.log('[DEBUG] Filtered transaction search: ' + search);
            }
        } else if (searchField === 'email') {
            // Method 2: Since /customers endpoint returns 404, try alternative approach
            return res.json({
                success: true,
                transactions: [],
                total: 0,
                totalFetched: 0,
                searchApplied: true,
                searchTerm: search,
                searchField: searchField,
                message: `Email search not yet supported. The QuickBooks Payments API customers endpoint is not available. Please use Transaction ID search.`,
                notice: `Found in transaction MS0289339177: Customer "Leeanne Camp" with card ending 0400. Try searching by Transaction ID.`,
                requestId: req.requestId
            });
        } else if (searchField === 'customerName' || searchField === 'firstName' || searchField === 'lastName') {
            // Method 3: Two-step process using QBO API - first find customer, then find their payments
            let customerQuery;
            
            if (searchField === 'firstName') {
                customerQuery = "SELECT Id FROM Customer WHERE GivenName = '" + search.replace(/'/g, "''") + "'";
            } else if (searchField === 'lastName') {
                customerQuery = "SELECT Id FROM Customer WHERE FamilyName = '" + search.replace(/'/g, "''") + "'";
            } else {
                // For full name, try DisplayName first, then split and try GivenName/FamilyName
                const nameParts = search.trim().split(/\s+/);
                if (nameParts.length >= 2) {
                    const firstName = nameParts[0].replace(/'/g, "''");
                    const lastName = nameParts.slice(1).join(' ').replace(/'/g, "''");
                    customerQuery = "SELECT Id FROM Customer WHERE GivenName = '" + firstName + "' AND FamilyName = '" + lastName + "'";
                } else {
                    // Single name - try as DisplayName with LIKE for partial match
                    customerQuery = "SELECT Id FROM Customer WHERE DisplayName LIKE '%" + search.replace(/'/g, "''") + "%'";
                }
            }
            
            const encodedQuery = encodeURIComponent(customerQuery);
            apiUrl = QB_QBO_BASE_URL + '/v3/company/' + realmId + '/query?query=' + encodedQuery;
            searchMethod = 'qbo_customer_lookup';
            console.log('[DEBUG] QBO Customer lookup query: ' + customerQuery);
            console.log('[DEBUG] Note: This searches QBO Customer records, not Payments API customer data');
        } else if (searchField === 'amount') {
            // Method 4: Use QBO Accounting API with SQL-like query for amount filtering
            const amount = parseFloat(search);
            if (!isNaN(amount)) {
                // Use QBO API with SQL query to find payments by amount
                const query = "SELECT * FROM Payment WHERE TotalAmt = '" + amount.toFixed(2) + "'";
                const encodedQuery = encodeURIComponent(query);
                apiUrl = QB_QBO_BASE_URL + '/v3/company/' + realmId + '/query?query=' + encodedQuery;
                searchMethod = 'qbo_payment_by_amount';
                console.log('[DEBUG] QBO Payment search by amount: $' + amount + ' using query: ' + query);
            } else {
                return res.json({
                    success: true,
                    transactions: [],
                    total: 0,
                    totalFetched: 0,
                    searchApplied: true,
                    searchTerm: search,
                    searchField: searchField,
                    message: `Invalid amount format: "${search}". Please enter a valid dollar amount (e.g., 200.00).`,
                    notice: `We found a $200.00 transaction: MS0289339177. Try searching by that Transaction ID.`,
                    requestId: req.requestId
                });
            }
        } else {
            // Default: provide guidance since customer endpoints don't work
            return res.json({
                success: true,
                transactions: [],
                total: 0,
                totalFetched: 0,
                searchApplied: true,
                searchTerm: search,
                searchField: searchField,
                message: `Search method not supported. QuickBooks Payments API has limited filtering capabilities.`,
                notice: `Only Transaction ID search is fully supported. Try searching for specific transaction IDs like MS0289339177.`,
                requestId: req.requestId
            });
        }
        
        console.log('[DEBUG] Search method: ' + searchMethod);
        console.log('[DEBUG] API URL: ' + apiUrl);

        let response = null;

        const options = {
            method: 'GET',
            headers: {
                'Authorization': 'Bearer ' + accessToken,
                'Accept': 'application/json',
                'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                'Content-Type': 'application/json',
                'Intuit-T-Id': realmId,
                'Request-Id': req.requestId
            },
            timeout: 15000 // 15 second timeout to prevent hanging
        };

        auditLog('ADMIN_PAYMENTS_QUERY_REQUEST', { 
            url: apiUrl, 
            searchMethod,
            searchField,
            search,
            realmId,
            environment: config.QB_ENVIRONMENT,
            headers: options.headers 
        }, req);
        
        // Add console logging for debugging
        console.log('[DEBUG] Calling QuickBooks Payments API:');
        console.log('[DEBUG] URL: ' + apiUrl);
        console.log('[DEBUG] Environment: ' + config.QB_ENVIRONMENT);

        try {
            response = await makeHttpsRequest(apiUrl, options);
            
            if (response.status === 200) {
                auditLog('ADMIN_PAYMENTS_QUERY_SUCCESS', { 
                    url: apiUrl, 
                    searchMethod,
                    status: response.status 
                }, req);
            } else {
                auditLog('ADMIN_PAYMENTS_QUERY_FAILED', { 
                    url: apiUrl, 
                    searchMethod,
                    status: response.status,
                    data: response.data 
                }, req);
                throw new Error(searchMethod + ' query failed with status ' + response.status);
            }
        } catch (error) {
            auditLog('ADMIN_PAYMENTS_QUERY_ERROR', { 
                url: apiUrl, 
                searchMethod,
                error: error.message 
            }, req);
            throw error;
        }

        if (!response || response.status !== 200) {
            throw new Error('Payment query failed');
        }
        
        // Process response based on search method
        let rawTransactions = [];
        let apiResponse = response.data;
        
        console.log('[DEBUG] ' + searchMethod + ' response:', JSON.stringify(apiResponse, null, 2));
        
        if (searchMethod === 'direct_transaction') {
            // Direct Payments API transaction lookup
            if (apiResponse && apiResponse.id) {
                rawTransactions = [apiResponse];
                console.log('[DEBUG] Successfully found transaction: ' + apiResponse.id);
            } else {
                console.log('[DEBUG] No transaction found with ID: ' + search);
            }
        } else if (searchMethod === 'filtered_transaction') {
            // Filtered transaction search - should return array of charges
            if (apiResponse && Array.isArray(apiResponse.charges)) {
                rawTransactions = apiResponse.charges;
                console.log('[DEBUG] Found ' + rawTransactions.length + ' transactions matching filter');
            } else if (apiResponse && Array.isArray(apiResponse)) {
                rawTransactions = apiResponse;
                console.log('[DEBUG] Found ' + rawTransactions.length + ' transactions (direct array)');
            } else {
                console.log('[DEBUG] No transactions found with filter. Response:', apiResponse);
            }
        } else if (searchMethod === 'qbo_payment_by_amount') {
            // Handle QBO Payment API amount search response
            console.log('[DEBUG] QBO Payment response:', JSON.stringify(apiResponse, null, 2));
            
            if (apiResponse && apiResponse.QueryResponse && apiResponse.QueryResponse.Payment) {
                const payments = Array.isArray(apiResponse.QueryResponse.Payment) 
                    ? apiResponse.QueryResponse.Payment 
                    : [apiResponse.QueryResponse.Payment];
                
                // Convert QBO Payment records to our transaction format
                rawTransactions = payments.map(payment => ({
                    id: payment.Id || 'QBO-' + (payment.PaymentRefNum || 'N/A'),
                    created: payment.MetaData?.CreateTime || payment.TxnDate || 'N/A',
                    status: 'QBO_PAYMENT',
                    amount: payment.TotalAmt || '0.00',
                    currency: 'USD',
                    card: {
                        name: payment.CustomerRef?.name || 'N/A',
                        number: 'N/A (QBO Payment Record)'
                    },
                    context: {
                        isEcommerce: false,
                        note: 'This is an accounting payment record from QuickBooks Online'
                    },
                    qboData: {
                        paymentRefNum: payment.PaymentRefNum,
                        txnDate: payment.TxnDate,
                        customerRef: payment.CustomerRef
                    }
                }));
                console.log('[DEBUG] Found ' + rawTransactions.length + ' QBO payments with amount: $' + search);
            } else {
                console.log('[DEBUG] No QBO payments found for amount: ' + search);
                rawTransactions = [];
            }
        } else if (searchMethod === 'qbo_customer_lookup') {
            // Handle QBO Customer lookup response - this is step 1 of 2-step process
            console.log('[DEBUG] QBO Customer lookup response:', JSON.stringify(apiResponse, null, 2));
            
            if (apiResponse && apiResponse.QueryResponse && apiResponse.QueryResponse.Customer) {
                const customers = Array.isArray(apiResponse.QueryResponse.Customer) 
                    ? apiResponse.QueryResponse.Customer 
                    : [apiResponse.QueryResponse.Customer];
                
                if (customers.length > 0) {
                    // Step 2: Now query payments for the found customer(s)
                    const customerIds = customers.map(customer => customer.Id);
                    console.log('[DEBUG] Found ' + customers.length + ' customers with IDs: ' + customerIds.join(', '));
                    
                    // Query payments for all found customers
                    const paymentQuery = customerIds.length === 1 
                        ? "SELECT * FROM Payment WHERE CustomerRef = '" + customerIds[0] + "'"
                        : "SELECT * FROM Payment WHERE CustomerRef IN ('" + customerIds.join("','") + "')";;
                    
                    console.log('[DEBUG] Step 2 - Payment query: ' + paymentQuery);
                    
                    // Make the second API call for payments
                    try {
                        const encodedPaymentQuery = encodeURIComponent(paymentQuery);
                        const paymentApiUrl = QB_QBO_BASE_URL + '/v3/company/' + realmId + '/query?query=' + encodedPaymentQuery;
                        
                        const paymentResponse = await makeHttpsRequest(paymentApiUrl, {
                            method: 'GET',
                            headers: {
                                'Authorization': 'Bearer ' + accessToken,
                                'Accept': 'application/json'
                            },
                            timeout: 15000
                        });
                        
                        console.log(`[DEBUG] Payment lookup response:`, JSON.stringify(paymentResponse.data, null, 2));
                        
                        if (paymentResponse.data && paymentResponse.data.QueryResponse && paymentResponse.data.QueryResponse.Payment) {
                            const payments = Array.isArray(paymentResponse.data.QueryResponse.Payment) 
                                ? paymentResponse.data.QueryResponse.Payment 
                                : [paymentResponse.data.QueryResponse.Payment];
                            
                            // Convert QBO Payment records to our transaction format
                            rawTransactions = payments.map(payment => ({
                                id: payment.Id || 'QBO-' + (payment.PaymentRefNum || 'N/A'),
                                created: payment.MetaData?.CreateTime || payment.TxnDate || 'N/A',
                                status: 'QBO_PAYMENT',
                                amount: payment.TotalAmt || '0.00',
                                currency: 'USD',
                                card: {
                                    name: payment.CustomerRef?.name || customers.find(c => c.Id === payment.CustomerRef?.value)?.DisplayName || 'N/A',
                                    number: 'N/A (QBO Payment Record)'
                                },
                                context: {
                                    isEcommerce: false,
                                    note: 'Payment record for customer: ' + (customers.find(c => c.Id === payment.CustomerRef?.value)?.DisplayName || 'Unknown')
                                },
                                qboData: {
                                    paymentRefNum: payment.PaymentRefNum,
                                    txnDate: payment.TxnDate,
                                    customerRef: payment.CustomerRef,
                                    customerName: customers.find(c => c.Id === payment.CustomerRef?.value)?.DisplayName
                                }
                            }));
                            console.log('[DEBUG] Found ' + rawTransactions.length + ' payments for customer(s): ' + search);
                        } else {
                            console.log('[DEBUG] No payments found for customer(s): ' + search);
                            rawTransactions = [];
                        }
                    } catch (paymentError) {
                        console.error('[ERROR] Failed to fetch payments for customer: ' + paymentError.message);
                        rawTransactions = [];
                    }
                } else {
                    console.log('[DEBUG] No customers found matching: ' + search);
                    rawTransactions = [];
                    
                    // Return early with helpful explanation
                    return res.json({
                        success: true,
                        transactions: [],
                        total: 0,
                        totalFetched: 0,
                        searchApplied: true,
                        searchTerm: search,
                        searchField: searchField,
                        message: `No accounting customer records found for "${search}".`,
                        notice: `Credit card customers (like "Leeanne Camp" in transaction MS0289339177) exist in the Payments API but may not exist as Customer records in QuickBooks Online accounting. Try searching by Transaction ID instead.`,
                        explanation: `The Payments API (credit card transactions) and QBO Accounting API (customer records) are separate systems. Customer name search only works if the customer exists in both systems.`,
                        requestId: req.requestId
                    });
                }
            } else {
                console.log('[DEBUG] No customers found in response for: ' + search);
                rawTransactions = [];
                
                // Add helpful message about the API limitation
                return res.json({
                    success: true,
                    transactions: [],
                    total: 0,
                    totalFetched: 0,
                    searchApplied: true,
                    searchTerm: search,
                    searchField: searchField,
                    message: `No accounting customer records found for "${search}".`,
                    notice: `Credit card customers (like "Leeanne Camp" in transaction MS0289339177) exist in the Payments API but may not exist as Customer records in QuickBooks Online accounting. Try searching by Transaction ID instead.`,
                    explanation: `The Payments API (credit card transactions) and QBO Accounting API (customer records) are separate systems. Customer name search only works if the customer exists in both systems.`,
                    requestId: req.requestId
                });
            }
        }
        
        auditLog('ADMIN_PAYMENTS_SUCCESS', { 
            count: rawTransactions.length,
            searchField,
            search
        }, req);

        // Transform QuickBooks Payments API data to standardized format
        let transactions = rawTransactions.map(charge => {
            // Extract customer information from the charge
            const customerName = charge.card?.name || 
                                (charge.card?.billing_address?.given_name || '') + ' ' + (charge.card?.billing_address?.family_name || '').trim() ||
                                'Unknown Customer';
            
            // Split customer name into first/last for search
            const nameParts = customerName.split(' ');
            const firstName = nameParts[0] || '';
            const lastName = nameParts.slice(1).join(' ') || '';
            
            return {
                id: charge.id || 'Unknown',
                fullName: customerName,
                firstName: firstName,
                lastName: lastName,
                email: charge.card?.billing_address?.email_address || 'N/A',
                amount: Math.abs(charge.amount || 0).toFixed(2),
                lastFourDigits: charge.card?.number || 'N/A',
                status: charge.status || 'UNKNOWN',
                created: charge.created || new Date().toISOString(),
                paymentMethod: charge.card?.brand || 'Unknown',
                description: charge.description || '',
                currency: charge.currency || 'USD',
                originalData: charge // Keep original for debugging
            };
        });

        // Apply client-side filtering for name searches (Payments API doesn't support complex name filtering)
        if (search && search.length > 0 && (searchField === 'firstName' || searchField === 'lastName' || searchField === 'all')) {
            const searchLower = search.toLowerCase();
            transactions = transactions.filter(transaction => {
                switch (searchField) {
                    case 'firstName':
                        return transaction.firstName.toLowerCase().includes(searchLower);
                    case 'lastName':
                        return transaction.lastName.toLowerCase().includes(searchLower);
                    case 'all':
                    default:
                        return transaction.fullName.toLowerCase().includes(searchLower) ||
                               transaction.email.toLowerCase().includes(searchLower) ||
                               transaction.id.toLowerCase().includes(searchLower);
                }
            });
        }

        res.json({
            success: true,
            transactions: transactions,
            total: transactions.length,
            totalFetched: rawTransactions.length,
            searchApplied: search ? true : false,
            searchTerm: search,
            searchField: searchField,
            message: transactions.length === 0 ? 'No transactions found' : `Found ${transactions.length} transactions`,
            requestId: req.requestId
        });
    } catch (error) {
        auditLog('ADMIN_TRANSACTIONS_ERROR', { error: error.message, stack: error.stack }, req);
        
        // Add detailed error logging
        console.error(`[ERROR] Transaction fetch failed:`, error.message);
        console.error(`[ERROR] Stack trace:`, error.stack);
        
        // Provide helpful error messages based on the error type
        let userMessage = 'Error fetching transactions';
        let statusCode = 500;
        
        if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {
            userMessage = 'QuickBooks API is responding slowly. Please try again in a moment.';
            statusCode = 503;
        } else if (error.message.includes('ECONNRESET') || error.message.includes('socket hang up')) {
            userMessage = 'Connection to QuickBooks API was interrupted. This might be temporary - please try again.';
            statusCode = 503;
        } else if (error.message.includes('ENOTFOUND')) {
            userMessage = 'Cannot reach QuickBooks API. Please check your internet connection.';
            statusCode = 503;
        } else if (error.message.includes('401') || error.message.includes('Authentication')) {
            userMessage = 'Authentication failed. Please reconnect your QuickBooks account.';
            statusCode = 401;
        } else if (error.message.includes('403')) {
            userMessage = 'Access denied. Your QuickBooks app may not have the required permissions.';
            statusCode = 403;
        }
        
        res.status(statusCode).json({
            success: false,
            message: userMessage,
            error: error.message,
            requestId: req.requestId,
            troubleshooting: [
                'Check your internet connection',
                'Verify QuickBooks API status at status.developer.intuit.com',
                'Try reconnecting your QuickBooks account',
                'Contact support if the issue persists'
            ]
        });
    }
});

// Get single transaction details
router.get('/api/transactions/:transactionId', async (req, res) => {
    try {
        const { transactionId } = req.params;
        auditLog('ADMIN_TRANSACTION_DETAILS_REQUEST', { transactionId }, req);
        
        // Get tokens from the main server context
        const { accessToken, refreshToken, tokenExpiresAt, realmId, refreshAccessToken } = req.qbTokens;
        
        if (!accessToken) {
            return res.status(401).json({
                success: false,
                message: 'QuickBooks not connected',
                requestId: req.requestId
            });
        }

        // Check if token refresh needed
        if (Date.now() >= tokenExpiresAt - 300000) {
            const refreshed = await refreshAccessToken();
            if (!refreshed) {
                return res.status(401).json({
                    success: false,
                    message: 'Authentication failed',
                    requestId: req.requestId
                });
            }
        }

        // Check if realm ID is available
        if (!realmId) {
            return res.status(500).json({
                success: false,
                message: 'QuickBooks company not connected. Please reconnect QuickBooks.',
                requestId: req.requestId
            });
        }

        const options = {
            method: 'GET',
            headers: {
                'Authorization': 'Bearer ' + accessToken,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                'Intuit-T-Id': realmId,
                'Request-Id': req.requestId
            }
        };

        const QB_API_BASE_URL = config.QB_ENVIRONMENT === 'production' 
            ? 'https://api.intuit.com' 
            : 'https://sandbox.api.intuit.com';
        const apiUrl = QB_API_BASE_URL + '/quickbooks/v4/payments/charges/' + transactionId;
        auditLog('ADMIN_TRANSACTION_DETAILS_API_REQUEST', { url: apiUrl, transactionId, realmId }, req);
        
        const response = await makeHttpsRequest(apiUrl, options);
        
        if (response.status === 200) {
            auditLog('ADMIN_TRANSACTION_DETAILS_SUCCESS', { transactionId }, req);
            res.json({
                success: true,
                transaction: response.data,
                requestId: req.requestId
            });
        } else {
            auditLog('ADMIN_TRANSACTION_DETAILS_FAILED', { transactionId, status: response.status }, req);
            res.status(response.status).json({
                success: false,
                message: 'Failed to fetch transaction details',
                error: response.data,
                requestId: req.requestId
            });
        }
    } catch (error) {
        auditLog('ADMIN_TRANSACTION_DETAILS_ERROR', { error: error.message }, req);
        res.status(500).json({
            success: false,
            message: 'Error fetching transaction details',
            requestId: req.requestId
        });
    }
});

// Void/Refund transaction
router.post('/api/transactions/:transactionId/refund', async (req, res) => {
    try {
        const { transactionId } = req.params;
        const { amount, reason } = req.body;
        
        auditLog('ADMIN_REFUND_REQUEST', { transactionId, amount, reason }, req);
        
        // Get tokens from the main server context
        const { accessToken, refreshToken, tokenExpiresAt, realmId, refreshAccessToken } = req.qbTokens;
        
        if (!accessToken) {
            return res.status(401).json({
                success: false,
                message: 'QuickBooks not connected',
                requestId: req.requestId
            });
        }

        // Check if token refresh needed
        if (Date.now() >= tokenExpiresAt - 300000) {
            const refreshed = await refreshAccessToken();
            if (!refreshed) {
                return res.status(401).json({
                    success: false,
                    message: 'Authentication failed',
                    requestId: req.requestId
                });
            }
        }

        // QuickBooks Payments API v4 Refunds format:
        // - For partial refund: {"amount": "200.00"} (string, not object)
        // - For full refund: {} (empty body)
        // - No 'context' field (that's only for charges, not refunds)
        const refundData = amount && parseFloat(amount) > 0 
            ? { amount: parseFloat(amount).toFixed(2) }  // Partial refund as string
            : {};  // Full refund (empty body)

        // Check if realm ID is available
        if (!realmId) {
            return res.status(500).json({
                success: false,
                message: 'QuickBooks company not connected. Please reconnect QuickBooks.',
                requestId: req.requestId
            });
        }

        const postData = JSON.stringify(refundData);
        const options = {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + accessToken,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                'Request-Id': req.requestId,
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        // QuickBooks Payments API uses different base URL than QuickBooks Online API
        const paymentsApiBaseUrl = config.QB_ENVIRONMENT === 'production' 
            ? 'https://api.intuit.com' 
            : 'https://sandbox.api.intuit.com';
        const apiUrl = paymentsApiBaseUrl + '/quickbooks/v4/payments/charges/' + transactionId + '/refunds';
        auditLog('ADMIN_REFUND_API_REQUEST', { url: apiUrl, transactionId, realmId, refundData }, req);
        
        // Get transaction details first to check if refund is possible
        console.error('REFUND_DEBUG: Fetching transaction details first...');
        const transactionResponse = await makeHttpsRequest(
            paymentsApiBaseUrl + '/quickbooks/v4/payments/charges/' + transactionId,
            {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + accessToken,
                    'Accept': 'application/json',
                    'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                    'Request-Id': req.requestId
                }
            }
        );
        
        // QuickBooks uses 'refundDetail' (not 'refunds') for existing refunds
        const existingRefunds = transactionResponse.data?.refundDetail || transactionResponse.data?.refunds || [];
        
        console.error('REFUND_DEBUG: Transaction Status:', transactionResponse.data?.status);
        console.error('REFUND_DEBUG: Transaction Amount:', transactionResponse.data?.amount);
        console.error('REFUND_DEBUG: Transaction Created:', transactionResponse.data?.created);
        console.error('REFUND_DEBUG: Transaction Refunds:', JSON.stringify(existingRefunds, null, 2));
        console.error('REFUND_DEBUG: Transaction Full Data:', JSON.stringify(transactionResponse.data, null, 2));
        
        // Check if transaction has already been refunded
        if (existingRefunds.length > 0) {
            const totalRefunded = existingRefunds.reduce((sum, refund) => {
                return sum + parseFloat(refund.amount || 0);
            }, 0);
            console.error('REFUND_DEBUG: ⚠️ Transaction already has refunds! Total refunded:', totalRefunded);
            
            if (totalRefunded >= parseFloat(transactionResponse.data.amount)) {
                return res.status(400).json({
                    success: false,
                    message: `Transaction has already been fully refunded (Refund ID: ${existingRefunds[0].id})`,
                    totalRefunded: totalRefunded,
                    transactionAmount: transactionResponse.data.amount,
                    existingRefunds: existingRefunds,
                    requestId: req.requestId
                });
            }
        }
        
        // Enhanced debug logging
        console.error('REFUND_DEBUG: Full API URL:', apiUrl);
        console.error('REFUND_DEBUG: Request Headers:', JSON.stringify(options.headers, null, 2));
        console.error('REFUND_DEBUG: Request Body:', postData);
        console.error('REFUND_DEBUG: Environment:', config.QB_ENVIRONMENT);
        
        const response = await makeHttpsRequest(apiUrl, options, postData);
        
        // Enhanced response logging
        console.error('REFUND_DEBUG: Response Status:', response.status);
        console.error('REFUND_DEBUG: Response Data:', JSON.stringify(response.data, null, 2));
        
        if (response.status === 200 || response.status === 201) {
            auditLog('ADMIN_REFUND_SUCCESS', { transactionId, refundId: response.data.id }, req);
            res.json({
                success: true,
                message: 'Refund processed successfully',
                refund: response.data,
                requestId: req.requestId
            });
        } else {
            auditLog('ADMIN_REFUND_FAILED', { transactionId, status: response.status }, req);
            res.status(response.status).json({
                success: false,
                message: 'Failed to process refund',
                error: response.data,
                requestId: req.requestId
            });
        }
    } catch (error) {
        auditLog('ADMIN_REFUND_ERROR', { error: error.message }, req);
        res.status(500).json({
            success: false,
            message: 'Error processing refund',
            requestId: req.requestId
        });
    }
});

// Admin transactions page
router.get('/transactions', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>QuickBooks Payment Gateway - Transactions</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
                .container { max-width: 1400px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                h1 { text-align: center; color: #333; margin-bottom: 30px; }
                .nav { display: flex; gap: 20px; margin-bottom: 30px; }
                .nav a { padding: 10px 20px; background: #007cba; color: white; text-decoration: none; border-radius: 4px; }
                .nav a:hover { background: #005a87; }
                .nav a.active { background: #005a87; }
                
                /* Search Section */
                .search-section { background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 25px; }
                .search-controls { display: flex; gap: 15px; align-items: end; flex-wrap: wrap; }
                .search-group { display: flex; flex-direction: column; }
                .search-group label { font-weight: bold; margin-bottom: 5px; color: #333; }
                .search-group input, .search-group select { padding: 8px 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
                .search-input { min-width: 250px; }
                .search-field { min-width: 150px; }
                .search-btn { padding: 8px 16px; background: #007cba; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
                .search-btn:hover { background: #005a87; }
                .clear-btn { padding: 8px 16px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
                .clear-btn:hover { background: #545b62; }
                
                /* Transaction Stats */
                .stats-section { display: flex; gap: 20px; margin-bottom: 25px; }
                .stat-card { background: linear-gradient(135deg, #007cba, #005a87); color: white; padding: 15px; border-radius: 6px; flex: 1; text-align: center; }
                .stat-number { font-size: 24px; font-weight: bold; }
                .stat-label { font-size: 12px; opacity: 0.9; }
                
                /* Table */
                .transactions-table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px; }
                .transactions-table th, .transactions-table td { padding: 12px 8px; text-align: left; border-bottom: 1px solid #ddd; }
                .transactions-table th { background: #f8f9fa; font-weight: bold; position: sticky; top: 0; }
                .transactions-table tr:hover { background: #f8f9fa; }
                
                /* Column widths */
                .col-name { width: 200px; }
                .col-email { width: 200px; }
                .col-transaction-id { width: 150px; }
                .col-card { width: 100px; text-align: center; }
                .col-amount { width: 100px; text-align: right; }
                .col-status { width: 100px; text-align: center; }
                .col-actions { width: 150px; text-align: center; }
                
                .status { padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
                .status.captured { background: #d4edda; color: #155724; }
                .status.settled { background: #d1ecf1; color: #0c5460; }
                .status.declined { background: #f8d7da; color: #721c24; }
                .status.pending { background: #fff3cd; color: #856404; }
                .status.authorized { background: #cce5ff; color: #004085; }
                
                .action-btn { padding: 6px 12px; border: none; border-radius: 4px; cursor: pointer; margin: 2px; font-size: 12px; }
                .refund-btn { background: #dc3545; color: white; }
                .refund-btn:hover { background: #c82333; }
                .view-btn { background: #007cba; color: white; }
                .view-btn:hover { background: #005a87; }
                
                .loading { text-align: center; padding: 20px; color: #666; }
                .error { color: red; text-align: center; padding: 20px; }
                .success { color: green; text-align: center; padding: 20px; }
                
                /* Card number styling */
                .card-digits { font-family: monospace; font-weight: bold; color: #333; }
                
                /* Email styling */
                .email-cell { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
                
                .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
                .modal-content { background: white; margin: 5% auto; padding: 20px; border-radius: 8px; width: 80%; max-width: 500px; max-height: 90vh; overflow-y: auto; }
                .close { float: right; font-size: 28px; font-weight: bold; cursor: pointer; }
                .form-group { margin-bottom: 15px; }
                .form-group label { display: block; margin-bottom: 5px; }
                .form-group input, .form-group textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
                
                /* Transaction Details Modal Styles */
                .detail-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0; }
                .detail-row:last-child { border-bottom: none; }
                .detail-row strong { color: #333; min-width: 120px; }
                .text-success { color: #155724; }
                .text-warning { color: #856404; }
                
                /* Responsive */
                @media (max-width: 768px) {
                    .search-controls { flex-direction: column; align-items: stretch; }
                    .search-input, .search-field { min-width: auto; }
                    .stats-section { flex-direction: column; }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>🏢 QuickBooks Payment Gateway</h1>
                <h2 style="text-align: center; color: #666;">Transaction Management</h2>
                
                <div class="nav">
                    <a href="/admin/dashboard">Dashboard</a>
                    <a href="/admin/transactions" class="active">Transactions</a>
                    <a href="/admin/logout">Logout</a>
                </div>
                
                <!-- Search Section -->
                <div class="search-section">
                    <div class="search-controls">
                        <div class="search-group">
                            <label for="searchInput">🔍 Search</label>
                            <input type="text" id="searchInput" class="search-input" placeholder="Enter search term..." />
                        </div>
                        <div class="search-group">
                            <label for="searchField">Search In</label>
                            <select id="searchField" class="search-field">
                                <option value="transactionId">🎯 Transaction ID (Recommended)</option>
                                <option value="customerName">👤 Customer Name</option>
                                <option value="email">📧 Email Address</option>
                                <option value="amount">💰 Amount ($)</option>
                                <option value="all">🔍 All Fields</option>
                                <option value="firstName">First Name</option>
                                <option value="lastName">Last Name</option>
                            </select>
                        </div>
                        <div class="search-group">
                            <label>&nbsp;</label>
                            <button class="search-btn" onclick="searchTransactions()">Search</button>
                        </div>
                        <div class="search-group">
                            <label>&nbsp;</label>
                            <button class="clear-btn" onclick="clearSearch()">Clear</button>
                        </div>
                    </div>
                    <div style="margin-top: 10px; padding: 10px; background: #e7f3ff; border-radius: 4px; border-left: 4px solid #007cba;">
                        <strong>🔍 Search Options:</strong> Transaction ID (Payments API - works for all credit card transactions), Amount & Customer Name (QBO Accounting API - only works for customers who exist in accounting system). Email search not supported.
                    </div>
                </div>
                
                <!-- Stats Section -->
                <div class="stats-section">
                    <div class="stat-card">
                        <div class="stat-number" id="totalTransactions">-</div>
                        <div class="stat-label">Total Transactions</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="showingTransactions">-</div>
                        <div class="stat-label">Showing</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="searchStatus">All</div>
                        <div class="stat-label">Filter Applied</div>
                    </div>
                </div>
                
                <div id="transactions-container">
                    <div class="loading">Loading transactions...</div>
                </div>
            </div>

            <!-- Refund Modal -->
            <div id="refundModal" class="modal">
                <div class="modal-content">
                    <span class="close" onclick="closeRefundModal()">&times;</span>
                    <h3>Process Refund</h3>
                    <form id="refundForm">
                        <div class="form-group">
                            <label for="refundAmount">Refund Amount ($):</label>
                            <input type="number" id="refundAmount" step="0.01" min="0.01" required>
                            <small>Leave empty for full refund</small>
                        </div>
                        <div class="form-group">
                            <label for="refundReason">Reason:</label>
                            <textarea id="refundReason" rows="3" required>Customer request</textarea>
                        </div>
                        <button type="submit" class="action-btn refund-btn">Process Refund</button>
                        <button type="button" onclick="closeRefundModal()" class="action-btn">Cancel</button>
                    </form>
                </div>
            </div>
            
            <script>
                const apiKey = sessionStorage.getItem('adminApiKey');
                if (!apiKey) {
                    window.location.href = '/admin/login';
                }
                
                let currentTransactionId = null;
                let allTransactions = []; // Store all fetched transactions
                
                async function loadTransactions(searchTerm = '', searchField = 'all') {
                    const container = document.getElementById('transactions-container');
                    
                    try {
                        // Build URL with search parameters
                        let url = '/admin/api/transactions?limit=20'; // Load up to 20 transactions for testing
                        if (searchTerm) {
                            url += '&search=' + encodeURIComponent(searchTerm) + '&searchField=' + searchField;
                        }
                        
                        const response = await fetch(url, {
                            headers: {
                                'X-Admin-API-Key': apiKey
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            allTransactions = data.transactions;
                            
                            // Update stats
                            document.getElementById('totalTransactions').textContent = data.totalFetched || 0;
                            document.getElementById('showingTransactions').textContent = data.total;
                            document.getElementById('searchStatus').textContent = data.searchApplied ? 
                                '"' + data.searchTerm + '"' : 'All';
                            
                            if (data.transactions.length === 0) {
                                let message;
                                if (data.notice) {
                                    // Special notice from server (e.g., "search by transaction ID only")
                                    message = 
                                        '<div class="success">' +
                                            '<h3>📋 Transaction Search</h3>' +
                                            '<p><strong>' + data.message + '</strong></p>' +
                                            '<p>' + data.notice + '</p>' +
                                            '<p style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 4px; border-left: 4px solid #007cba;">' +
                                                '💡 <strong>How to search:</strong><br>' +
                                                '1. Select "Transaction ID (Recommended)" from the dropdown<br>' +
                                                '2. Enter your transaction ID (e.g., MS0289339177)<br>' +
                                                '3. Click Search' +
                                            '</p>' +
                                        '</div>';
                                } else {
                                    message = data.searchApplied ? 
                                        'No transactions found matching "' + data.searchTerm + '"' : 
                                        'No transactions found';
                                }
                                container.innerHTML = message;
                                return;
                            }
                            
                            displayTransactionTable(data.transactions);
                        } else {
                            // Show helpful message if bulk API is down
                            container.innerHTML = 
                                '<div class="error" style="text-align: left; padding: 20px;">' +
                                    '<h3 style="color: #721c24; margin-top: 0;">⚠️ Bulk Transaction Loading Unavailable</h3>' +
                                    '<p><strong>Issue:</strong> ' + data.message + '</p>' +
                                    '<p><strong>Workaround:</strong> Use Transaction ID search for specific transactions.</p>' +
                                    '<div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-top: 15px;">' +
                                        '<h4 style="margin-top: 0; color: #333;">🎯 How to Search by Transaction ID:</h4>' +
                                        '<ol style="margin-bottom: 0;">' +
                                            '<li>Select "Transaction ID (Recommended)" from the dropdown above</li>' +
                                            '<li>Enter your transaction ID (e.g., MQ0283554190)</li>' +
                                            '<li>Click Search</li>' +
                                        '</ol>' +
                                    '</div>' +
                                    '<p style="margin-bottom: 0; color: #666; font-size: 14px;">' +
                                        "<em>This issue is on QuickBooks' side and should resolve automatically.</em>" +
                                    '</p>' +
                                '</div>';
                        }
                    } catch (error) {
                        container.innerHTML = 
                            '<div class="error">' +
                                '<h3>Connection Error</h3>' +
                                '<p>Failed to load transactions. Please check your connection and try again.</p>' +
                                '<p><strong>Alternative:</strong> Use Transaction ID search for specific transactions.</p>' +
                            '</div>';
                    }
                }
                
                // [Rest of the JavaScript functions remain the same as in the original file...]
                // I'll include the key functions but truncate for brevity
                
                async function viewTransaction(transactionId) {
                    try {
                        console.log('Fetching transaction details for:', transactionId);
                        
                        const response = await fetch('/admin/api/transactions/' + transactionId, {
                            headers: {
                                'X-Admin-API-Key': apiKey
                            }
                        });
                        
                        console.log('Response status:', response.status);
                        
                        if (!response.ok) {
                            throw new Error('HTTP ' + response.status + ': ' + response.statusText);
                        }
                        
                        const data = await response.json();
                        console.log('Response data:', data);
                        
                        if (data.success) {
                            showTransactionModal(data.transaction);
                        } else {
                            alert('Failed to load transaction details: ' + (data.message || 'Unknown error'));
                        }
                    } catch (error) {
                        console.error('Error loading transaction details:', error);
                        alert('Error loading transaction details: ' + error.message + '. Please check the console for more details.');
                    }
                }
                
                function showTransactionModal(transaction) {
                    // Create a simple alert with transaction details for now
                    // TODO: Replace with proper modal later
                    const details = 
                        'Transaction Details:\\n\\n' +
                        'ID: ' + transaction.id + '\\n' +
                        'Amount: $' + transaction.amount + '\\n' +
                        'Status: ' + transaction.status + '\\n' +
                        'Created: ' + transaction.created + '\\n' +
                        'Card: ' + (transaction.card?.cardType || 'N/A') + ' - ' + (transaction.card?.number || 'N/A') + '\\n' +
                        'Cardholder: ' + (transaction.card?.name || 'N/A');
                    
                    alert(details);
                }
                
                function displayTransactionTable(transactions) {
                    const container = document.getElementById('transactions-container');
                    
                    if (!transactions || transactions.length === 0) {
                        container.innerHTML = '<div class="error">No transactions to display</div>';
                        return;
                    }
                    
                    let tableHTML = '<table class="transactions-table">' +
                        '<thead>' +
                            '<tr>' +
                                '<th class="col-name">Customer</th>' +
                                '<th class="col-email">Email</th>' +
                                '<th class="col-transaction-id">Transaction ID</th>' +
                                '<th class="col-card">Card</th>' +
                                '<th class="col-amount">Amount</th>' +
                                '<th class="col-status">Status</th>' +
                                '<th class="col-actions">Actions</th>' +
                            '</tr>' +
                        '</thead>' +
                        '<tbody>';
                    
                    transactions.forEach(transaction => {
                        const statusClass = transaction.status ? transaction.status.toLowerCase() : 'unknown';
                        const cardDisplay = transaction.card && transaction.card.number ? 
                            (transaction.card.cardType || 'Card') + ' - ' + transaction.card.number : 
                            'N/A';
                        
                        const refundButton = (transaction.status === 'CAPTURED' || transaction.status === 'SETTLED') ? 
                            '<button class="action-btn refund-btn" onclick="openRefundModal(' + "'" + transaction.id + "'" + ')">Refund</button>' : 
                            '';
                        
                        tableHTML += '<tr>' +
                            '<td class="col-name">' + (transaction.fullName || 'N/A') + '</td>' +
                            '<td class="col-email email-cell" title="' + (transaction.email || 'N/A') + '">' + (transaction.email || 'N/A') + '</td>' +
                            '<td class="col-transaction-id">' +
                                '<span class="card-digits">' + transaction.id + '</span>' +
                            '</td>' +
                            '<td class="col-card">' + cardDisplay + '</td>' +
                            '<td class="col-amount">$' + parseFloat(transaction.amount || 0).toFixed(2) + '</td>' +
                            '<td class="col-status">' +
                                '<span class="status ' + statusClass + '">' + (transaction.status || 'Unknown') + '</span>' +
                            '</td>' +
                            '<td class="col-actions">' +
                                '<button class="action-btn view-btn" onclick="viewTransaction(' + "'" + transaction.id + "'" + ')">View</button>' +
                                refundButton +
                            '</td>' +
                        '</tr>';
                    });
                    
                    tableHTML += '</tbody></table>';
                    container.innerHTML = tableHTML;
                }
                
                async function searchByTransactionId(transactionId) {
                    const container = document.getElementById('transactions-container');
                    container.innerHTML = '<div class="loading">Searching for transaction...</div>';
                    
                    try {
                        const response = await fetch('/admin/api/transactions/' + encodeURIComponent(transactionId), {
                            headers: {
                                'X-Admin-API-Key': apiKey
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (data.success && data.transaction) {
                            // Display single transaction as a list
                            allTransactions = [data.transaction];
                            
                            // Update stats
                            document.getElementById('totalTransactions').textContent = '1';
                            document.getElementById('showingTransactions').textContent = '1';
                            document.getElementById('searchStatus').textContent = '"' + transactionId + '"';
                            
                            displayTransactionTable([data.transaction]);
                        } else {
                            container.innerHTML = 
                                '<div class="error">' +
                                    '<h3>❌ Transaction Not Found</h3>' +
                                    '<p><strong>Transaction ID "' + transactionId + '" was not found.</strong></p>' +
                                    '<p>Please check the transaction ID and try again.</p>' +
                                    '<div style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 4px; border-left: 4px solid #dc3545;">' +
                                        '💡 <strong>Tips:</strong><br>' +
                                        '• Make sure the transaction ID is correct (e.g., MS0289339177)<br>' +
                                        '• Transaction IDs are case-sensitive<br>' +
                                        '• Only transactions processed through this gateway can be found' +
                                    '</div>' +
                                '</div>';
                            
                            // Reset stats
                            document.getElementById('totalTransactions').textContent = '0';
                            document.getElementById('showingTransactions').textContent = '0';
                            document.getElementById('searchStatus').textContent = '"' + transactionId + '"';
                        }
                    } catch (error) {
                        console.error('Error searching for transaction:', error);
                        container.innerHTML = 
                            '<div class="error">' +
                                '<h3>⚠️ Search Error</h3>' +
                                '<p>An error occurred while searching for the transaction.</p>' +
                                '<p>Please try again or contact support if the problem persists.</p>' +
                            '</div>';
                    }
                }
                
                function searchTransactions() {
                    const searchTerm = document.getElementById('searchInput').value.trim();
                    const searchField = document.getElementById('searchField').value;
                    
                    if (searchTerm.length === 0) {
                        alert('Please enter a search term');
                        return;
                    }
                    
                    // If searching by transaction ID, use direct lookup
                    if (searchField === 'transactionId') {
                        searchByTransactionId(searchTerm);
                    } else {
                        loadTransactions(searchTerm, searchField);
                    }
                }
                
                function clearSearch() {
                    document.getElementById('searchInput').value = '';
                    document.getElementById('searchField').value = 'transactionId';
                    loadTransactions(); // Load all transactions
                }
                
                // Refund Modal Functions
                function openRefundModal(transactionId) {
                    currentTransactionId = transactionId;
                    document.getElementById('refundModal').style.display = 'block';
                    document.getElementById('refundAmount').value = '';
                    document.getElementById('refundReason').value = 'Customer request';
                }
                
                function closeRefundModal() {
                    document.getElementById('refundModal').style.display = 'none';
                    currentTransactionId = null;
                }
                
                // Handle refund form submission
                document.addEventListener('DOMContentLoaded', function() {
                    document.getElementById('refundForm').addEventListener('submit', async function(e) {
                        e.preventDefault();
                        
                        if (!currentTransactionId) {
                            alert('No transaction selected for refund');
                            return;
                        }
                        
                        const amount = document.getElementById('refundAmount').value;
                        const reason = document.getElementById('refundReason').value;
                        
                        if (!reason.trim()) {
                            alert('Please provide a reason for the refund');
                            return;
                        }
                        
                        try {
                            const response = await fetch('/admin/api/transactions/' + currentTransactionId + '/refund', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-Admin-API-Key': apiKey
                                },
                                body: JSON.stringify({
                                    amount: amount || null,
                                    reason: reason
                                })
                            });
                            
                            const data = await response.json();
                            
                            if (data.success) {
                                alert('Refund processed successfully!');
                                closeRefundModal();
                                // Refresh the transaction display
                                if (allTransactions.length === 1) {
                                    // If showing single transaction, refresh it
                                    searchByTransactionId(currentTransactionId);
                                } else {
                                    // If showing multiple transactions, reload all
                                    loadTransactions();
                                }
                            } else {
                                alert('Refund failed: ' + data.message);
                            }
                        } catch (error) {
                            alert('Error processing refund. Please try again.');
                            console.error('Refund error:', error);
                        }
                    });
                });
                
                // Allow Enter key to trigger search
                document.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter' && document.activeElement.id === 'searchInput') {
                        searchTransactions();
                    }
                });
                
                // Close modal when clicking outside
                window.addEventListener('click', function(e) {
                    const modal = document.getElementById('refundModal');
                    if (e.target === modal) {
                        closeRefundModal();
                    }
                });
                
                // Load transactions on page load
                document.addEventListener('DOMContentLoaded', function() {
                    loadTransactions();
                });
            </script>
        </body>
        </html>
    `);
});

module.exports = router;
