<?php
include('shikanisha.kts.php');

$ingredient_id = isset($_POST['ingredient_id']) ? intval($_POST['ingredient_id']) : 0;
$name = isset($_POST['ingredient_name']) ? $_POST['ingredient_name'] : '';
$cost_per_unit = isset($_POST['ingredient_cost_per_unit']) ? floatval($_POST['ingredient_cost_per_unit']) : 0;
$buying_price = isset($_POST['ingredient_buying_price']) ? floatval($_POST['ingredient_buying_price']) : 0;

if ($ingredient_id > 0 && !empty($name) && $cost_per_unit >= 0 && $buying_price >= 0) {
    $query = "UPDATE ingredients SET name = ?, cost_per_unit = ?, buying_price = ? WHERE id = ?";
    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param('sdsi', $name, $cost_per_unit, $buying_price, $ingredient_id);
        if ($stmt->execute()) {
            $response = ['status' => 'success', 'message' => 'Ingredient updated successfully.'];
        } else {
            $response = ['status' => 'error', 'message' => 'Failed to update ingredient.'];
        }
        $stmt->close();
    } else {
        $response = ['status' => 'error', 'message' => 'Failed to prepare the SQL query.'];
    }
} else {
    $response = ['status' => 'error', 'message' => 'Invalid input data.'];
}

$conn->close();
header('Content-Type: application/json');
echo json_encode($response);
?>
