/**
 * Dashboard JavaScript
 * Handles fetching and rendering dashboard data
 */

document.addEventListener('DOMContentLoaded', function () {
    // Initial load
    loadDashboardData();

    // Filter click handlers
    document.querySelectorAll('[data-filter]').forEach(item => {
        item.addEventListener('click', function (e) {
            e.preventDefault();
            const section = this.dataset.filter;
            const period = this.dataset.period;
            const label = this.textContent;

            // Update dropdown label
            if (section === 'income') {
                document.getElementById('incomeFilterLabel').textContent = label;
                loadIncomeData(period);
            } else if (section === 'products') {
                document.getElementById('productsFilterLabel').textContent = label;
                loadProductsData(period);
            }
        });
    });
});

async function loadDashboardData() {
    try {
        const response = await fetch('api/dashboard.php?section=all');
        const data = await response.json();

        if (data.success) {
            const dashboard = data.data;

            // 1. Render Top Stats
            renderStats(dashboard.stats);

            // 2. Render Charts
            renderCharts(dashboard.charts);

            // 3. Render Recent Orders
            renderRecentOrders(dashboard.recent_orders);

            // 4. Render Order Status Summary
            renderOrderStatus(dashboard.order_status);

            // 5. Render Low Stock
            renderLowStock(dashboard.low_stock);

            // 6. Render Best Selling Products
            renderBestSellingProducts(dashboard.best_selling_products);

            // 7. Render Best Selling Categories
            renderBestSellingCategories(dashboard.best_selling_categories);

            // 8. Render Recent Refunds
            renderRecentRefunds(dashboard.recent_refunds);

        } else {
            console.error('Failed to load dashboard data:', data.message);
        }
    } catch (error) {
        console.error('Error loading dashboard data:', error);
    }
}

async function loadIncomeData(period) {
    try {
        const chartContainer = document.querySelector("#monthly_income");
        chartContainer.style.opacity = '0.5';

        const response = await fetch(`api/dashboard.php?section=income&period=${period}`);
        const data = await response.json();

        if (data.success) {
            // Update chart
            const chartData = data.data;
            if (window.incomeChart) {
                window.incomeChart.updateOptions({
                    series: [{
                        name: 'Income',
                        data: chartData.data
                    }],
                    xaxis: {
                        categories: chartData.labels
                    }
                });
            }
        }
        chartContainer.style.opacity = '1';
    } catch (error) {
        console.error('Error loading income data:', error);
    }
}

async function loadProductsData(period) {
    try {
        const tableBody = document.getElementById('bestSellingProductsTable');
        tableBody.innerHTML = '<tr><td colspan="5" class="text-center">Loading...</td></tr>';

        const response = await fetch(`api/dashboard.php?section=products&period=${period}`);
        const data = await response.json();

        if (data.success) {
            renderBestSellingProducts(data.data);
        }
    } catch (error) {
        console.error('Error loading products data:', error);
    }
}

function renderStats(stats) {
    document.getElementById('totalRevenue').textContent = formatCurrency(stats.revenue);
    document.getElementById('totalOrders').textContent = stats.orders.toLocaleString();
    document.getElementById('totalCustomers').textContent = stats.customers.toLocaleString();
    document.getElementById('totalProducts').textContent = stats.products.toLocaleString();
    document.getElementById('activeProductsCount').textContent = stats.products.toLocaleString();
}

