// Costing Actions JavaScript
document.addEventListener('DOMContentLoaded', function() {
    const ingredientSelect = document.getElementById('ingredientSelect');
    const quantityInput = document.getElementById('quantityInput');
    const addIngredientBtn = document.getElementById('addIngredientBtn');
    const costingLines = document.getElementById('costingLines');
    const totalCostElement = document.getElementById('totalCost');
    const costPerPortionElement = document.getElementById('costPerPortion');
    const foodCostPercentElement = document.getElementById('foodCostPercent');
    const gpPercentElement = document.getElementById('gpPercent');
    const recalculateBtn = document.getElementById('recalculateBtn');
    const costingForm = document.getElementById('costingForm');
    const savedSheetsTable = document.getElementById('savedSheetsTable');

    let ingredients = [];
    let currentIngredients = [];

    // Load ingredients from server
    async function loadIngredients() {
        try {
            const response = await fetch('../api/get_ingredients.php');
            ingredients = await response.json();
            
            // Populate ingredient select
            ingredientSelect.innerHTML = '<option value="">Select Ingredient</option>';
            ingredients.forEach(ingredient => {
                const option = document.createElement('option');
                option.value = ingredient.id;
                option.textContent = `${ingredient.name} (R${ingredient.unit_cost}/${ingredient.unit_type})`;
                option.setAttribute('data-cost', ingredient.unit_cost);
                option.setAttribute('data-unit', ingredient.unit_type);
                ingredientSelect.appendChild(option);
            });
        } catch (error) {
            console.error('Error loading ingredients:', error);
        }
    }

    // Add ingredient to costing sheet
    addIngredientBtn.addEventListener('click', function() {
        const selectedOption = ingredientSelect.options[ingredientSelect.selectedIndex];
        const quantity = parseFloat(quantityInput.value);
        
        if (!selectedOption.value || isNaN(quantity) || quantity <= 0) {
            alert('Please select an ingredient and enter a valid quantity');
            return;
        }

        const ingredientId = selectedOption.value;
        const ingredientName = selectedOption.text.split(' (')[0];
        const unitCost = parseFloat(selectedOption.getAttribute('data-cost'));
        const unitType = selectedOption.getAttribute('data-unit');
        const lineCost = unitCost * quantity;

        // Add to current ingredients array
        currentIngredients.push({
            id: ingredientId,
            name: ingredientName,
            quantity: quantity,
            unitCost: unitCost,
            unitType: unitType,
            lineCost: lineCost
        });

        updateCostingTable();
        recalculateTotals();
        
        // Reset inputs
        ingredientSelect.selectedIndex = 0;
        quantityInput.value = '';
    });

    // Update costing table
    function updateCostingTable() {
        if (currentIngredients.length === 0) {
            costingLines.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center text-muted py-3">
                        <i class="fas fa-list-check fa-2x mb-2 d-block"></i>
                        No ingredients added yet
                    </td>
                </tr>
            `;
            return;
        }

        costingLines.innerHTML = currentIngredients.map((ingredient, index) => `
            <tr>
                <td>${ingredient.name}</td>
                <td>${ingredient.quantity} ${ingredient.unitType}</td>
                <td>R ${ingredient.unitCost.toFixed(2)}</td>
                <td>R ${ingredient.lineCost.toFixed(2)}</td>
                <td>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-ingredient" data-index="${index}">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `).join('');

        // Add event listeners to remove buttons
        document.querySelectorAll('.remove-ingredient').forEach(button => {
            button.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                currentIngredients.splice(index, 1);
                updateCostingTable();
                recalculateTotals();
            });
        });
    }

    // Recalculate totals
    function recalculateTotals() {
        const totalCost = currentIngredients.reduce((sum, ingredient) => sum + ingredient.lineCost, 0);
        const yieldPortions = parseFloat(document.getElementById('yieldPortions').value) || 1;
        const sellingPrice = parseFloat(document.getElementById('sellingPrice').value) || 0;
        
        const costPerPortion = totalCost / yieldPortions;
        const foodCostPercent = sellingPrice > 0 ? (costPerPortion / sellingPrice) * 100 : 0;
        const gpPercent = sellingPrice > 0 ? 100 - foodCostPercent : 0;

        totalCostElement.textContent = `R ${totalCost.toFixed(2)}`;
        costPerPortionElement.textContent = `R ${costPerPortion.toFixed(2)}`;
        foodCostPercentElement.textContent = `${foodCostPercent.toFixed(2)}%`;
        gpPercentElement.textContent = `${gpPercent.toFixed(2)}%`;
    }

    // Recalculate button
    recalculateBtn.addEventListener('click', recalculateTotals);

    // Form submission
    costingForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        if (currentIngredients.length === 0) {
            alert('Please add at least one ingredient to the costing sheet');
            return;
        }

        const formData = new FormData(this);
        formData.append('ingredients', JSON.stringify(currentIngredients));

        try {
            const response = await fetch('../api/save_costing.php', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success) {
                alert('Costing sheet saved successfully!');
                currentIngredients = [];
                updateCostingTable();
                recalculateTotals();
                this.reset();
                loadSavedSheets();
            } else {
                alert('Error saving costing sheet: ' + result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error saving costing sheet');
        }
    });

    // Load saved costing sheets
    async function loadSavedSheets() {
        try {
            const response = await fetch('../api/get_costing_sheets.php');
            const sheets = await response.json();
            
            if (sheets.length === 0) {
                savedSheetsTable.innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            No costing sheets found
                        </td>
                    </tr>
                `;
                return;
            }

            savedSheetsTable.innerHTML = sheets.map(sheet => `
                <tr>
                    <td>${sheet.id}</td>
                    <td>${sheet.name}</td>
                    <td>${sheet.yield_portions}</td>
                    <td>R ${parseFloat(sheet.total_cost).toFixed(2)}</td>
                    <td>R ${parseFloat(sheet.cost_per_portion).toFixed(2)}</td>
                    <td>${parseFloat(sheet.gp_percent).toFixed(2)}%</td>
                    <td class="text-end">
                        <button class="btn btn-sm btn-outline-primary download-sheet" data-id="${sheet.id}">
                            <i class="fas fa-download"></i> Excel
                        </button>
                        <button class="btn btn-sm btn-outline-danger delete-sheet" data-id="${sheet.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            // Add event listeners
            document.querySelectorAll('.download-sheet').forEach(button => {
                button.addEventListener('click', function() {
                    const sheetId = this.getAttribute('data-id');
                    downloadExcel(sheetId);
                });
            });

            document.querySelectorAll('.delete-sheet').forEach(button => {
                button.addEventListener('click', function() {
                    const sheetId = this.getAttribute('data-id');
                    deleteSheet(sheetId);
                });
            });

        } catch (error) {
            console.error('Error loading sheets:', error);
            savedSheetsTable.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-danger py-4">
                        Error loading costing sheets
                    </td>
                </tr>
            `;
        }
    }

    // Download Excel function
    async function downloadExcel(sheetId) {
        try {
            const response = await fetch(`../api/download_costing.php?id=${sheetId}`);
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `costing_sheet_${sheetId}.xlsx`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            } else {
                alert('Error downloading sheet');
            }
        } catch (error) {
            console.error('Download error:', error);
            alert('Error downloading sheet');
        }
    }

    // Delete sheet function
    async function deleteSheet(sheetId) {
        if (!confirm('Are you sure you want to delete this costing sheet?')) {
            return;
        }

        try {
            const response = await fetch('../api/delete_costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: sheetId })
            });

            const result = await response.json();

            if (result.success) {
                loadSavedSheets();
            } else {
                alert('Error deleting sheet: ' + result.message);
            }
        } catch (error) {
            console.error('Delete error:', error);
            alert('Error deleting sheet');
        }
    }

    // Initialize
    loadIngredients();
    loadSavedSheets();

    // Add real-time recalculation
    document.getElementById('yieldPortions').addEventListener('input', recalculateTotals);
    document.getElementById('sellingPrice').addEventListener('input', recalculateTotals);
});