<?php
// Use absolute paths to avoid any path issues
$base_path = $_SERVER['DOCUMENT_ROOT'] . '/rcp/includes/';
$config_path = $base_path . 'config.php';

// Include config first
if (file_exists($config_path)) {
    require_once $config_path;
} else {
    die("Config file not found at: " . $config_path);
}

// AUTH CHECK - SAME AS COSTING.PHP
$auth_token = $_COOKIE['rcp_auth'] ?? null;
if (!$auth_token) {
    error_log("No auth token found - redirecting to login");
    header("Location: login.php");
    exit;
}

try {
    require_once __DIR__ . '/../includes/database.php';
    
    $pdo = Database::getInstance()->getConnection();
    
    $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
    $stmt->execute([$auth_token]);
    $session_data = $stmt->fetchColumn();
    
    if (!$session_data) {
        error_log("Invalid or expired session - redirecting to login");
        header("Location: login.php");
        exit;
    }
    
    $user = json_decode($session_data, true);
    
    // Update last activity (same as costing.php)
    $user['last_activity'] = time();
    $updateStmt = $pdo->prepare("UPDATE user_sessions SET session_data = ?, expires_at = DATE_ADD(NOW(), INTERVAL 2 HOUR) WHERE session_id = ?");
    $updateStmt->execute([json_encode($user), $auth_token]);
    
    // Set user variables for use in the page
    $user_id = $user['user_id'];
    $is_superuser = $user['user_role'] === 'superuser';
    
} catch (Throwable $t) {
    die("Error: " . $t->getMessage());
}

