<?php
header('Content-Type: application/json');
require_once __DIR__ . '/auth_helper.php';

try {
    $pdo = db();
    $userId = get_logged_in_user_id();

    if ($userId) {
        $recipes_stmt = $pdo->prepare('SELECT * FROM recipes WHERE user_id = ? OR user_id IS NULL ORDER BY created_at DESC');
        $recipes_stmt->execute([$userId]);
    } else {
        $recipes_stmt = $pdo->query('SELECT * FROM recipes WHERE user_id IS NULL ORDER BY created_at DESC');
    }
    $recipes = $recipes_stmt->fetchAll();

    $recipeIds = array_column($recipes, 'id');
    $all_ingredients = [];
    if (!empty($recipeIds)) {
        $placeholders = implode(',', array_fill(0, count($recipeIds), '?'));
        $ingredients_stmt = $pdo->prepare("SELECT * FROM ingredients WHERE recipe_id IN ($placeholders)");
        $ingredients_stmt->execute($recipeIds);
        $all_ingredients = $ingredients_stmt->fetchAll();
    }

    $ingredients_by_recipe = [];
    foreach ($all_ingredients as $ingredient) {
        $ingredients_by_recipe[$ingredient['recipe_id']][] = $ingredient;
    }

    foreach ($recipes as $i => $recipe) {
        $recipes[$i]['ingredients'] = $ingredients_by_recipe[$recipe['id']] ?? [];
    }

    echo json_encode(['success' => true, 'recipes' => $recipes]);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
