// meals_actions.js
class MealsManager {
    constructor() {
        this.selectedCostings = [];
        this.meals = [];
        this.basePath = window.BASE_PATH || '';
        this.userId = window.USER_ID || 1;
        this.init();
    }

    init() {
        console.log('MealsManager initialized with user ID:', this.userId);
        this.loadCostingSheets();
        this.loadMeals();
        this.setupEventListeners();
    }

    setupEventListeners() {
        // Add costing sheet button
        const addBtn = document.getElementById('addCostingBtn');
        if (addBtn) {
            addBtn.addEventListener('click', () => this.addCostingSheet());
        }
        
        // Meal form submission
        const mealForm = document.getElementById('mealForm');
        if (mealForm) {
            mealForm.addEventListener('submit', (e) => this.saveMeal(e));
        }
        
        // Selling price change listener
        const sellingPrice = document.getElementById('sellingPrice');
        if (sellingPrice) {
            sellingPrice.addEventListener('input', () => this.updateFinancialSummary());
        }
    }

    async loadCostingSheets() {
        try {
            console.log('Loading costing sheets from:', this.basePath + 'api/get_costings.php');
            const response = await fetch(this.basePath + 'api/get_costings.php');
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const costings = await response.json();
            console.log('Costing sheets response:', costings);
            
            const select = document.getElementById('costingSelect');
            if (!select) {
                console.error('Costing select element not found');
                return;
            }
            
            select.innerHTML = '<option value="">Select Costing Sheet</option>';
            
            if (Array.isArray(costings) && costings.length > 0) {
                costings.forEach(costing => {
                    const option = document.createElement('option');
                    option.value = costing.id;
                    const cost = parseFloat(costing.total_cost) || 0;
                    const portionCost = parseFloat(costing.cost_per_portion) || 0;
                    const portions = costing.portions || 1;
                    
                    option.textContent = `${costing.name} (R ${cost.toFixed(2)}) - ${portions} portions`;
                    option.dataset.cost = cost;
                    option.dataset.portionCost = portionCost;
                    select.appendChild(option);
                });
                
                console.log('Costing sheets loaded:', costings.length);
            } else {
                console.log('No costing sheets available');
                select.innerHTML = '<option value="">No costing sheets available</option>';
            }
        } catch (error) {
            console.error('Error loading costing sheets:', error);
            this.showAlert('Error loading costing sheets. Please check console for details.', 'danger');
        }
    }

    addCostingSheet() {
        const select = document.getElementById('costingSelect');
        const servingsInput = document.getElementById('costingServings');
        
        if (!select || !servingsInput) {
            console.error('Required elements not found');
            return;
        }
        
        const costingId = select.value;
        if (!costingId) {
            this.showAlert('Please select a costing sheet', 'warning');
            return;
        }
        
        const costingName = select.options[select.selectedIndex].text;
        const unitCost = parseFloat(select.options[select.selectedIndex].dataset.cost) || 0;
        const portionCost = parseFloat(select.options[select.selectedIndex].dataset.portionCost) || 0;
        const servings = parseInt(servingsInput.value) || 1;
        
        // Check if already added
        if (this.selectedCostings.find(c => c.id === costingId)) {
            this.showAlert('This costing sheet is already added to the meal', 'warning');
            return;
        }
        
        const totalCost = portionCost * servings;
        
        this.selectedCostings.push({
            id: costingId,
            name: costingName,
            unitCost: unitCost,
            portionCost: portionCost,
            servings: servings,
            totalCost: totalCost
        });
        
        this.updateSelectedCostingsDisplay();
        this.updateFinancialSummary();
        
        // Reset inputs
        servingsInput.value = 1;
        select.selectedIndex = 0;
        
        this.showAlert('Costing sheet added successfully', 'success');
    }