function renderCharts(charts) {
    // Monthly Income Chart
    const incomeOptions = {
        series: [{
            name: 'Income',
            data: charts.monthly_income.data
        }],
        chart: {
            height: 350,
            type: 'area',
            toolbar: { show: false }
        },
        colors: ['#22c55e'],
        dataLabels: { enabled: false },
        stroke: { curve: 'smooth', width: 2 },
        xaxis: {
            categories: charts.monthly_income.labels,
        },
        yaxis: {
            labels: {
                formatter: function (value) {
                    return "$" + value.toLocaleString();
                }
            }
        },
        tooltip: {
            y: {
                formatter: function (value) {
                    return "$" + value.toLocaleString();
                }
            }
        }
    };

    // Destroy existing chart if any
    if (window.incomeChart) {
        window.incomeChart.destroy();
    }
    window.incomeChart = new ApexCharts(document.querySelector("#monthly_income"), incomeOptions);
    window.incomeChart.render();

    // New Customers Chart
    const customerOptions = {
        series: [{
            name: 'New Customers',
            data: charts.new_customers.map(item => item.count)
        }],
        chart: {
            height: 350,
            type: 'bar',
            toolbar: { show: false }
        },
        colors: ['#08b0e7'],
        plotOptions: {
            bar: {
                borderRadius: 4,
                columnWidth: '45%',
            }
        },
        dataLabels: { enabled: false },
        xaxis: {
            categories: charts.new_customers.map(item => item.day),
        }
    };
    new ApexCharts(document.querySelector("#customers"), customerOptions).render();
}

function renderRecentOrders(orders) {
    const container = document.getElementById('recentOrdersTable');
    if (!orders || orders.length === 0) {
        container.innerHTML = '<tr><td colspan="2" class="text-center text-muted">No recent orders</td></tr>';
        return;
    }

    container.innerHTML = orders.map(order => `
        <tr>
            <td class="px-0">
                <a href="order-details.php?id=${order.id}" class="text-primary fw-semibold">#${order.order_number}</a>
                <p class="mb-0 text-muted fs-12">${order.customer_first_name} ${order.customer_last_name}</p>
            </td>
            <td class="text-end">
                <h6 class="m-0">${formatCurrency(order.total_amount)}</h6>
                <span class="badge ${getPaymentStatusClass(order.payment_status)} px-2 fs-11">${capitalize(order.payment_status)}</span>
            </td>
        </tr>
    `).join('');
}

function renderOrderStatus(statusData) {
    const container = document.getElementById('orderStatusSummary');
    const counts = statusData.counts;
    const percentages = statusData.percentages;

    const statuses = [
        { key: 'fulfilled', label: 'Fulfilled', icon: 'iconoir-check-circle', color: 'success' },
        { key: 'unfulfilled', label: 'Pending', icon: 'iconoir-clock', color: 'warning' },
        { key: 'shipped', label: 'Shipped', icon: 'iconoir-delivery-truck', color: 'info' },
        { key: 'cancelled', label: 'Cancelled', icon: 'iconoir-xmark-circle', color: 'danger' }
    ];

    container.innerHTML = statuses.map(status => `
        <div class="mb-3">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="d-flex align-items-center">
                    <i class="${status.icon} text-${status.color} me-2 fs-5"></i>
                    <span class="text-dark">${status.label}</span>
                </div>
                <span class="fw-semibold">${counts[status.key] || 0}</span>
            </div>
            <div class="progress" style="height: 6px;">
                <div class="progress-bar bg-${status.color}" role="progressbar" style="width: ${percentages[status.key] || 0}%" aria-valuenow="${percentages[status.key] || 0}" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div>
    `).join('');
}

function renderLowStock(products) {
    const container = document.getElementById('lowStockList');
    document.getElementById('lowStockCount').textContent = `${products.length} Items`;

    if (!products || products.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-3">No low stock items</div>';
        return;
    }

    container.innerHTML = products.map(product => `
        <div class="d-flex align-items-center mb-3 pb-3 border-bottom">
            <img src="${product.image ? '../' + product.image : 'assets/images/products/01.png'}" height="40" class="me-3 rounded" alt="...">
            <div class="flex-grow-1">
                <h6 class="m-0 text-truncate">${product.title}</h6>
                <small class="text-danger">Only ${product.min_stock} left</small>
            </div> 
            <a href="product-detail.php?slug=${product.slug}" class="btn btn-sm btn-soft-primary">View</a>
        </div>
    `).join('');
}

