// Sales Reports Dashboard JavaScript

$(document).ready(function() {
    // Initialize the dashboard
    initializeDashboard();
    
    // Setup event listeners
    setupEventListeners();
    
    // Load initial data
    loadSummaryStats();
    loadDropdownData();
    loadCharts();
});

/**
 * Initialize Dashboard
 */
function initializeDashboard() {
    // Set default date to current month
    $('#filterDateRange').val('this_month');
    
    // Initialize date inputs
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    $('#customDateFrom').val(formatDate(firstDay));
    $('#customDateTo').val(formatDate(lastDay));
}

/**
 * Setup Event Listeners
 */
function setupEventListeners() {
    // Date range filter change
    $('#filterDateRange').on('change', function() {
        const value = $(this).val();
        if (value === 'custom') {
            $('#customDateRangeContainer').show();
            $('#customDateToContainer').show();
        } else {
            $('#customDateRangeContainer').hide();
            $('#customDateToContainer').hide();
            loadSummaryStats();
            loadCharts();
        }
    });
    
    // Custom date change
    $('#customDateFrom, #customDateTo').on('change', function() {
        if ($('#filterDateRange').val() === 'custom') {
            loadSummaryStats();
            loadCharts();
        }
    });
    
    // Filter changes
    $('#filterSalesType, #filterCustomer, #filterCategory').on('change', function() {
        loadSummaryStats();
        loadCharts();
    });
    
    // Reset filters
    $('#resetFilters').on('click', function() {
        resetFilters();
    });
}

/**
 * Load Summary Statistics
 */
function loadSummaryStats() {
    const filters = getFilters();
    
    // Show loading state
    $('#totalSalesAmount, #totalInvoices, #totalItemsSold, #avgInvoiceValue').html('<i class="fas fa-spinner fa-spin"></i>');
    
    $.ajax({
        url: 'api/get-dashboard-stats.php',
        type: 'GET',
        data: filters,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const data = response.data;
                
                // Update stats with animation
                animateValue('totalSalesAmount', 0, parseFloat(data.totalSalesAmount), 1000, true);
                animateValue('totalInvoices', 0, parseInt(data.totalInvoices), 1000, false);
                animateValue('totalItemsSold', 0, parseInt(data.totalItemsSold), 1000, false);
                animateValue('avgInvoiceValue', 0, parseFloat(data.avgInvoiceValue), 1000, true);
            } else {
                showError('Failed to load statistics');
                resetStats();
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading stats:', error);
            showError('Error loading statistics');
            resetStats();
        }
    });
}

/**
 * Load Dropdown Data
 */
function loadDropdownData() {
    // Load Sales Types
    $.ajax({
        url: '../api/get-sales-types.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success && response.data) {
                const select = $('#filterSalesType');
                select.empty().append('<option value="">All Sales Types</option>');
                response.data.forEach(function(type) {
                    select.append(`<option value="${type.SalesType}">${type.SalesType}</option>`);
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading sales types:', error);
        }
    });
    
    // Load Customers
    $.ajax({
        url: '../api/get-customers.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success && response.customers) {
                const select = $('#filterCustomer');
                select.empty().append('<option value="">All Customers</option>');
                response.customers.forEach(function(customer) {
                    select.append(`<option value="${customer.ID}">${customer.CustomerName} - ${customer.Mobile}</option>`);
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading customers:', error);
        }
    });
    
    // Load Categories
    $.ajax({
        url: '../api/get-categories.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success && response.data) {
                const select = $('#filterCategory');
                select.empty().append('<option value="">All Categories</option>');
                response.data.forEach(function(category) {
                    select.append(`<option value="${category.ID}">${category.CategoryName}</option>`);
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading categories:', error);
        }
    });
}

/**
 * Load Charts
 */
let salesTrendChart = null;
let salesTypeChart = null;

function loadCharts() {
    const filters = getFilters();
    
    // Load Sales Trend Chart
    $.ajax({
        url: 'api/get-sales-trend.php',
        type: 'GET',
        data: filters,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                renderSalesTrendChart(response.data);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading sales trend:', error);
        }
    });
    
    // Load Sales Type Chart
    $.ajax({
        url: 'api/get-sales-by-type.php',
        type: 'GET',
        data: filters,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                renderSalesTypeChart(response.data);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading sales by type:', error);
        }
    });
}

/**
 * Render Sales Trend Chart
 */
function renderSalesTrendChart(data) {
    const ctx = document.getElementById('salesTrendChart');
    
    if (salesTrendChart) {
        salesTrendChart.destroy();
    }
    
    salesTrendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: data.labels,
            datasets: [{
                label: 'Sales Amount',
                data: data.values,
                borderColor: 'rgb(78, 115, 223)',
                backgroundColor: 'rgba(78, 115, 223, 0.05)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0,0,0,0.8)',
                    padding: 12,
                    titleFont: { size: 14 },
                    bodyFont: { size: 13 },
                    callbacks: {
                        label: function(context) {
                            return 'Amount: ₹' + formatNumber(context.parsed.y);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '₹' + formatNumber(value);
                        }
                    }
                }
            }
        }
    });
}

