// Theme Applier - Enhanced version for receipts and dynamic content
(function() {
    'use strict';
    
    console.log('Theme Applier loaded');
    
    // Store settings globally
    window.themeSettings = window.themeSettings || {};
    window.hotelSettings = window.hotelSettings || {};
    
    // Function to apply theme from settings
    function applyTheme() {
        console.log('Applying theme...');

        function applyThemeClass(mode) {
            const body = document.body;
            if (!body) return;

            body.classList.remove('theme-light', 'theme-dark');

            if (mode === 'dark') {
                body.classList.add('theme-dark');
            } else {
                body.classList.add('theme-light');
            }
        }
        
        // Use hotelSettings if available (from @hotelSettings directive)
        if (window.hotelSettings) {
            console.log('Using hotelSettings:', window.hotelSettings);
            
            // Apply theme mode class to body
            if (window.hotelSettings.theme && window.hotelSettings.theme.mode) {
                const mode = window.hotelSettings.theme.mode === 'dark' ? 'dark' : 'light';
                applyThemeClass(mode);
            }
            
            // Apply theme variables as CSS custom properties
            const root = document.documentElement;
            if (window.hotelSettings.theme && window.hotelSettings.theme.variables) {
                Object.keys(window.hotelSettings.theme.variables).forEach(key => {
                    root.style.setProperty(key, window.hotelSettings.theme.variables[key]);
                });
            }
            
            // Update page title with hotel name if not already updated
            if (window.hotelSettings.name && document.title) {
                // Check if title already contains the hotel name
                if (!document.title.includes(window.hotelSettings.name)) {
                    // If title has a dash or pipe separator, replace the second part
                    const titleParts = document.title.split(/[-\|]/);
                    if (titleParts.length > 1) {
                        document.title = titleParts[0].trim() + ' - ' + window.hotelSettings.name;
                    } else {
                        // Just append if no separator
                        document.title = document.title + ' - ' + window.hotelSettings.name;
                    }
                }
            }
            
            console.log('Theme applied from hotelSettings');
            return true;
        }
        
        // Fallback to themeSettings if available
        if (window.themeSettings) {
            console.log('Using themeSettings:', window.themeSettings);
            
            const mode = window.themeSettings.mode === 'dark' ? 'dark' : 'light';
            applyThemeClass(mode);
            
            const root = document.documentElement;
            if (window.themeSettings.variables) {
                Object.keys(window.themeSettings.variables).forEach(key => {
                    root.style.setProperty(key, window.themeSettings.variables[key]);
                });
            }
            
            console.log('Theme applied from themeSettings');
            return true;
        }
        
        console.log('No theme settings found');
        return false;
    }
    
    // Function to update receipts with hotel settings
    function updateReceiptsWithHotelSettings() {
        if (!window.hotelSettings) return;
        
        // Update hotel name in receipts
        document.querySelectorAll('.hotel-name, .receipt-header .hotel-name, .receipt-header h5, .hotel-name').forEach(el => {
            if (el && window.hotelSettings.name) {
                el.textContent = window.hotelSettings.name;
            }
        });
        
        // Update hotel address
        document.querySelectorAll('.hotel-address, .receipt-header .hotel-details').forEach(el => {
            if (el && window.hotelSettings.address) {
                el.textContent = window.hotelSettings.address;
            }
        });
        
        // Update hotel phone
        document.querySelectorAll('.hotel-phone, .receipt-header .hotel-details').forEach(el => {
            if (el && window.hotelSettings.phone && el.textContent.includes('Tel:')) {
                el.textContent = 'Tel: ' + window.hotelSettings.phone;
            }
        });
        
        // Update VAT rate in receipts
        document.querySelectorAll('.vat-rate, .vat-section').forEach(el => {
            if (el && window.hotelSettings.vat_rate) {
                el.textContent = el.textContent.replace(/\d+%/, window.hotelSettings.vat_rate + '%');
            }
        });
    }
    
    // Function to observe DOM changes and apply theme to new content
    function observeDomChanges() {
        const observer = new MutationObserver(function(mutations) {
            let needsUpdate = false;
            
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    // Check if any new node contains receipt or modal content
                    const hasReceiptContent = Array.from(mutation.addedNodes).some(node => {
                        if (node.nodeType === 1) {
                            return node.classList && (
                                node.classList.contains('receipt-print') ||
                                node.classList.contains('modal-content') ||
                                node.id === 'receiptContent' ||
                                node.id === 'orderDetailsContent' ||
                                node.querySelector('.receipt-header') ||
                                node.querySelector('.hotel-name')
                            );
                        }
                        return false;
                    });
                    
                    if (hasReceiptContent) {
                        needsUpdate = true;
                    }
                }
            });
            
            if (needsUpdate) {
                setTimeout(() => {
                    applyTheme();
                    updateReceiptsWithHotelSettings();
                }, 100);
            }
        });
        
        observer.observe(document.body, { childList: true, subtree: true });
    }
    
    // Apply theme immediately
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            applyTheme();
            updateReceiptsWithHotelSettings();
            observeDomChanges();
        });
    } else {
        applyTheme();
        updateReceiptsWithHotelSettings();
        observeDomChanges();
    }
    
    // Also apply when any modal is shown
    document.addEventListener('shown.bs.modal', function() {
        setTimeout(() => {
            applyTheme();
            updateReceiptsWithHotelSettings();
        }, 200);
    });
    
    // Apply when any AJAX content is loaded
    document.addEventListener('ajaxComplete', function() {
        setTimeout(() => {
            applyTheme();
            updateReceiptsWithHotelSettings();
        }, 100);
    });
    
    console.log('Enhanced Theme Applier loaded');
})();