function renderBestSellingProducts(products) {
    const container = document.getElementById('bestSellingProductsTable');

    if (!products || products.length === 0) {
        container.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No sales yet</td></tr>';
        return;
    }

    container.innerHTML = products.map(product => `
        <tr>                                                        
            <td>
                <div class="d-flex align-items-center">
                    <img src="${product.image ? '../' + product.image : 'assets/images/products/01.png'}" height="40" class="me-3 align-self-center rounded" alt="...">
                    <div class="flex-grow-1 text-truncate"> 
                        <h6 class="m-0">${product.title}</h6>
                        <a href="product-detail.php?slug=${product.slug}" class="fs-12 text-primary">${product.category || 'Uncategorized'}</a>                                                                                           
                    </div>
                </div>
            </td>
            <td>${formatCurrency(product.price)}</td>                                   
            <td>${product.total_sold} <small class="text-muted">sold</small></td>
            <td><span class="badge bg-success-subtle text-success px-2">${capitalize(product.status)}</span></td>
            <td>                                                       
                <a href="product-detail.php?slug=${product.slug}"><i class="las la-pen text-secondary fs-18"></i></a>
            </td>
        </tr>
    `).join('');
}

function renderBestSellingCategories(categories) {
    const container = document.getElementById('bestSellingCategoriesList');

    if (!categories || categories.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-3">No sales data</div>';
        return;
    }

    const colors = ['primary', 'info', 'warning', 'success', 'danger'];
    const icons = ['iconoir-droplet', 'iconoir-wind', 'iconoir-flask', 'iconoir-battery-75', 'iconoir-settings'];

    // Calculate max sold for progress bar
    const maxSold = Math.max(...categories.map(c => c.total_sold));

    container.innerHTML = categories.map((cat, index) => {
        const color = colors[index % colors.length];
        const icon = icons[index % icons.length];
        const percentage = maxSold > 0 ? Math.round((cat.total_sold / maxSold) * 100) : 0;

        return `
        <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="d-flex align-items-center">
                    <div class="avatar-sm bg-${color}-subtle text-${color} rounded me-3 d-flex align-items-center justify-content-center">
                        <i class="${icon} fs-4"></i>
                    </div>
                    <div>
                        <h6 class="m-0">${cat.title}</h6>
                        <small class="text-muted">${cat.total_sold} sold</small>
                    </div>
                </div>
                <div class="text-end">
                    <h5 class="m-0 fw-bold">${formatCurrency(cat.total_revenue)}</h5>
                </div>
            </div>
            <div class="progress" style="height: 8px;">
                <div class="progress-bar bg-${color}" role="progressbar" style="width: ${percentage}%" aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div>
        `;
    }).join('');
}

function renderRecentRefunds(refunds) {
    const container = document.getElementById('recentRefundsTable');

    if (!refunds || refunds.length === 0) {
        container.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No recent refunds</td></tr>';
        return;
    }

    container.innerHTML = refunds.map(refund => `
        <tr>
            <td class="px-0">
                <a href="refunds.php" class="text-primary fw-semibold">#${refund.refund_number}</a>
                <p class="mb-0 text-muted fs-11">${new Date(refund.created_at).toLocaleDateString()}</p>
            </td>
            <td>
                <h6 class="m-0 fs-13">${refund.first_name} ${refund.last_name}</h6>
                <small class="text-muted">${refund.refund_reason}</small>
            </td>
            <td class="fw-semibold">${formatCurrency(refund.refund_amount)}</td>
            <td class="text-end">
                <span class="badge bg-success-subtle text-success px-2">Refunded</span>
            </td>
        </tr>
    `).join('');
}

// Helper Functions
function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

function capitalize(str) {
    if (!str) return '';
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function getPaymentStatusClass(status) {
    switch (status) {
        case 'paid': return 'bg-success-subtle text-success';
        case 'pending': return 'bg-warning-subtle text-warning';
        case 'failed': return 'bg-danger-subtle text-danger';
        default: return 'bg-secondary-subtle text-secondary';
    }
}
