$(document).ready(function() {
    // Initialize DataTables
    const empSalesTable = $('#employee-sales-table').DataTable({
        ajax: {
            url: './gearbox/get_employee_sales.kts.php',
            dataSrc: ''
        },
        columns: [
            { data: 'employee_name' },
            { data: 'total_sales', render: $.fn.dataTable.render.number(',', '.', 2) },
            { data: 'total_amount', render: $.fn.dataTable.render.number(',', '.', 2) },
            { data: 'average_sale', render: $.fn.dataTable.render.number(',', '.', 2) }
        ]
    });

    const expensesTable = $('#expenses-table').DataTable({
        ajax: {
            url: './gearbox/get_expenses.kts.php',
            dataSrc: ''
        },
        columns: [
            { data: 'expense_name' },
            { data: 'expense_amount', render: $.fn.dataTable.render.number(',', '.', 2) },
            { data: 'date_incurred' },
            { data: 'shift_id' }
        ]
    });

    const inventoryTable = $('#inventory-table').DataTable({
        ajax: {
            url: './gearbox/get_inventory.kts.php',
            dataSrc: ''
        },
        columns: [
            { data: 'item_name' },
            { data: 'category' },
            { data: 'subcategory' },
            { data: 'quantity' },
            { data: 'buying_price', render: $.fn.dataTable.render.number(',', '.', 2) },
            { data: 'selling_price', render: $.fn.dataTable.render.number(',', '.', 2) },
            { 
                data: null,
                render: function(data, type, row) {
                    const margin = ((row.selling_price - row.buying_price) / row.buying_price * 100).toFixed(2);
                    return margin + '%';
                }
            }
        ]
    });

    const dailyTopItemsTable = $('#daily-top-items').DataTable({
        ajax: {
            url: './gearbox/get_daily_top_items.kts.php',
            dataSrc: ''
        },
        columns: [
            { data: 'product_name' },
            { data: 'category' },
            { data: 'quantity' },
            { data: 'subtotal', render: $.fn.dataTable.render.number(',', '.', 2) }
        ]
    });

    // Initialize Charts
    let empSalesChart, expensesChart, inventoryChart, dailySalesChart;

    // Load initial data
    loadEmployeeSales();
    loadExpenses();
    loadInventory();
    loadDailyReport();

    // Populate dropdowns
    $.get('./gearbox/get_employees.kts.php', function(data) {
        data.forEach(employee => {
            $('#emp-sales-employee').append(`<option value="${employee.employee_id}">${employee.name}</option>`);
        });
    });

    $.get('./gearbox/get_categories.kts.php', function(data) {
        data.forEach(category => {
            $('#inventory-subcategory').append(`<option value="${category}">${category}</option>`);
        });
    });

    // Filter buttons
    $('#emp-sales-filter').click(loadEmployeeSales);
    $('#expenses-filter').click(loadExpenses);
    $('#inventory-filter').click(loadInventory);
    $('#daily-filter').click(loadDailyReport);

    // Functions to load data
    function loadEmployeeSales() {
        const employeeId = $('#emp-sales-employee').val();
        const dateFrom = $('#emp-sales-date-from').val();
        const dateTo = $('#emp-sales-date-to').val();

        empSalesTable.ajax.url(`./gearbox/get_employee_sales.kts.php?employee_id=${employeeId}&date_from=${dateFrom}&date_to=${dateTo}`).load();

        $.get(`./gearbox/get_employee_sales_chart.kts.php?employee_id=${employeeId}&date_from=${dateFrom}&date_to=${dateTo}`, function(data) {
            if (empSalesChart) empSalesChart.destroy();
            
            const ctx = document.getElementById('employee-sales-chart').getContext('2d');
            empSalesChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'Total Sales Amount',
                        data: data.data,
                        backgroundColor: 'rgba(54, 162, 235, 0.5)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Employee Sales Performance'
                        },
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        });
    }

    function loadExpenses() {
        const dateFrom = $('#expenses-date-from').val();
        const dateTo = $('#expenses-date-to').val();
        const shiftId = $('#expenses-shift').val();

        expensesTable.ajax.url(`./gearbox/get_expenses.kts.php?date_from=${dateFrom}&date_to=${dateTo}&shift_id=${shiftId}`).load();

        $.get(`./gearbox/get_expenses_chart.kts.php?date_from=${dateFrom}&date_to=${dateTo}&shift_id=${shiftId}`, function(data) {
            if (expensesChart) expensesChart.destroy();
            
            const ctx = document.getElementById('expenses-chart').getContext('2d');
            expensesChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: data.labels,
                    datasets: [{
                        data: data.data,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.5)',
                            'rgba(54, 162, 235, 0.5)',
                            'rgba(255, 206, 86, 0.5)',
                            'rgba(75, 192, 192, 0.5)',
                            'rgba(153, 102, 255, 0.5)',
                            'rgba(255, 159, 64, 0.5)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Expenses Breakdown'
                        },
                    }
                }
            });
        });
    }

    function loadInventory() {
        const category = $('#inventory-category').val();
        const subcategory = $('#inventory-subcategory').val();
        const availability = $('#inventory-availability').val();

        inventoryTable.ajax.url(`./gearbox/get_inventory.kts.php?category=${category}&subcategory=${subcategory}&availability=${availability}`).load();

        $.get(`./gearbox/get_inventory_chart.kts.php?category=${category}&subcategory=${subcategory}`, function(data) {
            if (inventoryChart) inventoryChart.destroy();
            
            const ctx = document.getElementById('inventory-chart').getContext('2d');
            inventoryChart = new Chart(ctx, {
                type: 'radar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'Stock Levels',
                        data: data.stock,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }, {
                        label: 'Profit Margins',
                        data: data.margins,
                        backgroundColor: 'rgba(153, 102, 255, 0.2)',
                        borderColor: 'rgba(153, 102, 255, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Inventory Analysis'
                        },
                    },
                    scales: {
                        r: {
                            angleLines: {
                                display: true
                            },
                            suggestedMin: 0
                        }
                    }
                }
            });
        });
    }

    function loadDailyReport() {
        const date = $('#daily-date').val();
        const shiftId = $('#daily-shift').val();

        $.get(`./gearbox/get_daily_summary.kts.php?date=${date}&shift_id=${shiftId}`, function(data) {
            $('#sales-summary').html(`
                <p><strong>Total Sales:</strong> $${data.total_sales.toFixed(2)}</p>
                <p><strong>Total Items Sold:</strong> ${data.total_items}</p>
                <p><strong>Average Sale:</strong> $${data.average_sale.toFixed(2)}</p>
                <p><strong>Transactions:</strong> ${data.total_transactions}</p>
            `);

            $('#expenses-summary').html(`
                <p><strong>Total Expenses:</strong> $${data.total_expenses.toFixed(2)}</p>
                <p><strong>Most Expensive Expense:</strong> ${data.top_expense_name || 'N/A'} ($${data.top_expense_amount ? data.top_expense_amount.toFixed(2) : '0.00'})</p>
                <p><strong>Net Profit:</strong> $${(data.total_sales - data.total_expenses).toFixed(2)}</p>
            `);

            dailyTopItemsTable.ajax.url(`./gearbox/get_daily_top_items.kts.php?date=${date}&shift_id=${shiftId}`).load();

            if (dailySalesChart) dailySalesChart.destroy();
            
            const ctx = document.getElementById('daily-sales-chart').getContext('2d');
            dailySalesChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.hourly_labels,
                    datasets: [{
                        label: 'Sales by Hour',
                        data: data.hourly_sales,
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 2,
                        tension: 0.1,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Hourly Sales Trend'
                        },
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        });
    }

    // Category change handler for inventory
    $('#inventory-category').change(function() {
        const category = $(this).val();
        $('#inventory-subcategory').empty().append('<option value="">All Subcategories</option>');
        
        if (category) {
            $.get(`./gearbox/get_subcategories.kts.php?category=${category}`, function(data) {
                data.forEach(subcat => {
                    $('#inventory-subcategory').append(`<option value="${subcat}">${subcat}</option>`);
                });
            });
        }
    });
});