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

    $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()]);
}