// Keep your existing displayReceipt function
function displayReceipt(order) {
    // Use hotel settings from global variable
    const hotel = window.hotelSettings || {
        name: 'Deluxe Hotel',
        address: '123 Luxury Avenue, Kampala',
        phone: '+256 123 456 789',
        vat_rate: 18,
        currency: 'UGX'
    };
    
    const ugTime = new Date(order.created_at).toLocaleString('en-UG', { 
        timeZone: 'Africa/Kampala',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });

    let itemsHtml = '';
    order.items.forEach(item => {
        itemsHtml += `
            <tr>
                <td>${item.name}</td>
                <td class="text-center">${item.quantity}</td>
                <td class="text-end">${formatNumber(item.total_price)}</td>
            </tr>
        `;
    });

    const html = `
        <div class="receipt-print">
            <div class="text-center mb-3">
                <h5 class="hotel-name">${hotel.name}</h5>
                <p class="hotel-address mb-0 small">${hotel.address}</p>
                <p class="hotel-phone small">Tel: ${hotel.phone}</p>
                <hr>
            </div>

            <div class="small">
                <p><strong>Order #:</strong> ${order.order_number}</p>
                <p><strong>Date:</strong> ${ugTime}</p>
                <p><strong>Customer:</strong> ${order.customer_name || 'Walk-in Customer'}</p>
                <p><strong>Type:</strong> ${order.order_type_display}</p>
                ${order.table_number ? `<p><strong>Table:</strong> ${order.table_number}</p>` : ''}
                ${order.room_number ? `<p><strong>Room:</strong> ${order.room_number}</p>` : ''}
            </div>

            <hr>

            <table class="w-100 small">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th class="text-center">Qty</th>
                        <th class="text-end">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    ${itemsHtml}
                </tbody>
            </table>

            <hr>

            <div class="small">
                <div class="d-flex justify-content-between">
                    <span>Subtotal:</span>
                    <span>${hotel.currency} ${formatNumber(order.subtotal)}</span>
                </div>
                <div class="d-flex justify-content-between">
                    <span>Tax (${hotel.vat_rate}%):</span>
                    <span>${hotel.currency} ${formatNumber(order.tax_amount)}</span>
                </div>
                <div class="d-flex justify-content-between">
                    <span>Service (10%):</span>
                    <span>${hotel.currency} ${formatNumber(order.service_charge)}</span>
                </div>
                <hr>
                <div class="d-flex justify-content-between fw-bold">
                    <span>TOTAL:</span>
                    <span>${hotel.currency} ${formatNumber(order.total_amount)}</span>
                </div>
            </div>

            <hr>

            <div class="text-center small">
                <p>Thank you for your order!</p>
                <p>Please visit again</p>
            </div>
        </div>
    `;

    document.getElementById('receiptContent').innerHTML = html;
}

// Keep your existing formatNumber function
function formatNumber(num) {
    return parseFloat(num || 0).toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}