/**
 * Ingredients Management
 */
class IngredientsManager {
    constructor() {
        this.ingredients = [];
        this.init();
    }

    async init() {
        await this.loadIngredients();
        this.setupEventListeners();
    }

    async loadIngredients() {
        try {
            const data = await window.rcpFetch('ingredients/get.php');
            
            if (data.success) {
                this.ingredients = data.ingredients;
                this.renderIngredients();
            } else {
                window.showAlert('Failed to load ingredients: ' + data.message, 'danger');
            }
        } catch (error) {
            console.error('Error loading ingredients:', error);
            window.showAlert('Network error loading ingredients', 'danger');
        }
    }

    renderIngredients() {
        const tbody = document.getElementById('ingredientsTable');
        
        if (this.ingredients.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center text-muted py-4">
                        <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                        No ingredients found. Add your first ingredient above.
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = this.ingredients.map(ingredient => `
            <tr data-id="${ingredient.id}">
                <td>
                    <strong>${window.escapeHtml(ingredient.name)}</strong>
                    ${ingredient.creator_name ? `
                        <br><small class="text-muted">Added by: ${window.escapeHtml(ingredient.creator_name)}</small>
                    ` : ''}
                </td>
                <td>${window.escapeHtml(ingredient.category || '-')}</td>
                <td>${window.escapeHtml(ingredient.unit)}</td>
                <td>${window.formatZAR(ingredient.cost_per_unit)}</td>
                <td>${window.escapeHtml(ingredient.supplier_info || '-')}</td>
                <td class="text-end">
                    <button class="btn btn-sm btn-outline-primary me-1" 
                            onclick="ingredientsManager.editIngredient(${ingredient.id})"
                            title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" 
                            onclick="ingredientsManager.deleteIngredient(${ingredient.id})"
                            title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `).join('');
    }

    setupEventListeners() {
        // Add ingredient form
        document.getElementById('ingredientForm').addEventListener('submit', (e) => this.handleAddIngredient(e));
        
        // Edit ingredient form
        document.getElementById('editIngredientForm').addEventListener('submit', (e) => this.handleEditIngredient(e));
        
        // Import form
        document.getElementById('importForm').addEventListener('submit', (e) => this.handleImport(e));
    }

    async handleAddIngredient(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        const ingredientData = {
            name: formData.get('name'),
            category: formData.get('category'),
            unit: formData.get('unit'),
            cost_per_unit: formData.get('cost_per_unit') || 0,
            supplier_info: formData.get('supplier_info')
        };

        const hideLoading = window.showLoading(e.submitter);

        try {
            const data = await window.rcpFetch('ingredients/add.php', {
                method: 'POST',
                body: JSON.stringify(ingredientData)
            });
            
            if (data.success) {
                window.showAlert('Ingredient added successfully!', 'success');
                form.reset();
                await this.loadIngredients();
            } else {
                window.showAlert('Failed to add ingredient: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error: ' + error.message, 'danger');
        } finally {
            hideLoading();
        }
    }

    editIngredient(ingredientId) {
        const ingredient = this.ingredients.find(i => i.id == ingredientId);
        if (!ingredient) return;

        document.getElementById('editIngredientId').value = ingredient.id;
        document.getElementById('editName').value = ingredient.name;
        document.getElementById('editCategory').value = ingredient.category || '';
        document.getElementById('editUnit').value = ingredient.unit;
        document.getElementById('editCostPerUnit').value = ingredient.cost_per_unit;
        document.getElementById('editSupplierInfo').value = ingredient.supplier_info || '';

        const modal = new bootstrap.Modal(document.getElementById('editIngredientModal'));
        modal.show();
    }

    async handleEditIngredient(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        const ingredientData = {
            id: parseInt(formData.get('id')),
            name: formData.get('name'),
            category: formData.get('category'),
            unit: formData.get('unit'),
            cost_per_unit: formData.get('cost_per_unit') || 0,
            supplier_info: formData.get('supplier_info')
        };

        const hideLoading = window.showLoading(e.submitter);

        try {
            const data = await window.rcpFetch('ingredients/update.php', {
                method: 'POST',
                body: JSON.stringify(ingredientData)
            });
            
            if (data.success) {
                window.showAlert('Ingredient updated successfully!', 'success');
                bootstrap.Modal.getInstance(document.getElementById('editIngredientModal')).hide();
                await this.loadIngredients();
            } else {
                window.showAlert('Failed to update ingredient: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error: ' + error.message, 'danger');
        } finally {
            hideLoading();
        }
    }

    async deleteIngredient(ingredientId) {
        const ingredient = this.ingredients.find(i => i.id == ingredientId);
        if (!ingredient) return;

        if (!confirm(`Are you sure you want to delete "${ingredient.name}"? This action cannot be undone.`)) {
            return;
        }

        try {
            const data = await window.rcpFetch('ingredients/delete.php', {
                method: 'POST',
                body: JSON.stringify({ id: ingredientId })
            });
            
            if (data.success) {
                window.showAlert('Ingredient deleted successfully!', 'success');
                await this.loadIngredients();
            } else {
                window.showAlert('Failed to delete ingredient: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error: ' + error.message, 'danger');
        }
    }

    async handleImport(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        const hideLoading = window.showLoading(e.submitter);

        try {
            const response = await fetch(window.APP_CONFIG.API_BASE + 'ingredients/import.php', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                let message = `Import successful: ${data.imported} new, ${data.updated} updated`;
                if (data.errors && data.errors.length > 0) {
                    message += ` (${data.errors.length} errors)`;
                }
                window.showAlert(message, 'success');
                form.reset();
                await this.loadIngredients();
            } else {
                window.showAlert('Import failed: ' + data.message, 'danger');
            }
        } catch (error) {
            window.showAlert('Network error during import: ' + error.message, 'danger');
        } finally {
            hideLoading();
        }
    }
}

// Initialize ingredients manager
let ingredientsManager;
document.addEventListener('DOMContentLoaded', () => {
    ingredientsManager = new IngredientsManager();
});