35604-vm/api/save_recipe.php
Flatlogic Bot 32cc8d6cd2 4
2025-11-12 19:46:05 +00:00

62 lines
2.2 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || !isset($data['name']) || !isset($data['guests']) || !isset($data['ingredients'])) {
echo json_encode(['success' => false, 'error' => 'Invalid input.']);
exit;
}
$pdo = db();
try {
$pdo->beginTransaction();
if (isset($data['id']) && !empty($data['id'])) {
// Update existing recipe
$recipeId = $data['id'];
$stmt = $pdo->prepare("UPDATE recipes SET name = ?, guests = ? WHERE id = ?");
$stmt->execute([$data['name'], $data['guests'], $recipeId]);
// Easiest way to handle ingredients is to delete old ones and insert new ones
$stmt = $pdo->prepare("DELETE FROM ingredients WHERE recipe_id = ?");
$stmt->execute([$recipeId]);
$stmt = $pdo->prepare("INSERT INTO ingredients (recipe_id, name, quantity, unit) VALUES (?, ?, ?, ?)");
foreach ($data['ingredients'] as $ing) {
$stmt->execute([$recipeId, $ing['name'], $ing['quantity'], $ing['unit']]);
}
} else {
// Insert new recipe
$stmt = $pdo->prepare("INSERT INTO recipes (name, guests) VALUES (?, ?)");
$stmt->execute([$data['name'], $data['guests']]);
$recipeId = $pdo->lastInsertId();
$stmt = $pdo->prepare("INSERT INTO ingredients (recipe_id, name, quantity, unit) VALUES (?, ?, ?, ?)");
foreach ($data['ingredients'] as $ing) {
$stmt->execute([$recipeId, $ing['name'], $ing['quantity'], $ing['unit']]);
}
}
$pdo->commit();
// Fetch the newly created recipe to return it to the client
$stmt = $pdo->prepare("SELECT * FROM recipes WHERE id = ?");
$stmt->execute([$recipeId]);
$recipe = $stmt->fetch();
$stmt = $pdo->prepare("SELECT * FROM ingredients WHERE recipe_id = ?");
$stmt->execute([$recipeId]);
$ingredients = $stmt->fetchAll();
$recipe['ingredients'] = $ingredients;
echo json_encode(['success' => true, 'recipe' => $recipe]);
} catch (PDOException $e) {
$pdo->rollBack();
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}