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 customers list with search and pagination
router.get('/api/customers', async (req, res) => {
    try {
        auditLog('ADMIN_CUSTOMERS_REQUEST', {}, 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. 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) || 50; // Default 50 customers
        const search = req.query.search || '';
        const searchField = req.query.searchField || 'all';

        const QB_QBO_BASE_URL = config.QB_ENVIRONMENT === 'production' 
            ? 'https://quickbooks.api.intuit.com' 
            : 'https://sandbox-quickbooks.api.intuit.com';

        let query;
        let searchMethod;

        if (!search || search.length === 0) {
            // Get all customers (limited)
            query = `SELECT * FROM Customer MAXRESULTS ${limit}`;
            searchMethod = 'all_customers';
        } else {
            // Search customers based on field
            if (searchField === 'name' || searchField === 'displayName') {
                query = `SELECT * FROM Customer WHERE DisplayName LIKE '%${search.replace(/'/g, "''")}%' MAXRESULTS ${limit}`;
                searchMethod = 'search_by_name';
            } else if (searchField === 'email') {
                query = `SELECT * FROM Customer WHERE PrimaryEmailAddr LIKE '%${search.replace(/'/g, "''")}%' MAXRESULTS ${limit}`;
                searchMethod = 'search_by_email';
            } else if (searchField === 'firstName') {
                query = `SELECT * FROM Customer WHERE GivenName LIKE '%${search.replace(/'/g, "''")}%' MAXRESULTS ${limit}`;
                searchMethod = 'search_by_first_name';
            } else if (searchField === 'lastName') {
                query = `SELECT * FROM Customer WHERE FamilyName LIKE '%${search.replace(/'/g, "''")}%' MAXRESULTS ${limit}`;
                searchMethod = 'search_by_last_name';
            } else if (searchField === 'phone') {
                query = `SELECT * FROM Customer WHERE PrimaryPhone LIKE '%${search.replace(/'/g, "''")}%' MAXRESULTS ${limit}`;
                searchMethod = 'search_by_phone';
            } else {
                // Search all fields
                query = `SELECT * FROM Customer WHERE DisplayName LIKE '%${search.replace(/'/g, "''")}%' OR PrimaryEmailAddr LIKE '%${search.replace(/'/g, "''")}%' OR GivenName LIKE '%${search.replace(/'/g, "''")}%' OR FamilyName LIKE '%${search.replace(/'/g, "''")}%' MAXRESULTS ${limit}`;
                searchMethod = 'search_all_fields';
            }
        }

        console.log(`[DEBUG] Customer search method: ${searchMethod}`);
        console.log(`[DEBUG] Customer query: ${query}`);

        const encodedQuery = encodeURIComponent(query);
        const apiUrl = `${QB_QBO_BASE_URL}/v3/company/${realmId}/query?query=${encodedQuery}`;

        const options = {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Accept': 'application/json',
                'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                'Request-Id': req.requestId
            },
            timeout: 15000
        };

        auditLog('ADMIN_CUSTOMERS_QUERY_REQUEST', { 
            url: apiUrl, 
            searchMethod,
            searchField,
            search,
            realmId,
            environment: config.QB_ENVIRONMENT
        }, req);

        const response = await makeHttpsRequest(apiUrl, options);

        if (response.status !== 200) {
            throw new Error(`Customer query failed with status ${response.status}`);
        }

        let customers = [];
        if (response.data && response.data.QueryResponse && response.data.QueryResponse.Customer) {
            customers = Array.isArray(response.data.QueryResponse.Customer) 
                ? response.data.QueryResponse.Customer 
                : [response.data.QueryResponse.Customer];
        }

        // Transform customers to standardized format
        const transformedCustomers = customers.map(customer => ({
            id: customer.Id,
            displayName: customer.DisplayName || 'Unknown',
            firstName: customer.GivenName || '',
            lastName: customer.FamilyName || '',
            email: customer.PrimaryEmailAddr?.Address || 'No email',
            phone: customer.PrimaryPhone?.FreeFormNumber || 'No phone',
            companyName: customer.CompanyName || '',
            balance: customer.Balance || '0.00',
            active: customer.Active !== false,
            created: customer.MetaData?.CreateTime || 'Unknown',
            lastUpdated: customer.MetaData?.LastUpdatedTime || 'Unknown',
            billingAddress: customer.BillAddr ? {
                line1: customer.BillAddr.Line1 || '',
                line2: customer.BillAddr.Line2 || '',
                city: customer.BillAddr.City || '',
                state: customer.BillAddr.CountrySubDivisionCode || '',
                postalCode: customer.BillAddr.PostalCode || '',
                country: customer.BillAddr.Country || 'US'
            } : null,
            originalData: customer
        }));

        auditLog('ADMIN_CUSTOMERS_SUCCESS', { 
            count: transformedCustomers.length,
            searchField,
            search
        }, req);

        res.json({
            success: true,
            customers: transformedCustomers,
            total: transformedCustomers.length,
            searchApplied: search ? true : false,
            searchTerm: search,
            searchField: searchField,
            message: transformedCustomers.length === 0 ? 'No customers found' : `Found ${transformedCustomers.length} customers`,
            requestId: req.requestId
        });

    } catch (error) {
        auditLog('ADMIN_CUSTOMERS_ERROR', { error: error.message, stack: error.stack }, req);
        
        console.error(`[ERROR] Customer fetch failed:`, error.message);
        
        let userMessage = 'Error fetching customers';
        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('401') || error.message.includes('Authentication')) {
            userMessage = 'Authentication failed. Please reconnect your QuickBooks account.';
            statusCode = 401;
        }
        
        res.status(statusCode).json({
            success: false,
            message: userMessage,
            error: error.message,
            requestId: req.requestId
        });
    }
});

