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');

// Customer details page
router.get('/customers/:customerId/details', (req, res) => {
    const { customerId } = req.params;
    
    res.send(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Admin: Customer Payment Management - QuickBooks Payment Gateway</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; }
                
                /* Customer Info Section */
                .customer-info { background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 25px; }
                .customer-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
                .customer-name { font-size: 24px; font-weight: bold; color: #333; }
                .customer-status { padding: 6px 12px; border-radius: 4px; font-size: 14px; font-weight: bold; }
                .customer-status.active { background: #d4edda; color: #155724; }
                .customer-status.inactive { background: #f8d7da; color: #721c24; }
                
                .customer-details { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
                .detail-group { }
                .detail-group h4 { margin: 0 0 10px 0; color: #555; font-size: 14px; text-transform: uppercase; }
                .detail-item { margin-bottom: 8px; }
                .detail-label { font-weight: bold; color: #333; }
                .detail-value { color: #666; }
                
                /* Balance styling */
                .balance-positive { color: #155724; font-weight: bold; font-size: 18px; }
                .balance-negative { color: #721c24; font-weight: bold; font-size: 18px; }
                .balance-zero { color: #666; font-size: 18px; }
                
                /* 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; }
                
                /* Tabs */
                .tabs { display: flex; gap: 5px; margin-bottom: 20px; border-bottom: 2px solid #ddd; }
                .tab { padding: 12px 20px; background: #f8f9fa; border: none; cursor: pointer; border-radius: 6px 6px 0 0; font-size: 14px; font-weight: bold; }
                .tab.active { background: #007cba; color: white; }
                .tab:hover:not(.active) { background: #e9ecef; }
                
                /* 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 for better layout */
                .transactions-table th:nth-child(1) { width: 120px; } /* Transaction ID */
                .transactions-table th:nth-child(2) { width: 100px; } /* Type */
                .transactions-table th:nth-child(3) { width: 100px; } /* Document # */
                .transactions-table th:nth-child(4) { width: 100px; } /* Date */
                .transactions-table th:nth-child(5) { width: 80px; text-align: right; } /* Amount */
                .transactions-table th:nth-child(6) { width: 80px; text-align: center; } /* Status */
                .transactions-table th:nth-child(7) { width: 200px; } /* Notes */
                .transactions-table th:nth-child(8) { width: 150px; text-align: center; } /* Actions */
                
                .transactions-table td:nth-child(5) { text-align: right; } /* Amount column */
                .transactions-table td:nth-child(6) { text-align: center; } /* Status column */
                .transactions-table td:nth-child(8) { text-align: center; } /* Actions column */
                
                .status { padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
                .status.sales_receipt { background: #d4edda; color: #155724; }
                .status.payment { background: #d1ecf1; color: #0c5460; }
                .status.captured { background: #d4edda; color: #155724; }
                .status.settled { background: #d1ecf1; color: #0c5460; }
                .status.declined { background: #f8d7da; color: #721c24; }
                .status.pending { background: #fff3cd; color: #856404; }
                
                .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; }
                .void-btn { background: #6c757d; color: white; }
                .void-btn:hover { background: #545b62; }
                .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; }
                
                .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; }
                .transaction-details { margin: 20px 0; }
                .detail-row { margin: 10px 0; padding: 8px 0; border-bottom: 1px solid #eee; }
                .detail-row:last-child { border-bottom: none; }
                .modal-actions { text-align: right; margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee; }
                .form-group { margin-bottom: 15px; }
                .form-group label { display: block; margin-bottom: 5px; }
                .form-group input, .form-group textarea, .form-group select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
                
                /* Responsive */
                @media (max-width: 768px) {
                    .customer-header { flex-direction: column; align-items: flex-start; gap: 10px; }
                    .customer-details { grid-template-columns: 1fr; }
                    .stats-section { flex-direction: column; }
                    .tabs { flex-wrap: wrap; }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>🔧 Admin: Customer Payment Management</h1>
                <h2 style="text-align: center; color: #666;">Employee Payment Management Tool</h2>
                
                <div class="nav">
                    <a href="/admin/dashboard">Admin Dashboard</a>
                    <a href="/admin/customers">Customer Management</a>
                    <a href="/admin/transactions">Transaction Search</a>
                    <a href="/admin/logout">Logout</a>
                </div>
                
                <!-- Customer Info Section -->
                <div class="customer-info" id="customer-info">
                    <div class="loading">Loading customer information...</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="totalReceipts">-</div>
                        <div class="stat-label">Sales Receipts</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalPayments">-</div>
                        <div class="stat-label">Payments</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalAmount">$0.00</div>
                        <div class="stat-label">Total Amount</div>
                    </div>
                </div>
                
                <!-- Admin Info -->
                <div style="margin-bottom: 20px; padding: 15px; background: #fff3cd; border-radius: 6px; border-left: 4px solid #ffc107;">
                    <strong>🔧 Admin Functions:</strong> Use this tool to monitor customer payments, process refunds, void transactions, and manage payment issues. All actions are logged for audit purposes.
                </div>
                
                <!-- Tabs -->
                <div class="tabs">
                    <button class="tab active" onclick="showTab('all')">All Transactions</button>
                    <button class="tab" onclick="showTab('sales-receipts')">Sales Receipts</button>
                    <button class="tab" onclick="showTab('refunds')">Refunds</button>
                    <button class="tab" onclick="showTab('payment-transactions')">Payment Transactions</button>
                </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">
                            <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>

            <!-- Void Modal -->
            <div id="voidModal" class="modal">
                <div class="modal-content">
                    <span class="close" onclick="closeVoidModal()">&times;</span>
                    <h3>Void Transaction</h3>
                    <form id="voidForm">
                        <div class="form-group">
                            <label for="voidReason">Reason for voiding:</label>
                            <select id="voidReason" required>
                                <option value="">Select reason...</option>
                                <option value="duplicate">Duplicate transaction</option>
                                <option value="error">Processing error</option>
                                <option value="customer_request">Customer request</option>
                                <option value="fraud">Suspected fraud</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="voidNotes">Additional notes:</label>
                            <textarea id="voidNotes" rows="3"></textarea>
                        </div>
                        <button type="submit" class="action-btn void-btn">Void Transaction</button>
                        <button type="button" onclick="closeVoidModal()" class="action-btn">Cancel</button>
                    </form>
                </div>
            </div>
            
            <script>
                const apiKey = sessionStorage.getItem('adminApiKey');
                if (!apiKey) {
                    window.location.href = '/admin/login';
                }
                
                const customerId = '${customerId}';
                let customerData = null;
                let allTransactions = [];
                let salesReceipts = [];
                let refundReceipts = [];
                let currentTab = 'all';
                let currentTransactionId = null;
                let currentTransactionType = null;
                
                async function loadCustomerDetails() {
                    try {
                        const response = await fetch(\`/admin/api/customers/\${customerId}\`, {
                            headers: {
                                'X-Admin-API-Key': apiKey
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            customerData = data.customer;
                            allTransactions = data.transactions;
                            salesReceipts = data.salesReceipts;
                            refundReceipts = data.refundReceipts;
                            
                            displayCustomerInfo(customerData);
                            updateStats(data.summary);
                            showTab(currentTab);
                        } else {
                            document.getElementById('customer-info').innerHTML = \`
                                <div class="error">
                                    <h3>Error Loading Customer</h3>
                                    <p>\${data.message}</p>
                                    <a href="/admin/customers" class="action-btn view-btn">Back to Customers</a>
                                </div>
                            \`;
                        }
                    } catch (error) {
                        document.getElementById('customer-info').innerHTML = \`
                            <div class="error">
                                <h3>Connection Error</h3>
                                <p>Failed to load customer details. Please check your connection and try again.</p>
                                <a href="/admin/customers" class="action-btn view-btn">Back to Customers</a>
                            </div>
                        \`;
                    }
                }
                
                function displayCustomerInfo(customer) {
                    const balance = parseFloat(customer.balance || 0);
                    const balanceClass = balance > 0 ? 'balance-positive' : balance < 0 ? 'balance-negative' : 'balance-zero';
                    const statusClass = customer.active ? 'active' : 'inactive';
                    
                    const customerInfoHTML = \`
                        <div class="customer-header">
                            <div>
                                <div class="customer-name">\${customer.displayName}</div>
                                \${customer.firstName || customer.lastName ? 
                                    \`<div style="color: #666; font-size: 16px;">\${customer.firstName} \${customer.lastName}</div>\` : 
                                    ''
                                }
                            </div>
                            <div class="customer-status \${statusClass}">\${customer.active ? 'Active' : 'Inactive'}</div>
                        </div>
                        
                        <div class="customer-details">
                            <div class="detail-group">
                                <h4>Contact Information</h4>
                                <div class="detail-item">
                                    <span class="detail-label">Email:</span>
                                    <span class="detail-value">\${customer.email}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">Phone:</span>
                                    <span class="detail-value">\${customer.phone}</span>
                                </div>
                                \${customer.companyName ? \`
                                    <div class="detail-item">
                                        <span class="detail-label">Company:</span>
                                        <span class="detail-value">\${customer.companyName}</span>
                                    </div>
                                \` : ''}
                            </div>
                            
                            <div class="detail-group">
                                <h4>Account Information</h4>
                                <div class="detail-item">
                                    <span class="detail-label">Customer ID:</span>
                                    <span class="detail-value">\${customer.id}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">Balance:</span>
                                    <span class="detail-value \${balanceClass}">$\${Math.abs(balance).toFixed(2)}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">Created:</span>
                                    <span class="detail-value">\${new Date(customer.created).toLocaleDateString()}</span>
                                </div>
                            </div>
                            
                            \${customer.billingAddress ? \`
                                <div class="detail-group">
                                    <h4>Billing Address</h4>
                                    <div class="detail-item">
                                        <span class="detail-value">
                                            \${customer.billingAddress.line1}<br>
                                            \${customer.billingAddress.line2 ? customer.billingAddress.line2 + '<br>' : ''}
                                            \${customer.billingAddress.city}, \${customer.billingAddress.state} \${customer.billingAddress.postalCode}<br>
                                            \${customer.billingAddress.country}
                                        </span>
                                    </div>
                                </div>
                            \` : ''}
                        </div>
                    \`;
                    
                    document.getElementById('customer-info').innerHTML = customerInfoHTML;
                }
                
                function updateStats(summary) {
                    document.getElementById('totalTransactions').textContent = summary.totalTransactions;
                    document.getElementById('totalReceipts').textContent = summary.totalSalesReceipts;
                    document.getElementById('totalPayments').textContent = summary.totalPayments;
                    document.getElementById('totalAmount').textContent = '$' + summary.totalAmount;
                }
                
                function showTab(tabName) {
                    currentTab = tabName;
                    
                    // Update tab buttons
                    document.querySelectorAll('.tab').forEach(tab => {
                        tab.classList.remove('active');
                    });
                    event?.target?.classList.add('active') || document.querySelector(\`[onclick="showTab('\${tabName}')"]\`).classList.add('active');
                    
                    let transactionsToShow = [];
                    
                    switch (tabName) {
                        case 'all':
                            transactionsToShow = allTransactions;
                            break;
                        case 'sales-receipts':
                            transactionsToShow = salesReceipts;
                            break;
                        case 'refunds':
                            transactionsToShow = refundReceipts;
                            break;
                        case 'payment-transactions':
                            loadPaymentTransactions();
                            return;
                    }
                    
                    displayTransactionTable(transactionsToShow);
                }
                
                async function loadPaymentTransactions() {
                    const container = document.getElementById('transactions-container');
                    container.innerHTML = '<div class="loading">Loading payment transactions...</div>';
                    
                    try {
                        const response = await fetch(\`/admin/api/customers/\${customerId}/payment-transactions\`, {
                            headers: {
                                'X-Admin-API-Key': apiKey
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            if (data.paymentTransactions.length === 0) {
                                container.innerHTML = \`
                                    <div class="success">
                                        <h3>💳 Payment Transactions</h3>
                                        <p><strong>\${data.message}</strong></p>
                                        <p>\${data.explanation}</p>
                                        <p style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 4px; border-left: 4px solid #007cba;">
                                            💡 <strong>\${data.recommendation}</strong>
                                        </p>
                                    </div>
                                \`;
                            } else {
                                displayTransactionTable(data.paymentTransactions);
                            }
                        } else {
                            container.innerHTML = \`<div class="error">Error: \${data.message}</div>\`;
                        }
                    } catch (error) {
                        container.innerHTML = '<div class="error">Failed to load payment transactions.</div>';
                    }
                }
                
                function displayTransactionTable(transactions) {
                    const container = document.getElementById('transactions-container');
                    
                    if (transactions.length === 0) {
                        container.innerHTML = '<div class="success">No transactions found for this customer.</div>';
                        return;
                    }
                    
                    let tableHTML = \`
                        <table class="transactions-table">
                            <thead>
                                <tr>
                                    <th>Transaction ID</th>
                                    <th>Type</th>
                                    <th>Document #</th>
                                    <th>Date</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Notes</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                    \`;
                    
                    transactions.forEach(transaction => {
                        const amount = parseFloat(transaction.totalAmount || 0).toFixed(2);
                        const statusClass = transaction.status.toLowerCase().replace('_', '');
                        const date = new Date(transaction.txnDate || transaction.created).toLocaleDateString();
                        
                        tableHTML += \`
                            <tr>
                                <td>
                                    <span style="font-family: monospace; background: #f5f5f5; padding: 2px 6px; border-radius: 3px; font-size: 12px;">
                                        \${transaction.id}
                                    </span>
                                </td>
                                <td>
                                    <span class="status \${statusClass}">\${transaction.type === 'receipt' ? 'Sales Receipt' : 'Payment'}</span>
                                </td>
                                <td>\${transaction.docNumber || transaction.paymentRefNum || 'N/A'}</td>
                                <td>\${date}</td>
                                <td>$\${amount}</td>
                                <td>
                                    <span class="status \${statusClass}">\${transaction.status}</span>
                                </td>
                                <td title="\${transaction.privateNote || ''}">\${(transaction.privateNote || '').substring(0, 50)}\${(transaction.privateNote || '').length > 50 ? '...' : ''}</td>
                                <td>
                                    <button class="action-btn view-btn" onclick="viewTransaction('\${transaction.id}', '\${transaction.type}')">📋 View Details</button>
                                    \${transaction.type === 'sales_receipt' && transaction.status === 'SALES_RECEIPT' ? 
                                        \`<button class="action-btn void-btn" onclick="openVoidModal('\${transaction.id}', 'receipt')">❌ Admin Void</button>\` : 
                                        ''
                                    }
                                    \${transaction.paymentTransactionId ? 
                                        \`<button class="action-btn refund-btn" onclick="openRefundModal('\${transaction.paymentTransactionId}', \${amount})">💰 Process Refund</button>\` : 
                                        ''
                                    }
                                </td>
                            </tr>
                        \`;
                    });
                    
                    tableHTML += '</tbody></table>';
                    container.innerHTML = tableHTML;
                }
                
                function viewTransaction(transactionId, type) {
                    // Find the transaction in our data
                    let transaction = null;
                    
                    if (type === 'sales_receipt') {
                        transaction = salesReceipts.find(p => p.id === transactionId);
                    } else if (type === 'refund') {
                        transaction = refundReceipts.find(r => r.id === transactionId);
                    } else {
                        // Look in all transactions
                        transaction = allTransactions.find(t => t.id === transactionId);
                    }
                    
                    if (!transaction) {
                        alert('Transaction not found');
                        return;
                    }
                    
                    // Create and show modal with transaction details
                    const modal = document.createElement('div');
                    modal.className = 'modal';
                    modal.style.display = 'block';
                    modal.innerHTML = \`
                        <div class="modal-content">
                            <span class="close" onclick="this.parentElement.parentElement.remove()">&times;</span>
                            <h2>Transaction Details</h2>
                            <div class="transaction-details">
                                <div class="detail-row">
                                    <strong>QuickBooks ID:</strong> \${transaction.id}
                                </div>
                                \${transaction.paymentTransactionId ? \`
                                <div class="detail-row" style="background: #e8f5e8; padding: 10px; border-radius: 4px;">
                                    <strong>🎯 Payment Transaction ID:</strong> \${transaction.paymentTransactionId}
                                    <br><small style="color: #666;">This ID can be searched in the main transactions page</small>
                                </div>
                                \` : ''}
                                <div class="detail-row">
                                    <strong>Type:</strong> \${transaction.type.toUpperCase().replace('_', ' ')}
                                </div>
                                <div class="detail-row">
                                    <strong>Date:</strong> \${new Date(transaction.txnDate).toLocaleDateString()}
                                </div>
                                <div class="detail-row">
                                    <strong>Amount:</strong> $\${Math.abs(parseFloat(transaction.totalAmount || 0)).toFixed(2)}
                                </div>
                                <div class="detail-row">
                                    <strong>Status:</strong> \${transaction.status}
                                </div>
                                \${transaction.privateNote ? \`
                                <div class="detail-row">
                                    <strong>Notes:</strong> \${transaction.privateNote}
                                </div>
                                \` : ''}
                                <div class="detail-row">
                                    <strong>Created:</strong> \${new Date(transaction.created).toLocaleString()}
                                </div>
                            </div>
                            <div class="modal-actions">
                                <button class="action-btn" onclick="this.parentElement.parentElement.parentElement.remove()">Close</button>
                            </div>
                        </div>
                    \`;
                    
                    document.body.appendChild(modal);
                }
                
                function openVoidModal(transactionId, type) {
                    currentTransactionId = transactionId;
                    currentTransactionType = type;
                    document.getElementById('voidModal').style.display = 'block';
                }
                
                function closeVoidModal() {
                    document.getElementById('voidModal').style.display = 'none';
                    currentTransactionId = null;
                    currentTransactionType = null;
                }
                
                function extractAndRefund(privateNote, amount) {
                    // Extract transaction ID from private note
                    const match = privateNote.match(/Transaction ID: ([A-Z0-9]+)/);
                    if (match) {
                        const transactionId = match[1];
                        openRefundModal(transactionId, amount);
                    } else {
                        alert('Could not extract payment transaction ID from receipt notes.');
                    }
                }
                
                function openRefundModal(transactionId, amount) {
                    currentTransactionId = transactionId;
                    document.getElementById('refundAmount').value = '';
                    document.getElementById('refundAmount').placeholder = \`Full refund: $\${amount}\`;
                    document.getElementById('refundModal').style.display = 'block';
                }
                
                function closeRefundModal() {
                    document.getElementById('refundModal').style.display = 'none';
                    currentTransactionId = null;
                }
                
                // Form handlers
                document.getElementById('refundForm').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    
                    const amount = document.getElementById('refundAmount').value;
                    const reason = document.getElementById('refundReason').value;
                    
                    try {
                        const response = await fetch(\`/admin/api/transactions/\${currentTransactionId}/refund\`, {
                            method: 'POST',
                            headers: {
                                'X-Admin-API-Key': apiKey,
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                amount: amount && parseFloat(amount) > 0 ? parseFloat(amount) : null,
                                reason: reason
                            })
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            alert('Refund processed successfully!');
                            closeRefundModal();
                            loadCustomerDetails(); // Reload the data
                        } else {
                            alert(\`Refund failed: \${data.message}\`);
                        }
                    } catch (error) {
                        alert('Error processing refund. Please try again.');
                    }
                });
                
                document.getElementById('voidForm').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    
                    const reason = document.getElementById('voidReason').value;
                    const notes = document.getElementById('voidNotes').value;
                    
                    // Note: Voiding sales receipts requires different API calls than refunding payments
                    alert('Void functionality not yet implemented for QuickBooks Online records. Use QuickBooks directly to void sales receipts.');
                    closeVoidModal();
                });
                
                // Close modals when clicking outside
                window.onclick = function(event) {
                    const refundModal = document.getElementById('refundModal');
                    const voidModal = document.getElementById('voidModal');
                    if (event.target === refundModal) {
                        closeRefundModal();
                    }
                    if (event.target === voidModal) {
                        closeVoidModal();
                    }
                }
                
                // Load customer details on page load
                document.addEventListener('DOMContentLoaded', function() {
                    loadCustomerDetails();
                });
            </script>
        </body>
        </html>
    `);
});

module.exports = router;
