// Walton Plaza POS System - Main Application

class WaltonPlazaApp {
    constructor() {
        this.init();
    }

    init() {
        this.initEventListeners();
        this.initCharts();
        this.initDataTables();
        this.initForms();
        this.initNotifications();
        this.initPrinting();
    }

    initEventListeners() {
        // Global search
        $('#globalSearch').on('keyup', this.debounce((e) => {
            this.performGlobalSearch(e.target.value);
        }, 500));

        // Sidebar toggle
        $('#sidebarToggle').click(() => {
            this.toggleSidebar();
        });

        // Auto refresh dashboard
        if (window.location.pathname.includes('dashboard')) {
            setInterval(() => {
                this.refreshDashboard();
            }, 300000); // Refresh every 5 minutes
        }
    }

    initCharts() {
        // Sales Chart
        const salesCtx = document.getElementById('salesChart');
        if (salesCtx) {
            this.salesChart = new Chart(salesCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Sales',
                        data: [],
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return '৳ ' + value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });

            this.loadSalesChartData();
        }

        // Payment Methods Chart
        const paymentCtx = document.getElementById('paymentChart');
        if (paymentCtx) {
            this.paymentChart = new Chart(paymentCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Cash', 'Card', 'Mobile Banking', 'Bank Transfer'],
                    datasets: [{
                        data: [0, 0, 0, 0],
                        backgroundColor: [
                            '#27ae60',
                            '#3498db',
                            '#f39c12',
                            '#9b59b6'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });

            this.loadPaymentChartData();
        }
    }

    initDataTables() {
        $('.data-table').DataTable({
            pageLength: 25,
            language: {
                search: "_INPUT_",
                searchPlaceholder: "Search...",
                lengthMenu: "Show _MENU_ entries",
                info: "Showing _START_ to _END_ of _TOTAL_ entries"
            },
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                 '<"row"<"col-sm-12"tr>>' +
                 '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
        });
    }

    initForms() {
        // Form validation
        $('form[data-validate]').each(function() {
            $(this).on('submit', function(e) {
                if (!this.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                $(this).addClass('was-validated');
            });
        });

        // Auto calculate fields
        $('[data-calc]').on('input change', () => {
            this.calculateFields();
        });

        // Date pickers
        $('.datepicker').flatpickr({
            dateFormat: 'Y-m-d',
            allowInput: true
        });

        // Time pickers
        $('.timepicker').flatpickr({
            enableTime: true,
            noCalendar: true,
            dateFormat: 'H:i',
            time_24hr: true
        });
    }

    initNotifications() {
        // WebSocket connection for real-time notifications
        if (window.Echo) {
            window.Echo.private('notifications')
                .listen('NewSale', (e) => {
                    this.showNotification('New Sale Created', 'success');
                    this.playSound('notification');
                })
                .listen('PaymentReceived', (e) => {
                    this.showNotification('Payment Received', 'success');
                    this.playSound('payment');
                })
                .listen('InstallmentDue', (e) => {
                    this.showNotification('Installment Due Reminder', 'warning');
                });
        }
    }

    initPrinting() {
        // Print handler
        window.printContent = (elementId) => {
            const printContent = document.getElementById(elementId).innerHTML;
            const originalContent = document.body.innerHTML;
            
            document.body.innerHTML = printContent;
            window.print();
            document.body.innerHTML = originalContent;
            
            // Reload to restore event listeners
            location.reload();
        };
    }

    // Utility Functions
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    formatCurrency(amount) {
        return new Intl.NumberFormat('bn-BD', {
            style: 'currency',
            currency: 'BDT',
            minimumFractionDigits: 2
        }).format(amount);
    }

    formatDate(date) {
        return new Date(date).toLocaleDateString('bn-BD', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    }

    showNotification(message, type = 'info') {
        const toast = $(`
            <div class="toast align-items-center text-white bg-${type} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `);

        $('.toast-container').append(toast);
        toast.toast({ delay: 5000 });
        toast.toast('show');
    }

    playSound(type) {
        const audio = new Audio(`/sounds/${type}.mp3`);
        audio.play().catch(e => console.log('Audio play failed:', e));
    }

    toggleSidebar() {
        $('.sidebar').toggleClass('collapsed');
        $('.main-content').toggleClass('expanded');
        
        // Save preference
        localStorage.setItem('sidebarCollapsed', $('.sidebar').hasClass('collapsed'));
    }

    performGlobalSearch(query) {
        if (query.length < 2) return;

        $.ajax({
            url: '/api/search',
            data: { query: query },
            success: (response) => {
                this.displaySearchResults(response);
            }
        });
    }

    displaySearchResults(results) {
        let html = '';
        
        if (results.customers.length) {
            html += '<h6>Customers</h6>';
            results.customers.forEach(c => {
                html += `<a href="/customers/${c.id}" class="dropdown-item">${c.name} (${c.phone})</a>`;
            });
        }
        
        if (results.products.length) {
            html += '<h6>Products</h6>';
            results.products.forEach(p => {
                html += `<a href="/products/${p.id}" class="dropdown-item">${p.name} (${p.code})</a>`;
            });
        }
        
        if (results.sales.length) {
            html += '<h6>Sales</h6>';
            results.sales.forEach(s => {
                html += `<a href="/sales/${s.id}" class="dropdown-item">${s.invoice_no}</a>`;
            });
        }

        $('#searchResults').html(html || '<p class="text-muted p-2">No results found</p>');
    }

    loadSalesChartData() {
        $.ajax({
            url: '/api/charts/sales',
            success: (data) => {
                this.salesChart.data.labels = data.labels;
                this.salesChart.data.datasets[0].data = data.values;
                this.salesChart.update();
            }
        });
    }

    loadPaymentChartData() {
        $.ajax({
            url: '/api/charts/payments',
            success: (data) => {
                this.paymentChart.data.datasets[0].data = data;
                this.paymentChart.update();
            }
        });
    }

    calculateFields() {
        const calcFields = $('[data-calc]');
        
        calcFields.each(function() {
            const formula = $(this).data('calc');
            const result = eval(formula);
            $(this).val(result);
        });
    }

    refreshDashboard() {
        if (!window.location.pathname.includes('dashboard')) return;

        $.ajax({
            url: '/api/dashboard/refresh',
            success: (data) => {
                $('#todaySales').text(this.formatCurrency(data.todaySales));
                $('#todayCollection').text(this.formatCurrency(data.todayCollection));
                $('#pendingInstallments').text(data.pendingInstallments);
                $('#lowStockCount').text(data.lowStockCount);
                
                this.loadSalesChartData();
                this.loadPaymentChartData();
            }
        });
    }

    exportData(type, format = 'excel') {
        const url = `/reports/export/${type}?format=${format}`;
        window.location.href = url;
    }

    printReport(reportId) {
        const printWindow = window.open('', '_blank');
        const reportContent = document.getElementById(reportId).innerHTML;
        
        printWindow.document.write(`
            <html>
                <head>
                    <title>Report</title>
                    <link href="/css/report.css" rel="stylesheet">
                </head>
                <body>
                    ${reportContent}
                    <script>
                        window.onload = function() {
                            window.print();
                            window.close();
                        }
                    <\/script>
                </body>
            </html>
        `);
        
        printWindow.document.close();
    }
}

// Initialize app when document is ready
$(document).ready(() => {
    window.waltonPlaza = new WaltonPlazaApp();
});

// Service Worker for PWA support
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js')
            .then(registration => {
                console.log('ServiceWorker registered');
            })
            .catch(err => {
                console.log('ServiceWorker registration failed:', err);
            });
    });
}