(function() {
    var refreshInterval = null;
    var REFRESH_MS = 15000;
    var monthlySalesChart = null;
    var repairStatusChart = null;

    function formatCurrency(amount) {
        var symbol = 'Rs.';
        return symbol + ' ' + parseFloat(amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function getStatusBadge(status) {
        var map = {
            'Pending': 'badge-pending', 'Completed': 'badge-completed', 'Cancelled': 'badge-cancelled',
            'Delivered': 'badge-delivered', 'Received': 'badge-pending', 'Checking': 'badge-waiting',
            'Waiting for Customer Approval': 'badge-waiting', 'Waiting for Parts': 'badge-waiting',
            'Repairing': 'badge-repairing', 'Cannot Repair': 'badge-cancelled',
            'Paid': 'badge-completed', 'Due': 'badge-pending', 'Partial': 'badge-waiting'
        };
        var cls = map[status] || 'badge-primary';
        return '<span class="badge ' + cls + '">' + $('<span>').text(status).html() + '</span>';
    }

    function updateCards(stats) {
        $('#stat-today-sales').text(formatCurrency(stats.today_sales));
        $('#stat-repair-income').text(formatCurrency(stats.today_repair_income));
        $('#stat-pending-repairs').text(stats.pending_repairs);
        $('#stat-completed-repairs').text(stats.completed_repairs);
        $('#stat-low-stock').text(stats.low_stock);
        $('#stat-total-customers').text(stats.total_customers);
        $('#stat-total-products').text(stats.total_products);
        $('#stat-total-invoices').text(stats.total_invoices);
        $('#stat-today-purchases').text(stats.today_purchases);
        $('#stat-supplier-due').text(formatCurrency(stats.supplier_due));
        $('#stat-customer-due').text(formatCurrency(stats.customer_due));
        $('#stat-today-expenses').text(formatCurrency(stats.today_expenses));
        $('#stat-net-profit').text(formatCurrency(stats.net_profit));
    }

    function updateRecentSales(sales) {
        var tbody = $('#recent-sales-tbody');
        if (!tbody.length) return;
        tbody.empty();
        if (!sales || sales.length === 0) {
            tbody.append('<tr><td colspan="5" class="text-muted">No recent sales.</td></tr>');
            return;
        }
        $.each(sales, function(i, s) {
            tbody.append(
                '<tr>' +
                '<td>' + $('<span>').text(s.invoice_no).html() + '</td>' +
                '<td>' + $('<span>').text(s.customer_name || 'Walk-in').html() + '</td>' +
                '<td>' + formatCurrency(s.total_amount) + '</td>' +
                '<td>' + getStatusBadge(s.payment_status) + '</td>' +
                '<td>' + (s.invoice_date || '-') + '</td>' +
                '</tr>'
            );
        });
    }

    function updateRecentRepairs(repairs) {
        var tbody = $('#recent-repairs-tbody');
        if (!tbody.length) return;
        tbody.empty();
        if (!repairs || repairs.length === 0) {
            tbody.append('<tr><td colspan="4" class="text-muted">No recent repairs.</td></tr>');
            return;
        }
        $.each(repairs, function(i, r) {
            tbody.append(
                '<tr>' +
                '<td>' + $('<span>').text(r.job_no).html() + '</td>' +
                '<td>' + $('<span>').text(r.customer_name || '-').html() + '</td>' +
                '<td>' + getStatusBadge(r.repair_status) + '</td>' +
                '<td>' + (r.created_at || '-') + '</td>' +
                '</tr>'
            );
        });
    }

    function updateLowStockProducts(products) {
        var tbody = $('#low-stock-tbody');
        if (!tbody.length) return;
        tbody.empty();
        if (!products || products.length === 0) {
            tbody.append('<tr><td colspan="3" class="text-muted">No low stock items.</td></tr>');
            return;
        }
        $.each(products, function(i, p) {
            tbody.append(
                '<tr>' +
                '<td>' + $('<span>').text(p.product_name).html() + '</td>' +
                '<td>' + p.current_stock + '</td>' +
                '<td>' + p.low_stock_qty + '</td>' +
                '</tr>'
            );
        });
    }

    function updateCharts(data) {
        var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

        // Monthly Sales Chart
        var salesData = new Array(12).fill(0);
        if (data.monthly_sales_chart) {
            $.each(data.monthly_sales_chart, function(i, v) {
                salesData[v.month - 1] = parseFloat(v.total) || 0;
            });
        }

        if (monthlySalesChart) {
            monthlySalesChart.data.datasets[0].data = salesData;
            monthlySalesChart.update();
        } else if (document.getElementById('monthlySalesChart')) {
            var ctx = document.getElementById('monthlySalesChart').getContext('2d');
            monthlySalesChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: months,
                    datasets: [{
                        label: 'Sales',
                        data: salesData,
                        borderColor: '#1a237e',
                        backgroundColor: 'rgba(26,35,126,0.1)',
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { display: false } },
                    scales: { y: { beginAtZero: true } }
                }
            });
        }

        // Repair Status Chart
        var labels = [], values = [], colors = [];
        var colorMap = {
            'Received': '#ef6c00', 'Checking': '#f9a825', 'Waiting for Customer Approval': '#ffb300',
            'Waiting for Parts': '#ff8f00', 'Repairing': '#7b1fa2', 'Completed': '#2e7d32',
            'Delivered': '#0277bd', 'Cancelled': '#c62828', 'Cannot Repair': '#d32f2f'
        };
        if (data.repair_status_chart) {
            $.each(data.repair_status_chart, function(i, v) {
                labels.push(v.status);
                values.push(parseInt(v.count) || 0);
                colors.push(colorMap[v.status] || '#999');
            });
        }

        if (repairStatusChart) {
            repairStatusChart.data.labels = labels;
            repairStatusChart.data.datasets[0].data = values;
            repairStatusChart.data.datasets[0].backgroundColor = colors;
            repairStatusChart.update();
        } else if (document.getElementById('repairStatusChart')) {
            var ctx2 = document.getElementById('repairStatusChart').getContext('2d');
            repairStatusChart = new Chart(ctx2, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{ data: values, backgroundColor: colors }]
                },
                options: { responsive: true, plugins: { legend: { position: 'bottom' } } }
            });
        }
    }

    function updateLastUpdated() {
        var now = new Date();
        var pad = function(n) { return n < 10 ? '0' + n : n; };
        var str = now.getFullYear() + '-' + pad(now.getMonth()+1) + '-' + pad(now.getDate()) +
                  ' ' + pad(now.getHours()) + ':' + pad(now.getMinutes()) + ':' + pad(now.getSeconds());
        $('#dashboard-last-updated').text(str);
    }

    function loadDashboardData() {
        $.ajax({
            url: BASE_URL + 'admin/dashboard_data.php',
            type: 'GET',
            dataType: 'json',
            timeout: 10000,
            success: function(resp) {
                if (resp.success) {
                    updateCards(resp.stats);
                    updateRecentSales(resp.recent_sales);
                    updateRecentRepairs(resp.recent_repairs);
                    updateLowStockProducts(resp.low_stock_products);
                    updateCharts(resp);
                    updateLastUpdated();
                } else {
                    $('#dashboard-error').html('<div class="alert alert-warning alert-dismissible fade show">Dashboard data error: ' + (resp.message || 'Unknown') + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('#dashboard-error').html('<div class="alert alert-warning alert-dismissible fade show">Failed to refresh dashboard: ' + textStatus + '. Data shown is from last successful load.<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>');
            }
        });
    }

    $(document).ready(function() {
        if (typeof BASE_URL === 'undefined') {
            BASE_URL = 'http://localhost/DigiMobiz/';
        }

        // Initial load
        loadDashboardData();

        // Auto-refresh
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
        refreshInterval = setInterval(loadDashboardData, REFRESH_MS);

        // Manual refresh
        $('#refresh-dashboard-btn').on('click', function() {
            $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Refreshing...');
            loadDashboardData();
            var btn = $(this);
            setTimeout(function() {
                btn.prop('disabled', false).html('<i class="fas fa-sync-alt me-1"></i>Refresh Now');
            }, 1000);
        });
    });
})();
