<?php
session_start();

// Check if the recipe session array exists, if not create it
if (!isset($_SESSION['recipe'])) {
    $_SESSION['recipe'] = [];
}

// Get the POST data
$id = $_POST['ingredient']['id'];  // Assuming 'id' is part of 'ingredient' array
$ingredientName = $_POST['ingredient']['name'];
$unit = $_POST['unit'];
$quantity = $_POST['quantity'];
$costprice = $_POST['ingredient']['cost_price'];
$cost =  $costprice/$quantity;

// Check if the ingredient already exists in the recipe
$ingredientExists = false;

foreach ($_SESSION['recipe'] as &$entry) {
    if ($entry['name'] === $ingredientName && $entry['unit'] === $unit) {
        // Update the quantity
        $entry['quantity'] += $quantity;
        $ingredientExists = true;
        break;
    }
}

if (!$ingredientExists) {
    // Create an ingredient entry
    $ingredientEntry = [
        'id' => $id,
        'name' => $ingredientName,
        'unit' => $unit,
        'cost' => $cost,
        'quantity' => $quantity
    ];

    // Add the ingredient to the session
    $_SESSION['recipe'][] = $ingredientEntry;
}

// Return a success response
echo json_encode(['status' => 'success', 'message' => 'Ingredient added to recipe']);
?>