// Get customer details with transactions and receipts
router.get('/api/customers/:customerId', async (req, res) => {
    try {
        const { customerId } = req.params;
        auditLog('ADMIN_CUSTOMER_DETAILS_REQUEST', { customerId }, 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
                });
            }
        }

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

        const QB_QBO_BASE_URL = config.QB_ENVIRONMENT === 'production' 
            ? 'https://quickbooks.api.intuit.com' 
            : 'https://sandbox-quickbooks.api.intuit.com';

        // Get customer details
        const customerQuery = `SELECT * FROM Customer WHERE Id = '${customerId}'`;
        const encodedCustomerQuery = encodeURIComponent(customerQuery);
        const customerApiUrl = `${QB_QBO_BASE_URL}/v3/company/${realmId}/query?query=${encodedCustomerQuery}`;

        // Get customer's sales receipts (contains actual payment transaction IDs)
        const salesReceiptQuery = `SELECT * FROM SalesReceipt WHERE CustomerRef = '${customerId}'`;
        const encodedSalesReceiptQuery = encodeURIComponent(salesReceiptQuery);
        const salesReceiptApiUrl = `${QB_QBO_BASE_URL}/v3/company/${realmId}/query?query=${encodedSalesReceiptQuery}`;

        // Get customer's refund receipts (for refunds)
        const refundReceiptQuery = `SELECT * FROM RefundReceipt WHERE CustomerRef = '${customerId}'`;
        const encodedRefundReceiptQuery = encodeURIComponent(refundReceiptQuery);
        const refundReceiptApiUrl = `${QB_QBO_BASE_URL}/v3/company/${realmId}/query?query=${encodedRefundReceiptQuery}`;

        const options = {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Accept': 'application/json',
                'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                'Request-Id': req.requestId
            },
            timeout: 15000
        };

        // Execute all queries in parallel
        const [customerResponse, salesReceiptResponse, refundReceiptResponse] = await Promise.all([
            makeHttpsRequest(customerApiUrl, options),
            makeHttpsRequest(salesReceiptApiUrl, options),
            makeHttpsRequest(refundReceiptApiUrl, options)
        ]);

        // Process customer data
        let customer = null;
        if (customerResponse.data && customerResponse.data.QueryResponse && customerResponse.data.QueryResponse.Customer) {
            const customerData = Array.isArray(customerResponse.data.QueryResponse.Customer) 
                ? customerResponse.data.QueryResponse.Customer[0] 
                : customerResponse.data.QueryResponse.Customer;
            
            customer = {
                id: customerData.Id,
                displayName: customerData.DisplayName || 'Unknown',
                firstName: customerData.GivenName || '',
                lastName: customerData.FamilyName || '',
                email: customerData.PrimaryEmailAddr?.Address || 'No email',
                phone: customerData.PrimaryPhone?.FreeFormNumber || 'No phone',
                companyName: customerData.CompanyName || '',
                balance: customerData.Balance || '0.00',
                active: customerData.Active !== false,
                created: customerData.MetaData?.CreateTime || 'Unknown',
                lastUpdated: customerData.MetaData?.LastUpdatedTime || 'Unknown',
                billingAddress: customerData.BillAddr ? {
                    line1: customerData.BillAddr.Line1 || '',
                    line2: customerData.BillAddr.Line2 || '',
                    city: customerData.BillAddr.City || '',
                    state: customerData.BillAddr.CountrySubDivisionCode || '',
                    postalCode: customerData.BillAddr.PostalCode || '',
                    country: customerData.BillAddr.Country || 'US'
                } : null
            };
        }

        if (!customer) {
            return res.status(404).json({
                success: false,
                message: 'Customer not found',
                requestId: req.requestId
            });
        }

        // Process sales receipts (contains actual payment transaction IDs)
        let salesReceipts = [];
        if (salesReceiptResponse.data && salesReceiptResponse.data.QueryResponse && salesReceiptResponse.data.QueryResponse.SalesReceipt) {
            const salesReceiptData = Array.isArray(salesReceiptResponse.data.QueryResponse.SalesReceipt) 
                ? salesReceiptResponse.data.QueryResponse.SalesReceipt 
                : [salesReceiptResponse.data.QueryResponse.SalesReceipt];
            
            salesReceipts = salesReceiptData.map(receipt => ({
                id: receipt.Id,
                docNumber: receipt.DocNumber || 'N/A', // This contains the payment transaction ID
                txnDate: receipt.TxnDate || 'Unknown',
                totalAmount: receipt.TotalAmt || '0.00',
                privateNote: receipt.PrivateNote || '', // Contains "Transaction ID: XXXXX"
                created: receipt.MetaData?.CreateTime || 'Unknown',
                status: 'SALES_RECEIPT',
                type: 'sales_receipt',
                paymentTransactionId: receipt.DocNumber, // The actual payment transaction ID
                originalData: receipt
            }));
        }

        // Process refund receipts
        let refundReceipts = [];
        if (refundReceiptResponse.data && refundReceiptResponse.data.QueryResponse && refundReceiptResponse.data.QueryResponse.RefundReceipt) {
            const refundData = Array.isArray(refundReceiptResponse.data.QueryResponse.RefundReceipt) 
                ? refundReceiptResponse.data.QueryResponse.RefundReceipt 
                : [refundReceiptResponse.data.QueryResponse.RefundReceipt];
            
            refundReceipts = refundData.map(refund => ({
                id: refund.Id,
                docNumber: refund.DocNumber || 'N/A',
                txnDate: refund.TxnDate || 'Unknown',
                totalAmount: `-${refund.TotalAmt || '0.00'}`, // Negative for refund
                privateNote: refund.PrivateNote || '',
                created: refund.MetaData?.CreateTime || 'Unknown',
                status: 'REFUND',
                type: 'refund',
                originalData: refund
            }));
        }

        // Combine and sort all transactions by date
        const allTransactions = [...salesReceipts, ...refundReceipts].sort((a, b) => {
            return new Date(b.created) - new Date(a.created);
        });

        auditLog('ADMIN_CUSTOMER_DETAILS_SUCCESS', { 
            customerId, 
            salesReceiptsCount: salesReceipts.length,
            refundReceiptsCount: refundReceipts.length,
            totalTransactions: allTransactions.length
        }, req);

        res.json({
            success: true,
            customer: customer,
            transactions: allTransactions,
            salesReceipts: salesReceipts,
            refundReceipts: refundReceipts,
            summary: {
                totalTransactions: allTransactions.length,
                totalSalesReceipts: salesReceipts.length,
                totalRefunds: refundReceipts.length,
                totalAmount: allTransactions.reduce((sum, t) => sum + parseFloat(t.totalAmount || 0), 0).toFixed(2)
            },
            requestId: req.requestId
        });

    } catch (error) {
        auditLog('ADMIN_CUSTOMER_DETAILS_ERROR', { error: error.message, customerId: req.params.customerId }, req);
        res.status(500).json({
            success: false,
            message: 'Error fetching customer details',
            error: error.message,
            requestId: req.requestId
        });
    }
});

