<?php
/**
 * Kitchen Get Recipe API
 * Retrieves full recipe details for a menu item
 * Phase 4: Kitchen Ingredient Check & Recipe View
 */

header('Content-Type: application/json');
require_once 'config.php';
require_once 'ingredient_unit_helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    sendResponse(false, 'Only POST method allowed', null);
}

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

if (!isset($input['menu_item_id']) && !isset($input['recipe_id'])) {
    sendResponse(false, 'Menu item ID or recipe ID required', null);
}

try {
    $menu_item_id = isset($input['menu_item_id']) ? (int)$input['menu_item_id'] : null;
    $recipe_id = isset($input['recipe_id']) ? (int)$input['recipe_id'] : null;

    if ($menu_item_id) {
        $recipe_sql = "SELECT * FROM recipes WHERE menu_item_id = ?";
        $stmt = $conn->prepare($recipe_sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        $stmt->bind_param('i', $menu_item_id);
    } else {
        $recipe_sql = "SELECT * FROM recipes WHERE id = ?";
        $stmt = $conn->prepare($recipe_sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        $stmt->bind_param('i', $recipe_id);
    }

    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $recipe_result = $stmt->get_result();
    if ($recipe_result->num_rows === 0) {
        sendResponse(false, 'Recipe not found', null);
    }

    $recipe = $recipe_result->fetch_assoc();
    $stmt->close();

    $item_sql = "SELECT id, item_name, description, price, image_path FROM menu_items WHERE id = ?";
    $stmt = $conn->prepare($item_sql);
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    $stmt->bind_param('i', $recipe['menu_item_id']);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $item = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$item) {
        throw new Exception('Menu item not found for this recipe');
    }

    $ing_sql = "
        SELECT
            ri.id as requirement_id,
            ri.ingredient_id,
            ri.quantity_required,
            ri.unit as required_unit,
            ri.notes as ingredient_notes,
            i.id,
            i.name,
            i.description,
            i.unit as ingredient_unit,
            i.current_stock,
            i.minimum_stock,
            i.unit_cost
        FROM recipe_ingredients ri
        JOIN ingredients i ON ri.ingredient_id = i.id
        WHERE ri.recipe_id = ?
        ORDER BY ri.id ASC
    ";

    $stmt = $conn->prepare($ing_sql);
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    $stmt->bind_param('i', $recipe['id']);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $ing_result = $stmt->get_result();
    $ingredients = [];
    $ingredient_cost = 0;
    $all_in_stock = true;

    while ($ing = $ing_result->fetch_assoc()) {
        $availability = calculateIngredientAvailability(
            $ing['current_stock'],
            $ing['ingredient_unit'],
            $ing['quantity_required'],
            $ing['required_unit']
        );

        $cost_per_requirement = $availability['required_quantity_in_stock_unit'] * $ing['unit_cost'];
        $ing['cost'] = $cost_per_requirement;
        $ing['quantity_required_in_stock_unit'] = $availability['required_quantity_in_stock_unit'];
        $ing['shortage_amount'] = $availability['shortage_amount'];
        $ing['in_stock'] = $availability['in_stock'];
        $ing['units_convertible'] = $availability['units_convertible'];
        $ing['availability_status'] = $availability['in_stock']
            ? 'Available'
            : ((float)$ing['current_stock'] > 0 ? 'Partial' : 'Out of Stock');

        $ingredient_cost += $cost_per_requirement;

        if (!$availability['in_stock']) {
            $all_in_stock = false;
        }

        $ingredients[] = $ing;
    }
    $stmt->close();

    $difficulty_colors = [
        'easy' => '#4caf50',
        'medium' => '#ff9800',
        'hard' => '#f44336'
    ];

    sendResponse(true, 'Recipe retrieved successfully', [
        'item' => [
            'id' => $item['id'],
            'name' => $item['item_name'],
            'description' => $item['description'],
            'price' => $item['price'],
            'image' => $item['image_path']
        ],
        'recipe' => [
            'id' => $recipe['id'],
            'name' => $recipe['name'],
            'description' => $recipe['description'],
            'preparation_time' => $recipe['preparation_time'],
            'difficulty_level' => $recipe['difficulty_level'],
            'difficulty_color' => $difficulty_colors[$recipe['difficulty_level']] ?? '#2196f3',
            'yield_quantity' => $recipe['yield_quantity'],
            'yield_unit' => $recipe['yield_unit'],
            'chef_notes' => $recipe['chef_notes'],
            'status' => $recipe['status']
        ],
        'ingredients' => $ingredients,
        'summary' => [
            'total_ingredients' => count($ingredients),
            'all_in_stock' => (bool)$all_in_stock,
            'estimated_ingredient_cost' => round($ingredient_cost, 2),
            'margin' => round(((float)$item['price']) - $ingredient_cost, 2)
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    sendResponse(false, $e->getMessage(), null);
}

$conn->close();