/**
 * Render Sales Type Chart
 */
function renderSalesTypeChart(data) {
    const ctx = document.getElementById('salesTypeChart');
    
    if (salesTypeChart) {
        salesTypeChart.destroy();
    }
    
    const colors = [
        'rgba(78, 115, 223, 0.8)',
        'rgba(28, 200, 138, 0.8)',
        'rgba(54, 185, 204, 0.8)',
        'rgba(246, 194, 62, 0.8)',
        'rgba(231, 74, 59, 0.8)',
        'rgba(133, 135, 150, 0.8)'
    ];
    
    salesTypeChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: data.labels,
            datasets: [{
                data: data.values,
                backgroundColor: colors.slice(0, data.labels.length),
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 15,
                        font: { size: 12 }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0,0,0,0.8)',
                    padding: 12,
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = formatNumber(context.parsed);
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((context.parsed / total) * 100).toFixed(1);
                            return `${label}: ₹${value} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

/**
 * Get Current Filters
 */
function getFilters() {
    const dateRange = $('#filterDateRange').val();
    let filters = {
        dateRange: dateRange,
        salesType: $('#filterSalesType').val(),
        customer: $('#filterCustomer').val(),
        category: $('#filterCategory').val()
    };
    
    if (dateRange === 'custom') {
        filters.dateFrom = $('#customDateFrom').val();
        filters.dateTo = $('#customDateTo').val();
    }
    
    return filters;
}

/**
 * Reset Filters
 */
function resetFilters() {
    $('#filterDateRange').val('this_month');
    $('#filterSalesType').val('');
    $('#filterCustomer').val('');
    $('#filterCategory').val('');
    $('#customDateRangeContainer').hide();
    $('#customDateToContainer').hide();
    
    // Reload data
    loadSummaryStats();
    loadCharts();
}

/**
 * Animate Value Counter
 */
function animateValue(elementId, start, end, duration, isCurrency) {
    const element = document.getElementById(elementId);
    const range = end - start;
    const increment = range / (duration / 16);
    let current = start;
    
    const timer = setInterval(function() {
        current += increment;
        if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
            current = end;
            clearInterval(timer);
        }
        
        if (isCurrency) {
            element.textContent = '₹' + formatNumber(current);
        } else {
            element.textContent = Math.round(current).toLocaleString('en-IN');
        }
    }, 16);
}

/**
 * Reset Stats to Zero
 */
function resetStats() {
    $('#totalSalesAmount').text('₹0');
    $('#totalInvoices').text('0');
    $('#totalItemsSold').text('0');
    $('#avgInvoiceValue').text('₹0');
}

/**
 * Format Number
 */
function formatNumber(num) {
    return parseFloat(num).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

/**
 * Format Date
 */
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

/**
 * Show Error Message
 */
function showError(message) {
    // You can implement a toast notification or alert here
    console.error(message);
}

/**
 * Show Success Message
 */
function showSuccess(message) {
    // You can implement a toast notification here
    console.log(message);
}

// Scroll to top functionality
$(window).scroll(function() {
    if ($(this).scrollTop() > 100) {
        $('.scroll-to-top').fadeIn();
    } else {
        $('.scroll-to-top').fadeOut();
    }
});

$('.scroll-to-top').click(function() {
    $('html, body').animate({scrollTop: 0}, 800);
    return false;
});
