<?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);
}

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// AUTH CHECK - SAME AS DASHBOARD.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 dashboard)
    $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) {
    // Ensure no HTML output for AJAX requests
    if (isset($_POST['action'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Database connection failed: ' . $t->getMessage()]);
        exit;
    } else {
        die("Error: " . $t->getMessage());
    }
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    // Ensure no previous output
    if (ob_get_length()) ob_clean();
    
    header('Content-Type: application/json');
    
    try {
        switch ($_POST['action']) {
            case 'get_ingredients':
                // Return ALL ingredients as JSON for JavaScript
                $stmt = $pdo->query("
                    SELECT i.id, i.name, i.unit, i.price, i.supplier_info 
                    FROM ingredients i 
                    ORDER BY i.name
                ");
                $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
                echo json_encode($ingredients);
                exit;
                
            case 'add_recipe':
                error_log("Starting add_recipe process for user: " . $user_id);
                
                // Validate required fields
                $recipe_name = $_POST['recipe_name'] ?? '';
                $portions = intval($_POST['portions'] ?? 0);
                
                if (empty($recipe_name)) {
                    echo json_encode(['success' => false, 'error' => 'Recipe name is required']);
                    exit;
                }
                
                if ($portions < 1) {
                    echo json_encode(['success' => false, 'error' => 'Portions must be at least 1']);
                    exit;
                }
                
                $pdo->beginTransaction();
                
                try {
                    // Insert recipe with created_by (assuming this is the correct column name)
                    $stmt = $pdo->prepare("INSERT INTO recipe_costings (recipe_name, category, portions, preparation_time, created_by) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $recipe_name,
                        $_POST['category'] ?? '',
                        $portions,
                        $_POST['preparation_time'] ?? 0,
                        $user_id
                    ]);
                    
                    $recipe_id = $pdo->lastInsertId();
                    error_log("Recipe inserted with ID: " . $recipe_id);
                    
                    $total_cost = 0;
                    
                    // Add ingredients if provided
                    if (!empty($_POST['ingredients'])) {
                        $ingredients_data = json_decode($_POST['ingredients'], true);
                        if ($ingredients_data && is_array($ingredients_data)) {
                            error_log("Adding " . count($ingredients_data) . " ingredients");
                            
                            foreach ($ingredients_data as $ing) {
                                // Validate ingredient data
                                if (!isset($ing['id']) || !isset($ing['quantity'])) {
                                    error_log("Invalid ingredient data: " . print_r($ing, true));
                                    continue;
                                }
                                
                                $ingredient_id = intval($ing['id']);
                                $quantity = floatval($ing['quantity']);
                                
                                if ($ingredient_id <= 0 || $quantity <= 0) {
                                    error_log("Invalid ingredient ID or quantity: " . $ingredient_id . ", " . $quantity);
                                    continue;
                                }
                                
                                // Get ingredient price
                                $stmt = $pdo->prepare("SELECT price FROM ingredients WHERE id = ?");
                                $stmt->execute([$ingredient_id]);
                                $ingredient = $stmt->fetch(PDO::FETCH_ASSOC);
                                
                                if ($ingredient) {
                                    $unit_cost = floatval($ingredient['price']);
                                    $line_cost = $unit_cost * $quantity;
                                    $total_cost += $line_cost;
                                    
                                    error_log("Adding ingredient: ID=$ingredient_id, Qty=$quantity, UnitCost=$unit_cost, LineCost=$line_cost");
                                    
                                    $stmt = $pdo->prepare("INSERT INTO recipe_ingredients (recipe_id, ingredient_id, quantity, unit_cost, line_cost) VALUES (?, ?, ?, ?, ?)");
                                    $stmt->execute([$recipe_id, $ingredient_id, $quantity, $unit_cost, $line_cost]);
                                } else {
                                    error_log("Ingredient not found with ID: " . $ingredient_id);
                                }
                            }
                        } else {
                            error_log("No valid ingredients data provided");
                        }
                    } else {
                        error_log("No ingredients provided in request");
                    }
                    
                    // Add preparation steps if provided
                    if (!empty($_POST['preparation_steps'])) {
                        $preparation_steps = json_decode($_POST['preparation_steps'], true);
                        if ($preparation_steps && is_array($preparation_steps)) {
                            error_log("Adding " . count($preparation_steps) . " preparation steps");
                            
                            foreach ($preparation_steps as $step) {
                                if (!isset($step['item']) || !isset($step['instruction']) || !isset($step['time'])) {
                                    continue;
                                }
                                
                                $item = trim($step['item']);
                                $instruction = trim($step['instruction']);
                                $time = trim($step['time']);
                                
                                if (empty($item) && empty($instruction) && empty($time)) {
                                    continue;
                                }
                                
                                $stmt = $pdo->prepare("INSERT INTO recipe_preparation_steps (recipe_id, item, instruction, time_allocation) VALUES (?, ?, ?, ?)");
                                $stmt->execute([$recipe_id, $item, $instruction, $time]);
                            }
                        }
                    }
                    
                    // Update total cost
                    $cost_per_portion = $portions > 0 ? $total_cost / $portions : 0;
                    $stmt = $pdo->prepare("UPDATE recipe_costings SET total_cost = ?, cost_per_portion = ? WHERE id = ?");
                    $stmt->execute([$total_cost, $cost_per_portion, $recipe_id]);
                    
                    $pdo->commit();
                    
                    error_log("Recipe saved successfully. Total cost: " . $total_cost . ", Cost per portion: " . $cost_per_portion);
                    
                    echo json_encode([
                        'success' => true, 
                        'id' => $recipe_id,
                        'message' => 'Recipe costing saved successfully!'
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    error_log("Error in add_recipe transaction: " . $e->getMessage());
                    throw $e;
                }

            case 'update_recipe':
                error_log("Starting update_recipe process for user: " . $user_id);
                
                $recipe_id = intval($_POST['recipe_id'] ?? 0);
                $recipe_name = $_POST['recipe_name'] ?? '';
                $portions = intval($_POST['portions'] ?? 0);
                
                if ($recipe_id <= 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid recipe ID']);
                    exit;
                }
                
                if (empty($recipe_name)) {
                    echo json_encode(['success' => false, 'error' => 'Recipe name is required']);
                    exit;
                }
                
                if ($portions < 1) {
                    echo json_encode(['success' => false, 'error' => 'Portions must be at least 1']);
                    exit;
                }
                
                $pdo->beginTransaction();
                
                try {
                    // Check if user has permission to edit this recipe
                    if (!$is_superuser) {
                        $checkStmt = $pdo->prepare("SELECT id FROM recipe_costings WHERE id = ? AND created_by = ?");
                        $checkStmt->execute([$recipe_id, $user_id]);
                        if (!$checkStmt->fetch()) {
                            echo json_encode(['success' => false, 'error' => 'You do not have permission to edit this recipe']);
                            exit;
                        }
                    }
                    
                    // Update recipe
                    $stmt = $pdo->prepare("UPDATE recipe_costings SET recipe_name = ?, category = ?, portions = ?, preparation_time = ? WHERE id = ?");
                    $stmt->execute([
                        $recipe_name,
                        $_POST['category'] ?? '',
                        $portions,
                        $_POST['preparation_time'] ?? 0,
                        $recipe_id
                    ]);
                    
                    // Delete existing ingredients
                    $stmt = $pdo->prepare("DELETE FROM recipe_ingredients WHERE recipe_id = ?");
                    $stmt->execute([$recipe_id]);
                    
                    // Delete existing preparation steps
                    $stmt = $pdo->prepare("DELETE FROM recipe_preparation_steps WHERE recipe_id = ?");
                    $stmt->execute([$recipe_id]);
                    
                    $total_cost = 0;
                    
                    // Add updated ingredients
                    if (!empty($_POST['ingredients'])) {
                        $ingredients_data = json_decode($_POST['ingredients'], true);
                        if ($ingredients_data && is_array($ingredients_data)) {
                            foreach ($ingredients_data as $ing) {
                                if (!isset($ing['id']) || !isset($ing['quantity'])) {
                                    continue;
                                }
                                
                                $ingredient_id = intval($ing['id']);
                                $quantity = floatval($ing['quantity']);
                                
                                if ($ingredient_id <= 0 || $quantity <= 0) {
                                    continue;
                                }
                                
                                // Get current ingredient price
                                $stmt = $pdo->prepare("SELECT price FROM ingredients WHERE id = ?");
                                $stmt->execute([$ingredient_id]);
                                $ingredient = $stmt->fetch(PDO::FETCH_ASSOC);
                                
                                if ($ingredient) {
                                    $unit_cost = floatval($ingredient['price']);
                                    $line_cost = $unit_cost * $quantity;
                                    $total_cost += $line_cost;
                                    
                                    $stmt = $pdo->prepare("INSERT INTO recipe_ingredients (recipe_id, ingredient_id, quantity, unit_cost, line_cost) VALUES (?, ?, ?, ?, ?)");
                                    $stmt->execute([$recipe_id, $ingredient_id, $quantity, $unit_cost, $line_cost]);
                                }
                            }
                        }
                    }
                    
                    // Add updated preparation steps
                    if (!empty($_POST['preparation_steps'])) {
                        $preparation_steps = json_decode($_POST['preparation_steps'], true);
                        if ($preparation_steps && is_array($preparation_steps)) {
                            foreach ($preparation_steps as $step) {
                                if (!isset($step['item']) || !isset($step['instruction']) || !isset($step['time'])) {
                                    continue;
                                }
                                
                                $item = trim($step['item']);
                                $instruction = trim($step['instruction']);
                                $time = trim($step['time']);
                                
                                if (empty($item) && empty($instruction) && empty($time)) {
                                    continue;
                                }
                                
                                $stmt = $pdo->prepare("INSERT INTO recipe_preparation_steps (recipe_id, item, instruction, time_allocation) VALUES (?, ?, ?, ?)");
                                $stmt->execute([$recipe_id, $item, $instruction, $time]);
                            }
                        }
                    }
                    
                    // Update total cost
                    $cost_per_portion = $portions > 0 ? $total_cost / $portions : 0;
                    $stmt = $pdo->prepare("UPDATE recipe_costings SET total_cost = ?, cost_per_portion = ? WHERE id = ?");
                    $stmt->execute([$total_cost, $cost_per_portion, $recipe_id]);
                    
                    $pdo->commit();
                    
                    echo json_encode([
                        'success' => true,
                        'message' => 'Recipe updated successfully!'
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    error_log("Error in update_recipe transaction: " . $e->getMessage());
                    throw $e;
                }
                
            case 'get_recipes':
                // Only show recipes for current user or all if superuser
                if ($is_superuser) {
                    $stmt = $pdo->prepare("
                        SELECT rc.*, COUNT(ri.id) as ingredient_count 
                        FROM recipe_costings rc 
                        LEFT JOIN recipe_ingredients ri ON rc.id = ri.recipe_id 
                        GROUP BY rc.id 
                        ORDER BY rc.created_at DESC
                    ");
                    $stmt->execute();
                } else {
                    $stmt = $pdo->prepare("
                        SELECT rc.*, COUNT(ri.id) as ingredient_count 
                        FROM recipe_costings rc 
                        LEFT JOIN recipe_ingredients ri ON rc.id = ri.recipe_id 
                        WHERE rc.created_by = ?
                        GROUP BY rc.id 
                        ORDER BY rc.created_at DESC
                    ");
                    $stmt->execute([$user_id]);
                }
                $recipes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                echo json_encode($recipes);
                exit;

            case 'get_recipe_details':
                $recipe_id = intval($_POST['id'] ?? 0);
                
                if ($recipe_id <= 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid recipe ID']);
                    exit;
                }
                
                // Get recipe basic info
                $stmt = $pdo->prepare("
                    SELECT rc.*, u.username as created_by_name 
                    FROM recipe_costings rc 
                    LEFT JOIN users u ON rc.created_by = u.id 
                    WHERE rc.id = ?
                ");
                $stmt->execute([$recipe_id]);
                $recipe = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$recipe) {
                    echo json_encode(['success' => false, 'error' => 'Recipe not found']);
                    exit;
                }
                
                // Get recipe ingredients WITH CURRENT PRICES AND OUTDATED FLAG
                $stmt = $pdo->prepare("
                    SELECT 
                        ri.*, 
                        i.name, 
                        i.unit,
                        i.price as current_price,
                        CASE 
                            WHEN ABS(ri.unit_cost - i.price) > 0.001 THEN 1 
                            ELSE 0 
                        END as price_outdated
                    FROM recipe_ingredients ri 
                    JOIN ingredients i ON ri.ingredient_id = i.id 
                    WHERE ri.recipe_id = ?
                    ORDER BY ri.id
                ");
                $stmt->execute([$recipe_id]);
                $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Get preparation steps
                $stmt = $pdo->prepare("
                    SELECT * FROM recipe_preparation_steps 
                    WHERE recipe_id = ?
                    ORDER BY id
                ");
                $stmt->execute([$recipe_id]);
                $preparation_steps = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true,
                    'recipe' => $recipe,
                    'ingredients' => $ingredients,
                    'preparation_steps' => $preparation_steps
                ]);
                exit;

            case 'update_ingredient_prices':
                // This will update all recipe costings when an ingredient price changes
                $ingredient_id = intval($_POST['ingredient_id'] ?? 0);
                $new_price = floatval($_POST['new_price'] ?? 0);
                
                if ($ingredient_id <= 0 || $new_price < 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid ingredient ID or price']);
                    exit;
                }
                
                $pdo->beginTransaction();
                
                try {
                    // Get the old price and ingredient details
                    $stmt = $pdo->prepare("SELECT price, name FROM ingredients WHERE id = ?");
                    $stmt->execute([$ingredient_id]);
                    $ingredient_data = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if (!$ingredient_data) {
                        throw new Exception("Ingredient not found");
                    }
                    
                    $old_price = floatval($ingredient_data['price']);
                    $ingredient_name = $ingredient_data['name'];
                    
                    // Only proceed if price actually changed significantly
                    if (abs($old_price - $new_price) < 0.001) {
                        $pdo->rollBack();
                        echo json_encode([
                            'success' => true,
                            'message' => 'Price unchanged, no updates needed',
                            'affected_recipes' => 0
                        ]);
                        exit;
                    }
                    
                    // Update the ingredient price FIRST
                    $stmt = $pdo->prepare("UPDATE ingredients SET price = ? WHERE id = ?");
                    $stmt->execute([$new_price, $ingredient_id]);
                    
                    // Log the price change in history
                    $stmt = $pdo->prepare("
                        INSERT INTO ingredient_price_history (ingredient_id, ingredient_name, old_price, new_price, changed_by, changed_at) 
                        VALUES (?, ?, ?, ?, ?, NOW())
                    ");
                    $stmt->execute([
                        $ingredient_id,
                        $ingredient_name,
                        $old_price,
                        $new_price,
                        $user_id
                    ]);
                    
                    // Get all recipes that use this ingredient WITH their current stored prices
                    $stmt = $pdo->prepare("
                        SELECT DISTINCT ri.recipe_id, ri.unit_cost as stored_unit_cost, ri.line_cost as stored_line_cost
                        FROM recipe_ingredients ri 
                        WHERE ri.ingredient_id = ?
                    ");
                    $stmt->execute([$ingredient_id]);
                    $affected_recipe_ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $affected_recipes = [];
                    foreach ($affected_recipe_ingredients as $ri) {
                        $affected_recipes[] = $ri['recipe_id'];
                    }
                    
                    // For each affected recipe, update the ingredient costs and recalculate
                    foreach ($affected_recipes as $recipe_id) {
                        // Get the quantity for this ingredient in the recipe
                        $stmt = $pdo->prepare("
                            SELECT quantity, unit_cost as stored_unit_cost
                            FROM recipe_ingredients 
                            WHERE ingredient_id = ? AND recipe_id = ?
                        ");
                        $stmt->execute([$ingredient_id, $recipe_id]);
                        $recipe_ingredient = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if (!$recipe_ingredient) continue;
                        
                        $old_unit_cost = floatval($recipe_ingredient['stored_unit_cost']);
                        $quantity = floatval($recipe_ingredient['quantity']);
                        $new_line_cost = $new_price * $quantity;
                        
                        // Only log if price actually changed significantly
                        if (abs($old_unit_cost - $new_price) > 0.001) {
                            // Log recipe price change BEFORE updating
                            $stmt = $pdo->prepare("
                                INSERT INTO recipe_price_history (recipe_id, ingredient_id, ingredient_name, old_price, new_price, changed_by, changed_at) 
                                VALUES (?, ?, ?, ?, ?, ?, NOW())
                            ");
                            $stmt->execute([
                                $recipe_id,
                                $ingredient_id,
                                $ingredient_name,
                                $old_unit_cost,
                                $new_price,
                                $user_id
                            ]);
                        }
                        
                        // Update recipe_ingredients with new price
                        $stmt = $pdo->prepare("
                            UPDATE recipe_ingredients 
                            SET unit_cost = ?, line_cost = ? 
                            WHERE ingredient_id = ? AND recipe_id = ?
                        ");
                        $stmt->execute([$new_price, $new_line_cost, $ingredient_id, $recipe_id]);
                        
                        // Recalculate total cost for this recipe
                        $stmt = $pdo->prepare("
                            SELECT SUM(line_cost) as total_cost 
                            FROM recipe_ingredients 
                            WHERE recipe_id = ?
                        ");
                        $stmt->execute([$recipe_id]);
                        $result = $stmt->fetch(PDO::FETCH_ASSOC);
                        $total_cost = floatval($result['total_cost'] ?? 0);
                        
                        // Get portions
                        $stmt = $pdo->prepare("SELECT portions FROM recipe_costings WHERE id = ?");
                        $stmt->execute([$recipe_id]);
                        $recipe = $stmt->fetch(PDO::FETCH_ASSOC);
                        $portions = intval($recipe['portions'] ?? 1);
                        
                        $cost_per_portion = $portions > 0 ? $total_cost / $portions : 0;
                        
                        // Update recipe costing
                        $stmt = $pdo->prepare("UPDATE recipe_costings SET total_cost = ?, cost_per_portion = ? WHERE id = ?");
                        $stmt->execute([$total_cost, $cost_per_portion, $recipe_id]);
                    }
                    
                    $pdo->commit();
                    
                    echo json_encode([
                        'success' => true,
                        'message' => 'Ingredient price updated and ' . count($affected_recipes) . ' recipes automatically recalculated!',
                        'affected_recipes' => count($affected_recipes)
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    error_log("Error updating ingredient prices: " . $e->getMessage());
                    echo json_encode(['success' => false, 'error' => 'Error updating prices: ' . $e->getMessage()]);
                    exit;
                }
                
            case 'recalculate_recipe':
                // Manual recalculation - should only be used as fallback
                $recipe_id = intval($_POST['id'] ?? 0);
                
                if ($recipe_id <= 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid recipe ID']);
                    exit;
                }
                
                $pdo->beginTransaction();
                
                try {
                    // Check permission
                    if (!$is_superuser) {
                        $checkStmt = $pdo->prepare("SELECT id FROM recipe_costings WHERE id = ? AND created_by = ?");
                        $checkStmt->execute([$recipe_id, $user_id]);
                        if (!$checkStmt->fetch()) {
                            echo json_encode(['success' => false, 'error' => 'You do not have permission to recalculate this recipe']);
                            exit;
                        }
                    }
                    
                    // Get all ingredients for this recipe with current prices
                    $stmt = $pdo->prepare("
                        SELECT ri.ingredient_id, ri.quantity, ri.unit_cost as old_unit_cost, i.price as new_price, i.name
                        FROM recipe_ingredients ri
                        JOIN ingredients i ON ri.ingredient_id = i.id
                        WHERE ri.recipe_id = ?
                    ");
                    $stmt->execute([$recipe_id]);
                    $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $total_cost = 0;
                    
                    // Update each ingredient line with current price
                    foreach ($ingredients as $ing) {
                        $ingredient_id = $ing['ingredient_id'];
                        $quantity = floatval($ing['quantity']);
                        $old_unit_cost = floatval($ing['old_unit_cost']);
                        $new_price = floatval($ing['new_price']);
                        $ingredient_name = $ing['name'];
                        $line_cost = $quantity * $new_price;
                        $total_cost += $line_cost;
                        
                        // Only log if price actually changed
                        if (abs($old_unit_cost - $new_price) > 0.001) {
                            // Log recipe price change history
                            $stmt = $pdo->prepare("
                                INSERT INTO recipe_price_history (recipe_id, ingredient_id, ingredient_name, old_price, new_price, changed_by, changed_at) 
                                VALUES (?, ?, ?, ?, ?, ?, NOW())
                            ");
                            $stmt->execute([
                                $recipe_id,
                                $ingredient_id,
                                $ingredient_name,
                                $old_unit_cost,
                                $new_price,
                                $user_id
                            ]);
                        }
                        
                        // Update ingredient in recipe
                        $updateStmt = $pdo->prepare("
                            UPDATE recipe_ingredients 
                            SET unit_cost = ?, line_cost = ? 
                            WHERE recipe_id = ? AND ingredient_id = ?
                        ");
                        $updateStmt->execute([$new_price, $line_cost, $recipe_id, $ingredient_id]);
                    }
                    
                    // Get portions for this recipe
                    $stmt = $pdo->prepare("SELECT portions FROM recipe_costings WHERE id = ?");
                    $stmt->execute([$recipe_id]);
                    $recipe = $stmt->fetch(PDO::FETCH_ASSOC);
                    $portions = intval($recipe['portions'] ?? 1);
                    $cost_per_portion = $portions > 0 ? $total_cost / $portions : 0;
                    
                    // Update recipe totals
                    $stmt = $pdo->prepare("UPDATE recipe_costings SET total_cost = ?, cost_per_portion = ? WHERE id = ?");
                    $stmt->execute([$total_cost, $cost_per_portion, $recipe_id]);
                    
                    $pdo->commit();
                    
                    echo json_encode([
                        'success' => true,
                        'message' => 'Recipe manually recalculated with current prices!',
                        'total_cost' => $total_cost,
                        'cost_per_portion' => $cost_per_portion
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    error_log("Error recalculating recipe: " . $e->getMessage());
                    echo json_encode(['success' => false, 'error' => 'Error recalculating: ' . $e->getMessage()]);
                    exit;
                }
                
            case 'get_recipe_price_history':
                // Get price history for a specific recipe
                $recipe_id = intval($_POST['recipe_id'] ?? 0);
                
                if ($recipe_id <= 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid recipe ID']);
                    exit;
                }
                
                try {
                    // Get recipe price history
                    $stmt = $pdo->prepare("
                        SELECT 
                            rph.*,
                            u.username as changed_by_name,
                            DATE_FORMAT(rph.changed_at, '%Y-%m-%d %H:%i:%s') as changed_at_formatted
                        FROM recipe_price_history rph
                        LEFT JOIN users u ON rph.changed_by = u.id
                        WHERE rph.recipe_id = ? 
                        ORDER BY rph.changed_at DESC
                        LIMIT 50
                    ");
                    $stmt->execute([$recipe_id]);
                    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    echo json_encode([
                        'success' => true,
                        'history' => $history
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    error_log("Error getting recipe price history: " . $e->getMessage());
                    echo json_encode(['success' => false, 'error' => 'Error retrieving price history: ' . $e->getMessage()]);
                    exit;
                }
                
            case 'get_ingredient_price_history':
                // Get price history for a specific ingredient
                $ingredient_id = intval($_POST['ingredient_id'] ?? 0);
                
                if ($ingredient_id <= 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid ingredient ID']);
                    exit;
                }
                
                try {
                    // Get ingredient price history
                    $stmt = $pdo->prepare("
                        SELECT 
                            iph.*,
                            u.username as changed_by_name,
                            DATE_FORMAT(iph.changed_at, '%Y-%m-%d %H:%i:%s') as changed_at_formatted
                        FROM ingredient_price_history iph
                        LEFT JOIN users u ON iph.changed_by = u.id
                        WHERE iph.ingredient_id = ? 
                        ORDER BY iph.changed_at DESC
                        LIMIT 50
                    ");
                    $stmt->execute([$ingredient_id]);
                    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    echo json_encode([
                        'success' => true,
                        'history' => $history
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    error_log("Error getting ingredient price history: " . $e->getMessage());
                    echo json_encode(['success' => false, 'error' => 'Error retrieving price history: ' . $e->getMessage()]);
                    exit;
                }
                
            case 'delete_recipe':
                $recipe_id = intval($_POST['id'] ?? 0);
                
                if ($recipe_id <= 0) {
                    echo json_encode(['success' => false, 'error' => 'Invalid recipe ID']);
                    exit;
                }
                
                // Check if user has permission to delete this recipe
                if ($is_superuser) {
                    // Superuser can delete any recipe
                    $stmt = $pdo->prepare("DELETE FROM recipe_costings WHERE id = ?");
                    $stmt->execute([$recipe_id]);
                } else {
                    // Regular user can only delete their own recipes
                    $stmt = $pdo->prepare("DELETE FROM recipe_costings WHERE id = ? AND created_by = ?");
                    $stmt->execute([$recipe_id, $user_id]);
                }
                
                if ($stmt->rowCount() > 0) {
                    echo json_encode(['success' => true, 'message' => 'Recipe deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Recipe not found or you do not have permission to delete it']);
                }
                exit;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Unknown action']);
                exit;
        }
    } catch (Exception $e) {
        error_log("Error in AJAX handler: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'Server error: ' . $e->getMessage()]);
        exit;
    }
}

$pageTitle = "Smart Serve Pro - Recipe Costings";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Smart Serve Pro</title>
    
    <!-- Bootstrap CSS -->
    <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.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        /* Fix for modal backdrop */
        body.modal-open {
            overflow: auto !important;
            padding-right: 0 !important;
        }
        
        .modal-backdrop {
            z-index: 1040 !important;
        }
        
        .modal {
            z-index: 1050 !important;
        }
        
        /* Price History Table Styles */
        .price-history-table {
            font-size: 14px;
        }

        .price-history-table th {
            background: #8B0000;
            color: white;
            font-weight: 600;
            white-space: nowrap;
        }

        .price-history-table .text-success {
            color: #198754 !important;
            font-weight: 600;
        }

        .price-history-table .text-danger {
            color: #dc3545 !important;
            font-weight: 600;
        }

        .price-history-table .text-muted {
            color: #6c757d !important;
        }

        .price-history-table .table-info {
            background-color: #e7f1ff;
        }

        /* Keep existing styles, add new ones for preparation steps table */
        .preparation-steps-table {
            background: white;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            margin: 20px 0;
            overflow: hidden;
        }
        
        .preparation-steps-table table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .preparation-steps-table th {
            background: #8B0000;
            color: white;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
        }
        
        .preparation-steps-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
            vertical-align: top;
        }
        
        .preparation-steps-table tr:last-child td {
            border-bottom: none;
        }
        
        .preparation-steps-table tr:hover {
            background: #f8f9fa;
        }
        
        .preparation-steps-table .step-row {
            position: relative;
        }
        
        .preparation-steps-table .step-number {
            position: absolute;
            left: 5px;
            top: 12px;
            color: #6c757d;
            font-weight: 600;
        }
        
        .preparation-steps-table input,
        .preparation-steps-table textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            font-size: 14px;
            background: white;
        }
        
        .preparation-steps-table textarea {
            min-height: 80px;
            resize: vertical;
        }
        
        .preparation-steps-table input:focus,
        .preparation-steps-table textarea:focus {
            outline: none;
            border-color: #d32f2f;
            box-shadow: 0 0 0 3px rgba(211, 47, 47, 0.1);
        }
        
        .step-actions {
            display: flex;
            gap: 8px;
            justify-content: center;
        }
        
        .step-actions button {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .add-step-row {
            background: #f8f9fa;
            padding: 15px;
            text-align: center;
            border-top: 2px solid #e9ecef;
        }
        
        .time-input {
            max-width: 100px;
        }
        
        .preparation-steps-container {
            margin-top: 10px;
        }
        
        .step-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .step-header h3 {
            margin: 0;
            color: #495057;
            font-weight: 600;
        }
        
        /* Keep all existing styles from previous file */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background: #f5f5f5;
            padding-top: 0;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            flex: 1;
        }
        
        .page-title {
            background: #8B0000 !important; /* Deep red */;
            color: white;
            padding: 30px;
            margin-bottom: 0;
            border-radius: 10px 10px 0 0;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .page-title h1 {
            margin: 0 0 10px 0;
            font-size: 32px;
            font-weight: 700;
        }
        
        .page-title p {
            margin: 0;
            font-size: 16px;
            opacity: 0.9;
        }
        
        .tabs {
            display: flex;
            background: white;
            border-bottom: 1px solid #dee2e6;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .tab {
            padding: 15px 30px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            font-weight: 600;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
            color: #6c757d;
        }
        
        .tab:hover {
            background: #f8f9fa;
            color: #495057;
        }
        
        .tab.active {
            border-bottom-color: #d32f2f;
            color: #d32f2f;
            background: #f8f9fa;
        }
        
        .tab-content {
            display: none;
            background: white;
            padding: 30px;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 2px 20px rgba(0,0,0,0.1);
            margin-top: 0;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-section {
            margin-bottom: 30px;
            padding: 25px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #d32f2f;
        }
        
        .form-section h3 {
            color: #495057;
            margin-bottom: 20px;
            font-weight: 600;
        }
        
        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            flex: 1;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #495057;
            font-size: 14px;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            font-size: 14px;
            box-sizing: border-box;
            transition: all 0.3s ease;
        }
        
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #d32f2f;
            box-shadow: 0 0 0 3px rgba(211, 47, 47, 0.1);
        }
        
        .ingredient-selector {
            background: white;
            padding: 25px;
            border-radius: 8px;
            margin: 25px 0;
            border: 2px dashed #e9ecef;
        }
        
        .ingredient-selector h3 {
            margin: 0 0 20px 0;
            color: #495057;
            font-weight: 600;
        }
        
        .selector-row {
            display: flex;
            gap: 15px;
            align-items: end;
        }
        
        .selector-row .form-group {
            margin-bottom: 0;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #d32f2f;
            color: white;
        }
        
        .btn-primary:hover {
            background: #b71c1c;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(211, 47, 47, 0.4);
        }
        
        .btn-success {
            background: #388e3c;
            color: white;
        }
        
        .btn-success:hover {
            background: #2e7d32;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(56, 142, 60, 0.4);
        }
        
        .btn-outline {
            background: transparent;
            border: 2px solid #6c757d;
            color: #6c757d;
        }
        
        .btn-outline:hover {
            background: #6c757d;
            color: white;
        }
        
        .btn-sm {
            padding: 8px 16px;
            font-size: 12px;
            margin: 2px;
        }
        
        .btn-sm i {
            font-size: 12px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }
        
        th {
            background: #d32f2f;
            color: white;
            font-weight: 600;
            font-size: 14px;
        }
        
        tr:hover {
            background: #f8f9fa;
        }
        
        .cost-summary {
            background: #d32f2f;
            color: white;
            padding: 25px;
            border-radius: 8px;
            margin: 25px 0;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .cost-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            font-size: 16px;
        }
        
        .total-cost {
            font-weight: 700;
            font-size: 20px;
            border-top: 2px solid rgba(255,255,255,0.3);
            padding-top: 15px;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
            color: #6c757d;
            font-style: italic;
            font-size: 16px;
        }
        
        .actions {
            text-align: right;
            margin-top: 30px;
        }
        
        .error {
            color: #dc3545;
            font-size: 12px;
            margin-top: 5px;
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        
        .modal-content {
            border-radius: 10px;
            border: none;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: #d32f2f;
            color: white;
            border-bottom: none;
            border-radius: 10px 10px 0 0;
            padding: 20px 25px;
        }
        
        .modal-footer {
            border-top: 1px solid #e9ecef;
            padding: 20px 25px;
        }
        
        .custom-ingredient-btn {
            background: #ff6b35;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .custom-ingredient-btn:hover {
            background: #e55a2b;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(255, 107, 53, 0.4);
        }
        
        .alert-info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
            border-radius: 6px;
        }
        
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            border-radius: 6px;
        }
        
        .alert-danger {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            border-radius: 6px;
        }
        
        .delete-modal .modal-header {
            background: #dc3545;
        }
        
        .edit-ingredient-item {
            background: #f8f9fa;
            padding: 15px;
            margin: 8px 0;
            border-radius: 6px;
            border-left: 4px solid #d32f2f;
            transition: all 0.3s ease;
        }
        
        .edit-ingredient-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        
        .price-update-alert {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 15px;
            margin: 15px 0;
            font-size: 14px;
            color: #856404;
        }
        
        .price-outdated {
            background: #f8d7da !important;
            border-left: 4px solid #dc3545 !important;
        }
        
        .price-update-btn {
            background: #ffc107;
            border: none;
            color: #212529;
        }
        
        .price-update-btn:hover {
            background: #e0a800;
            color: #212529;
        }

        .view-modal .modal-lg {
            max-width: 900px;
        }

        .recipe-details {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .recipe-details h4 {
            color: #d32f2f;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .ingredient-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .cost-breakdown {
            background: white;
            padding: 20px;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .pdf-preview {
            background: #d32f2f;
            color: white;
            padding: 30px;
            border-radius: 8px;
            text-align: center;
            margin-top: 20px;
        }

        .pdf-icon {
            font-size: 48px;
            color: white;
            margin-bottom: 15px;
        }

        .recipe-header {
            border-bottom: 3px solid #d32f2f;
            padding-bottom: 15px;
            margin-bottom: 25px;
        }

        .ingredient-row {
            border-bottom: 1px solid #e9ecef;
            padding: 12px 0;
            transition: all 0.3s ease;
        }

        .ingredient-row:hover {
            background: #f8f9fa;
        }

        .ingredient-row:last-child {
            border-bottom: none;
        }
        
        .preparation-steps-view {
            background: white;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            margin-top: 20px;
            overflow: hidden;
        }
        
        .preparation-steps-view table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .preparation-steps-view th {
            background: #8B0000;
            color: white;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
        }
        
        .preparation-steps-view td {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .preparation-steps-view tr:last-child td {
            border-bottom: none;
        }
        
        .preparation-steps-view tr:nth-child(even) {
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <?php
    // Fix navbar path - use relative path from pages directory
    $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>';
    }
    ?>

    <div class="container">
        <div class="page-title">
            <h1>Recipe Costing</h1>
            <p>Create and manage recipe costing calculations</p>
        </div>
        
        <div class="tabs">
            <button class="tab active" onclick="switchTab('new-costing')">New Costing Sheet</button>
            <button class="tab" onclick="switchTab('saved-costings')">Saved Costing Sheets</button>
        </div>
        
        <div id="new-costing" class="tab-content active">
            <form id="recipeForm">
                <div class="form-section">
                    <h3>Recipe Information</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="recipe_name">Recipe Name *</label>
                            <input type="text" id="recipe_name" name="recipe_name" required placeholder="Enter recipe name">
                            <div id="recipe_name_error" class="error"></div>
                        </div>
                        <div class="form-group">
                            <label for="category">Category</label>
                            <input type="text" id="category" name="category" placeholder="e.g., Main Course, Dessert">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="portions">Yield (Portions) *</label>
                            <input type="number" id="portions" name="portions" min="1" value="1" required>
                            <div id="portions_error" class="error"></div>
                        </div>
                        <div class="form-group">
                            <label for="preparation_time">Total Preparation Time (minutes)</label>
                            <input type="number" id="preparation_time" name="preparation_time" min="0" value="0">
                            <small class="text-muted">Total estimated time for all steps</small>
                        </div>
                    </div>
                </div>
                
                <div class="ingredient-selector">
                    <h3>Add Ingredients</h3>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        All ingredients from the system are available. Select ingredients and quantities to build your recipe.
                    </div>
                    <div class="selector-row">
                        <div class="form-group" style="flex: 0.3;">
                            <label>Quantity</label>
                            <input type="number" id="ingredient_qty" step="0.01" min="0.01" placeholder="0.00">
                            <div id="qty_error" class="error"></div>
                        </div>
                        <div class="form-group" style="flex: 0.6;">
                            <label>Select Ingredients</label>
                            <select id="ingredient_select">
                                <option value="">-- Select Ingredient --</option>
                            </select>
                            <div id="ingredient_error" class="error"></div>
                        </div>
                        <div class="form-group" style="flex: 0.2;">
                            <button type="button" class="btn btn-primary" onclick="addIngredient()" style="width: 100%; margin-top: 23px;">
                                <i class="fas fa-plus me-2"></i>Add
                            </button>
                        </div>
                    </div>
                    <div style="text-align: center; margin: 15px 0;">
                        <span style="color: #666; font-weight: 600;">OR</span>
                    </div>
                    <div style="text-align: center;">
                        <button type="button" class="btn custom-ingredient-btn" onclick="openCustomIngredientModal()">
                            <i class="fas fa-plus-circle me-2"></i>Add Custom Ingredient
                        </button>
                    </div>
                    <div id="ingredient-count" style="margin-top: 15px; font-size: 14px; color: #666; text-align: center;">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading available ingredients...
                    </div>
                </div>
                
                <div class="form-section">
                    <h3>Recipe Ingredients</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>Ingredient</th>
                                <th>Quantity</th>
                                <th>Unit Cost</th>
                                <th>Line Cost</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="ingredients-tbody">
                            <tr>
                                <td colspan="5" class="empty-state">No ingredients added yet. Start by adding ingredients above.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- New Preparation Steps Section -->
                <div class="form-section">
                    <div class="step-header">
                        <h3>Preparation Steps</h3>
                        <button type="button" class="btn btn-outline" onclick="addStepRow()">
                            <i class="fas fa-plus me-2"></i>Add Step
                        </button>
                    </div>
                    
                    <div class="preparation-steps-container">
                        <div class="preparation-steps-table">
                            <table id="preparation-steps-table">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="30%">Recipe Item</th>
                                        <th width="50%">Instruction</th>
                                        <th width="15%">Time Allocation</th>
                                        <th width="10%">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="preparation-steps-tbody">
                                    <!-- Steps will be added here dynamically -->
                                    <tr class="step-row empty-row">
                                        <td colspan="5" class="empty-state">No preparation steps added yet. Click "Add Step" to start.</td>
                                    </tr>
                                </tbody>
                            </table>
                            <div class="add-step-row">
                                <button type="button" class="btn btn-outline" onclick="addStepRow()">
                                    <i class="fas fa-plus me-2"></i>Add Another Step
                                </button>
                            </div>
                        </div>
                        <small class="text-muted">Add each preparation step with item, detailed instructions, and time allocation.</small>
                    </div>
                </div>
                
                <div class="cost-summary">
                    <div class="cost-item total-cost">
                        <span>Total Recipe Cost:</span>
                        <span id="total-cost">R 0.00</span>
                    </div>
                    <div class="cost-item">
                        <span>Cost per Portion:</span>
                        <span id="cost-per-portion">R 0.00</span>
                    </div>
                </div>
                
                <div id="form-message"></div>
                
                <div class="actions">
                    <button type="button" class="btn btn-outline" onclick="clearForm()">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save me-2"></i>Save Costing Sheet
                    </button>
                </div>
            </form>
        </div>
        
        <div id="saved-costings" class="tab-content">
            <div class="form-section">
                <h3>Saved Costing Sheets</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Recipe Name</th>
                            <th>Category</th>
                            <th>Yield</th>
                            <th>Ingredients</th>
                            <th>Preparation Steps</th>
                            <th>Total Cost</th>
                            <th>Cost/Portion</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="recipes-tbody">
                        <tr>
                            <td colspan="9" class="empty-state">No saved costing sheets yet. Create your first recipe costing above.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- View Recipe Modal -->
    <div class="modal fade view-modal" id="viewRecipeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-eye me-2"></i>Recipe Costing Details</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="viewRecipeContent">
                        <!-- Content will be loaded dynamically -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Close
                    </button>
                    <button type="button" class="btn btn-warning" onclick="recalculateRecipeCost(currentViewRecipe.recipe.id)" id="recalculateBtn">
                        <i class="fas fa-calculator me-2"></i>Recalculate (Fallback)
                    </button>
                    <button type="button" class="btn btn-primary" onclick="downloadPDF()">
                        <i class="fas fa-download me-2"></i>Download PDF
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Recipe Modal -->
    <div class="modal fade" id="editRecipeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Recipe Costing</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editRecipeForm">
                        <input type="hidden" id="edit_recipe_id" name="recipe_id">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="edit_recipe_name">Recipe Name *</label>
                                <input type="text" id="edit_recipe_name" name="recipe_name" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_category">Category</label>
                                <input type="text" id="edit_category" name="category">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="edit_portions">Yield (Portions) *</label>
                                <input type="number" id="edit_portions" name="portions" min="1" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_preparation_time">Total Preparation Time (minutes)</label>
                                <input type="number" id="edit_preparation_time" name="preparation_time" min="0">
                            </div>
                        </div>
                        
                        <div class="ingredient-selector">
                            <h4>Edit Ingredients</h4>
                            <div class="price-update-alert">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Note:</strong> When ingredient prices are updated in the system, all recipes using those ingredients are automatically recalculated.
                            </div>
                            <div class="selector-row mt-3">
                                <div class="form-group" style="flex: 0.3;">
                                    <label>Quantity</label>
                                    <input type="number" id="edit_ingredient_qty" step="0.01" min="0.01">
                                </div>
                                <div class="form-group" style="flex: 0.6;">
                                    <label>Select Ingredients</label>
                                    <select id="edit_ingredient_select">
                                        <option value="">-- Select Ingredient --</option>
                                    </select>
                                </div>
                                <div class="form-group" style="flex: 0.2;">
                                    <button type="button" class="btn btn-primary" onclick="addEditIngredient()" style="width: 100%; margin-top: 23px;">
                                        <i class="fas fa-plus me-2"></i>Add
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div id="edit-ingredients-list">
                            <!-- Ingredients will be loaded here -->
                        </div>
                        
                        <!-- Edit Preparation Steps Section -->
                        <div class="form-section mt-4">
                            <div class="step-header">
                                <h4>Edit Preparation Steps</h4>
                                <button type="button" class="btn btn-outline" onclick="addEditStepRow()">
                                    <i class="fas fa-plus me-2"></i>Add Step
                                </button>
                            </div>
                            
                            <div class="preparation-steps-container">
                                <div class="preparation-steps-table">
                                    <table id="edit-preparation-steps-table">
                                        <thead>
                                            <tr>
                                                <th width="5%">#</th>
                                                <th width="30%">Recipe Item</th>
                                                <th width="50%">Instruction</th>
                                                <th width="15%">Time Allocation</th>
                                                <th width="10%">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="edit-preparation-steps-tbody">
                                            <!-- Steps will be added here dynamically -->
                                        </tbody>
                                    </table>
                                    <div class="add-step-row">
                                        <button type="button" class="btn btn-outline" onclick="addEditStepRow()">
                                            <i class="fas fa-plus me-2"></i>Add Another Step
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="cost-summary">
                            <div class="cost-item total-cost">
                                <span>Total Recipe Cost:</span>
                                <span id="edit-total-cost">R 0.00</span>
                            </div>
                            <div class="cost-item">
                                <span>Cost per Portion:</span>
                                <span id="edit-cost-per-portion">R 0.00</span>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="button" class="btn btn-success" onclick="updateRecipe()">
                        <i class="fas fa-save me-2"></i>Update Recipe
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade delete-modal" id="deleteRecipeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Confirm Delete</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete the recipe: <strong id="deleteRecipeName"></strong>?</p>
                    <p class="text-danger"><small>This action cannot be undone.</small></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteRecipe">
                        <i class="fas fa-trash me-2"></i>Delete Recipe
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Price Update Modal -->
    <div class="modal fade" id="priceUpdateModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-money-bill-wave me-2"></i>Update Ingredient Price</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="priceUpdateForm">
                        <input type="hidden" id="update_ingredient_id">
                        <div class="form-group">
                            <label for="update_ingredient_name">Ingredient Name</label>
                            <input type="text" id="update_ingredient_name" class="form-control" readonly>
                        </div>
                        <div class="form-group">
                            <label for="update_ingredient_price">New Price *</label>
                            <input type="number" id="update_ingredient_price" step="0.01" min="0" class="form-control" required>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            Updating this price will automatically recalculate costs for all recipes that use this ingredient.
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="button" class="btn btn-warning" onclick="confirmPriceUpdate()">
                        <i class="fas fa-sync-alt me-2"></i>Update Price
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Price History Modal -->
    <div class="modal fade" id="priceHistoryModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-history me-2"></i>Price Update History</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="priceHistoryContent">
                        <!-- Content will be loaded dynamically -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Custom Ingredient Modal -->
    <div class="modal fade" id="customIngredientModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Add Custom Ingredient</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="customIngredientForm">
                        <div class="form-group">
                            <label for="custom_ingredient_name">Ingredient Name *</label>
                            <input type="text" id="custom_ingredient_name" name="name" required>
                        </div>
                        <div class="form-group">
                            <label for="custom_ingredient_unit">Unit *</label>
                            <input type="text" id="custom_ingredient_unit" name="unit" required placeholder="e.g., kg, g, ml, L">
                        </div>
                        <div class="form-group">
                            <label for="custom_ingredient_price">Price per Unit *</label>
                            <input type="number" id="custom_ingredient_price" name="price" step="0.01" min="0" required>
                        </div>
                        <div class="form-group">
                            <label for="custom_ingredient_supplier">Supplier Info</label>
                            <input type="text" id="custom_ingredient_supplier" name="supplier_info" placeholder="Optional supplier information">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="button" class="btn btn-primary" onclick="saveCustomIngredient()">
                        <i class="fas fa-save me-2"></i>Save Ingredient
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php
    // Fix footer path - use relative path from pages directory
    $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>';
    }
    ?>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jsPDF for PDF generation -->
    <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/html2canvas/1.4.1/html2canvas.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            loadIngredients();
            
            // Setup delete confirmation button
            document.getElementById('confirmDeleteRecipe').addEventListener('click', function() {
                if (!currentDeleteRecipeId) return;
                
                const deleteBtn = this;
                const originalText = deleteBtn.innerHTML;
                deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Deleting...';
                deleteBtn.disabled = true;
                
                fetch('costing.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=delete_recipe&id=' + currentDeleteRecipeId
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        showMessage(result.message || 'Recipe deleted successfully!', 'success');
                        bootstrap.Modal.getInstance(document.getElementById('deleteRecipeModal')).hide();
                        loadRecipes();
                    } else {
                        showMessage('Error deleting recipe: ' + result.error, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('Error deleting recipe: ' + error.message, 'danger');
                })
                .finally(() => {
                    deleteBtn.innerHTML = originalText;
                    deleteBtn.disabled = false;
                    currentDeleteRecipeId = null;
                    currentDeleteRecipeName = null;
                });
            });
            
            // Add initial step row
            addStepRow();
            
            // Fix for modal backdrop issues
            document.addEventListener('hidden.bs.modal', function (event) {
                // Remove any lingering backdrop
                const backdrops = document.getElementsByClassName('modal-backdrop');
                while (backdrops[0]) {
                    backdrops[0].parentNode.removeChild(backdrops[0]);
                }
                
                // Enable body scrolling
                document.body.classList.remove('modal-open');
                document.body.style.overflow = 'auto';
                document.body.style.paddingRight = '0';
            });
        });

        let selectedIngredients = [];
        let editSelectedIngredients = [];
        let currentDeleteRecipeId = null;
        let currentDeleteRecipeName = null;
        let currentViewRecipe = null;
        let currentEditRecipeId = null;
        let stepCounter = 1;
        let editStepCounter = 1;

        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.style.display = 'none';
            });
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Show selected tab
            const targetTab = document.getElementById(tabName);
            if (targetTab) {
                targetTab.style.display = 'block';
            }
            
            // Activate clicked tab
            event.target.classList.add('active');
            
            // Load recipes if needed
            if (tabName === 'saved-costings') {
                loadRecipes();
            }
        }

        function loadIngredients() {
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_ingredients'
            })
            .then(response => {
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('Server returned non-JSON response');
                }
                return response.json();
            })
            .then(ingredients => {
                const select = document.getElementById('ingredient_select');
                const editSelect = document.getElementById('edit_ingredient_select');
                
                [select, editSelect].forEach(selectElement => {
                    selectElement.innerHTML = '<option value="">-- Select Ingredient --</option>';
                    
                    if (Array.isArray(ingredients)) {
                        ingredients.forEach(ingredient => {
                            const supplierText = ingredient.supplier_info ? ` (${ingredient.supplier_info})` : '';
                            const option = new Option(
                                `${ingredient.name} - R ${parseFloat(ingredient.price).toFixed(2)}/${ingredient.unit}${supplierText}`,
                                ingredient.id
                            );
                            option.setAttribute('data-price', ingredient.price);
                            option.setAttribute('data-unit', ingredient.unit);
                            selectElement.appendChild(option);
                        });
                    }
                });
                
                const countElement = document.getElementById('ingredient-count');
                if (countElement) {
                    countElement.innerHTML = `<i class="fas fa-check me-2"></i>Available ingredients (${Array.isArray(ingredients) ? ingredients.length : 0} items)`;
                }
            })
            .catch(error => {
                console.error('Error loading ingredients:', error);
                showMessage('Error loading ingredients: ' + error.message, 'danger');
            });
        }

        function addIngredient() {
            const qtyInput = document.getElementById('ingredient_qty');
            const select = document.getElementById('ingredient_select');
            const selectedOption = select.options[select.selectedIndex];
            
            const quantity = parseFloat(qtyInput.value);
            const ingredientId = select.value;
            
            if (!quantity || quantity <= 0) {
                showMessage('Please enter a valid quantity', 'danger');
                return;
            }
            
            if (!ingredientId) {
                showMessage('Please select an ingredient', 'danger');
                return;
            }
            
            if (selectedIngredients.find(ing => ing.id == ingredientId)) {
                showMessage('Ingredient already added', 'danger');
                return;
            }
            
            const ingredientName = selectedOption.text.split(' - ')[0];
            const ingredientUnit = selectedOption.getAttribute('data-unit');
            const ingredientPrice = parseFloat(selectedOption.getAttribute('data-price'));
            
            const ingredient = {
                id: ingredientId,
                name: ingredientName,
                quantity: quantity,
                unitCost: ingredientPrice,
                unit: ingredientUnit,
                lineCost: quantity * ingredientPrice
            };
            
            selectedIngredients.push(ingredient);
            updateIngredientsTable();
            
            qtyInput.value = '';
            select.selectedIndex = 0;
        }

        function updateIngredientsTable() {
            const tbody = document.getElementById('ingredients-tbody');
            const totalElement = document.getElementById('total-cost');
            const portionElement = document.getElementById('cost-per-portion');
            const portions = parseInt(document.getElementById('portions').value) || 1;
            
            if (selectedIngredients.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="empty-state">No ingredients added yet. Start by adding ingredients above.</td></tr>';
                totalElement.textContent = 'R 0.00';
                portionElement.textContent = 'R 0.00';
                return;
            }
            
            let totalCost = 0;
            tbody.innerHTML = '';
            
            selectedIngredients.forEach((ingredient, index) => {
                totalCost += ingredient.lineCost;
                const row = `<tr>
                    <td>${ingredient.name}</td>
                    <td>${ingredient.quantity} ${ingredient.unit}</td>
                    <td>R ${ingredient.unitCost.toFixed(2)}</td>
                    <td>R ${ingredient.lineCost.toFixed(2)}</td>
                    <td><button class="btn btn-outline btn-sm" onclick="removeIngredient(${index})"><i class="fas fa-times"></i> Remove</button></td>
                </tr>`;
                tbody.innerHTML += row;
            });
            
            const costPerPortion = totalCost / portions;
            totalElement.textContent = 'R ' + totalCost.toFixed(2);
            portionElement.textContent = 'R ' + costPerPortion.toFixed(2);
        }

        function removeIngredient(index) {
            selectedIngredients.splice(index, 1);
            updateIngredientsTable();
        }

        function addStepRow() {
            const tbody = document.getElementById('preparation-steps-tbody');
            
            // Remove empty state if present
            const emptyRow = tbody.querySelector('.empty-row');
            if (emptyRow) {
                emptyRow.remove();
            }
            
            const stepNumber = stepCounter++;
            const row = document.createElement('tr');
            row.className = 'step-row';
            row.innerHTML = `
                <td>
                    <span class="step-number">${stepNumber}</span>
                    <input type="hidden" name="step_number[]" value="${stepNumber}">
                </td>
                <td>
                    <input type="text" class="form-control" name="step_item[]" placeholder="e.g., Matlabela, Water, Salt" required>
                </td>
                <td>
                    <textarea class="form-control" name="step_instruction[]" placeholder="Detailed instructions..." rows="2" required></textarea>
                </td>
                <td>
                    <input type="text" class="form-control time-input" name="step_time[]" placeholder="e.g., 30 mins" required>
                </td>
                <td class="step-actions">
                    <button type="button" class="btn btn-outline btn-sm" onclick="removeStepRow(this)">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        }

        function addEditStepRow() {
            const tbody = document.getElementById('edit-preparation-steps-tbody');
            
            const stepNumber = editStepCounter++;
            const row = document.createElement('tr');
            row.className = 'step-row';
            row.innerHTML = `
                <td>
                    <span class="step-number">${stepNumber}</span>
                    <input type="hidden" name="edit_step_number[]" value="${stepNumber}">
                </td>
                <td>
                    <input type="text" class="form-control" name="edit_step_item[]" placeholder="e.g., Matlabela, Water, Salt" required>
                </td>
                <td>
                    <textarea class="form-control" name="edit_step_instruction[]" placeholder="Detailed instructions..." rows="2" required></textarea>
                </td>
                <td>
                    <input type="text" class="form-control time-input" name="edit_step_time[]" placeholder="e.g., 30 mins" required>
                </td>
                <td class="step-actions">
                    <button type="button" class="btn btn-outline btn-sm" onclick="removeEditStepRow(this)">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        }

        function removeStepRow(button) {
            const row = button.closest('tr');
            row.remove();
            
            // Update step numbers
            const rows = document.querySelectorAll('#preparation-steps-tbody .step-row');
            rows.forEach((row, index) => {
                const stepNumberCell = row.querySelector('.step-number');
                const stepNumberInput = row.querySelector('input[name="step_number[]"]');
                if (stepNumberCell) stepNumberCell.textContent = index + 1;
                if (stepNumberInput) stepNumberInput.value = index + 1;
            });
            
            // If no rows left, show empty state
            if (rows.length === 0) {
                const tbody = document.getElementById('preparation-steps-tbody');
                tbody.innerHTML = '<tr class="step-row empty-row"><td colspan="5" class="empty-state">No preparation steps added yet. Click "Add Step" to start.</td></tr>';
                stepCounter = 1;
            }
        }

        function removeEditStepRow(button) {
            const row = button.closest('tr');
            row.remove();
            
            // Update step numbers
            const rows = document.querySelectorAll('#edit-preparation-steps-tbody .step-row');
            rows.forEach((row, index) => {
                const stepNumberCell = row.querySelector('.step-number');
                const stepNumberInput = row.querySelector('input[name="edit_step_number[]"]');
                if (stepNumberCell) stepNumberCell.textContent = index + 1;
                if (stepNumberInput) stepNumberInput.value = index + 1;
            });
            
            editStepCounter = rows.length + 1;
        }

        function getPreparationSteps() {
            const steps = [];
            const rows = document.querySelectorAll('#preparation-steps-tbody .step-row:not(.empty-row)');
            
            rows.forEach(row => {
                const item = row.querySelector('input[name="step_item[]"]').value.trim();
                const instruction = row.querySelector('textarea[name="step_instruction[]"]').value.trim();
                const time = row.querySelector('input[name="step_time[]"]').value.trim();
                
                if (item || instruction || time) {
                    steps.push({
                        item: item,
                        instruction: instruction,
                        time: time
                    });
                }
            });
            
            return steps;
        }

        function getEditPreparationSteps() {
            const steps = [];
            const rows = document.querySelectorAll('#edit-preparation-steps-tbody .step-row');
            
            rows.forEach(row => {
                const item = row.querySelector('input[name="edit_step_item[]"]')?.value.trim() || '';
                const instruction = row.querySelector('textarea[name="edit_step_instruction[]"]')?.value.trim() || '';
                const time = row.querySelector('input[name="edit_step_time[]"]')?.value.trim() || '';
                
                if (item || instruction || time) {
                    steps.push({
                        item: item,
                        instruction: instruction,
                        time: time
                    });
                }
            });
            
            return steps;
        }

        function clearForm() {
            document.getElementById('recipeForm').reset();
            selectedIngredients = [];
            updateIngredientsTable();
            
            // Clear preparation steps
            const tbody = document.getElementById('preparation-steps-tbody');
            tbody.innerHTML = '<tr class="step-row empty-row"><td colspan="5" class="empty-state">No preparation steps added yet. Click "Add Step" to start.</td></tr>';
            stepCounter = 1;
            
            showMessage('Form cleared', 'success');
        }

        function showMessage(message, type = 'info') {
            const messageDiv = document.getElementById('form-message');
            messageDiv.innerHTML = `<div class="alert alert-${type}">${message}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 5000);
        }

        // Form submission with actual save to database
        document.getElementById('recipeForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const recipeName = document.getElementById('recipe_name').value.trim();
            const portions = document.getElementById('portions').value;
            
            if (!recipeName) {
                showMessage('Please enter a recipe name', 'danger');
                return;
            }
            
            if (!portions || portions < 1) {
                showMessage('Please enter a valid number of portions', 'danger');
                return;
            }
            
            if (selectedIngredients.length === 0) {
                showMessage('Please add at least one ingredient', 'danger');
                return;
            }
            
            const preparationSteps = getPreparationSteps();
            if (preparationSteps.length === 0) {
                showMessage('Please add at least one preparation step', 'danger');
                return;
            }
            
            const submitBtn = document.querySelector('#recipeForm button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            submitBtn.disabled = true;
            
            const formData = new FormData(this);
            formData.append('ingredients', JSON.stringify(selectedIngredients));
            formData.append('preparation_steps', JSON.stringify(preparationSteps));
            formData.append('action', 'add_recipe');
            
            fetch('costing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    return response.text().then(text => {
                        throw new Error('Server returned HTML instead of JSON: ' + text.substring(0, 100));
                    });
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    showMessage(result.message || 'Recipe costing saved successfully!', 'success');
                    setTimeout(() => {
                        clearForm();
                        switchTab('saved-costings');
                        loadRecipes();
                    }, 1500);
                } else {
                    showMessage('Error saving recipe: ' + (result.error || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                showMessage('Error saving recipe: ' + error.message, 'danger');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });

        function loadRecipes() {
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_recipes'
            })
            .then(response => response.json())
            .then(recipes => {
                const tbody = document.getElementById('recipes-tbody');
                
                if (!tbody) return;
                
                if (!Array.isArray(recipes) || recipes.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="9" class="empty-state">No saved costing sheets yet. Create your first recipe costing above.</td></tr>';
                    return;
                }
                
                tbody.innerHTML = '';
                
                recipes.forEach(recipe => {
                    // Count preparation steps
                    const stepsCount = getPreparationStepsCount(recipe.id);
                    
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${recipe.recipe_name}</td>
                        <td>${recipe.category || '-'}</td>
                        <td>${recipe.portions}</td>
                        <td>${recipe.ingredient_count || 0}</td>
                        <td>${stepsCount}</td>
                        <td>R ${parseFloat(recipe.total_cost || 0).toFixed(2)}</td>
                        <td>R ${parseFloat(recipe.cost_per_portion || 0).toFixed(2)}</td>
                        <td>${new Date(recipe.created_at).toLocaleDateString()}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn btn-outline btn-sm" onclick="viewRecipe(${recipe.id})" title="View">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-outline btn-sm" onclick="editRecipe(${recipe.id})" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-outline btn-sm" onclick="confirmDeleteRecipe(${recipe.id}, '${recipe.recipe_name.replace(/'/g, "\\'")}')" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
            })
            .catch(error => {
                console.error('Error loading recipes:', error);
                showMessage('Error loading recipes: ' + error.message, 'danger');
            });
        }

        function getPreparationStepsCount(recipeId) {
            // This would need to be fetched from the database
            // For now, return a placeholder
            return '-';
        }

        function viewRecipe(recipeId) {
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_recipe_details&id=' + recipeId
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    currentViewRecipe = result;
                    displayRecipeDetails(result);
                    const viewModal = new bootstrap.Modal(document.getElementById('viewRecipeModal'));
                    viewModal.show();
                } else {
                    showMessage('Error loading recipe: ' + result.error, 'danger');
                }
            })
            .catch(error => {
                showMessage('Error loading recipe: ' + error.message, 'danger');
            });
        }

        function displayRecipeDetails(data) {
            const content = document.getElementById('viewRecipeContent');
            const recipe = data.recipe;
            const ingredients = data.ingredients;
            const preparationSteps = data.preparation_steps || [];
            
            let ingredientsHtml = '';
            let totalCost = 0;
            
            if (ingredients && ingredients.length > 0) {
                ingredients.forEach(ingredient => {
                    totalCost += parseFloat(ingredient.line_cost);
                    const isOutdated = parseInt(ingredient.price_outdated) === 1;
                    const rowClass = isOutdated ? 'price-outdated' : '';
                    const storedPrice = parseFloat(ingredient.unit_cost);
                    const currentPrice = parseFloat(ingredient.current_price);
                    
                    // REMOVED individual history buttons - only showing price info
                    ingredientsHtml += `
                        <div class="ingredient-row ${rowClass}">
                            <div class="row">
                                <div class="col-6">
                                    ${ingredient.name}
                                    ${isOutdated ? '<span class="badge bg-warning ms-2">Price Updated</span>' : ''}
                                </div>
                                <div class="col-2">${ingredient.quantity} ${ingredient.unit}</div>
                                <div class="col-2">
                                    R ${storedPrice.toFixed(2)}
                                    ${isOutdated ? `<br><small class="text-success">Current: R ${currentPrice.toFixed(2)}</small>` : ''}
                                </div>
                                <div class="col-2">R ${parseFloat(ingredient.line_cost).toFixed(2)}</div>
                            </div>
                        </div>
                    `;
                });
            } else {
                ingredientsHtml = '<div class="empty-state">No ingredients found</div>';
            }
            
            let preparationStepsHtml = '';
            if (preparationSteps && preparationSteps.length > 0) {
                preparationStepsHtml = `
                    <div class="preparation-steps-view">
                        <table>
                            <thead>
                                <tr>
                                    <th width="5%">#</th>
                                    <th width="30%">Recipe Item</th>
                                    <th width="50%">Instruction</th>
                                    <th width="15%">Time Allocation</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                preparationSteps.forEach((step, index) => {
                    preparationStepsHtml += `
                        <tr>
                            <td>${index + 1}</td>
                            <td>${step.item || ''}</td>
                            <td>${step.instruction || ''}</td>
                            <td>${step.time_allocation || ''}</td>
                        </tr>
                    `;
                });
                
                preparationStepsHtml += `
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                preparationStepsHtml = '<div class="empty-state">No preparation steps found</div>';
            }
            
            content.innerHTML = `
                <div class="recipe-details">
                    <div class="recipe-header">
                        <h3>${recipe.recipe_name}</h3>
                        <p class="mb-1"><strong>Category:</strong> ${recipe.category || 'Not specified'}</p>
                        <p class="mb-1"><strong>Yield:</strong> ${recipe.portions} portions</p>
                        <p class="mb-1"><strong>Total Preparation Time:</strong> ${recipe.preparation_time || 0} minutes</p>
                        <p class="mb-0"><strong>Created by:</strong> ${recipe.created_by_name || 'Unknown'}</p>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <h4>Ingredients</h4>
                            <div class="ingredient-list">
                                <div class="ingredient-row">
                                    <div class="row fw-bold">
                                        <div class="col-6">Ingredient</div>
                                        <div class="col-2">Quantity</div>
                                        <div class="col-2">Unit Cost</div>
                                        <div class="col-2">Line Cost</div>
                                    </div>
                                </div>
                                ${ingredientsHtml}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h4>Preparation Steps</h4>
                            ${preparationStepsHtml}
                        </div>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <div class="cost-breakdown">
                                <h4>Cost Summary</h4>
                                <div class="cost-item">
                                    <span>Total Recipe Cost:</span>
                                    <span class="fw-bold">R ${parseFloat(recipe.total_cost || 0).toFixed(2)}</span>
                                </div>
                                <div class="cost-item">
                                    <span>Cost per Portion:</span>
                                    <span class="fw-bold text-danger">R ${parseFloat(recipe.cost_per_portion || 0).toFixed(2)}</span>
                                </div>
                                <div class="cost-item">
                                    <span>Portions:</span>
                                    <span>${recipe.portions}</span>
                                </div>
                                <button class="btn btn-outline mt-2" onclick="showRecipePriceHistory(${recipe.id}, '${recipe.recipe_name.replace(/'/g, "\\'")}')">
                                    <i class="fas fa-history me-2"></i>View Recipe Price History
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="pdf-preview mt-4">
                        <div class="pdf-icon">
                            <i class="fas fa-file-pdf"></i>
                        </div>
                        <h5>PDF Export Ready</h5>
                        <p class="text-muted">Click "Download PDF" to export this recipe costing as a professional PDF document.</p>
                    </div>
                </div>
            `;
        }

        function downloadPDF() {
            if (!currentViewRecipe) return;
            
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            const recipe = currentViewRecipe.recipe;
            const ingredients = currentViewRecipe.ingredients;
            const preparationSteps = currentViewRecipe.preparation_steps || [];
            
            // Add header image
            const img = new Image();
            img.src = '../assets/uploads/header1.png';
            
            img.onload = function() {
                // Calculate image dimensions
                const pdfWidth = doc.internal.pageSize.getWidth();
                const imgWidth = pdfWidth - 20;
                const imgHeight = (img.height * imgWidth) / img.width;
                
                // Add the image at the top
                doc.addImage(img, 'PNG', 10, 10, imgWidth, imgHeight);
                
                let yPosition = imgHeight + 25;
                doc.setTextColor(0, 0, 0);
                
                // Recipe details
                doc.setFontSize(16);
                doc.text(recipe.recipe_name, 20, yPosition);
                yPosition += 8;
                
                doc.setFontSize(10);
                doc.text(`Category: ${recipe.category || 'Not specified'}`, 20, yPosition);
                yPosition += 5;
                doc.text(`Yield: ${recipe.portions} portions`, 20, yPosition);
                yPosition += 5;
                doc.text(`Total Preparation Time: ${recipe.preparation_time || 0} minutes`, 20, yPosition);
                yPosition += 10;
                
                // Ingredients table header
                doc.setFontSize(11);
                doc.setTextColor(139, 0, 0);
                doc.text('INGREDIENTS', 20, yPosition);
                yPosition += 6;
                
                doc.setFontSize(9);
                doc.setTextColor(0, 0, 0);
                doc.setFillColor(245, 245, 245);
                doc.rect(20, yPosition, 170, 6, 'F');
                doc.text('Ingredient', 22, yPosition + 4);
                doc.text('Quantity', 80, yPosition + 4);
                doc.text('Unit Cost', 120, yPosition + 4);
                doc.text('Line Cost', 160, yPosition + 4);
                yPosition += 6;
                
                // Ingredients list
                let totalCost = 0;
                ingredients.forEach(ingredient => {
                    if (yPosition > 270) {
                        doc.addPage();
                        yPosition = 20;
                    }
                    
                    totalCost += parseFloat(ingredient.line_cost);
                    doc.text(ingredient.name.substring(0, 30), 22, yPosition + 4);
                    doc.text(`${ingredient.quantity} ${ingredient.unit}`, 80, yPosition + 4);
                    doc.text(`R ${parseFloat(ingredient.unit_cost).toFixed(2)}`, 120, yPosition + 4);
                    doc.text(`R ${parseFloat(ingredient.line_cost).toFixed(2)}`, 160, yPosition + 4);
                    yPosition += 6;
                });
                
                yPosition += 8;
                
                // Preparation Steps table header
                if (preparationSteps.length > 0) {
                    if (yPosition > 250) {
                        doc.addPage();
                        yPosition = 20;
                    }
                    
                    doc.setFontSize(11);
                    doc.setTextColor(139, 0, 0);
                    doc.text('PREPARATION STEPS', 20, yPosition);
                    yPosition += 6;
                    
                    doc.setFontSize(9);
                    doc.setTextColor(0, 0, 0);
                    doc.setFillColor(245, 245, 245);
                    doc.rect(20, yPosition, 170, 6, 'F');
                    doc.text('#', 22, yPosition + 4);
                    doc.text('Recipe Item', 30, yPosition + 4);
                    doc.text('Instruction', 80, yPosition + 4);
                    doc.text('Time', 160, yPosition + 4);
                    yPosition += 6;
                    
                    // Preparation Steps list
                    preparationSteps.forEach((step, index) => {
                        if (yPosition > 270) {
                            doc.addPage();
                            yPosition = 20;
                            // Redraw header on new page
                            doc.setFillColor(245, 245, 245);
                            doc.rect(20, yPosition, 170, 6, 'F');
                            doc.text('#', 22, yPosition + 4);
                            doc.text('Recipe Item', 30, yPosition + 4);
                            doc.text('Instruction', 80, yPosition + 4);
                            doc.text('Time', 160, yPosition + 4);
                            yPosition += 6;
                        }
                        
                        doc.text(`${index + 1}`, 22, yPosition + 4);
                        doc.text(step.item ? step.item.substring(0, 20) : '', 30, yPosition + 4);
                        doc.text(step.instruction ? step.instruction.substring(0, 40) : '', 80, yPosition + 4);
                        doc.text(step.time_allocation || '', 160, yPosition + 4);
                        yPosition += 6;
                    });
                    
                    yPosition += 8;
                }
                
                // Cost summary
                doc.setFontSize(12);
                doc.setTextColor(139, 0, 0);
                doc.text('COST SUMMARY', 20, yPosition);
                yPosition += 8;
                
                doc.setFontSize(10);
                doc.setTextColor(0, 0, 0);
                doc.text(`Total Recipe Cost: R ${parseFloat(recipe.total_cost || 0).toFixed(2)}`, 22, yPosition);
                yPosition += 6;
                doc.setTextColor(211, 47, 47);
                doc.text(`Cost per Portion: R ${parseFloat(recipe.cost_per_portion || 0).toFixed(2)}`, 22, yPosition);
                doc.setTextColor(0, 0, 0);
                yPosition += 6;
                doc.text(`Portions: ${recipe.portions}`, 22, yPosition);
                
                // Footer
                const pageCount = doc.internal.getNumberOfPages();
                for (let i = 1; i <= pageCount; i++) {
                    doc.setPage(i);
                    doc.setFontSize(8);
                    doc.setTextColor(128, 128, 128);
                    doc.text(`Page ${i} of ${pageCount}`, 105, 290, { align: 'center' });
                    doc.text(`Generated on ${new Date().toLocaleDateString()}`, 105, 295, { align: 'center' });
                }
                
                // Save the PDF
                doc.save(`Recipe_Costing_${recipe.recipe_name.replace(/[^a-zA-Z0-9]/g, '_')}.pdf`);
            };
            
            img.onerror = function() {
                console.error('Header image not found, generating PDF without header image');
                generatePDFWithoutImage(doc, recipe, ingredients, preparationSteps);
            };
        }

        function generatePDFWithoutImage(doc, recipe, ingredients, preparationSteps) {
            // Fallback PDF generation without image
            
            let yPosition = 20;
            doc.setTextColor(0, 0, 0);
            
            // Recipe details
            doc.setFontSize(16);
            doc.text(recipe.recipe_name, 20, yPosition);
            yPosition += 8;
            
            doc.setFontSize(10);
            doc.text(`Category: ${recipe.category || 'Not specified'}`, 20, yPosition);
            yPosition += 5;
            doc.text(`Yield: ${recipe.portions} portions`, 20, yPosition);
            yPosition += 5;
            doc.text(`Total Preparation Time: ${recipe.preparation_time || 0} minutes`, 20, yPosition);
            yPosition += 10;
            
            // Ingredients table header
            doc.setFontSize(11);
            doc.setTextColor(139, 0, 0);
            doc.text('INGREDIENTS', 20, yPosition);
            yPosition += 6;
            
            doc.setFontSize(9);
            doc.setTextColor(0, 0, 0);
            doc.setFillColor(245, 245, 245);
            doc.rect(20, yPosition, 170, 6, 'F');
            doc.text('Ingredient', 22, yPosition + 4);
            doc.text('Quantity', 80, yPosition + 4);
            doc.text('Unit Cost', 120, yPosition + 4);
            doc.text('Line Cost', 160, yPosition + 4);
            yPosition += 6;
            
            // Ingredients list
            let totalCost = 0;
            ingredients.forEach(ingredient => {
                if (yPosition > 270) {
                    doc.addPage();
                    yPosition = 20;
                }
                
                totalCost += parseFloat(ingredient.line_cost);
                doc.text(ingredient.name.substring(0, 30), 22, yPosition + 4);
                doc.text(`${ingredient.quantity} ${ingredient.unit}`, 80, yPosition + 4);
                doc.text(`R ${parseFloat(ingredient.unit_cost).toFixed(2)}`, 120, yPosition + 4);
                doc.text(`R ${parseFloat(ingredient.line_cost).toFixed(2)}`, 160, yPosition + 4);
                yPosition += 6;
            });
            
            yPosition += 8;
            
            // Preparation Steps table header
            if (preparationSteps && preparationSteps.length > 0) {
                if (yPosition > 250) {
                    doc.addPage();
                    yPosition = 20;
                }
                
                doc.setFontSize(11);
                doc.setTextColor(139, 0, 0);
                doc.text('PREPARATION STEPS', 20, yPosition);
                yPosition += 6;
                
                doc.setFontSize(9);
                doc.setTextColor(0, 0, 0);
                doc.setFillColor(245, 245, 245);
                doc.rect(20, yPosition, 170, 6, 'F');
                doc.text('#', 22, yPosition + 4);
                doc.text('Recipe Item', 30, yPosition + 4);
                doc.text('Instruction', 80, yPosition + 4);
                doc.text('Time', 160, yPosition + 4);
                yPosition += 6;
                
                // Preparation Steps list
                preparationSteps.forEach((step, index) => {
                    if (yPosition > 270) {
                        doc.addPage();
                        yPosition = 20;
                        // Redraw header on new page
                        doc.setFillColor(245, 245, 245);
                        doc.rect(20, yPosition, 170, 6, 'F');
                        doc.text('#', 22, yPosition + 4);
                        doc.text('Recipe Item', 30, yPosition + 4);
                        doc.text('Instruction', 80, yPosition + 4);
                        doc.text('Time', 160, yPosition + 4);
                        yPosition += 6;
                    }
                    
                    doc.text(`${index + 1}`, 22, yPosition + 4);
                    doc.text(step.item ? step.item.substring(0, 20) : '', 30, yPosition + 4);
                    doc.text(step.instruction ? step.instruction.substring(0, 40) : '', 80, yPosition + 4);
                    doc.text(step.time_allocation || '', 160, yPosition + 4);
                    yPosition += 6;
                });
                
                yPosition += 8;
            }
            
            // Cost summary
            doc.setFontSize(12);
            doc.setTextColor(139, 0, 0);
            doc.text('COST SUMMARY', 20, yPosition);
            yPosition += 8;
            
            doc.setFontSize(10);
            doc.setTextColor(0, 0, 0);
            doc.text(`Total Recipe Cost: R ${parseFloat(recipe.total_cost || 0).toFixed(2)}`, 22, yPosition);
            yPosition += 6;
            doc.setTextColor(211, 47, 47);
            doc.text(`Cost per Portion: R ${parseFloat(recipe.cost_per_portion || 0).toFixed(2)}`, 22, yPosition);
            doc.setTextColor(0, 0, 0);
            yPosition += 6;
            doc.text(`Portions: ${recipe.portions}`, 22, yPosition);
            
            // Footer
            const pageCount = doc.internal.getNumberOfPages();
            for (let i = 1; i <= pageCount; i++) {
                doc.setPage(i);
                doc.setFontSize(8);
                doc.setTextColor(128, 128, 128);
                doc.text(`Page ${i} of ${pageCount}`, 105, 290, { align: 'center' });
                doc.text(`Generated on ${new Date().toLocaleDateString()}`, 105, 295, { align: 'center' });
            }
            
            // Save the PDF
            doc.save(`Recipe_Costing_${recipe.recipe_name.replace(/[^a-zA-Z0-9]/g, '_')}.pdf`);
        }

        function editRecipe(recipeId) {
            console.log('Edit recipe called with ID:', recipeId);
            currentEditRecipeId = recipeId;
            
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_recipe_details&id=' + recipeId
            })
            .then(response => response.json())
            .then(result => {
                console.log('Edit recipe response:', result);
                if (result.success) {
                    loadEditRecipeData(result);
                    const editModal = new bootstrap.Modal(document.getElementById('editRecipeModal'));
                    editModal.show();
                } else {
                    showMessage('Error loading recipe: ' + result.error, 'danger');
                }
            })
            .catch(error => {
                console.error('Error loading recipe for edit:', error);
                showMessage('Error loading recipe: ' + error.message, 'danger');
            });
        }

        function loadEditRecipeData(data) {
            const recipe = data.recipe;
            const ingredients = data.ingredients;
            const preparationSteps = data.preparation_steps || [];
            
            // Populate form fields
            document.getElementById('edit_recipe_id').value = recipe.id;
            document.getElementById('edit_recipe_name').value = recipe.recipe_name;
            document.getElementById('edit_category').value = recipe.category || '';
            document.getElementById('edit_portions').value = recipe.portions;
            document.getElementById('edit_preparation_time').value = recipe.preparation_time || '';
            
            // Load ingredients
            editSelectedIngredients = [];
            if (ingredients && ingredients.length > 0) {
                ingredients.forEach(ingredient => {
                    editSelectedIngredients.push({
                        id: ingredient.ingredient_id,
                        name: ingredient.name,
                        quantity: parseFloat(ingredient.quantity),
                        unitCost: parseFloat(ingredient.unit_cost),
                        unit: ingredient.unit,
                        lineCost: parseFloat(ingredient.line_cost),
                        currentPrice: parseFloat(ingredient.current_price),
                        priceOutdated: parseInt(ingredient.price_outdated) === 1
                    });
                });
            }
            
            updateEditIngredientsTable();
            
            // Load preparation steps
            const tbody = document.getElementById('edit-preparation-steps-tbody');
            tbody.innerHTML = '';
            editStepCounter = 1;
            
            if (preparationSteps && preparationSteps.length > 0) {
                preparationSteps.forEach((step, index) => {
                    const row = document.createElement('tr');
                    row.className = 'step-row';
                    row.innerHTML = `
                        <td>
                            <span class="step-number">${index + 1}</span>
                            <input type="hidden" name="edit_step_number[]" value="${index + 1}">
                        </td>
                        <td>
                            <input type="text" class="form-control" name="edit_step_item[]" value="${step.item || ''}" placeholder="e.g., Matlabela, Water, Salt" required>
                        </td>
                        <td>
                            <textarea class="form-control" name="edit_step_instruction[]" placeholder="Detailed instructions..." rows="2" required>${step.instruction || ''}</textarea>
                        </td>
                        <td>
                            <input type="text" class="form-control time-input" name="edit_step_time[]" value="${step.time_allocation || ''}" placeholder="e.g., 30 mins" required>
                        </td>
                        <td class="step-actions">
                            <button type="button" class="btn btn-outline btn-sm" onclick="removeEditStepRow(this)">
                                <i class="fas fa-times"></i>
                            </button>
                        </td>
                    `;
                    tbody.appendChild(row);
                    editStepCounter = index + 2;
                });
            } else {
                addEditStepRow();
            }
        }

        function updateEditIngredientsTable() {
            const container = document.getElementById('edit-ingredients-list');
            const totalElement = document.getElementById('edit-total-cost');
            const portionElement = document.getElementById('edit-cost-per-portion');
            const portions = parseInt(document.getElementById('edit_portions').value) || 1;
            
            if (editSelectedIngredients.length === 0) {
                container.innerHTML = '<div class="empty-state">No ingredients added</div>';
                totalElement.textContent = 'R 0.00';
                portionElement.textContent = 'R 0.00';
                return;
            }
            
            let totalCost = 0;
            let html = '<h5>Current Ingredients</h5>';
            
            editSelectedIngredients.forEach((ingredient, index) => {
                totalCost += ingredient.lineCost;
                const isOutdated = ingredient.priceOutdated || (ingredient.unitCost !== ingredient.currentPrice);
                const itemClass = isOutdated ? 'edit-ingredient-item price-outdated' : 'edit-ingredient-item';
                
                html += `
                    <div class="${itemClass}">
                        <div class="row align-items-center">
                            <div class="col-4">
                                <strong>${ingredient.name}</strong>
                                ${isOutdated ? '<span class="badge bg-warning ms-2">Price Updated</span>' : ''}
                            </div>
                            <div class="col-2">
                                ${ingredient.quantity} ${ingredient.unit}
                            </div>
                            <div class="col-2">
                                R ${ingredient.unitCost.toFixed(2)}
                                ${isOutdated ? `<br><small class="text-success">Current: R ${ingredient.currentPrice.toFixed(2)}</small>` : ''}
                            </div>
                            <div class="col-2">
                                R ${ingredient.lineCost.toFixed(2)}
                            </div>
                            <div class="col-2">
                                <button type="button" class="btn btn-outline btn-sm" onclick="removeEditIngredient(${index})" title="Remove">
                                    <i class="fas fa-times"></i>
                                </button>
                                <button type="button" class="btn btn-warning btn-sm price-update-btn" onclick="openPriceUpdateModal(${ingredient.id}, '${ingredient.name.replace(/'/g, "\\'")}', ${ingredient.currentPrice})" title="Update Price">
                                    <i class="fas fa-edit"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
            
            const costPerPortion = totalCost / portions;
            totalElement.textContent = 'R ' + totalCost.toFixed(2);
            portionElement.textContent = 'R ' + costPerPortion.toFixed(2);
        }

        function addEditIngredient() {
            const qtyInput = document.getElementById('edit_ingredient_qty');
            const select = document.getElementById('edit_ingredient_select');
            const selectedOption = select.options[select.selectedIndex];
            
            const quantity = parseFloat(qtyInput.value);
            const ingredientId = select.value;
            
            if (!quantity || quantity <= 0) {
                alert('Please enter a valid quantity');
                return;
            }
            
            if (!ingredientId) {
                alert('Please select an ingredient');
                return;
            }
            
            if (editSelectedIngredients.find(ing => ing.id == ingredientId)) {
                alert('Ingredient already added');
                return;
            }
            
            const ingredientName = selectedOption.text.split(' - ')[0];
            const ingredientUnit = selectedOption.getAttribute('data-unit');
            const ingredientPrice = parseFloat(selectedOption.getAttribute('data-price'));
            
            const ingredient = {
                id: ingredientId,
                name: ingredientName,
                quantity: quantity,
                unitCost: ingredientPrice,
                unit: ingredientUnit,
                lineCost: quantity * ingredientPrice,
                currentPrice: ingredientPrice,
                priceOutdated: false
            };
            
            editSelectedIngredients.push(ingredient);
            updateEditIngredientsTable();
            
            qtyInput.value = '';
            select.selectedIndex = 0;
        }

        function removeEditIngredient(index) {
            editSelectedIngredients.splice(index, 1);
            updateEditIngredientsTable();
        }

        function updateRecipe() {
            if (!currentEditRecipeId) return;
            
            const recipeName = document.getElementById('edit_recipe_name').value.trim();
            const portions = document.getElementById('edit_portions').value;
            
            if (!recipeName) {
                alert('Please enter a recipe name');
                return;
            }
            
            if (!portions || portions < 1) {
                alert('Please enter a valid number of portions');
                return;
            }
            
            if (editSelectedIngredients.length === 0) {
                alert('Please add at least one ingredient');
                return;
            }
            
            const preparationSteps = getEditPreparationSteps();
            if (preparationSteps.length === 0) {
                alert('Please add at least one preparation step');
                return;
            }
            
            const submitBtn = document.querySelector('#editRecipeModal .btn-success');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            submitBtn.disabled = true;
            
            const formData = new FormData(document.getElementById('editRecipeForm'));
            formData.append('ingredients', JSON.stringify(editSelectedIngredients));
            formData.append('preparation_steps', JSON.stringify(preparationSteps));
            formData.append('action', 'update_recipe');
            
            fetch('costing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showMessage(result.message || 'Recipe updated successfully!', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('editRecipeModal')).hide();
                    loadRecipes();
                } else {
                    alert('Error updating recipe: ' + result.error);
                }
            })
            .catch(error => {
                alert('Error updating recipe: ' + error.message);
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }

        function openPriceUpdateModal(ingredientId, ingredientName, currentPrice) {
            document.getElementById('update_ingredient_id').value = ingredientId;
            document.getElementById('update_ingredient_name').value = ingredientName;
            document.getElementById('update_ingredient_price').value = currentPrice;
            document.getElementById('update_ingredient_price').focus();
            
            const modal = new bootstrap.Modal(document.getElementById('priceUpdateModal'));
            modal.show();
        }

        function confirmPriceUpdate() {
            const ingredientId = document.getElementById('update_ingredient_id').value;
            const newPrice = document.getElementById('update_ingredient_price').value;
            
            console.log('Updating ingredient:', {
                ingredientId: ingredientId,
                newPrice: newPrice
            });
            
            if (!ingredientId || !newPrice) {
                alert('Please enter a valid price');
                return;
            }
            
            const submitBtn = document.querySelector('#priceUpdateModal .btn-warning');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            submitBtn.disabled = true;
            
            // Log the request
            console.log('Sending request to update ingredient price...');
            
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=update_ingredient_prices&ingredient_id=' + ingredientId + '&new_price=' + newPrice
            })
            .then(response => {
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                return response.json();
            })
            .then(result => {
                console.log('Update result:', result);
                if (result.success) {
                    showMessage(result.message + ' (' + result.affected_recipes + ' recipes automatically recalculated)', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('priceUpdateModal')).hide();
                    
                    // Force reload of ingredients and refresh views
                    setTimeout(() => {
                        loadIngredients();
                        if (currentEditRecipeId) {
                            editRecipe(currentEditRecipeId);
                        }
                        if (currentViewRecipe) {
                            viewRecipe(currentViewRecipe.recipe.id);
                        }
                        loadRecipes();
                    }, 500);
                } else {
                    alert('Error updating price: ' + result.error);
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                alert('Error updating price: ' + error.message);
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }

        function refreshRecipeView() {
            if (currentViewRecipe && currentViewRecipe.recipe) {
                // Force reload by closing and reopening the modal
                const viewModal = bootstrap.Modal.getInstance(document.getElementById('viewRecipeModal'));
                if (viewModal) {
                    viewModal.hide();
                }
                
                // Small delay to ensure modal is closed
                setTimeout(() => {
                    viewRecipe(currentViewRecipe.recipe.id);
                }, 300);
            }
        }

        function recalculateRecipeCost(recipeId) {
            if (!confirm('Manually recalculate this recipe with current ingredient prices? (Use only if automatic update failed)')) return;
            
            const recalcBtn = document.getElementById('recalculateBtn');
            const originalText = recalcBtn.innerHTML;
            recalcBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Recalculating...';
            recalcBtn.disabled = true;
            
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=recalculate_recipe&id=' + recipeId
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showMessage(result.message + ' (Manual recalculation completed)', 'success');
                    refreshRecipeView(); // Refresh the view
                    loadRecipes(); // Refresh the list
                } else {
                    showMessage('Error: ' + result.error, 'danger');
                }
            })
            .catch(error => {
                showMessage('Error: ' + error.message, 'danger');
            })
            .finally(() => {
                recalcBtn.innerHTML = originalText;
                recalcBtn.disabled = false;
            });
        }

        function confirmDeleteRecipe(recipeId, recipeName) {
            currentDeleteRecipeId = recipeId;
            currentDeleteRecipeName = recipeName;
            
            document.getElementById('deleteRecipeName').textContent = recipeName;
            const deleteModal = new bootstrap.Modal(document.getElementById('deleteRecipeModal'));
            deleteModal.show();
        }

        function openCustomIngredientModal() {
            const modal = new bootstrap.Modal(document.getElementById('customIngredientModal'));
            modal.show();
        }

        function saveCustomIngredient() {
            // Implementation for saving custom ingredient
            showMessage('Custom ingredient functionality coming soon!', 'info');
        }

        // Price history functions
        function showIngredientPriceHistory(ingredientId, ingredientName) {
            // Show loading state
            const content = document.getElementById('priceHistoryContent');
            content.innerHTML = `
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading ingredient price history...</p>
                </div>
            `;
            
            const modal = new bootstrap.Modal(document.getElementById('priceHistoryModal'));
            modal.show();
            
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_ingredient_price_history&ingredient_id=' + ingredientId
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    displayIngredientPriceHistory(result.history, ingredientName);
                } else {
                    content.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading price history: ${result.error || 'Unknown error'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading price history:', error);
                content.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Error loading price history: ${error.message}
                        <p class="mt-2 small">Please check your network connection and try again.</p>
                    </div>
                `;
            });
        }

        function showRecipePriceHistory(recipeId, recipeName) {
            // Show loading state
            const content = document.getElementById('priceHistoryContent');
            content.innerHTML = `
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading recipe price history...</p>
                </div>
            `;
            
            const modal = new bootstrap.Modal(document.getElementById('priceHistoryModal'));
            modal.show();
            
            fetch('costing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_recipe_price_history&recipe_id=' + recipeId
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    displayRecipePriceHistory(result.history, recipeName);
                } else {
                    content.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading price history: ${result.error || 'Unknown error'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading price history:', error);
                content.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Error loading price history: ${error.message}
                        <p class="mt-2 small">Please check your network connection and try again.</p>
                    </div>
                `;
            });
        }

        function displayIngredientPriceHistory(history, ingredientName) {
            const content = document.getElementById('priceHistoryContent');
            
            if (!history || history.length === 0) {
                content.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-history fa-3x mb-3 text-muted"></i>
                        <h5>No Price History Found</h5>
                        <p class="text-muted">No price changes have been recorded for ${ingredientName} yet.</p>
                    </div>
                `;
                return;
            }
            
            let html = `
                <h4>Price History: ${ingredientName}</h4>
                <div class="table-responsive price-history-table">
                    <table class="table table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>Date & Time</th>
                                <th>Changed By</th>
                                <th>Old Price</th>
                                <th>New Price</th>
                                <th>Change</th>
                                <th>% Change</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            history.forEach((update, index) => {
                const oldPrice = parseFloat(update.old_price || 0);
                const newPrice = parseFloat(update.new_price || 0);
                const change = newPrice - oldPrice;
                const percentChange = oldPrice > 0 ? ((change / oldPrice) * 100).toFixed(2) : 0;
                
                // Determine color based on change
                let changeClass = 'text-muted';
                let changeSymbol = '';
                if (change > 0) {
                    changeClass = 'text-danger';
                    changeSymbol = '+';
                } else if (change < 0) {
                    changeClass = 'text-success';
                }
                
                // Format date
                const changedAt = update.changed_at_formatted || update.changed_at || update.updated_at;
                const dateObj = new Date(changedAt);
                const formattedDate = dateObj.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                html += `
                    <tr>
                        <td>${formattedDate}</td>
                        <td>${update.changed_by_name || 'Unknown'}</td>
                        <td>R ${oldPrice.toFixed(2)}</td>
                        <td>
                            <strong>R ${newPrice.toFixed(2)}</strong>
                        </td>
                        <td class="${changeClass}">
                            <strong>${changeSymbol}R ${Math.abs(change).toFixed(2)}</strong>
                        </td>
                        <td class="${changeClass}">
                            ${changeSymbol}${Math.abs(percentChange)}%
                        </td>
                    </tr>
                `;
            });
            
            html += `
                        </tbody>
                    </table>
                </div>
                
                <div class="alert alert-info mt-3">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Note:</strong> This shows all price changes for this ingredient. When a price is updated, all recipes using this ingredient are automatically recalculated.
                </div>
            `;
            
            content.innerHTML = html;
        }

        function displayRecipePriceHistory(history, recipeName) {
            const content = document.getElementById('priceHistoryContent');
            
            if (!history || history.length === 0) {
                content.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-history fa-3x mb-3 text-muted"></i>
                        <h5>No Price History Found</h5>
                        <p class="text-muted">No price changes have been recorded for ${recipeName} yet.</p>
                    </div>
                `;
                return;
            }
            
            let html = `
                <h4>Price History: ${recipeName}</h4>
                <div class="table-responsive price-history-table">
                    <table class="table table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>Date & Time</th>
                                <th>Ingredient</th>
                                <th>Changed By</th>
                                <th>Old Price</th>
                                <th>New Price</th>
                                <th>Change</th>
                                <th>% Change</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            history.forEach((update, index) => {
                const oldPrice = parseFloat(update.old_price || 0);
                const newPrice = parseFloat(update.new_price || 0);
                const change = newPrice - oldPrice;
                const percentChange = oldPrice > 0 ? ((change / oldPrice) * 100).toFixed(2) : 0;
                
                // Determine color based on change
                let changeClass = 'text-muted';
                let changeSymbol = '';
                if (change > 0) {
                    changeClass = 'text-danger';
                    changeSymbol = '+';
                } else if (change < 0) {
                    changeClass = 'text-success';
                }
                
                // Format date
                const changedAt = update.changed_at_formatted || update.changed_at || update.updated_at;
                const dateObj = new Date(changedAt);
                const formattedDate = dateObj.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                html += `
                    <tr>
                        <td>${formattedDate}</td>
                        <td>${update.ingredient_name || 'Unknown'}</td>
                        <td>${update.changed_by_name || 'Unknown'}</td>
                        <td>R ${oldPrice.toFixed(2)}</td>
                        <td>
                            <strong>R ${newPrice.toFixed(2)}</strong>
                        </td>
                        <td class="${changeClass}">
                            <strong>${changeSymbol}R ${Math.abs(change).toFixed(2)}</strong>
                        </td>
                        <td class="${changeClass}">
                            ${changeSymbol}${Math.abs(percentChange)}%
                        </td>
                    </tr>
                `;
            });
            
            html += `
                        </tbody>
                    </table>
                </div>
                
                <div class="alert alert-info mt-3">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Note:</strong> This shows all ingredient price changes that affected this recipe. Recipes are automatically recalculated when ingredient prices change.
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h6 class="card-title">Summary</h6>
                                <ul class="list-unstyled mb-0">
                                    <li>Total Changes: <strong>${history.length}</strong></li>
                                    <li>Latest Change: <strong>${history.length > 0 ? new Date(history[0].changed_at_formatted || history[0].changed_at).toLocaleDateString() : 'N/A'}</strong></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            content.innerHTML = html;
        }
    </script>
</body>
</html>