<?php
/**
 * Add Recipe API
 */
require_once '../guard.php';
require_once __DIR__ . '/../../includes/database.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);

if (empty($input['name'])) {
    echo json_encode(['success' => false, 'message' => 'Recipe name is required']);
    exit();
}

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    // Check if recipe name already exists for this user
    $checkStmt = $conn->prepare("SELECT id FROM recipes WHERE name = ? AND created_by = ?");
    $checkStmt->execute([trim($input['name']), $_SESSION['user_id']]);
    
    if ($checkStmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'A recipe with this name already exists']);
        exit();
    }
    
    // Insert new recipe
    $stmt = $conn->prepare("
        INSERT INTO recipes (name, description, category, servings, prep_time, cook_time, instructions, created_by) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        trim($input['name']),
        $input['description'] ?? null,
        $input['category'] ?? null,
        $input['servings'] ?? 1,
        $input['prep_time'] ?? null,
        $input['cook_time'] ?? null,
        $input['instructions'] ?? null,
        $_SESSION['user_id']
    ]);
    
    $recipeId = $conn->lastInsertId();
    
    // Log activity
    $logStmt = $conn->prepare("INSERT INTO activity_log (unit_id, created_by, type, label) VALUES (?, ?, 'recipe', ?)");
    $logStmt->execute([$_SESSION['unit_id'], $_SESSION['user_id'], "Created recipe: " . trim($input['name'])]);
    
    echo json_encode([
        'success' => true, 
        'message' => 'Recipe created successfully',
        'recipe_id' => $recipeId
    ]);
    
} catch (Exception $e) {
    error_log("Recipe creation error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>