    updateSelectedCostingsDisplay() {
        const container = document.getElementById('selectedCostings');
        const totalCostElement = document.getElementById('mealTotalCost');
        
        if (!container || !totalCostElement) {
            console.error('Display elements not found');
            return;
        }
        
        if (this.selectedCostings.length === 0) {
            container.innerHTML = '<i class="fas fa-info-circle me-1"></i>No costing sheets added yet';
            totalCostElement.textContent = 'Total Cost: R 0.00';
            return;
        }
        
        let html = '';
        let totalCost = 0;
        
        this.selectedCostings.forEach((costing, index) => {
            totalCost += costing.totalCost;
            html += `
                <div class="d-flex justify-content-between align-items-center mb-2 pb-2 border-bottom">
                    <div>
                        <strong>${costing.name}</strong>
                        <br>
                        <small class="text-muted">${costing.servings} serving(s) × R ${costing.portionCost.toFixed(2)}</small>
                    </div>
                    <div class="text-end">
                        <strong>R ${costing.totalCost.toFixed(2)}</strong>
                        <br>
                        <button class="btn btn-sm btn-outline-danger mt-1" onclick="mealsManager.removeCosting(${index})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
        totalCostElement.textContent = `Total Cost: R ${totalCost.toFixed(2)}`;
    }

    removeCosting(index) {
        this.selectedCostings.splice(index, 1);
        this.updateSelectedCostingsDisplay();
        this.updateFinancialSummary();
        this.showAlert('Costing sheet removed', 'info');
    }

    updateFinancialSummary() {
        const sellingPriceInput = document.getElementById('sellingPrice');
        if (!sellingPriceInput) return;
        
        const sellingPrice = parseFloat(sellingPriceInput.value) || 0;
        const totalCost = this.selectedCostings.reduce((sum, costing) => sum + costing.totalCost, 0);
        const profit = sellingPrice - totalCost;
        const gpPercentage = sellingPrice > 0 ? ((profit / sellingPrice) * 100) : 0;
        
        // Update summary elements
        const summarySellingPrice = document.getElementById('summarySellingPrice');
        const summaryTotalCost = document.getElementById('summaryTotalCost');
        const summaryProfit = document.getElementById('summaryProfit');
        const summaryGP = document.getElementById('summaryGP');
        
        if (summarySellingPrice) summarySellingPrice.textContent = `R ${sellingPrice.toFixed(2)}`;
        if (summaryTotalCost) summaryTotalCost.textContent = `R ${totalCost.toFixed(2)}`;
        if (summaryProfit) {
            summaryProfit.textContent = `R ${profit.toFixed(2)}`;
            // Color code profit
            summaryProfit.className = `fw-bold ${profit >= 0 ? 'text-success' : 'text-danger'}`;
        }
        if (summaryGP) {
            summaryGP.textContent = `${gpPercentage.toFixed(1)}%`;
            // Color code GP%
            if (gpPercentage >= 15) {
                summaryGP.className = 'fw-bold text-success';
            } else if (gpPercentage >= 5) {
                summaryGP.className = 'fw-bold text-warning';
            } else {
                summaryGP.className = 'fw-bold text-danger';
            }
        }
    }

    async saveMeal(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const sellingPrice = parseFloat(formData.get('selling_price'));
        const totalCost = this.selectedCostings.reduce((sum, costing) => sum + costing.totalCost, 0);
        
        // Validation
        if (!formData.get('name')?.trim()) {
            this.showAlert('Please enter a meal name', 'danger');
            return;
        }
        
        if (this.selectedCostings.length === 0) {
            this.showAlert('Please add at least one costing sheet to the meal', 'danger');
            return;
        }
        
        if (sellingPrice <= 0) {
            this.showAlert('Please enter a valid selling price', 'danger');
            return;
        }
        
        const profit = sellingPrice - totalCost;
        const gpPercentage = ((profit / sellingPrice) * 100);
        
        const mealData = {
            name: formData.get('name').trim(),
            description: formData.get('description')?.trim() || '',
            category: formData.get('category')?.trim() || '',
            meal_type: formData.get('meal_type') || '',
            selling_price: sellingPrice,
            costings: this.selectedCostings,
            total_cost: totalCost,
            profit: profit,
            gp_percentage: gpPercentage,
            user_id: this.userId
        };
        
        console.log('Saving meal data:', mealData);
        
        try {
            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
            submitBtn.disabled = true;
            
            const response = await fetch(this.basePath + 'api/save_meal.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(mealData)
            });
            
            const result = await response.json();
            console.log('Save meal response:', result);
            
            if (result.success) {
                this.showAlert(result.message || 'Meal saved successfully!', 'success');
                this.resetForm();
                this.loadMeals();
            } else {
                this.showAlert('Error saving meal: ' + (result.message || 'Unknown error'), 'danger');
            }
        } catch (error) {
            console.error('Error saving meal:', error);
            this.showAlert('Error saving meal. Please check console for details.', 'danger');
        } finally {
            const submitBtn = e.target.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="fas fa-save me-2"></i>Save Meal';
                submitBtn.disabled = false;
            }
        }
    }

    resetForm() {
        const form = document.getElementById('mealForm');
        if (form) {
            form.reset();
        }
        this.selectedCostings = [];
        this.updateSelectedCostingsDisplay();
        this.updateFinancialSummary();
    }

    async loadMeals() {
        try {
            console.log('Loading meals for user:', this.userId);
            const url = this.basePath + `api/get_meals.php?user_id=${this.userId}`;
            console.log('Loading meals from:', url);
            
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            this.meals = await response.json();
            console.log('Meals response:', this.meals);
            
            this.renderMealsTable();
        } catch (error) {
            console.error('Error loading meals:', error);
            this.showAlert('Error loading meals. Please check console for details.', 'danger');
            this.renderMealsTable(); // Still render empty table
        }
    }

    renderMealsTable() {
        const tbody = document.getElementById('mealsTable');
        if (!tbody) {
            console.error('Meals table body not found');
            return;
        }
        
        if (!Array.isArray(this.meals) || this.meals.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-4 text-muted">
                        <i class="fas fa-utensils me-2"></i>No meals created yet
                    </td>
                </tr>
            `;
            return;
        }
        
        tbody.innerHTML = this.meals.map(meal => {
            const gpPercentage = parseFloat(meal.gp_percentage) || 0;
            let gpBadgeClass = 'bg-danger'; // Default red for <5%
            
            if (gpPercentage >= 15) {
                gpBadgeClass = 'bg-success'; // Green for ≥15%
            } else if (gpPercentage >= 5) {
                gpBadgeClass = 'bg-warning'; // Yellow for 5-14.9%
            }
            
            return `
                <tr>
                    <td>
                        <strong>${this.escapeHtml(meal.name)}</strong>
                        ${meal.description ? `<br><small class="text-muted">${this.escapeHtml(meal.description)}</small>` : ''}
                    </td>
                    <td>
                        <span class="badge bg-secondary">${meal.meal_type || 'N/A'}</span>
                        ${meal.category ? `<br><small class="text-muted">${this.escapeHtml(meal.category)}</small>` : ''}
                    </td>
                    <td>
                        <small>${meal.costing_count || 0} sheet(s)</small>
                    </td>
                    <td>R ${parseFloat(meal.total_cost || 0).toFixed(2)}</td>
                    <td>R ${parseFloat(meal.selling_price || 0).toFixed(2)}</td>
                    <td>
                        <span class="badge ${gpBadgeClass}">
                            ${gpPercentage.toFixed(1)}%
                        </span>
                    </td>
                    <td class="text-end">
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="mealsManager.viewMeal(${meal.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-warning me-1" onclick="mealsManager.editMeal(${meal.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="mealsManager.deleteMeal(${meal.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    }

    showAlert(message, type = 'info') {
        // Create alert element
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // Add to page
        const container = document.querySelector('.container-fluid');
        if (container) {
            container.insertBefore(alertDiv, container.firstChild);
            
            // Auto remove after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
    }

    escapeHtml(unsafe) {
        if (!unsafe) return '';
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    viewMeal(mealId) {
        const meal = this.meals.find(m => m.id == mealId);
        if (!meal) {
            this.showAlert('Meal not found', 'danger');
            return;
        }
        
        const modalBody = document.getElementById('mealDetailsBody');
        if (!modalBody) return;
        
        modalBody.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <h6>Meal Information</h6>
                    <p><strong>Name:</strong> ${this.escapeHtml(meal.name)}</p>
                    <p><strong>Description:</strong> ${this.escapeHtml(meal.description) || 'N/A'}</p>
                    <p><strong>Category:</strong> ${this.escapeHtml(meal.category) || 'N/A'}</p>
                    <p><strong>Type:</strong> ${meal.meal_type || 'N/A'}</p>
                </div>
                <div class="col-md-6">
                    <h6>Financial Summary</h6>
                    <p><strong>Selling Price:</strong> R ${parseFloat(meal.selling_price || 0).toFixed(2)}</p>
                    <p><strong>Total Cost:</strong> R ${parseFloat(meal.total_cost || 0).toFixed(2)}</p>
                    <p><strong>Profit:</strong> R ${parseFloat(meal.profit || 0).toFixed(2)}</p>
                    <p><strong>GP%:</strong> ${parseFloat(meal.gp_percentage || 0).toFixed(1)}%</p>
                </div>
            </div>
            <hr>
            <h6>Costing Sheets</h6>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Costing Sheet</th>
                            <th>Servings</th>
                            <th>Unit Cost</th>
                            <th>Total Cost</th>
                        </tr>
                    </thead>
                    <tbody id="mealCostingsList">
                        <tr>
                            <td colspan="4" class="text-center">
                                <div class="spinner-border spinner-border-sm" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                Loading costings...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        `;
        
        // Load costing sheets for this meal
        this.loadMealCostings(mealId);
        
        const modalElement = document.getElementById('mealDetailsModal');
        if (modalElement) {
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
        }
    }

    async loadMealCostings(mealId) {
        try {
            const response = await fetch(`${this.basePath}api/get_meal_costings.php?meal_id=${mealId}`);
            if (!response.ok) {
                throw new Error('Failed to fetch meal costings');
            }
            const costings = await response.json();
            
            const tbody = document.getElementById('mealCostingsList');
            if (tbody) {
                if (Array.isArray(costings) && costings.length > 0) {
                    tbody.innerHTML = costings.map(costing => `
                        <tr>
                            <td>${this.escapeHtml(costing.costing_name)}</td>
                            <td>${costing.servings}</td>
                            <td>R ${parseFloat(costing.unit_cost || 0).toFixed(2)}</td>
                            <td>R ${parseFloat(costing.total_cost || 0).toFixed(2)}</td>
                        </tr>
                    `).join('');
                } else {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="4" class="text-center text-muted">No costing sheets found</td>
                        </tr>
                    `;
                }
            }
        } catch (error) {
            console.error('Error loading meal costings:', error);
            const tbody = document.getElementById('mealCostingsList');
            if (tbody) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="4" class="text-center text-danger">Error loading costings</td>
                    </tr>
                `;
            }
        }
    }

    exportToExcel() {
        if (!Array.isArray(this.meals) || this.meals.length === 0) {
            this.showAlert('No meals to export', 'warning');
            return;
        }
        
        try {
            const worksheetData = this.meals.map(meal => ({
                'Meal Name': meal.name,
                'Description': meal.description || '',
                'Category': meal.category || '',
                'Type': meal.meal_type || '',
                'Total Cost': parseFloat(meal.total_cost || 0).toFixed(2),
                'Selling Price': parseFloat(meal.selling_price || 0).toFixed(2),
                'Profit': parseFloat(meal.profit || 0).toFixed(2),
                'GP%': parseFloat(meal.gp_percentage || 0).toFixed(1) + '%',
                'Costing Sheets': meal.costing_count || 0
            }));
            
            const worksheet = XLSX.utils.json_to_sheet(worksheetData);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Meals');
            XLSX.writeFile(workbook, 'meals_export.xlsx');
            
            this.showAlert('Excel file downloaded successfully', 'success');
        } catch (error) {
            console.error('Error exporting to Excel:', error);
            this.showAlert('Error exporting to Excel. Check console for details.', 'danger');
        }
    }

    exportMealToExcel() {
        this.showAlert('Single meal export functionality coming soon!', 'info');
    }

    editMeal(mealId) {
        this.showAlert('Edit meal functionality coming soon!', 'info');
    }

    deleteMeal(mealId) {
        if (confirm('Are you sure you want to delete this meal?')) {
            this.showAlert('Delete meal functionality coming soon!', 'info');
        }
    }
}

// Initialize meals manager when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, initializing MealsManager...');
    window.mealsManager = new MealsManager();
});