// Get payment transactions for a customer (from Payments API)
router.get('/api/customers/:customerId/payment-transactions', async (req, res) => {
    try {
        const { customerId } = req.params;
        auditLog('ADMIN_CUSTOMER_PAYMENT_TRANSACTIONS_REQUEST', { customerId }, 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
                });
            }
        }

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

        // Note: The QuickBooks Payments API doesn't have a direct way to search by customer ID
        // This is a limitation of the API. We would need to:
        // 1. Get all charges and filter by customer name/email (not efficient)
        // 2. Store payment transaction IDs when creating sales receipts (recommended)
        // 3. Use the sales receipt's private note field to store payment transaction IDs

        // For now, we'll return a helpful message explaining the limitation
        res.json({
            success: true,
            paymentTransactions: [],
            message: 'Payment transaction lookup by customer ID is not directly supported by QuickBooks Payments API',
            explanation: 'The Payments API and QuickBooks Online API are separate systems. To link them, payment transaction IDs should be stored in sales receipt notes when payments are processed.',
            recommendation: 'Use the Transaction ID search in the main transactions page to find specific payment transactions.',
            requestId: req.requestId
        });

    } catch (error) {
        auditLog('ADMIN_CUSTOMER_PAYMENT_TRANSACTIONS_ERROR', { error: error.message, customerId: req.params.customerId }, req);
        res.status(500).json({
            success: false,
            message: 'Error fetching customer payment transactions',
            error: error.message,
            requestId: req.requestId
        });
    }
});