$pageTitle = "Meal Planning";
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Smart Serve Pro - Meals</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    .rcp-main {
      min-height: calc(100vh - 120px);
    }
    .card {
      border: 1px solid #e0e0e0;
      border-radius: 8px;
    }
    .card-header {
      background-color: #f8f9fa;
      border-bottom: 1px solid #e0e0e0;
    }
    .table th {
      background-color: #f8f9fa;
      border-bottom: 2px solid #dee2e6;
    }
    .fa-spinner {
      animation: fa-spin 1s infinite linear;
    }
    @keyframes fa-spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
    .financial-metric {
      font-size: 0.9rem;
    }
    .metric-value {
      font-weight: 600;
      font-size: 1rem;
    }
    .gp-good { color: #198754; }
    .gp-warning { color: #fd7e14; }
    .gp-danger { color: #dc3545; }
    .btn-issue {
      background-color: #28a745;
      color: white;
      border: none;
    }
    .btn-issue:hover {
      background-color: #218838;
      color: white;
    }
  </style>
</head>
<body class="bg-light">
<?php
// Fix navbar path - use relative path from pages directory (SAME AS COSTING.PHP)
$navbar_path = __DIR__ . '/../includes/navbar.php';
if (file_exists($navbar_path)) {
    include $navbar_path;
} else {
    // Fallback basic navbar if file not found
    echo '
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="dashboard.php">RCP</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="dashboard.php">Dashboard</a>
                <a class="nav-link" href="logout.php">Logout</a>
            </div>
        </div>
    </nav>';
}
?>

<main class="rcp-main">
  <div class="container-fluid py-4">
    <div class="row mb-4">
      <div class="col-12">
        <h1 class="h3 mb-1">Meal Planning</h1>
        <p class="text-muted">Build meals by combining multiple costing sheets</p>
      </div>
    </div>

    <div class="row g-4">
      <!-- Build Meal Card -->
      <div class="col-lg-5">
        <div class="card shadow-sm">
          <div class="card-header bg-white">
            <h5 class="card-title mb-0">Build New Meal</h5>
          </div>
          <div class="card-body">
            <form id="mealForm">
              <div class="mb-3">
                <label for="mealName" class="form-label">Meal Name *</label>
                <input type="text" class="form-control" id="mealName" name="name" required>
              </div>
              
              <div class="mb-3">
                <label for="mealDescription" class="form-label">Description</label>
                <textarea class="form-control" id="mealDescription" name="description" rows="2"
                          placeholder="Describe this meal combination"></textarea>
              </div>
              
              <div class="mb-3">
                <label for="mealCategory" class="form-label">Category</label>
                <input type="text" class="form-control" id="mealCategory" name="category"
                       placeholder="e.g., Buffet, Set Menu, Catering">
              </div>
              
              <div class="row">
                <div class="col-md-6">
                  <div class="mb-3">
                    <label for="mealType" class="form-label">Meal Type</label>
                    <select class="form-select" id="mealType" name="meal_type">
                      <option value="">Select Type</option>
                      <option value="breakfast">Breakfast</option>
                      <option value="lunch">Lunch</option>
                      <option value="dinner">Dinner</option>
                      <option value="snack">Snack</option>
                      <option value="catering">Catering</option>
                    </select>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="mb-3">
                    <label for="peopleCount" class="form-label">Number of People *</label>
                    <input type="number" class="form-control" id="peopleCount" name="people_count" 
                           value="1" min="1" max="1000" required>
                  </div>
                </div>
              </div>

              <!-- Selling Price Input -->
              <div class="mb-3">
                <label for="sellingPrice" class="form-label">Selling Price Per Person (Excl VAT) *</label>
                <div class="input-group">
                  <span class="input-group-text">R</span>
                  <input type="number" class="form-control" id="sellingPrice" name="selling_price" 
                         step="0.01" min="0" required placeholder="0.00">
                </div>
                <small class="text-muted">Price charged per person</small>
              </div>
              
              <hr>
              
              <!-- Add Costing Sheet to Meal -->
              <div class="mb-3">
                <label for="costingSelect" class="form-label">Add Costing Sheet to Meal</label>
                <div class="input-group">
                  <select class="form-select" id="costingSelect">
                    <option value="">Select Costing Sheet</option>
                  </select>
                  <input type="number" class="form-control" id="costingServings" 
                         placeholder="Servings" value="1" min="1" style="max-width: 120px;">
                  <button class="btn btn-outline-secondary" type="button" id="addCostingBtn">
                    <i class="fas fa-plus me-1"></i>Add
                  </button>
                </div>
                <small class="text-muted">Cost per serving shown below is for one person</small>
              </div>
              
              <button type="submit" class="btn btn-success w-100">
                <i class="fas fa-save me-2"></i>Save Meal
              </button>
            </form>
            
            <!-- Selected Costing Sheets -->
            <div class="mt-4">
              <div class="card border-primary">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                  <span>Selected Costing Sheets (Per Serving)</span>
                  <span class="fw-bold" id="mealTotalCost">Total Cost Per Person: R 0.00</span>
                </div>
                <div class="card-body">
                  <div id="selectedCostings" class="text-muted">
                    <i class="fas fa-info-circle me-1"></i>No costing sheets added yet
                  </div>
                </div>
              </div>
            </div>

            <!-- Financial Summary -->
            <div class="mt-3">
              <div class="card border-success">
                <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                  <span>Financial Summary</span>
                  <small id="summaryPeopleCount">For 1 person</small>
                </div>
                <div class="card-body">
                  <!-- Per Person Metrics -->
                  <div class="mb-3 pb-3 border-bottom">
                    <h6 class="text-success mb-3">Per Person Metrics</h6>
                    <div class="row">
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Selling Price</small>
                          <div class="metric-value" id="perPersonSellingPrice">R 0.00</div>
                        </div>
                      </div>
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Cost</small>
                          <div class="metric-value" id="perPersonCost">R 0.00</div>
                        </div>
                      </div>
                    </div>
                    <div class="row mt-2">
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Profit</small>
                          <div class="metric-value" id="perPersonProfit">R 0.00</div>
                        </div>
                      </div>
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Food GP%</small>
                          <div class="metric-value" id="perPersonGP">0%</div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- Total Metrics -->
                  <div>
                    <h6 class="text-success mb-3">Total Metrics</h6>
                    <div class="row">
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Total Revenue</small>
                          <div class="metric-value" id="totalRevenue">R 0.00</div>
                        </div>
                      </div>
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Total Cost</small>
                          <div class="metric-value" id="totalCost">R 0.00</div>
                        </div>
                      </div>
                    </div>
                    <div class="row mt-2">
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Total Profit</small>
                          <div class="metric-value" id="totalProfit">R 0.00</div>
                        </div>
                      </div>
                      <div class="col-6">
                        <div class="financial-metric">
                          <small class="text-muted">Food GP%</small>
                          <div class="metric-value" id="totalGP">0%</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Meals List -->
      <div class="col-lg-7">
        <div class="card shadow-sm">
          <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">My Meals</h5>
            <div>
              <a href="issue_sheets.php" class="btn btn-sm btn-issue me-2">
                <i class="fas fa-file-export me-1"></i>Stock Issue Sheets
              </a>
              <button class="btn btn-sm btn-outline-danger me-2" id="exportPdfBtn">
                <i class="fas fa-file-pdf me-1"></i>Export PDF
              </button>
              <button class="btn btn-sm btn-outline-secondary" id="refreshMealsBtn">
                <i class="fas fa-sync-alt me-1"></i>Refresh
              </button>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-hover">
                <thead class="table-light">
                  <tr>
                    <th>Name</th>
                    <th>Type</th>
                    <th>People</th>
                    <th>Costing Sheets</th>
                    <th>Cost Per Person</th>
                    <th>Price Per Person</th>
                    <th>GP%</th>
                    <th width="180" class="text-end">Actions</th>
                  </tr>
                </thead>
                <tbody id="mealsTable">
                  <tr>
                    <td colspan="8" class="text-center py-4">
                      <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<!-- Meal Details Modal -->
<div class="modal fade" id="mealDetailsModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Meal Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="mealDetailsBody">
        <!-- Content loaded dynamically -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-issue me-2" id="exportMealIssueSheetBtn">
          <i class="fas fa-file-export me-1"></i>Issue Sheet
        </button>
        <button type="button" class="btn btn-danger" id="exportMealPdfBtn">
          <i class="fas fa-file-pdf me-1"></i>Export to PDF
        </button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<script>
// Make BASE_PATH and USER_ID available to JavaScript
window.BASE_PATH = '<?= BASE_PATH ?>';
window.USER_ID = <?= $user_id ?>;

// Inline JavaScript to avoid external file dependency
class MealsManager {
    constructor() {
        this.selectedCostings = [];
        this.meals = [];
        this.basePath = window.BASE_PATH || '';
        this.userId = window.USER_ID || 1;
        this.currentViewingMealId = null;
        this.editingMealId = null;
        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 and people count change listeners
        const sellingPrice = document.getElementById('sellingPrice');
        if (sellingPrice) {
            sellingPrice.addEventListener('input', () => this.updateFinancialSummary());
        }
        
        const peopleCount = document.getElementById('peopleCount');
        if (peopleCount) {
            peopleCount.addEventListener('input', () => this.updateFinancialSummary());
        }
        
        // Export buttons
        const exportPdfBtn = document.getElementById('exportPdfBtn');
        if (exportPdfBtn) {
            exportPdfBtn.addEventListener('click', () => this.exportToPDF());
        }
        
        const refreshMealsBtn = document.getElementById('refreshMealsBtn');
        if (refreshMealsBtn) {
            refreshMealsBtn.addEventListener('click', () => this.loadMeals());
        }
        
        const exportMealPdfBtn = document.getElementById('exportMealPdfBtn');
        if (exportMealPdfBtn) {
            exportMealPdfBtn.addEventListener('click', () => this.exportMealToPDF());
        }
        
        // Stock Issue Sheet button
        const exportMealIssueSheetBtn = document.getElementById('exportMealIssueSheetBtn');
        if (exportMealIssueSheetBtn) {
            exportMealIssueSheetBtn.addEventListener('click', () => this.generateIssueSheet());
        }
    }

    async loadCostingSheets() {
        try {
            console.log('Loading costing sheets for user:', this.userId);
            const response = await fetch(`../api/meals/get_costings.php?user_id=${this.userId}`);
            
            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 ${portionCost.toFixed(2)} per serving) - ${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 for this user');
                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;
        }
        
        // For per person cost, we use portionCost * servings (not multiplied by people count)
        const totalCostPerPerson = portionCost * servings;
        
        this.selectedCostings.push({
            id: costingId,
            name: costingName,
            unitCost: unitCost,
            portionCost: portionCost,
            servings: servings,
            totalCostPerPerson: totalCostPerPerson
        });
        
        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 Per Person: R 0.00';
            return;
        }
        
        let html = '';
        let totalCostPerPerson = 0;
        
        this.selectedCostings.forEach((costing, index) => {
            totalCostPerPerson += costing.totalCostPerPerson;
            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.totalCostPerPerson.toFixed(2)}</strong>
                        <br>
                        <button class="btn btn-sm btn-outline-danger mt-1" onclick="window.mealsManager.removeCosting(${index})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
        totalCostElement.textContent = `Total Cost Per Person: R ${totalCostPerPerson.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');
        const peopleCountInput = document.getElementById('peopleCount');
        if (!sellingPriceInput || !peopleCountInput) return;
        
        const sellingPricePerPerson = parseFloat(sellingPriceInput.value) || 0;
        const peopleCount = parseInt(peopleCountInput.value) || 1;
        
        // Per Person Calculations (based on per-serving costs only)
        const totalCostPerPerson = this.selectedCostings.reduce((sum, costing) => sum + costing.totalCostPerPerson, 0);
        const profitPerPerson = sellingPricePerPerson - totalCostPerPerson;
        const gpPercentagePerPerson = sellingPricePerPerson > 0 ? ((profitPerPerson / sellingPricePerPerson) * 100) : 0;
        
        // Total Calculations (multiplied by number of people)
        const totalRevenue = sellingPricePerPerson * peopleCount;
        const totalCost = totalCostPerPerson * peopleCount;
        const totalProfit = profitPerPerson * peopleCount;
        const gpPercentageTotal = totalRevenue > 0 ? ((totalProfit / totalRevenue) * 100) : 0;
        
        // Update Per Person Metrics
        this.updateFinancialElement('perPersonSellingPrice', sellingPricePerPerson, false);
        this.updateFinancialElement('perPersonCost', totalCostPerPerson, false);
        this.updateFinancialElement('perPersonProfit', profitPerPerson, false);
        this.updateFinancialElement('perPersonGP', gpPercentagePerPerson, true);
        
        // Update Total Metrics
        this.updateFinancialElement('totalRevenue', totalRevenue, false);
        this.updateFinancialElement('totalCost', totalCost, false);
        this.updateFinancialElement('totalProfit', totalProfit, false);
        this.updateFinancialElement('totalGP', gpPercentageTotal, true);
        
        // Update people count label
        const summaryPeopleCount = document.getElementById('summaryPeopleCount');
        if (summaryPeopleCount) {
            summaryPeopleCount.textContent = `For ${peopleCount} person${peopleCount > 1 ? 's' : ''}`;
        }
    }

    updateFinancialElement(elementId, value, isPercentage) {
        const element = document.getElementById(elementId);
        if (!element) return;
        
        if (isPercentage) {
            element.textContent = `${Math.max(0, value).toFixed(1)}%`;
            // Color coding for GP%
            if (value >= 20) {
                element.className = 'metric-value gp-good';
            } else if (value >= 10) {
                element.className = 'metric-value gp-warning';
            } else {
                element.className = 'metric-value gp-danger';
            }
        } else {
            element.textContent = `R ${value.toFixed(2)}`;
            // Color coding for profit values
            if (elementId.includes('Profit')) {
                element.className = value >= 0 ? 'metric-value gp-good' : 'metric-value gp-danger';
            } else {
                element.className = 'metric-value';
            }
        }
    }

    async saveMeal(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const sellingPricePerPerson = parseFloat(formData.get('selling_price'));
        const peopleCount = parseInt(formData.get('people_count')) || 1;
        const totalCostPerPerson = this.selectedCostings.reduce((sum, costing) => sum + costing.totalCostPerPerson, 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 (sellingPricePerPerson <= 0) {
            this.showAlert('Please enter a valid selling price per person', 'danger');
            return;
        }
        
        if (peopleCount <= 0) {
            this.showAlert('Please enter a valid number of people', 'danger');
            return;
        }
        
        const profitPerPerson = sellingPricePerPerson - totalCostPerPerson;
        const gpPercentagePerPerson = ((profitPerPerson / sellingPricePerPerson) * 100);
        
        const mealData = {
            name: formData.get('name').trim(),
            description: formData.get('description')?.trim() || '',
            category: formData.get('category')?.trim() || '',
            meal_type: formData.get('meal_type') || '',
            people_count: peopleCount,
            selling_price: sellingPricePerPerson, // This is now per person
            costings: this.selectedCostings,
            total_cost: totalCostPerPerson, // This is now per person
            profit: profitPerPerson, // This is now per person
            gp_percentage: gpPercentagePerPerson,
            user_id: this.userId
        };
        
        // Add meal ID if editing
        if (this.editingMealId) {
            mealData.meal_id = this.editingMealId;
        }
        
        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('../api/meals/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();
            document.getElementById('peopleCount').value = 1;
        }
        this.selectedCostings = [];
        this.editingMealId = null;
        this.updateSelectedCostingsDisplay();
        this.updateFinancialSummary();
    }

    async loadMeals() {
        try {
            console.log('Loading meals for user:', this.userId);
            const url = `../api/meals/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="8" 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.people_count || 1} people</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="window.mealsManager.viewMeal(${meal.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-warning me-1" onclick="window.mealsManager.editMeal(${meal.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <form method="post" action="issue_sheets.php" class="d-inline me-1">
                            <input type="hidden" name="meal_id" value="${meal.id}">
                            <input type="hidden" name="people_count" value="${meal.people_count || 1}">
                            <button type="submit" name="generate_issue_sheet" 
                                    class="btn btn-sm btn-issue"
                                    title="Generate Stock Issue Sheet">
                                <i class="fas fa-file-export"></i>
                            </button>
                        </form>
                        <button class="btn btn-sm btn-outline-danger" onclick="window.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) {
        this.currentViewingMealId = 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;
        
        const peopleCount = meal.people_count || 1;
        
        // Calculate totals from per-person values
        const totalRevenue = parseFloat(meal.selling_price || 0) * peopleCount;
        const totalCost = parseFloat(meal.total_cost || 0) * peopleCount;
        const totalProfit = parseFloat(meal.profit || 0) * peopleCount;
        const gpPercentageTotal = totalRevenue > 0 ? ((totalProfit / totalRevenue) * 100) : 0;
        
        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>
                    <p><strong>People:</strong> ${peopleCount}</p>
                </div>
                <div class="col-md-6">
                    <h6>Financial Summary</h6>
                    <div class="mb-3">
                        <h6 class="text-success">Per Person Metrics</h6>
                        <p><strong>Selling Price:</strong> R ${parseFloat(meal.selling_price || 0).toFixed(2)}</p>
                        <p><strong>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 class="mb-3">
                        <h6 class="text-success">Total Metrics</h6>
                        <p><strong>Total Revenue:</strong> R ${totalRevenue.toFixed(2)}</p>
                        <p><strong>Total Cost:</strong> R ${totalCost.toFixed(2)}</p>
                        <p><strong>Total Profit:</strong> R ${totalProfit.toFixed(2)}</p>
                        <p><strong>GP%:</strong> ${gpPercentageTotal.toFixed(1)}%</p>
                    </div>
                </div>
            </div>
            <hr>
            <h6>Costing Sheets (Per Serving)</h6>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Costing Sheet</th>
                            <th>Servings</th>
                            <th>Cost Per Serving</th>
                            <th>Total Cost Per Person</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(`../api/meals/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>
                `;
            }
        }
    }

    generateIssueSheet() {
        const currentMealId = this.currentViewingMealId;
        if (!currentMealId) {
            this.showAlert('No meal selected for issue sheet generation', 'warning');
            return;
        }
        
        const meal = this.meals.find(m => m.id == currentMealId);
        if (!meal) {
            this.showAlert('Meal not found', 'danger');
            return;
        }
        
        // Create a form and submit it to issue_sheets.php
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'issue_sheets.php';
        form.style.display = 'none';
        
        const mealIdInput = document.createElement('input');
        mealIdInput.type = 'hidden';
        mealIdInput.name = 'meal_id';
        mealIdInput.value = currentMealId;
        
        const peopleCountInput = document.createElement('input');
        peopleCountInput.type = 'hidden';
        peopleCountInput.name = 'people_count';
        peopleCountInput.value = meal.people_count || 1;
        
        form.appendChild(mealIdInput);
        form.appendChild(peopleCountInput);
        document.body.appendChild(form);
        
        this.showAlert('Generating stock issue sheet...', 'info');
        form.submit();
    }

    // ... (rest of the existing methods remain the same - exportToPDF, exportMealToPDF, loadMealCostingsForPDF, generateMealPDF, editMeal, loadMealCostingsForEdit, deleteMeal)

exportToPDF() {
    if (!Array.isArray(this.meals) || this.meals.length === 0) {
        this.showAlert('No meals to export', 'warning');
        return;
    }
    
    this.showAlert('Preparing PDF export for all meals...', 'info');
    
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    
    // Set document properties
    doc.setProperties({
        title: 'Meals Export - Recipe Control Pro',
        subject: 'Meal Planning Export',
        author: 'Smart Serve Pro',
        keywords: 'meals, costing, recipes',
        creator: 'Recipe Control Pro'
    });
    
    // Add header image
    const img = new Image();
    img.src = '../assets/uploads/header2.png';
    
    img.onload = function() {
        // Calculate image dimensions to fit the PDF width while maintaining aspect ratio
        const pdfWidth = doc.internal.pageSize.getWidth();
        const imgWidth = pdfWidth - 20; // 10px margin on each side
        const imgHeight = (img.height * imgWidth) / img.width;
        
        // Add the image at the top
        doc.addImage(img, 'PNG', 10, 10, imgWidth, imgHeight);
        
        let yPosition = imgHeight + 20; // Start content below the image
        
        // Table headers
        const headers = [['Meal Name', 'Type', 'People', 'Cost P/P', 'Price P/P', 'GP%']];
        
        // Table data
        const tableData = this.meals.map(meal => [
            meal.name.substring(0, 30), // Limit name length
            meal.meal_type || 'N/A',
            meal.people_count.toString(),
            `R ${parseFloat(meal.total_cost || 0).toFixed(2)}`,
            `R ${parseFloat(meal.selling_price || 0).toFixed(2)}`,
            `${parseFloat(meal.gp_percentage || 0).toFixed(1)}%`
        ]);
        
        // Generate table
        doc.autoTable({
            head: headers,
            body: tableData,
            startY: yPosition,
            theme: 'grid',
            headStyles: {
                fillColor: [139, 0, 0], // Deep red
                textColor: 255,
                fontStyle: 'bold'
            },
            alternateRowStyles: {
                fillColor: [245, 245, 245] // Light gray for readability
            },
            styles: {
                textColor: [0, 0, 0] // Black text
            },
            margin: { top: 20 }
        });
        
        // Footer
        const pageCount = doc.internal.getNumberOfPages();
        for (let i = 1; i <= pageCount; i++) {
            doc.setPage(i);
            doc.setFontSize(8);
            doc.setTextColor(0, 0, 0); // Black text
            doc.text(`Page ${i} of ${pageCount}`, 105, 290, { align: 'center' });
            doc.text('Generated by Recipe Control Pro', 105, 293, { align: 'center' });
        }
        
        // Save the PDF
        doc.save('meals_export.pdf');
        this.showAlert('PDF file downloaded successfully', 'success');
    }.bind(this);
    
    img.onerror = function() {
        // If image fails to load, proceed without it
        console.error('Header image not found, generating PDF without header image');
        this.generatePDFWithoutImage(doc);
    }.bind(this);
}

// Fallback function if image fails to load
generatePDFWithoutImage(doc) {
    let yPosition = 20;
    
    // Table headers
    const headers = [['Meal Name', 'Type', 'People', 'Cost P/P', 'Price P/P', 'GP%']];
    
    // Table data
    const tableData = this.meals.map(meal => [
        meal.name.substring(0, 30),
        meal.meal_type || 'N/A',
        meal.people_count.toString(),
        `R ${parseFloat(meal.total_cost || 0).toFixed(2)}`,
        `R ${parseFloat(meal.selling_price || 0).toFixed(2)}`,
        `${parseFloat(meal.gp_percentage || 0).toFixed(1)}%`
    ]);
    
    // Generate table
    doc.autoTable({
        head: headers,
        body: tableData,
        startY: yPosition,
        theme: 'grid',
        headStyles: {
            fillColor: [139, 0, 0],
            textColor: 255,
            fontStyle: 'bold'
        },
        alternateRowStyles: {
            fillColor: [245, 245, 245]
        },
        styles: {
            textColor: [0, 0, 0]
        },
        margin: { top: 20 }
    });
    
    // Footer
    const pageCount = doc.internal.getNumberOfPages();
    for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(0, 0, 0);
        doc.text(`Page ${i} of ${pageCount}`, 105, 290, { align: 'center' });
        doc.text('Generated by Recipe Control Pro', 105, 293, { align: 'center' });
    }
    
    // Save the PDF
    doc.save('meals_export.pdf');
    this.showAlert('PDF file downloaded successfully', 'success');
}

    exportMealToPDF() {
        const currentMealId = this.currentViewingMealId;
        if (!currentMealId) {
            this.showAlert('No meal selected for export', 'warning');
            return;
        }
        
        const meal = this.meals.find(m => m.id == currentMealId);
        if (!meal) {
            this.showAlert('Meal not found', 'danger');
            return;
        }
        
        this.showAlert('Preparing PDF export...', 'info');
        this.loadMealCostingsForPDF(currentMealId, meal);
    }

    async loadMealCostingsForPDF(mealId, meal) {
        try {
            const response = await fetch(`../api/meals/get_meal_costings.php?meal_id=${mealId}`);
            if (!response.ok) {
                throw new Error('Failed to fetch meal costings');
            }
            const costings = await response.json();
            
            this.generateMealPDF(meal, costings);
            
        } catch (error) {
            console.error('Error loading meal costings for PDF:', error);
            this.showAlert('Error preparing PDF export. Check console for details.', 'danger');
        }
    }
generateMealPDF(meal, costings) {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    
    // Set document properties
    doc.setProperties({
        title: `Meal: ${meal.name} - Recipe Control Pro`,
        subject: 'Meal Costing Details',
        author: 'Smart Serve Pro',
        keywords: 'meal, costing, recipe, financial',
        creator: 'Recipe Control Pro'
    });
    
    // Add header image
    const img = new Image();
    img.src = '../assets/uploads/header2.png';
    
    img.onload = function() {
        // Calculate image dimensions to fit the PDF width while maintaining aspect ratio
        const pdfWidth = doc.internal.pageSize.getWidth();
        const imgWidth = pdfWidth - 20; // 10px margin on each side
        const imgHeight = (img.height * imgWidth) / img.width;
        
        // Add the image at the top
        doc.addImage(img, 'PNG', 10, 10, imgWidth, imgHeight);
        
        let yPosition = imgHeight + 20; // Start content below the image
        
        // Meal Information Section
        doc.setFontSize(14);
        doc.setTextColor(139, 0, 0); // Deep red
        doc.text('MEAL INFORMATION', 20, yPosition);
        yPosition += 10;
        
        doc.setFontSize(10);
        doc.setTextColor(0, 0, 0); // Black text
        
        const mealInfo = [
            ['Meal Name:', meal.name],
            ['Description:', meal.description || 'N/A'],
            ['Category:', meal.category || 'N/A'],
            ['Meal Type:', meal.meal_type || 'N/A'],
            ['Number of People:', meal.people_count.toString()]
        ];
        
        mealInfo.forEach(([label, value]) => {
            doc.setFont(undefined, 'bold');
            doc.text(label, 20, yPosition);
            doc.setFont(undefined, 'normal');
            doc.text(value, 60, yPosition);
            yPosition += 6;
        });
        
        yPosition += 10;
        
        // Financial Summary Section
        const peopleCount = meal.people_count || 1;
        const totalRevenue = parseFloat(meal.selling_price || 0) * peopleCount;
        const totalCost = parseFloat(meal.total_cost || 0) * peopleCount;
        const totalProfit = parseFloat(meal.profit || 0) * peopleCount;
        const gpPercentageTotal = totalRevenue > 0 ? ((totalProfit / totalRevenue) * 100) : 0;
        
        doc.setFontSize(14);
        doc.setTextColor(139, 0, 0); // Deep red
        doc.text('FINANCIAL SUMMARY', 20, yPosition);
        yPosition += 10;
        
        // Per Person Metrics
        doc.setFontSize(11);
        doc.setTextColor(0, 0, 0); // Black text
        doc.text('Per Person Metrics:', 20, yPosition);
        yPosition += 6;
        
        const perPersonData = [
            ['Selling Price:', `R ${parseFloat(meal.selling_price || 0).toFixed(2)}`],
            ['Cost:', `R ${parseFloat(meal.total_cost || 0).toFixed(2)}`],
            ['Profit:', `R ${parseFloat(meal.profit || 0).toFixed(2)}`],
            ['GP%:', `${parseFloat(meal.gp_percentage || 0).toFixed(1)}%`]
        ];
        
        perPersonData.forEach(([label, value]) => {
            doc.setFont(undefined, 'bold');
            doc.text(label, 25, yPosition);
            doc.setFont(undefined, 'normal');
            doc.text(value, 60, yPosition);
            yPosition += 5;
        });
        
        yPosition += 5;
        
        // Total Metrics
        doc.setFontSize(11);
        doc.setTextColor(0, 0, 0); // Black text
        doc.text('Total Metrics:', 20, yPosition);
        yPosition += 6;
        
        const totalData = [
            ['Total Revenue:', `R ${totalRevenue.toFixed(2)}`],
            ['Total Cost:', `R ${totalCost.toFixed(2)}`],
            ['Total Profit:', `R ${totalProfit.toFixed(2)}`],
            ['GP%:', `${gpPercentageTotal.toFixed(1)}%`]
        ];
        
        totalData.forEach(([label, value]) => {
            doc.setFont(undefined, 'bold');
            doc.text(label, 25, yPosition);
            doc.setFont(undefined, 'normal');
            doc.text(value, 60, yPosition);
            yPosition += 5;
        });
        
        yPosition += 15;
        
        // Costing Sheets Section
        doc.setFontSize(14);
        doc.setTextColor(139, 0, 0); // Deep red
        doc.text('COSTING SHEETS (PER SERVING)', 20, yPosition);
        yPosition += 10;
        
        if (Array.isArray(costings) && costings.length > 0) {
            const costingHeaders = [['Costing Sheet', 'Servings', 'Cost/Serving', 'Total Cost']];
            const costingData = costings.map(costing => [
                costing.costing_name.substring(0, 35),
                costing.servings.toString(),
                `R ${parseFloat(costing.unit_cost || 0).toFixed(2)}`,
                `R ${parseFloat(costing.total_cost || 0).toFixed(2)}`
            ]);
            
            // Add total row
            const totalCostPerPerson = costings.reduce((sum, costing) => sum + parseFloat(costing.total_cost || 0), 0);
            costingData.push(['TOTAL PER PERSON', '', '', `R ${totalCostPerPerson.toFixed(2)}`]);
            
            doc.autoTable({
                head: costingHeaders,
                body: costingData,
                startY: yPosition,
                theme: 'grid',
                headStyles: {
                    fillColor: [139, 0, 0], // Deep red
                    textColor: 255,
                    fontStyle: 'bold'
                },
                alternateRowStyles: {
                    fillColor: [245, 245, 245] // Light gray for readability
                },
                styles: {
                    fontSize: 9,
                    cellPadding: 2,
                    textColor: [0, 0, 0] // Black text
                },
                margin: { left: 20, right: 20 }
            });
        } else {
            doc.setFontSize(10);
            doc.setTextColor(0, 0, 0); // Black text
            doc.text('No costing sheets found', 20, yPosition);
        }
        
        // Footer
        const pageCount = doc.internal.getNumberOfPages();
        for (let i = 1; i <= pageCount; i++) {
            doc.setPage(i);
            doc.setFontSize(8);
            doc.setTextColor(0, 0, 0); // Black text
            doc.text(`Page ${i} of ${pageCount}`, 105, 290, { align: 'center' });
            doc.text('Generated by Recipe Control Pro', 105, 293, { align: 'center' });
        }
        
        // Save the PDF
        const filename = `meal_${meal.name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_costing.pdf`;
        doc.save(filename);
        this.showAlert('PDF file downloaded successfully!', 'success');
    }.bind(this);
    
    img.onerror = function() {
        // If image fails to load, proceed without it
        console.error('Header image not found, generating PDF without header image');
        this.generateMealPDFWithoutImage(doc, meal, costings);
    }.bind(this);
}

// Fallback function for meal PDF without image
generateMealPDFWithoutImage(doc, meal, costings) {
    let yPosition = 20;
    
    // Meal Information Section
    doc.setFontSize(14);
    doc.setTextColor(139, 0, 0); // Deep red
    doc.text('MEAL INFORMATION', 20, yPosition);
    yPosition += 10;
    
    doc.setFontSize(10);
    doc.setTextColor(0, 0, 0); // Black text
    
    const mealInfo = [
        ['Meal Name:', meal.name],
        ['Description:', meal.description || 'N/A'],
        ['Category:', meal.category || 'N/A'],
        ['Meal Type:', meal.meal_type || 'N/A'],
        ['Number of People:', meal.people_count.toString()]
    ];
    
    mealInfo.forEach(([label, value]) => {
        doc.setFont(undefined, 'bold');
        doc.text(label, 20, yPosition);
        doc.setFont(undefined, 'normal');
        doc.text(value, 60, yPosition);
        yPosition += 6;
    });
    
    yPosition += 10;
    
    // Financial Summary Section
    const peopleCount = meal.people_count || 1;
    const totalRevenue = parseFloat(meal.selling_price || 0) * peopleCount;
    const totalCost = parseFloat(meal.total_cost || 0) * peopleCount;
    const totalProfit = parseFloat(meal.profit || 0) * peopleCount;
    const gpPercentageTotal = totalRevenue > 0 ? ((totalProfit / totalRevenue) * 100) : 0;
    
    doc.setFontSize(14);
    doc.setTextColor(139, 0, 0); // Deep red
    doc.text('FINANCIAL SUMMARY', 20, yPosition);
    yPosition += 10;
    
    // Per Person Metrics
    doc.setFontSize(11);
    doc.setTextColor(0, 0, 0); // Black text
    doc.text('Per Person Metrics:', 20, yPosition);
    yPosition += 6;
    
    const perPersonData = [
        ['Selling Price:', `R ${parseFloat(meal.selling_price || 0).toFixed(2)}`],
        ['Cost:', `R ${parseFloat(meal.total_cost || 0).toFixed(2)}`],
        ['Profit:', `R ${parseFloat(meal.profit || 0).toFixed(2)}`],
        ['GP%:', `${parseFloat(meal.gp_percentage || 0).toFixed(1)}%`]
    ];
    
    perPersonData.forEach(([label, value]) => {
        doc.setFont(undefined, 'bold');
        doc.text(label, 25, yPosition);
        doc.setFont(undefined, 'normal');
        doc.text(value, 60, yPosition);
        yPosition += 5;
    });
    
    yPosition += 5;
    
    // Total Metrics
    doc.setFontSize(11);
    doc.setTextColor(0, 0, 0); // Black text
    doc.text('Total Metrics:', 20, yPosition);
    yPosition += 6;
    
    const totalData = [
        ['Total Revenue:', `R ${totalRevenue.toFixed(2)}`],
        ['Total Cost:', `R ${totalCost.toFixed(2)}`],
        ['Total Profit:', `R ${totalProfit.toFixed(2)}`],
        ['GP%:', `${gpPercentageTotal.toFixed(1)}%`]
    ];
    
    totalData.forEach(([label, value]) => {
        doc.setFont(undefined, 'bold');
        doc.text(label, 25, yPosition);
        doc.setFont(undefined, 'normal');
        doc.text(value, 60, yPosition);
        yPosition += 5;
    });
    
    yPosition += 15;
    
    // Costing Sheets Section
    doc.setFontSize(14);
    doc.setTextColor(139, 0, 0); // Deep red
    doc.text('COSTING SHEETS (PER SERVING)', 20, yPosition);
    yPosition += 10;
    
    if (Array.isArray(costings) && costings.length > 0) {
        const costingHeaders = [['Costing Sheet', 'Servings', 'Cost/Serving', 'Total Cost']];
        const costingData = costings.map(costing => [
            costing.costing_name.substring(0, 35),
            costing.servings.toString(),
            `R ${parseFloat(costing.unit_cost || 0).toFixed(2)}`,
            `R ${parseFloat(costing.total_cost || 0).toFixed(2)}`
        ]);
        
        // Add total row
        const totalCostPerPerson = costings.reduce((sum, costing) => sum + parseFloat(costing.total_cost || 0), 0);
        costingData.push(['TOTAL PER PERSON', '', '', `R ${totalCostPerPerson.toFixed(2)}`]);
        
        doc.autoTable({
            head: costingHeaders,
            body: costingData,
            startY: yPosition,
            theme: 'grid',
            headStyles: {
                fillColor: [139, 0, 0], // Deep red
                textColor: 255,
                fontStyle: 'bold'
            },
            alternateRowStyles: {
                fillColor: [245, 245, 245] // Light gray for readability
            },
            styles: {
                fontSize: 9,
                cellPadding: 2,
                textColor: [0, 0, 0] // Black text
            },
            margin: { left: 20, right: 20 }
        });
    } else {
        doc.setFontSize(10);
        doc.setTextColor(0, 0, 0); // Black text
        doc.text('No costing sheets found', 20, yPosition);
    }
    
    // Footer
    const pageCount = doc.internal.getNumberOfPages();
    for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(0, 0, 0); // Black text
        doc.text(`Page ${i} of ${pageCount}`, 105, 290, { align: 'center' });
        doc.text('Generated by Recipe Control Pro', 105, 293, { align: 'center' });
    }
    
    // Save the PDF
    const filename = `meal_${meal.name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_costing.pdf`;
    doc.save(filename);
    this.showAlert('PDF file downloaded successfully!', 'success');
}
    editMeal(mealId) {
        const meal = this.meals.find(m => m.id == mealId);
        if (!meal) {
            this.showAlert('Meal not found', 'danger');
            return;
        }
        
        this.editingMealId = mealId;
        
        // Populate form with meal data
        document.getElementById('mealName').value = meal.name;
        document.getElementById('mealDescription').value = meal.description || '';
        document.getElementById('mealCategory').value = meal.category || '';
        document.getElementById('mealType').value = meal.meal_type || '';
        document.getElementById('peopleCount').value = meal.people_count || 1;
        document.getElementById('sellingPrice').value = parseFloat(meal.selling_price || 0).toFixed(2);
        
        // Load and populate costings
        this.loadMealCostingsForEdit(mealId);
        
        // Scroll to form
        document.querySelector('.col-lg-5').scrollIntoView({ behavior: 'smooth' });
        
        this.showAlert('Meal loaded for editing. Update the details and click Save Meal.', 'info');
    }

    async loadMealCostingsForEdit(mealId) {
        try {
            const response = await fetch(`../api/meals/get_meal_costings.php?meal_id=${mealId}`);
            if (!response.ok) {
                throw new Error('Failed to fetch meal costings');
            }
            const costings = await response.json();
            
            // Clear current selections
            this.selectedCostings = [];
            
            // Add costings to selected list
            if (Array.isArray(costings) && costings.length > 0) {
                costings.forEach(costing => {
                    this.selectedCostings.push({
                        id: costing.costing_sheet_id,
                        name: costing.costing_name,
                        unitCost: parseFloat(costing.unit_cost || 0),
                        portionCost: parseFloat(costing.unit_cost || 0),
                        servings: parseInt(costing.servings || 1),
                        totalCostPerPerson: parseFloat(costing.total_cost || 0)
                    });
                });
                
                this.updateSelectedCostingsDisplay();
                this.updateFinancialSummary();
            }
            
        } catch (error) {
            console.error('Error loading meal costings for edit:', error);
            this.showAlert('Error loading meal details for editing', 'danger');
        }
    }

    async deleteMeal(mealId) {
        if (confirm('Are you sure you want to delete this meal? This action cannot be undone.')) {
            try {
                const response = await fetch(`../api/meals/delete_meal.php?meal_id=${mealId}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    this.showAlert('Meal deleted successfully', 'success');
                    this.loadMeals();
                } else {
                    this.showAlert('Error deleting meal: ' + (result.message || 'Unknown error'), 'danger');
                }
            } catch (error) {
                console.error('Error deleting meal:', error);
                this.showAlert('Error deleting meal. Please check console for details.', 'danger');
            }
        }
    }
}

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

<?php
// Fix footer path - use relative path from pages directory (SAME AS COSTING.PHP)
$footer_path = __DIR__ . '/../includes/footer.php';
if (file_exists($footer_path)) {
    include $footer_path;
} else {
    // Fallback footer if file not found
    echo '<footer class="bg-dark text-light mt-5"><div class="container py-4 text-center">Recipe Control Pro &copy; ' . date('Y') . '</div></footer>';
}
?>
</body>
</html>