// Customers page
router.get('/customers', (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>Admin: Customer Payment Management - QuickBooks 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; }
                
                /* 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; }
                
                /* Customer 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 */
                .customers-table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px; }
                .customers-table th, .customers-table td { padding: 12px 8px; text-align: left; border-bottom: 1px solid #ddd; }
                .customers-table th { background: #f8f9fa; font-weight: bold; position: sticky; top: 0; }
                .customers-table tr:hover { background: #f8f9fa; }
                
                /* Column widths */
                .col-name { width: 200px; }
                .col-email { width: 200px; }
                .col-phone { width: 150px; }
                .col-company { width: 150px; }
                .col-balance { width: 100px; text-align: right; }
                .col-status { width: 80px; text-align: center; }
                .col-actions { width: 120px; text-align: center; }
                
                .status { padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
                .status.active { background: #d4edda; color: #155724; }
                .status.inactive { background: #f8d7da; color: #721c24; }
                
                .action-btn { padding: 6px 12px; border: none; border-radius: 4px; cursor: pointer; margin: 2px; font-size: 12px; }
                .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; }
                
                /* Email styling */
                .email-cell { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
                
                /* Balance styling */
                .balance-positive { color: #155724; font-weight: bold; }
                .balance-negative { color: #721c24; font-weight: bold; }
                .balance-zero { color: #666; }
                
                /* 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>🔧 Admin: Customer Payment Management</h1>
                <h2 style="text-align: center; color: #666;">Employee Tool - Monitor & Manage Customer Payments</h2>
                
                <div class="nav">
                    <a href="/admin/dashboard">Admin Dashboard</a>
                    <a href="/admin/customers" class="active">Customer Management</a>
                    <a href="/admin/transactions">Transaction Search</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 Customers</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="all">🔍 All Fields</option>
                                <option value="name">👤 Display Name</option>
                                <option value="email">📧 Email Address</option>
                                <option value="firstName">First Name</option>
                                <option value="lastName">Last Name</option>
                                <option value="phone">📞 Phone Number</option>
                            </select>
                        </div>
                        <div class="search-group">
                            <label>&nbsp;</label>
                            <button class="search-btn" onclick="searchCustomers()">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>💡 Employee Tool:</strong> Search QuickBooks customer records to monitor payments, process refunds, void transactions, and manage customer payment history.
                    </div>
                </div>
                
                <!-- Stats Section -->
                <div class="stats-section">
                    <div class="stat-card">
                        <div class="stat-number" id="totalCustomers">-</div>
                        <div class="stat-label">Total Customers</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="showingCustomers">-</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="customers-container">
                    <div class="loading">Loading customers...</div>
                </div>
            </div>
            
            <script>
                const apiKey = sessionStorage.getItem('adminApiKey');
                if (!apiKey) {
                    window.location.href = '/admin/login';
                }
                
                let allCustomers = []; // Store all fetched customers
                
                async function loadCustomers(searchTerm = '', searchField = 'all') {
                    const container = document.getElementById('customers-container');
                    
                    try {
                        // Build URL with search parameters
                        let url = '/admin/api/customers?limit=50';
                        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) {
                            allCustomers = data.customers;
                            
                            // Update stats
                            document.getElementById('totalCustomers').textContent = data.total;
                            document.getElementById('showingCustomers').textContent = data.total;
                            document.getElementById('searchStatus').textContent = data.searchApplied ? 
                                \`"\${data.searchTerm}"\` : 'All';
                            
                            if (data.customers.length === 0) {
                                const message = data.searchApplied ? 
                                    \`No customers found matching "\${data.searchTerm}"\` : 
                                    'No customers found';
                                container.innerHTML = \`<div class="success">\${message}</div>\`;
                                return;
                            }
                            
                            displayCustomerTable(data.customers);
                        } else {
                            container.innerHTML = \`
                                <div class="error">
                                    <h3>Error Loading Customers</h3>
                                    <p>\${data.message}</p>
                                </div>
                            \`;
                        }
                    } catch (error) {
                        container.innerHTML = \`
                            <div class="error">
                                <h3>Connection Error</h3>
                                <p>Failed to load customers. Please check your connection and try again.</p>
                            </div>
                        \`;
                    }
                }
                
                function displayCustomerTable(customers) {
                    const container = document.getElementById('customers-container');
                    
                    let tableHTML = \`
                        <table class="customers-table">
                            <thead>
                                <tr>
                                    <th class="col-name">Customer Name</th>
                                    <th class="col-email">Email</th>
                                    <th class="col-phone">Phone</th>
                                    <th class="col-company">Company</th>
                                    <th class="col-balance">Balance</th>
                                    <th class="col-status">Status</th>
                                    <th class="col-actions">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                    \`;
                    
                    customers.forEach(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';
                        
                        tableHTML += \`
                            <tr>
                                <td class="col-name" title="\${customer.displayName}">
                                    <strong>\${customer.displayName}</strong>
                                    \${customer.firstName || customer.lastName ? 
                                        \`<br><small style="color: #666;">\${customer.firstName} \${customer.lastName}</small>\` : 
                                        ''
                                    }
                                </td>
                                <td class="col-email email-cell" title="\${customer.email}">\${customer.email}</td>
                                <td class="col-phone">\${customer.phone}</td>
                                <td class="col-company">\${customer.companyName || '-'}</td>
                                <td class="col-balance">
                                    <span class="\${balanceClass}">$\${Math.abs(balance).toFixed(2)}</span>
                                </td>
                                <td class="col-status">
                                    <span class="status \${statusClass}">\${customer.active ? 'Active' : 'Inactive'}</span>
                                </td>
                                <td class="col-actions">
                                    <button class="action-btn view-btn" onclick="viewCustomer('\${customer.id}')">🔧 Manage Payments</button>
                                </td>
                            </tr>
                        \`;
                    });
                    
                    tableHTML += '</tbody></table>';
                    container.innerHTML = tableHTML;
                }
                
                function viewCustomer(customerId) {
                    // Navigate to customer details page
                    window.location.href = \`/admin/customers/\${customerId}/details\`;
                }
                
                function searchCustomers() {
                    const searchTerm = document.getElementById('searchInput').value.trim();
                    const searchField = document.getElementById('searchField').value;
                    
                    loadCustomers(searchTerm, searchField);
                }
                
                function clearSearch() {
                    document.getElementById('searchInput').value = '';
                    document.getElementById('searchField').value = 'all';
                    updatePlaceholder();
                    loadCustomers(); // Load all customers
                }
                
                // Update placeholder text based on selected search field
                function updatePlaceholder() {
                    const searchField = document.getElementById('searchField').value;
                    const searchInput = document.getElementById('searchInput');
                    
                    const placeholders = {
                        'all': 'Search customers by name, email, phone...',
                        'name': 'Enter customer display name...',
                        'email': 'Enter email address...',
                        'firstName': 'Enter first name...',
                        'lastName': 'Enter last name...',
                        'phone': 'Enter phone number...'
                    };
                    
                    searchInput.placeholder = placeholders[searchField] || 'Enter search term...';
                }
                
                // Allow Enter key to trigger search
                document.addEventListener('DOMContentLoaded', function() {
                    document.getElementById('searchInput').addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            searchCustomers();
                        }
                    });
                    
                    // Update placeholder when search field changes
                    document.getElementById('searchField').addEventListener('change', updatePlaceholder);
                    
                    // Set initial placeholder
                    updatePlaceholder();
                    
                    // Load customers on page load
                    loadCustomers();
                });
            </script>
        </body>
        </html>
    `);
});

module.exports = router;
